diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..f91f646 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,12 @@ +# +# https://help.github.com/articles/dealing-with-line-endings/ +# +# Linux start script should use lf +/gradlew text eol=lf + +# These are Windows script files and should use crlf +*.bat text eol=crlf + +# Binary files should be left untouched +*.jar binary + diff --git a/.gitignore b/.gitignore index 7730c2f..0f51950 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,8 @@ -/java/run -/java/bin -/java/dev -/export -/.metadata +/dev +.metadata +.classpath +.project +.settings +.gradle +bin +build diff --git a/README.md b/README.md index 58d9bbb..6e35be5 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,8 @@ -# TCR +# TCR - That Cube Rocks -Ein Minecraft®™ 1.8.9 "Fork" +Ein Block-basiertes Open-World-Spiel mit vielen Dimensionen und RPG-Elementen. + +**Projekt ist in der frühen Entwicklungsphase / Alpha** + +Dieses Projekt ist Public Domain, siehe UNLICENSE. +Der Client verwendet LWJGL für GLFW und OpenGL, für dessen Lizenz siehe [Die LWJGL Website](https://www.lwjgl.org/license). diff --git a/client/build.gradle.kts b/client/build.gradle.kts new file mode 100644 index 0000000..78abd8c --- /dev/null +++ b/client/build.gradle.kts @@ -0,0 +1,47 @@ + +plugins { + application + id("com.gradleup.shadow") version "8.3.6" +} + +repositories { + mavenCentral() +} + +dependencies { + implementation(project(":common")) + + implementation(platform("org.lwjgl:lwjgl-bom:3.3.6")) + + implementation("org.lwjgl", "lwjgl") + implementation("org.lwjgl", "lwjgl-glfw") + implementation("org.lwjgl", "lwjgl-opengl") + + runtimeOnly("org.lwjgl", "lwjgl", classifier = "natives-linux") + runtimeOnly("org.lwjgl", "lwjgl", classifier = "natives-freebsd") + runtimeOnly("org.lwjgl", "lwjgl", classifier = "natives-windows") + runtimeOnly("org.lwjgl", "lwjgl-glfw", classifier = "natives-linux") + runtimeOnly("org.lwjgl", "lwjgl-glfw", classifier = "natives-freebsd") + runtimeOnly("org.lwjgl", "lwjgl-glfw", classifier = "natives-windows") + runtimeOnly("org.lwjgl", "lwjgl-opengl", classifier = "natives-linux") + runtimeOnly("org.lwjgl", "lwjgl-opengl", classifier = "natives-freebsd") + runtimeOnly("org.lwjgl", "lwjgl-opengl", classifier = "natives-windows") +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +application { + mainClass = "client.Client" + tasks.run.get().workingDir = rootProject.file("dev/client") + tasks.run.get().workingDir.mkdirs() + tasks.run.get().systemProperties.put("runtime.devmode", "") +} + +tasks.shadowJar { + destinationDirectory = rootProject.file("dev") + archiveFileName = "tcr_client.jar" +} diff --git a/java/src/game/Game.java b/client/src/main/java/client/Client.java similarity index 68% rename from java/src/game/Game.java rename to client/src/main/java/client/Client.java index efd3175..135071b 100755 --- a/java/src/game/Game.java +++ b/client/src/main/java/client/Client.java @@ -1,4 +1,4 @@ -package game; +package client; import java.awt.image.BufferedImage; import java.io.BufferedInputStream; @@ -19,10 +19,10 @@ import java.util.ArrayDeque; import java.util.Date; import java.util.Iterator; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Map.Entry; import java.util.Queue; -import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; @@ -30,130 +30,152 @@ import java.util.concurrent.FutureTask; import java.util.function.Function; import javax.imageio.ImageIO; +import javax.swing.JFileChooser; + import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import game.collect.Lists; -import game.collect.Maps; -import game.future.Futures; -import game.future.ListenableFuture; -import game.future.ListenableFutureTask; - -import game.audio.AudioInterface; -import game.audio.PositionedSound; -import game.audio.SoundManager; -import game.audio.Volume; -import game.biome.Biome; -import game.block.Block; -import game.color.Colorizer; -import game.color.TextColor; -import game.entity.Entity; -import game.entity.animal.EntityHorse; -import game.entity.npc.Energy; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.gui.Font; -import game.gui.Gui; -import game.gui.GuiConsole; -import game.gui.GuiInfo; -import game.gui.GuiLoading; -import game.gui.GuiMenu; -import game.gui.GuiServer; -import game.gui.Style; -import game.gui.character.GuiChar; -import game.gui.container.GuiContainer; -import game.gui.container.GuiInventory; -import game.gui.element.Textbox; -import game.gui.ingame.GuiGameOver; -import game.init.BlockRegistry; -import game.init.Config; -import game.init.EntityRegistry; -import game.init.ItemRegistry; -import game.init.Items; -import game.init.Registry; -import game.init.SoundEvent; -import game.inventory.InventoryPlayer; -import game.item.Item; -import game.item.ItemBlock; -import game.item.ItemControl; -import game.item.ItemStack; -import game.log.Log; -import game.log.LogLevel; -import game.log.Message; -import game.material.Material; -import game.model.ModelManager; -import game.network.IThreadListener; -import game.network.NetConnection; -import game.network.NetHandler.ThreadQuickExitException; -import game.network.ClientLoginHandler; -import game.network.ClientPlayer; -import game.network.PlayerController; -import game.packet.CPacketAction; -import game.packet.CPacketAction.Action; -import game.packet.CPacketCheat; -import game.packet.CPacketMessage; -import game.packet.HPacketHandshake; -import game.packet.LPacketPasswordResponse; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.potion.PotionHelper; -import game.properties.IProperty; -import game.renderer.BlockRenderer; -import game.renderer.Drawing; -import game.renderer.EntityRenderer; -import game.renderer.GlState; -import game.renderer.ItemRenderer; -import game.renderer.RenderGlobal; -import game.renderer.chunk.RenderChunk; -import game.renderer.entity.RenderItem; -import game.renderer.entity.RenderManager; -import game.renderer.particle.EffectRenderer; -import game.renderer.texture.EntityTexManager; -import game.renderer.texture.TextureManager; -import game.renderer.texture.TextureMap; -import game.rng.Random; -import game.util.CharValidator; -import game.util.ExtMath; -import game.util.FileCallback; -import game.util.FileUtils; -import game.util.PerfSection; -import game.util.Timing; -import game.util.Util; -import game.vars.BaseVar.VarFunction; -import game.vars.BoolVar; -import game.vars.BoolVar.BoolFunction; -import game.vars.CVar; -import game.vars.CVarCategory; -import game.vars.ColorVar; -import game.vars.EnumVar; -import game.vars.EnumVar.EnumFunction; -import game.vars.FloatVar; -import game.vars.FloatVar.FloatFunction; -import game.vars.IntVar; -import game.vars.IntVar.IntFunction; -import game.vars.StringVar; -import game.vars.StringVar.StringFunction; -import game.vars.Variable; -import game.vars.Variable.IntType; -import game.window.Bind; -import game.window.Button; -import game.window.DisplayMode; -import game.window.KeyEvent; -import game.window.Keysym; -import game.window.Wheel; -import game.window.Window; -import game.window.WindowEvent; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Chunk; -import game.world.Facing; -import game.world.HitPosition; -import game.world.HitPosition.ObjectType; -import game.world.LightType; -import game.world.Region; -import game.world.State; -import game.world.World; -import game.world.WorldClient; +import client.audio.AudioInterface; +import client.audio.SoundManager; +import client.audio.Volume; +import client.gui.FileCallback; +import client.gui.Font; +import client.gui.Gui; +import client.gui.GuiConnect.ServerInfo; +import client.gui.GuiConsole; +import client.gui.GuiInfo; +import client.gui.GuiLoading; +import client.gui.GuiMenu; +import client.gui.GuiServer; +import client.gui.Style; +import client.gui.character.GuiChar; +import client.gui.container.GuiContainer; +import client.gui.container.GuiInventory; +import client.gui.element.Area; +import client.gui.ingame.GuiGameOver; +import client.network.ClientLoginHandler; +import client.network.ClientPlayer; +import client.network.DummyConnection; +import client.renderer.BlockRenderer; +import client.renderer.Drawing; +import client.renderer.EntityRenderer; +import client.renderer.GlState; +import client.renderer.ItemRenderer; +import client.renderer.RenderGlobal; +import client.renderer.blockmodel.ModelBlock; +import client.renderer.blockmodel.ModelManager; +import client.renderer.chunk.RenderChunk; +import client.renderer.entity.RenderItem; +import client.renderer.entity.RenderManager; +import client.renderer.particle.EffectRenderer; +import client.renderer.texture.ColormapLoader; +import client.renderer.texture.EntityTexManager; +import client.renderer.texture.TextureManager; +import client.renderer.texture.TextureMap; +import client.util.FileUtils; +import client.util.Message; +import client.util.PerfSection; +import client.util.PlayerController; +import client.vars.BoolVar; +import client.vars.CVar; +import client.vars.CVarCategory; +import client.vars.ColorVar; +import client.vars.EnumVar; +import client.vars.FloatVar; +import client.vars.IntVar; +import client.vars.StringVar; +import client.vars.Variable; +import client.vars.BaseVar.VarFunction; +import client.vars.BoolVar.BoolFunction; +import client.vars.EnumVar.EnumFunction; +import client.vars.FloatVar.FloatFunction; +import client.vars.IntVar.IntFunction; +import client.vars.StringVar.StringFunction; +import client.vars.Variable.IntType; +import client.window.Bind; +import client.window.Button; +import client.window.DisplayMode; +import client.window.KeyEvent; +import client.window.Keysym; +import client.window.Wheel; +import client.window.Window; +import client.window.WindowEvent; +import client.world.ChunkClient; +import client.world.WorldClient; +import common.Version; +import common.biome.Biome; +import common.block.Block; +import common.collect.Lists; +import common.collect.Maps; +import common.color.TextColor; +import common.dimension.Space; +import common.entity.Entity; +import common.entity.animal.EntityHorse; +import common.entity.npc.Energy; +import common.entity.npc.EntityCpu; +import common.entity.npc.EntityNPC; +import common.entity.npc.PlayerCharacter; +import common.entity.types.EntityLiving; +import common.future.Futures; +import common.future.ListenableFuture; +import common.future.ListenableFutureTask; +import common.future.ThreadFactoryBuilder; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.EntityRegistry; +import common.init.ItemRegistry; +import common.init.Items; +import common.init.Registry; +import common.init.SoundEvent; +import common.init.UniverseRegistry; +import common.inventory.InventoryPlayer; +import common.item.Item; +import common.item.ItemBlock; +import common.item.ItemControl; +import common.item.ItemStack; +import common.log.Log; +import common.log.LogLevel; +import common.net.bootstrap.Bootstrap; +import common.net.channel.Channel; +import common.net.channel.ChannelException; +import common.net.channel.ChannelHandler; +import common.net.channel.ChannelInitializer; +import common.net.channel.ChannelOption; +import common.net.channel.nio.NioEventLoopGroup; +import common.net.channel.socket.nio.NioSocketChannel; +import common.net.handler.timeout.ReadTimeoutHandler; +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; +import common.network.IThreadListener; +import common.network.NetConnection; +import common.network.PacketDecoder; +import common.network.PacketEncoder; +import common.network.PacketPrepender; +import common.network.PacketRegistry; +import common.network.PacketSplitter; +import common.network.NetHandler.ThreadQuickExitException; +import common.packet.CPacketAction; +import common.packet.CPacketCheat; +import common.packet.CPacketMessage; +import common.packet.HPacketHandshake; +import common.packet.CPacketAction.Action; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.properties.IProperty; +import common.sound.EventType; +import common.sound.PositionedSound; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.CharValidator; +import common.util.ExtMath; +import common.util.Facing; +import common.util.HitPosition; +import common.util.LazyLoader; +import common.util.Util; +import common.util.HitPosition.ObjectType; +import common.world.LightType; +import common.world.State; +import common.world.World; /* Een net ganz funktionierndes Programm ... @@ -176,46 +198,52 @@ import game.world.WorldClient; [[oder einfach einen Toaster mit nem LCD und Maus]] */ -public class Game implements IThreadListener { +public class Client implements IThreadListener { public static class SyncFunction implements IntFunction { public void apply(IntVar cv, int value) { - Game.getGame().sync(value); + Client.CLIENT.sync(value); } } public static class TickFunction implements FloatFunction { public void apply(FloatVar cv, float value) { - Game.getGame().tick_target(value); + Client.CLIENT.tick_target(value); } } public static class ConsoleFunction implements IntFunction { public void apply(IntVar cv, int value) { - Game.getGame().resizeConsole(); + Client.CLIENT.resizeConsole(); } } public static class ChatFunction implements IntFunction { public void apply(IntVar cv, int value) { - Game.getGame().resizeChat(); + Client.CLIENT.resizeChat(); } } public static class FeedFunction implements IntFunction { public void apply(IntVar cv, int value) { - Game.getGame().resizeFeed(); + Client.CLIENT.resizeFeed(); } } public static class HotbarFunction implements IntFunction { public void apply(IntVar cv, int value) { - Game.getGame().resizeHotbar(); + Client.CLIENT.resizeHotbar(); } } public static class DistanceFunction implements IntFunction { public void apply(IntVar cv, int value) { - Game.getGame().distance(value); + Client.CLIENT.distance(value); + } + } + + public static class RedrawFunction implements IntFunction { + public void apply(IntVar cv, int value) { + Client.CLIENT.rescale(); } } @@ -225,6 +253,13 @@ public class Game implements IThreadListener { } } + public static class FontFunction implements BoolFunction { + public void apply(BoolVar cv, boolean value) { + Font.load(value); + Client.CLIENT.rescale(); + } + } + private interface DebugRunner { void execute(Keysym key); } @@ -240,8 +275,18 @@ public class Game implements IThreadListener { this.help = help; } } - + + public static final String VERSION = Version.NAME + " Client " + Util.VERSION; public static final int LOG_BUFFER = 32768; + public static final int MIN_WIDTH = 800; + public static final int MIN_HEIGHT = 450; + private static final LazyLoader CLIENT_NIO_EVENTLOOP = new LazyLoader() + { + protected NioEventLoopGroup load() + { + return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Client IO #%d").setDaemon(true).build()); + } + }; private final Queue> tasks = new ArrayDeque>(); private final Map bars = Maps.newTreeMap(); @@ -252,8 +297,10 @@ public class Game implements IThreadListener { private final List chat = Lists.newArrayList(); private final List feed = Lists.newArrayList(); private final List hotbar = Lists.newArrayList(); - private final File config = new File(System.getProperty("config.file", "game.cfg")); - + private final File config = new File(System.getProperty("config.file", "client.cfg")); + public final Map playerList = Maps.newTreeMap(); + public final List characterList = Lists.newArrayList(); + private boolean primary; private boolean secondary; private boolean tertiary; @@ -283,6 +330,7 @@ public class Game implements IThreadListener { public int thirdPersonView; public int timeFactor = 1; public int chunksUpdated; + public int selectedCharacter = -1; private long lastTicked = 0L; private long debugUpdateTime = System.currentTimeMillis(); @@ -294,6 +342,33 @@ public class Game implements IThreadListener { public float moveForward; public float zoomLevel; public float gravity = 1.0f; + + private long tmr_timer; + private long tmr_start; + private long tmr_current; + private long tmr_last; + + private long tmr_delta; + private long tmr_update; + private long tmr_frames; + private long tmr_iters; + + private long tick_torun; + private long tick_done; + private long tick_total; + private long tick_time; + private long tick_stime; + private long tick_ftime; + + private long tick_ttime; + private long tick_update; + + private double tick_fraction; + private float framerate; + private float tickrate; + private float fdelta; + private int tickTarget; + private int tickFrame; private TextureManager textureManager; private RenderManager renderManager; @@ -315,13 +390,13 @@ public class Game implements IThreadListener { private BufferedImage skin; private Object popupTarget; public PlayerController controller; - public WorldClient theWorld; - public EntityNPC thePlayer; + public WorldClient world; + public EntityNPC player; public HitPosition pointed; - @Variable(name = "chunk_view_distance", category = CVarCategory.RENDER, min = 2, max = 16 /* 128 */, callback = DistanceFunction.class, display = "Sichtweite", unit = "Chunks") + @Variable(name = "chunk_view_distance", category = CVarCategory.RENDER, min = 2, max = 16, callback = DistanceFunction.class, display = "Sichtweite", unit = "Chunks") public int renderDistance = 8; - @Variable(name = "chunk_build_time", category = CVarCategory.RENDER, min = 1, max = 100, display = "Max. Zeit für Chunk-Bau pro Frame", unit = "ms") + @Variable(name = "chunk_build_time", category = CVarCategory.RENDER, min = 1, max = 100, display = "Zeit für Chunk-Bau", unit = "ms") public int maxBuildTime = 8; @Variable(name = "gl_fov", category = CVarCategory.RENDER, min = 1.0f, max = 179.0f, display = "Sichtfeld (FOV)", unit = "°", precision = 1) public float fov = 70.0f; @@ -336,20 +411,27 @@ public class Game implements IThreadListener { @Variable(name = "win_sync", category = CVarCategory.WINDOW, min = -1, max = 16384, callback = SyncFunction.class, display = "Maximale Bildrate") public int sync = 0; - public int width; - public int height; - public int mouse_x; - public int mouse_y; - @Variable(name = "win_width", category = CVarCategory.WINDOW, min = 1, max = 65536, display = "Fensterbreite") + @Variable(name = "win_width", category = CVarCategory.WINDOW, min = MIN_WIDTH, max = 65536, display = "Fensterbreite") public int xsize = 1280; - @Variable(name = "win_height", category = CVarCategory.WINDOW, min = 1, max = 65536, display = "Fensterhöhe") + @Variable(name = "win_height", category = CVarCategory.WINDOW, min = MIN_HEIGHT, max = 65536, display = "Fensterhöhe") public int ysize = 800; @Variable(name = "win_pos_x", category = CVarCategory.WINDOW, min = -65536, max = 65536, display = "Fenster X-Position") public int saved_xpos = 0x80000000; @Variable(name = "win_pos_y", category = CVarCategory.WINDOW, min = -65536, max = 65536, display = "Fenster Y-Position") public int saved_ypos = 0x80000000; + + public int fb_raw_x; + public int fb_raw_y; + private int mouse_raw_x; + private int mouse_raw_y; public int fb_x; public int fb_y; + public int mouse_x; + public int mouse_y; + private int scale = 1; + + @Variable(name = "gui_scale", category = CVarCategory.GUI, min = 1, max = 5, display = "Skalierung", unit = "x", callback = RedrawFunction.class) + private int scaleVar = 1; @Variable(name = "phy_sensitivity", category = CVarCategory.INPUT, min = 0.01f, max = 10.0f, display = "Mausempfindlichkeit", precision = 2, unit = "%") public float sensitivity = 1.0f; @@ -360,19 +442,19 @@ public class Game implements IThreadListener { public DisplayMode vidMode; @Variable(name = "gui_dclick_delay", category = CVarCategory.INPUT, min = 150, max = 750, display = "Doppelklick bei", unit = "ms") public int dclickDelay = 250; - @Variable(name = "console_size", category = CVarCategory.CONSOLE, min = 0, max = 128, callback = ConsoleFunction.class, display = "Nachrichten in der Konsole") + @Variable(name = "console_size", category = CVarCategory.CONSOLE, min = 0, max = 128, callback = ConsoleFunction.class, display = "Nachrichten in Konsole") public int consoleSize = 32; @Variable(name = "chat_size", category = CVarCategory.CONSOLE, min = 0, max = 128, callback = ChatFunction.class, display = "Nachrichten im Chat") public int chatSize = 32; @Variable(name = "feed_size", category = CVarCategory.CONSOLE, min = 0, max = 128, callback = FeedFunction.class, display = "Nachrichten im Feed") public int feedSize = 8; - @Variable(name = "hotbar_size", category = CVarCategory.CONSOLE, min = 0, max = 16, callback = HotbarFunction.class, display = "Nachrichten in der Hotbar") + @Variable(name = "hotbar_size", category = CVarCategory.CONSOLE, min = 0, max = 16, callback = HotbarFunction.class, display = "Nachrichten in Hotbar") public int hotbarSize = 2; - @Variable(name = "overlay_fadeout", category = CVarCategory.CONSOLE, min = 1, max = 60, display = "Dauer bis zum Ausblenden", unit = "s") + @Variable(name = "overlay_fadeout", category = CVarCategory.CONSOLE, min = 1, max = 60, display = "Anzeigedauer", unit = "s") public int hudFadeout = 8; @Variable(name = "overlay_enabled", category = CVarCategory.CONSOLE, display = "Nachrichten-Overlay") public boolean hudOverlay = true; - @Variable(name = "chat_permanent", category = CVarCategory.CONSOLE, display = "Nachrichten im Chat immer einblenden") + @Variable(name = "chat_permanent", category = CVarCategory.CONSOLE, display = "Chat immer einblenden") public boolean chatPermanent = false; @Variable(name = "overlay_opacity", category = CVarCategory.CONSOLE, min = 0x00, max = 0xff, display = "Deckkraft Hintergrund") public int hudOpacity = 0x40; @@ -382,7 +464,7 @@ public class Game implements IThreadListener { public boolean saving; public boolean drawFps; public boolean drawDebug; - @Variable(name = "gl_vsync_flush", category = CVarCategory.RENDER, display = "Puffer vor Synch. leeren") + @Variable(name = "gl_vsync_flush", category = CVarCategory.RENDER, display = "Puffer leeren") public boolean glFlush = false; @Variable(name = "con_autoclose", category = CVarCategory.CONSOLE, display = "Schließen") public boolean conAutoclose = true; @@ -391,6 +473,8 @@ public class Game implements IThreadListener { public Style style = Style.DEFAULT; @Variable(name = "gui_scroll_lines", category = CVarCategory.GUI, min = 1, max = 10, display = "Scrollbreite", unit = "Zeilen") public int scrollLines = 3; + @Variable(name = "gui_font_tiny", category = CVarCategory.GUI, display = "Kleine Schrift", callback = FontFunction.class) + public boolean tinyFont = false; @@ -401,9 +485,9 @@ public class Game implements IThreadListener { @Variable(name = "snd_enabled", category = CVarCategory.SOUND, display = "Tonausgabe") public boolean soundEnabled = true; - @Variable(name = "snd_buffer_size", category = CVarCategory.SOUND, min = 0, max = 1048576, display = "Puffergröße") - public int soundBufferSize = 2048; - @Variable(name = "snd_frame_size", category = CVarCategory.SOUND, min = 2, max = 8192, display = "PCM-Intervall") + @Variable(name = "snd_buffer_size", category = CVarCategory.SOUND, min = 0, max = 1048576, display = "Puffer") + public int soundBufferSize = 16384; + @Variable(name = "snd_frame_size", category = CVarCategory.SOUND, min = 2, max = 8192, display = "Intervall") public int soundFrameSize = 32; private String serverInfo; @@ -428,45 +512,104 @@ public class Game implements IThreadListener { private long frameWait; private long startNanoTime = System.nanoTime(); - private static final Game INSTANCE = new Game(); + public static final Client CLIENT = new Client(); private final Bind[] keyBindsHotbar = new Bind[] { Bind.SELECT1, Bind.SELECT2, Bind.SELECT3, Bind.SELECT4, Bind.SELECT5, Bind.SELECT6, Bind.SELECT7, Bind.SELECT8, Bind.SELECT9 }; - private Game() { + private Client() { } - public static Game getGame() { - return INSTANCE; + private static NetConnection createNetworkManagerAndConnect(InetAddress address, int serverPort) + { + final NetConnection networkmanager = new NetConnection(); + ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group(CLIENT_NIO_EVENTLOOP.getValue())).handler(new ChannelInitializer() + { + protected void initChannel(Channel p_initChannel_1_) throws Exception + { + try + { + p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true)); + } + catch (ChannelException var3) + { + ; + } + + p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new PacketSplitter())).addLast((String)"decoder", (ChannelHandler)(new PacketDecoder(false))).addLast((String)"prepender", (ChannelHandler)(new PacketPrepender())).addLast((String)"encoder", (ChannelHandler)(new PacketEncoder(true))).addLast((String)"packet_handler", (ChannelHandler)networkmanager); + } + })).channel(NioSocketChannel.class)).connect(address, serverPort).syncUninterruptibly(); + return networkmanager; + } + + public void displayConnecting(ServerInfo server) { + this.displayGuiScreen(GuiLoading.makeWaitTask("Verbinde zu " + (server.getAddress() == null ? "localhost" : server.getAddress()) + ":" + server.getPort() + " ...")); } - public void connect(String address, int port, String user, String pass, String access) { - this.displayGuiScreen(GuiLoading.makeWaitTask("Verbinde zu " + (address == null ? "localhost" : address) + ":" + port + " ...")); - Log.JNI.info("Verbinde zu " + (address == null ? "localhost" : address) + ":" + port); - NetConnection connection = null; - try - { - connection = NetConnection.createNetworkManagerAndConnect(address == null ? InetAddress.getLoopbackAddress() : InetAddress.getByName(IDN.toASCII(address)), port); - connection.setNetHandler(new ClientLoginHandler(connection, this)); - connection.sendPacket(new HPacketHandshake(Config.PROTOCOL)); - connection.sendPacket(new LPacketPasswordResponse(user, access, pass)); - } - catch (UnknownHostException u) - { - Log.JNI.error(u, "Konnte nicht zu Server verbinden"); - this.disconnected("Unbekannter Hostname: " + (address == null ? "localhost" : address)); - return; - } - catch (Exception e) - { - Log.JNI.error(e, "Konnte nicht zu Server verbinden"); - this.disconnected(e.toString()); - return; - } - this.connection = connection; + public void connect(final ServerInfo server) { + this.displayConnecting(server); + Log.NETWORK.info("Verbinde zu " + (server.getAddress() == null ? "localhost" : server.getAddress()) + ":" + server.getPort()); + new Thread(new Runnable() { + public void run() { + final NetConnection connection; + try + { + connection = createNetworkManagerAndConnect(server.getAddress() == null ? InetAddress.getLoopbackAddress() : InetAddress.getByName(IDN.toASCII(server.getAddress())), server.getPort()); + connection.setNetHandler(new ClientLoginHandler(connection, Client.this, server)); + connection.sendPacket(new HPacketHandshake(Util.PROTOCOL), new GenericFutureListener>() { + public void operationComplete(Future u) throws Exception { + connection.setConnectionState(PacketRegistry.LOGIN); + } + }); + } + catch (UnknownHostException u) + { + Log.NETWORK.error(u, "Konnte nicht zu Server verbinden"); + Client.this.schedule(new Runnable() { + public void run() { + Client.this.disconnected("Unbekannter Hostname: " + (server.getAddress() == null ? "localhost" : server.getAddress())); + } + }); + return; + } + catch (Exception e) + { + Log.NETWORK.error(e, "Konnte nicht zu Server verbinden"); + Client.this.schedule(new Runnable() { + public void run() { + Client.this.disconnected((e instanceof RuntimeException && !(e.getCause() instanceof RuntimeException) ? e.getCause() : e).toString()); + } + }); + return; + } + Client.this.schedule(new Runnable() { + public void run() { + Client.this.connection = connection; + } + }); + } + }, "Server connector").start(); } + public void joinDebugWorld() { + ClientPlayer player = new ClientPlayer(this, new DummyConnection()); + this.debugWorld = true; + this.charEditor = false; + this.controller = new PlayerController(this, player); + WorldClient world = new WorldClient(this, Space.INSTANCE); + this.loadWorld(world, EntityRegistry.getEntityID(EntityCpu.class)); + this.player.setId(0); + this.displayGuiScreen(null); + this.player.flying = true; + this.player.noclip = true; + this.player.addEffect(new PotionEffect(Potion.FLYING, Integer.MAX_VALUE, 1)); + this.player.setHeight(2.0f); + world.setGravity(this.gravity = 1.0f); + world.setTimeFactor(this.timeFactor = 1); + this.dayCycle = true; + } + public void unloadWorld() { ClientPlayer netHandler = this.getNetHandler(); if(netHandler != null) @@ -475,17 +618,20 @@ public class Game implements IThreadListener { this.charEditor = false; this.viewEntity = null; this.connection = null; - this.theWorld = null; - this.thePlayer = null; + this.world = null; + this.player = null; this.serverInfo = null; this.lastTickTime = -1; + this.selectedCharacter = -1; + this.playerList.clear(); + this.characterList.clear(); this.soundManager.stopSounds(); } public void refreshResources() { this.textureManager.onReload(); - Colorizer.reload(); + ColormapLoader.reload(); this.modelManager.onReload(); this.renderItem.onReload(); this.blockRenderer.onReload(); @@ -499,7 +645,7 @@ public class Game implements IThreadListener { this.textureManager = new TextureManager(); this.textureManager.onReload(); this.soundManager = new SoundManager(this); - Colorizer.reload(); + ColormapLoader.reload(); GlState.enableTexture2D(); GlState.shadeModel(GL11.GL_SMOOTH); GL11.glClearDepth(1.0D); @@ -529,7 +675,7 @@ public class Game implements IThreadListener { this.renderGlobal = new RenderGlobal(this); this.renderGlobal.onReload(); EntityTexManager.loadNpcTextures(); - this.effectRenderer = new EffectRenderer(this.theWorld, this.textureManager); + this.effectRenderer = new EffectRenderer(this.world, this.textureManager); } public void start() @@ -546,10 +692,10 @@ public class Game implements IThreadListener { } catch(ExecutionException e1) { if(!(e1.getCause() instanceof ThreadQuickExitException)) - Log.JNI.error(e1, "Fehler beim Ausführen von Render-Task " + task); + Log.SYSTEM.error(e1, "Fehler beim Ausführen von Render-Task " + task); } catch(InterruptedException e2) { - Log.JNI.error(e2, "Fehler beim Ausführen von Render-Task " + task); + Log.SYSTEM.error(e2, "Fehler beim Ausführen von Render-Task " + task); } } } @@ -599,7 +745,7 @@ public class Game implements IThreadListener { if (this.keyBindsHotbar[l].isPressed()) { // if(!this.showDebugProfilerChart) { - this.thePlayer.inventory.currentItem = l; + this.player.inventory.currentItem = l; // } } } @@ -610,7 +756,7 @@ public class Game implements IThreadListener { if (Bind.THROW.isPressed()) { - this.thePlayer.dropOneItem(this.ctrl()); + this.player.dropOneItem(this.ctrl()); } this.primary |= Bind.PRIMARY.isPressed(); @@ -627,9 +773,9 @@ public class Game implements IThreadListener { } // this.ingameGui.updateTick(); this.entityRenderer.getMouseOver(1.0F); - if (/* !this.paused && */ this.theWorld != null) + if (/* !this.paused && */ this.world != null) { - this.controller.updateController(); + this.controller.update(); } this.textureMap.updateAnimations(); if (this.open != null) @@ -637,9 +783,9 @@ public class Game implements IThreadListener { this.open.updateScreen(); } - if (this.open == null && this.thePlayer != null) + if (this.open == null && this.player != null) { - if (this.thePlayer.getHealth() <= 0) + if (this.player.getHealth() <= 0) { this.displayGuiScreen(null); } @@ -654,12 +800,12 @@ public class Game implements IThreadListener { --this.leftClickCounter; } - if (this.open == null && this.thePlayer != null) { - if (this.thePlayer.isUsingItem()) + if (this.open == null && this.player != null) { + if (this.player.isUsingItem()) { if (!Bind.SECONDARY.isDown()) { - this.controller.onStoppedUsingItem(this.thePlayer); + this.controller.stopUsing(this.player); } } else @@ -685,7 +831,7 @@ public class Game implements IThreadListener { } } - if (Bind.SECONDARY.isDown() && this.rightClickTimer == 0 && !this.thePlayer.isUsingItem()) + if (Bind.SECONDARY.isDown() && this.rightClickTimer == 0 && !this.player.isUsingItem()) { this.secondary(); } @@ -695,36 +841,39 @@ public class Game implements IThreadListener { this.primary = this.secondary = this.tertiary = this.quarternary = false; - if (this.theWorld != null) + if (this.world != null) { - if (this.thePlayer != null) + if (this.player != null) { ++this.chunkLoadTimer; if (this.chunkLoadTimer == 30) { this.chunkLoadTimer = 0; - this.theWorld.ensureAreaLoaded(this.thePlayer); + this.world.ensureAreaLoaded(this.player); } } this.entityRenderer.updateRenderer(); this.renderGlobal.updateClouds(); - this.theWorld.decrLightning(); - this.theWorld.updateEntities(); + this.world.decrLightning(); + this.world.updateEntities(); } this.soundManager.update(); - if (this.theWorld != null) + if (this.world != null) { - this.theWorld.tick(); - if (/* !this.paused && */ this.theWorld != null) + this.world.tick(); + if (/* !this.paused && */ this.world != null) { - this.theWorld.displayTick(ExtMath.floord(this.thePlayer.posX), ExtMath.floord(this.thePlayer.posY), ExtMath.floord(this.thePlayer.posZ)); + this.world.displayTick(ExtMath.floord(this.player.posX), ExtMath.floord(this.player.posY), ExtMath.floord(this.player.posZ)); } this.effectRenderer.updateEffects(); } else if (this.connection != null) { - this.connection.processReceivedPackets(); + if(this.connection.isChannelOpen()) + this.connection.processReceivedPackets(); + else + this.connection.checkDisconnected(); } } @@ -738,19 +887,19 @@ public class Game implements IThreadListener { GL11.glPolygonMode(GL11.GL_FRONT_AND_BACK, GL11.GL_LINE); // GL_FRONT_AND_BACK, GL_LINE } if(this.open == null) { - if(this.thePlayer != null) - this.thePlayer.setAngles(this.deltaX, this.deltaY); + if(this.player != null) + this.player.setAngles(this.deltaX, this.deltaY); this.deltaX = this.deltaY = 0.0f; } - if(this.thePlayer != null) - this.soundManager.setListener(this.thePlayer, (float)Timing.tick_fraction); - if(this.thePlayer != null && this.thePlayer.isEntityInsideOpaqueBlock()) + if(this.player != null) + this.soundManager.setListener(this.player, (float)this.tick_fraction); + if(this.player != null && this.player.isEntityInsideOpaqueBlock()) this.thirdPersonView = 0; GL11.glPushMatrix(); GL11.glClear(16640); GlState.enableTexture2D(); - if(this.theWorld != null) - this.entityRenderer.renderWorld((float)Timing.tick_fraction, System.nanoTime() - this.tickStart); + if(this.world != null) + this.entityRenderer.renderWorld((float)this.tick_fraction, System.nanoTime() - this.tickStart); GL11.glPopMatrix(); GlState.disableTexture2D(); @@ -781,16 +930,16 @@ public class Game implements IThreadListener { public void renderHud() { this.setupOverlay(); - if(this.theWorld != null && this.open == null && this.thirdPersonView == 0 && this.viewEntity != null) { + if(this.world != null && this.open == null && this.thirdPersonView == 0 && this.viewEntity != null) { if(this.drawDebug) { - this.renderWorldDirections((float)Timing.tick_fraction); + this.renderWorldDirections((float)this.tick_fraction); } else { Drawing.drawRect(this.fb_x / 2 - 1, this.fb_y / 2 - 16, 2, 32, this.pointed != null && this.pointed.type != ObjectType.MISS ? 0xffffffff : 0xffcfcfcf); Drawing.drawRect(this.fb_x / 2 - 16, this.fb_y / 2 - 1, 32, 2, this.pointed != null && this.pointed.type != ObjectType.MISS ? 0xffffffff : 0xffcfcfcf); } } - if(this.theWorld != null && this.open == null) { + if(this.world != null && this.open == null) { int selected = // this.getRenderViewEntity() != null && this.getRenderViewEntity().isPlayer() ? 9 : 0, this.getRenderViewEntity() != null && this.getRenderViewEntity().isPlayer() ? ((EntityNPC)this.getRenderViewEntity()).inventory.currentItem : -1; @@ -801,12 +950,12 @@ public class Game implements IThreadListener { Drawing.drawRectBorder(x - 1, y - 1, 36, 36, 0xff6f6f6f, selected == n ? 0xffffffff : 0xff000000, 0xffafafaf, 0xff4f4f4f); } - ItemStack itemstack = this.thePlayer != null ? this.thePlayer.inventory.getCurrentItem() : null; - String current = itemstack != null ? itemstack.getItem().getHotbarText(this.thePlayer, itemstack) : ""; + ItemStack itemstack = this.player != null ? this.player.inventory.getCurrentItem() : null; + String current = itemstack != null ? itemstack.getItem().getHotbarText(this.player, itemstack) : ""; if(!current.isEmpty()) Drawing.drawTextUpward(current, this.fb_x / 2, this.fb_y - 60, 0xffffffff); } - if(this.theWorld != null && !(this.open instanceof GuiConsole)) { + if(this.world != null && !(this.open instanceof GuiConsole)) { int x = this.fb_x / 2; int y = 0; Iterator> iter = this.bars.entrySet().iterator(); @@ -814,7 +963,7 @@ public class Game implements IThreadListener { while(iter.hasNext()) { Entry status = iter.next(); Entity ent; - if(this.thePlayer != null && now - status.getValue() < 10000L && (ent = this.thePlayer.worldObj.getEntityByID(status.getKey())) instanceof EntityLiving) { + if(this.player != null && now - status.getValue() < 10000L && (ent = this.player.worldObj.getEntityByID(status.getKey())) instanceof EntityLiving) { EntityLiving entity = (EntityLiving)ent; String s = entity.getName() + TextColor.GRAY + " [" + EntityLiving.getHealthColor(entity.getHealth(), entity.getMaxHealth()) + @@ -832,19 +981,19 @@ public class Game implements IThreadListener { } } - if(this.thePlayer != null && (!this.drawDebug || this.open != null)) { + if(this.player != null && (!this.drawDebug || this.open != null)) { x = 40; y = 40; - for(PotionEffect effect : this.thePlayer.getEffects()) { + for(PotionEffect effect : this.player.getEffects()) { Potion potion = effect.getPotion(); int color = potion.getColor(); - String name = (potion.isBadEffect() ? TextColor.ORANGE : TextColor.ACID) + potion.getDisplay() + PotionHelper.getPotionPotency(effect.getAmplifier()); + String name = (potion.isBadEffect() ? TextColor.ORANGE : TextColor.ACID) + effect.getEffectName(); String desc = TextColor.NEON + effect.getDurationString(); // Drawing.drawRectColor(x, y, 250, Font.DEFAULT.yglyph + 2, color | 0xff000000); - Drawing.drawRectBorder(x, y, 250, Font.YGLYPH + 4, 0xff000000, 0xff202020, 0xffcfcfcf, 0xff6f6f6f); - Drawing.drawGradient(x + 2, y + 2, effect.isInfinite() ? 246 : ((int)(246.0f * ((float)effect.getRemaining() / (float)effect.getDuration()))), Font.YGLYPH, color | 0xff000000, Util.mixColor(color | 0xff000000, 0xff000000)); - Drawing.drawText(name, x + 4, y + 2, 0xffffffff); - Drawing.drawTextRight(desc, x + 250 - 4, y + 2, 0xffffffff); + Drawing.drawRectBorder(x, y, 250, Font.YGLYPH + 6, 0xff000000, 0xff202020, 0xffcfcfcf, 0xff6f6f6f); + Drawing.drawGradient(x + 2, y + 2, effect.isInfinite() ? 246 : ((int)(246.0f * ((float)effect.getRemaining() / (float)effect.getDuration()))), Font.YGLYPH + 2, color | 0xff000000, Util.mixColor(color | 0xff000000, 0xff000000)); + Drawing.drawText(name, x + 4, y + 3, 0xffffffff); + Drawing.drawTextRight(desc, x + 250 - 4, y + 3, 0xffffffff); y += 24; } } @@ -854,7 +1003,7 @@ public class Game implements IThreadListener { int absorb = entity.getAbsorptionAmount(); int armor = entity.getTotalArmorValue(); int stats = 1 + (absorb > 0 ? 1 : 0) + (armor > 0 ? 1 : 0) + (entity.vehicle instanceof EntityLiving ? 1 : 0) - + (entity instanceof EntityNPC && ((EntityNPC)entity).canUseMagic() ? 1 : 0); + + (entity instanceof EntityNPC npc && npc.getManaPoints() > 0 ? 1 : 0); for(Energy energy : Energy.values()) { if(entity.getEnergy(energy) > 0) stats += 1; @@ -874,9 +1023,9 @@ public class Game implements IThreadListener { int vhMax = living.getMaxHealth(); y = stats(x, y, living.getDisplayName() /* + " (Reittier)" */, vh, vhMax, 0xff6060); } - if(entity instanceof EntityNPC && ((EntityNPC)entity).canUseMagic()) { - int mana = entity.getManaPoints(); - int maxm = entity.getMaxMana(); + if(entity instanceof EntityNPC npc && npc.getManaPoints() > 0) { + int mana = npc.getManaPoints(); + int maxm = npc.getMaxMana(); y = stats(x, y, TextColor.CYAN + "Mana", mana, maxm, 0x0000ff); } for(int z = 0; z < Energy.values().length; z++) { @@ -889,15 +1038,15 @@ public class Game implements IThreadListener { } } - if(this.thePlayer != null) { + if(this.player != null) { x = 40; - y = this.fb_y - 40 - (this.thePlayer.isRidingHorse() && this.thePlayer.getHorseJumpPower() != 0.0f ? 2 : 1) * 40; - if(this.thePlayer.isRidingHorse() && this.thePlayer.getHorseJumpPower() != 0.0f) // { - y = bar(x, y, String.format(TextColor.NEON + "Sprungkraft: " + TextColor.CYAN + "%d %%", (int)(this.thePlayer.getHorseJumpPower() * 100.0f)), - this.thePlayer.getHorseJumpPower(), 0x4040ff); + y = this.fb_y - 40 - (this.player.isRidingHorse() && this.player.getHorseJumpPower() != 0.0f ? 2 : 1) * 40; + if(this.player.isRidingHorse() && this.player.getHorseJumpPower() != 0.0f) // { + y = bar(x, y, String.format(TextColor.NEON + "Sprungkraft: " + TextColor.CYAN + "%d %%", (int)(this.player.getHorseJumpPower() * 100.0f)), + this.player.getHorseJumpPower(), 0x4040ff); // } // else { - y = bar(x, y, String.format(TextColor.ACID + "EXP: " + TextColor.GREEN + "Level %d, %d/%d", this.thePlayer.experienceLevel, (int)((float)this.thePlayer.xpBarCap() * this.thePlayer.experience), this.thePlayer.xpBarCap()), this.thePlayer.experience, 0x40ff40); + y = bar(x, y, String.format(TextColor.ACID + "EXP: " + TextColor.GREEN + "Level %d, %d/%d", this.player.experienceLevel, (int)((float)this.player.xpBarCap() * this.player.experience), this.player.xpBarCap()), this.player.experience, 0x40ff40); // } } @@ -968,9 +1117,9 @@ public class Game implements IThreadListener { } if(this.open != null) this.open.render(); - else if(this.theWorld == null || this.theWorld.hasNoChunks() || this.charEditor) - Drawing.drawScaled(this, Gui.DIRT_BACKGROUND); - if(Bind.INFO.isDown() && (this.open == null || !(this.open.selected instanceof Textbox))) + else if(this.world == null || this.charEditor) + Drawing.drawScaled(this, Gui.BACKGROUND); + if(Bind.INFO.isDown() && (this.open == null || !(this.open.selected instanceof client.gui.element.Field || this.open.selected instanceof Area))) this.drawInfo(); if(this.hudOverlay && !(this.open instanceof GuiConsole)) { this.drawOverlay(this.feed, this.feedSize, false, 1, 0, 0); @@ -984,7 +1133,7 @@ public class Game implements IThreadListener { this.renderLagometer(); } else { - Drawing.drawText(String.format("%s%.2f", framecode(), Timing.framerate), 0, 0, 0xffffffff); + Drawing.drawText(String.format("%s%.2f", framecode(), this.framerate), 0, 0, 0xffffffff); } } GlState.enableBlend(); @@ -1012,13 +1161,13 @@ public class Game implements IThreadListener { , GL11.glGetString(GL11.GL_VERSION), // WCF.glGetString(WCF.GL_SHADING_LANGUAGE_VERSION), GL11.glGetString(GL11.GL_RENDERER), GL11.glGetString(GL11.GL_VENDOR), - this.framecode(), Timing.framerate < 1.0f ? 1.0f / Timing.framerate : Timing.framerate, Timing.framerate < 1.0f ? "SPF" : "FPS", + this.framecode(), this.framerate < 1.0f ? 1.0f / this.framerate : this.framerate, this.framerate < 1.0f ? "SPF" : "FPS", this.vsync ? TextColor.DGRAY + "VSYNC" : (this.syncLimited ? TextColor.GREEN + "" + this.syncLimit : TextColor.RED + "UNL"), - (float)PerfSection.getTotal(false) / 1000.0f, this.fb_x, this.fb_y, - this.fullscreen ? " @ " + (this.vidMode == null ? "?" : this.vidMode.refresh) + " Hz" : "", - this.tpscode(), Timing.tickrate < 1.0f ? 1.0f / Timing.tickrate : Timing.tickrate, - Timing.tickrate < 1.0f ? "SPT" : "TPS", (float)Timing.tickTarget / 1000.0f, - (float)Timing.tick_time / 1000.0f, this.tickTimeout, + (float)PerfSection.getTotal(false) / 1000.0f, this.fb_raw_x, this.fb_raw_y, + this.fullscreen ? " @ " + (this.vidMode == null ? "?" : this.vidMode.refresh()) + " Hz" : "", + this.tpscode(), this.tickrate < 1.0f ? 1.0f / this.tickrate : this.tickrate, + this.tickrate < 1.0f ? "SPT" : "TPS", (float)this.tickTarget / 1000.0f, + (float)this.tick_time / 1000.0f, this.tickTimeout, str != null ? "\n" : "", str != null ? str : "" ); // if(str) @@ -1067,8 +1216,8 @@ public class Game implements IThreadListener { } if(this.cameraUsed) { this.cameraUsed = false; - if(this.theWorld != null) - this.theWorld.setLastLightning(1, 0xffffff); + if(this.world != null) + this.world.setLastLightning(1, 0xffffff); } if(this.isDirty()) this.save(); @@ -1095,8 +1244,8 @@ public class Game implements IThreadListener { // } if(this.zooming) this.zoomLevel = ExtMath.clampf(this.zoomLevel + (dir < 0 ? -0.25f : 0.25f), 2.0f, 16.0f); - else if(this.thePlayer != null) - this.thePlayer.inventory.changeCurrentItem(dir); + else if(this.player != null) + this.player.inventory.changeCurrentItem(dir); } // public void resize(int width, int height) @@ -1135,8 +1284,8 @@ public class Game implements IThreadListener { { if(!this.refreshing) this.waitingForFile = false; - if(this.thePlayer != null) - this.thePlayer.setScreenClosed(); + if(this.player != null) + this.player.setScreenClosed(); if (this.open != null) { this.open.onGuiClosed(); @@ -1149,7 +1298,7 @@ public class Game implements IThreadListener { // guiScreenIn = new GuiMainMenu(); // } // else - if (gui == null && this.theWorld != null && this.thePlayer.getHealth() <= 0) + if (gui == null && this.world != null && this.player.getHealth() <= 0) { gui = GuiGameOver.INSTANCE; } @@ -1171,14 +1320,14 @@ public class Game implements IThreadListener { // SKC.setGuiMenu(); // else // SKC.setGuiAny(); - Window.setTitle(String.format("%s - %s", Config.VERSION, gui.getTitle())); + Window.setTitle(String.format("%s - %s", VERSION, gui.getTitle())); } else { this.menu(false); this.leftClickCounter = 10000; Bind.disableMouse(); - Window.setTitle(String.format("%s - %s%s", Config.VERSION, "Welt / Render", this.nograb ? "" : " (Maus gefangen)")); + Window.setTitle(String.format("%s - %s%s", VERSION, "Welt / Render", this.nograb ? "" : " (Maus gefangen)")); // SKC.setGuiNone(); } } @@ -1191,21 +1340,21 @@ public class Game implements IThreadListener { this.controller.resetInteraction(); } - if (this.leftClickCounter <= 0 && !this.thePlayer.isUsingItem()) + if (this.leftClickCounter <= 0 && !this.player.isUsingItem()) { if (leftClick && this.pointed != null && this.pointed.type == HitPosition.ObjectType.BLOCK) { BlockPos blockpos = this.pointed.block; - if (this.theWorld.getState(blockpos).getBlock().getMaterial() != Material.air && this.controller.onPlayerDamageBlock(blockpos, this.pointed.side)) + if (this.world.getState(blockpos).getBlock() != Blocks.air && this.controller.damageBlock(blockpos, this.pointed.side)) { this.effectRenderer.addBlockHitEffects(blockpos, this.pointed.side); - this.thePlayer.swingItem(); + this.player.swingItem(); } } else { - this.controller.resetBlockRemoving(); + this.controller.resetProgress(); } } } @@ -1216,17 +1365,17 @@ public class Game implements IThreadListener { { if (this.pointed == null) { - this.thePlayer.swingItem(); - Log.JNI.warn("Null zurückgegeben als 'hitResult', das sollte niemals passieren!"); + this.player.swingItem(); + Log.TICK.warn("Null zurückgegeben als 'hitResult', das sollte niemals passieren!"); this.leftClickCounter = 10; } else { - ItemStack itemstack = this.thePlayer.inventory.getCurrentItem(); - if ((this.pointed.type != ObjectType.BLOCK || this.theWorld.getState(this.pointed.block).getBlock().getMaterial() == Material.air) && itemstack != null && itemstack.getItem().onAction(itemstack, this.thePlayer, this.theWorld, ItemControl.PRIMARY, null)) + ItemStack itemstack = this.player.inventory.getCurrentItem(); + if ((this.pointed.type != ObjectType.BLOCK || this.world.getState(this.pointed.block).getBlock() == Blocks.air) && itemstack != null && itemstack.getItem().onAction(itemstack, this.player, this.world, ItemControl.PRIMARY, null)) { - this.thePlayer.swingItem(); - this.thePlayer.sendQueue.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.PRIMARY.ordinal())); + this.player.swingItem(); + this.player.client.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.PRIMARY.ordinal())); this.leftClickCounter = 10; return; } @@ -1234,13 +1383,13 @@ public class Game implements IThreadListener { switch (this.pointed.type) { case ENTITY: - this.thePlayer.swingItem(); - this.controller.attackEntity(this.thePlayer, this.pointed.entity); + this.player.swingItem(); + this.controller.attackEntity(this.player, this.pointed.entity); break; case BLOCK: - this.thePlayer.swingItem(); + this.player.swingItem(); BlockPos blockpos = this.pointed.block; - if (this.theWorld.getState(blockpos).getBlock().getMaterial() != Material.air) + if (this.world.getState(blockpos).getBlock() != Blocks.air) { this.controller.clickBlock(blockpos, this.pointed.side); break; @@ -1249,7 +1398,7 @@ public class Game implements IThreadListener { break; case MISS: default: - this.thePlayer.swingItem(); + this.player.swingItem(); this.leftClickCounter = 10; } } @@ -1258,11 +1407,11 @@ public class Game implements IThreadListener { private void secondary() { - if (!this.controller.getIsHittingBlock()) + if (!this.controller.isHittingBlock()) { this.rightClickTimer = 4; boolean flag = true; - ItemStack itemstack = this.thePlayer.inventory.getCurrentItem(); + ItemStack itemstack = this.player.inventory.getCurrentItem(); if (itemstack != null && itemstack.getItem() == Items.camera && !this.saving) { @@ -1271,14 +1420,14 @@ public class Game implements IThreadListener { if (this.pointed == null) { - Log.JNI.warn("Null zurückgegeben als 'hitResult', das sollte niemals passieren!"); + Log.TICK.warn("Null zurückgegeben als 'hitResult', das sollte niemals passieren!"); } else { - if ((this.pointed.type != ObjectType.BLOCK || this.theWorld.getState(this.pointed.block).getBlock().getMaterial() == Material.air) && itemstack != null && itemstack.getItem().onAction(itemstack, this.thePlayer, this.theWorld, ItemControl.SECONDARY, null)) + if ((this.pointed.type != ObjectType.BLOCK || this.world.getState(this.pointed.block).getBlock() == Blocks.air) && itemstack != null && itemstack.getItem().onAction(itemstack, this.player, this.world, ItemControl.SECONDARY, null)) { - this.thePlayer.swingItem(); - this.thePlayer.sendQueue.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.SECONDARY.ordinal())); + this.player.swingItem(); + this.player.client.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.SECONDARY.ordinal())); return; } @@ -1290,7 +1439,7 @@ public class Game implements IThreadListener { // flag = false; // } // else - if (this.controller.interactWithEntitySendPacket(this.thePlayer, this.pointed.entity)) + if (this.controller.interact(this.player, this.pointed.entity)) { flag = false; } @@ -1300,14 +1449,14 @@ public class Game implements IThreadListener { case BLOCK: BlockPos blockpos = this.pointed.block; - if (this.theWorld.getState(blockpos).getBlock().getMaterial() != Material.air) + if (this.world.getState(blockpos).getBlock() != Blocks.air) { - int i = itemstack != null ? itemstack.stackSize : 0; + int i = itemstack != null ? itemstack.size : 0; - if (this.controller.onPlayerRightClick(this.thePlayer, this.theWorld, itemstack, blockpos, this.pointed.side, this.pointed.vec)) + if (this.controller.clickRight(this.player, this.world, itemstack, blockpos, this.pointed.side, this.pointed.vec)) { flag = false; - this.thePlayer.swingItem(); + this.player.swingItem(); } if (itemstack == null) @@ -1315,11 +1464,11 @@ public class Game implements IThreadListener { return; } - if (itemstack.stackSize == 0) + if (itemstack.size == 0) { - this.thePlayer.inventory.mainInventory[this.thePlayer.inventory.currentItem] = null; + this.player.inventory.mainInventory[this.player.inventory.currentItem] = null; } - else if (itemstack.stackSize != i) // || this.controller.isCreative()) + else if (itemstack.size != i) // || this.controller.isCreative()) { this.entityRenderer.itemRenderer.resetEquippedProgress(); } @@ -1329,9 +1478,9 @@ public class Game implements IThreadListener { if (flag) { - ItemStack itemstack1 = this.thePlayer.inventory.getCurrentItem(); + ItemStack itemstack1 = this.player.inventory.getCurrentItem(); - if (itemstack1 != null && this.controller.sendUseItem(this.thePlayer, this.theWorld, itemstack1)) + if (itemstack1 != null && this.controller.sendUseItem(this.player, this.world, itemstack1)) { this.entityRenderer.itemRenderer.resetEquippedProgress2(); } @@ -1343,29 +1492,26 @@ public class Game implements IThreadListener { { if (this.pointed != null) { - if(this.thePlayer.getHeldItem() != null && this.thePlayer.getHeldItem().getItem().onAction(this.thePlayer.getHeldItem(), this.thePlayer, this.theWorld, ItemControl.TERTIARY, null)) { - this.thePlayer.sendQueue.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.TERTIARY.ordinal())); + if(this.player.getHeldItem() != null && this.player.getHeldItem().getItem().onAction(this.player.getHeldItem(), this.player, this.world, ItemControl.TERTIARY, null)) { + this.player.client.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.TERTIARY.ordinal())); return; } -// boolean flag = this.thePlayer.creative; int meta = 0; boolean flag1 = false; -// TileEntity tileentity = null; Item item = null; -// NBTTagCompound tag = null; if (this.pointed.type == HitPosition.ObjectType.BLOCK) { BlockPos blockpos = this.pointed.block; - Block block = this.theWorld.getState(blockpos).getBlock(); + Block block = this.world.getState(blockpos).getBlock(); - if (block.getMaterial() == Material.air) + if (block == Blocks.air) { return; } - item = block.getItem(this.theWorld, blockpos); + item = block.getItem(this.world, blockpos); if (item == null) { @@ -1373,7 +1519,7 @@ public class Game implements IThreadListener { } Block block1 = item instanceof ItemBlock && !block.isPickStrict() ? item.getBlock() : block; - meta = block1.getDamageValue(this.theWorld, blockpos); + meta = block1.getDamageValue(this.world, blockpos); flag1 = item.getHasSubtypes(); } else @@ -1387,11 +1533,11 @@ public class Game implements IThreadListener { return; } - InventoryPlayer inventoryplayer = this.thePlayer.inventory; + InventoryPlayer inventoryplayer = this.player.inventory; inventoryplayer.setCurrentItem(item, meta, flag1); if(this.itemCheat) { - this.thePlayer.sendQueue.addToSendQueue(new CPacketCheat(new ItemStack(item, 1, meta), inventoryplayer.currentItem, this.ctrl())); + this.player.client.addToSendQueue(new CPacketCheat(new ItemStack(item, 1, meta), inventoryplayer.currentItem, this.ctrl())); } } } @@ -1400,8 +1546,8 @@ public class Game implements IThreadListener { { if (this.pointed != null) { - if(this.thePlayer.getHeldItem() != null && this.thePlayer.getHeldItem().getItem().onAction(this.thePlayer.getHeldItem(), this.thePlayer, this.theWorld, ItemControl.QUARTERNARY, null)) { - this.thePlayer.sendQueue.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.QUARTERNARY.ordinal())); + if(this.player.getHeldItem() != null && this.player.getHeldItem().getItem().onAction(this.player.getHeldItem(), this.player, this.world, ItemControl.QUARTERNARY, null)) { + this.player.client.addToSendQueue(new CPacketAction(Action.ITEM_ACTION, ItemControl.QUARTERNARY.ordinal())); return; } } @@ -1421,7 +1567,7 @@ public class Game implements IThreadListener { this.viewEntity = null; this.connection = null; this.soundManager.stopSounds(); - this.theWorld = world; + this.world = world; if (this.renderGlobal != null) { @@ -1433,15 +1579,15 @@ public class Game implements IThreadListener { this.effectRenderer.clearEffects(world); } - if (this.thePlayer == null) + if (this.player == null) { - this.thePlayer = this.controller.createPlayerEntity(world, type); - this.thePlayer.rotYaw = -180.0F; + this.player = this.controller.createPlayerEntity(world, type); + this.player.rotYaw = -180.0F; } - this.thePlayer.preparePlayerToSpawn(); - world.spawnEntityInWorld(this.thePlayer); - this.viewEntity = this.thePlayer; + this.player.preparePlayerToSpawn(); + world.spawnEntityInWorld(this.player); + this.viewEntity = this.player; System.gc(); // SKC.loaded(true); @@ -1449,24 +1595,24 @@ public class Game implements IThreadListener { public void setDimensionAndSpawnPlayer(int dimension, int type) { - this.theWorld.removeAllEntities(); + this.world.removeAllEntities(); int i = 0; - if (this.thePlayer != null) + if (this.player != null) { - i = this.thePlayer.getId(); - this.theWorld.removeEntity(this.thePlayer); + i = this.player.getId(); + this.world.removeEntity(this.player); } this.viewEntity = null; - EntityNPC entityplayersp = this.thePlayer; - this.thePlayer = this.controller.createPlayerEntity(this.theWorld, type); - this.thePlayer.getDataWatcher().updateWatchedObjectsFromList(entityplayersp.getDataWatcher().getAllWatched()); - this.viewEntity = this.thePlayer; - this.thePlayer.preparePlayerToSpawn(); - this.theWorld.spawnEntityInWorld(this.thePlayer); - this.thePlayer.rotYaw = -180.0F; - this.thePlayer.setId(i); + EntityNPC entityplayersp = this.player; + this.player = this.controller.createPlayerEntity(this.world, type); + this.player.getDataWatcher().updateWatchedObjectsFromList(entityplayersp.getDataWatcher().getAllWatched()); + this.viewEntity = this.player; + this.player.preparePlayerToSpawn(); + this.world.spawnEntityInWorld(this.player); + this.player.rotYaw = -180.0F; + this.player.setId(i); // if (this.open instanceof GuiGameOver) // { @@ -1477,7 +1623,7 @@ public class Game implements IThreadListener { public ClientPlayer getNetHandler() { - return this.thePlayer != null ? this.thePlayer.sendQueue : null; + return this.player != null ? (ClientPlayer)this.player.client : null; } // public void setSkin(BufferedImage skin, String id, ModelType model, boolean slim) @@ -1523,8 +1669,8 @@ public class Game implements IThreadListener { } public void performAction(Action action) { - if(this.thePlayer != null) - this.thePlayer.sendQueue.addToSendQueue(new CPacketAction(action)); + if(this.player != null) + this.player.client.addToSendQueue(new CPacketAction(action)); } public void setBossStatus(EntityLiving entity) { @@ -1572,6 +1718,7 @@ public class Game implements IThreadListener { } catch (Exception exception) { + Log.SYSTEM.error(exception, "Fehler beim sofortigen Ausführen von Render-Task " + callableToSchedule); return Futures.immediateFailedFuture(exception); } } @@ -1664,7 +1811,7 @@ public class Game implements IThreadListener { String mem = String.format("JVM-Speicher: %d%% %d/%dMB", usedMem * 100L / maxMem, usedMem / 1024L / 1024L, maxMem / 1024L / 1024L) + "\n" + String.format("JVM-Reserviert: %d%% %dMB", totalMem * 100L / maxMem, totalMem / 1024L / 1024L); - if(this.theWorld == null) { + if(this.world == null) { return mem; } @@ -1692,27 +1839,27 @@ public class Game implements IThreadListener { Biome biome = null; String bline; String lline; - if(this.theWorld.isBlockLoaded(blockpos)) { - Chunk chunk = this.theWorld.getChunk(blockpos); - biome = chunk.getBiome(blockpos, null); + if(this.world.isBlockLoaded(blockpos)) { + ChunkClient chunk = this.world.getChunk(blockpos); + biome = chunk.getBiome(blockpos); bline = "Biom: " + biome.display + " (" + biome.id + ")" + /* (this.debugHideInfo ? "" : */ (", D: " + - TextColor.stripCodes(this.theWorld.dimension.getFormattedName(false)) + - " (" + this.theWorld.dimension.getDimensionId() + ")"); + TextColor.stripCodes(this.world.dimension.getFormattedName(false)) + + " (" + this.world.dimension.getDimensionId() + ")"); lline = "Licht: " + chunk.getLightSub(blockpos, 0) + " (" + chunk.getLight(LightType.SKY, blockpos) + " Himmel, " + chunk.getLight(LightType.BLOCK, blockpos) + " Blöcke, " + String.format( - "%.1f", this.theWorld.getSunBrightness(1.0f) * 15.0f) + " Welt), A: " - + String.format("%.3f", this.theWorld.getCelestialAngle(1.0f)); + "%.1f", this.world.getSunBrightness(1.0f) * 15.0f) + " Welt), A: " + + String.format("%.3f", this.world.getCelestialAngle(1.0f)); } else { bline = "Biom: , D: " + - TextColor.stripCodes(this.theWorld.dimension.getFormattedName(false)) + - " (" + this.theWorld.dimension.getDimensionId() + ")"; + TextColor.stripCodes(this.world.dimension.getFormattedName(false)) + + " (" + this.world.dimension.getDimensionId() + ")"; lline = "Licht: " + String.format( - "%.1f", this.theWorld.getSunBrightness(1.0f) * 15.0f) + " Welt, A: " - + String.format("%.3f", this.theWorld.getCelestialAngle(1.0f)); + "%.1f", this.world.getSunBrightness(1.0f) * 15.0f) + " Welt, A: " + + String.format("%.3f", this.world.getCelestialAngle(1.0f)); } - float temp = this.theWorld.getTempOffset() + (biome != null ? biome.getTemperature(blockpos) : 0.0f); + float temp = Math.max(this.world.getTempOffset() + (biome != null ? biome.getTemperature(blockpos) : 0.0f), 0.0f); long ticked = System.currentTimeMillis() - this.lastTicked; return @@ -1723,14 +1870,14 @@ public class Game implements IThreadListener { // this.connected != null ? this.connected : "[???]"))), this.renderGlobal.getDebugInfoRenders() + "\n" + this.renderGlobal.getDebugInfoEntities() + "\n" + - "Partikel: " + this.effectRenderer.getStatistics() + ". O: " + this.theWorld.getDebugLoadedEntities() + "\n" + - this.theWorld.getInfo() + "\n" + + "Partikel: " + this.effectRenderer.getStatistics() + ". O: " + this.world.getDebugLoadedEntities() + "\n" + + this.world.getInfo() + "\n" + // "", String.format("XYZ: %.3f / %.3f / %.3f", this.viewEntity.posX, this.viewEntity.getEntityBoundingBox().minY, this.viewEntity.posZ) + "\n" + String.format("Block: %d %d %d, R: '%s/%s'", blockpos.getX(), blockpos.getY(), blockpos.getZ(), - Region.getRegionFolder(blockpos.getX() >> 4, blockpos.getZ() >> 4), - Region.getRegionName(blockpos.getX() >> 4, blockpos.getZ() >> 4)) + "\n" + + Util.getRegionFolder(blockpos.getX() >> 4, blockpos.getZ() >> 4), + Util.getRegionName(blockpos.getX() >> 4, blockpos.getZ() >> 4)) + "\n" + String.format("Chunk: %d %d %d + %d %d %d, FOV: %.1f °%s", blockpos.getX() >> 4, blockpos.getY() >> 4, blockpos.getZ() >> 4, blockpos.getX() & 15, blockpos.getY() & 15, blockpos.getZ() & 15, this.zooming ? (this.fov / this.zoomLevel) : this.fov, this.zooming ? @@ -1740,97 +1887,84 @@ public class Game implements IThreadListener { bline + "\n" + lline + "\n" + String.format("Zeit: %d T, R %d / %d T, U %d / %d T", - this.theWorld.getDayTime(), - this.theWorld.getDayTime() % this.theWorld.dimension.getRotationalPeriod(), - this.theWorld.dimension.getRotationalPeriod(), - this.theWorld.getDayTime() % this.theWorld.dimension.getOrbitalPeriod(), - this.theWorld.dimension.getOrbitalPeriod() + this.world.getDayTime(), + this.world.getDayTime() % this.world.dimension.getRotationalPeriod(), + this.world.dimension.getRotationalPeriod(), + this.world.getDayTime() % this.world.dimension.getOrbitalPeriod(), + this.world.dimension.getOrbitalPeriod() ) + "\n" + String.format("Laub: %s%s, T: %.2f K / %.2f °C, %s (R %.1f, %.1f)", - !this.theWorld.dimension.getType().days ? "*" : "", - this.theWorld.getLeavesGen(blockpos).getDisplayName(), + !this.world.dimension.getType().days ? "*" : "", + this.world.getLeavesGen(blockpos).getDisplayName(), temp, World.ABSOLUTE_ZERO + temp, - this.theWorld.getWeather().getDisplay(), this.theWorld.getRainStrength(), - this.theWorld.getDarkness() + this.world.getWeather().getDisplay(), this.world.getRainStrength(), + this.world.getDarkness() ) + "\n" + String.format("Zeitfaktor: %dx, Schwerkraft: %.2f m/s²", - this.timeFactor, this.theWorld.gravity * 10.0 + this.timeFactor, this.world.gravity * 10.0 ) + "\n" + String.format("Letzte Zeitsynch.: + %d.%d s", ticked / 1000L, (ticked / 100L) % 10L - ) + + ) + "\n" + + "Startwert: " + this.world.dimension.getSeed() + (this.serverInfo != null ? "\n" + this.serverInfo : "") -// WorldServer world = this.server.getWorld(this.theWorld.dimension.getDimensionId()); +// IWorldServer world = this.server.getWorld(this.theWorld.dimension.getDimensionId()); // if(world != null) // list.add("Seed: " + world.getSeed()); ; } public String getRight(boolean showPlayerInfo) { - if(this.theWorld == null) { + if(this.world == null) { return null; } if(!showPlayerInfo && this.pointed != null && this.pointed.type == HitPosition.ObjectType.BLOCK && this.pointed.block != null) { BlockPos pos = this.pointed.block; - State block = this.theWorld.getState(pos); + State block = this.world.getState(pos); if(!this.debugWorld) { - block = block.getBlock().getActualState(block, this.theWorld, pos); + block = block.getBlock().getActualState(block, this.world, pos); } StringBuilder str = new StringBuilder( - "Schaue auf: " + BlockRegistry.REGISTRY.getNameForObject(block.getBlock()) + " [" + BlockRegistry.getIdFromBlock(block.getBlock()) + + "Schaue auf: " + BlockRegistry.getNameFromBlock(block.getBlock()) + " [" + BlockRegistry.getIdFromBlock(block.getBlock()) + ":" + block.getBlock().getMetaFromState(block) + "]" + "\n" + String.format("Position: %d %d %d", pos.getX(), pos.getY(), pos.getZ()) ); -// int off = 2; for(Entry entry : block.getProperties().entrySet()) { str.append("\n" + entry.getKey().getName() + ": " + entry.getValue().toString()); } - return str.toString(); // new String[] { -// list.add(""); -// list.add(); -// }; + return str.toString(); } - else if((this.pointed != null && this.pointed.type == HitPosition.ObjectType.ENTITY - && this.pointed.entity != null) || showPlayerInfo) { - Entity entity = showPlayerInfo ? this.thePlayer : this.pointed.entity; + else if((this.pointed != null && this.pointed.type == HitPosition.ObjectType.ENTITY && this.pointed.entity != null) || showPlayerInfo) { + Entity entity = showPlayerInfo ? this.player : this.pointed.entity; ItemStack held = entity instanceof EntityLiving && ((EntityLiving)entity).getHeldItem() != null ? ((EntityLiving)entity).getHeldItem() : null; return -// list.add(""); - (showPlayerInfo ? "Charakter: " : "Schaue auf: ") + (entity.isPlayer() ? "Player/" : "") + EntityRegistry.getEntityString(entity) + // " [" + (entity.isPlayer() ? "player" : - /* (EntityRegistry.getEntityID(entity) + "/" + EntityRegistry.getObjectID(entity))) + "]" */ " (" + entity.getId() + ")" - + "\n" + + (showPlayerInfo ? "Charakter: " : "Schaue auf: ") + EntityRegistry.getEntityString(entity) + " (" + entity.getId() + ")" + "\n" + String.format("Position: %.3f %.3f %.3f", entity.posX, entity.posY, entity.posZ) + "\n" + - // list.add("Name: '" + entity.getName() + "'"); "Geladen: " + entity.ticksExisted + "t" + (entity instanceof EntityLiving ? (", Alter: " + ((EntityLiving)entity).getGrowingAge()) + "t" : "") + "\n" + String.format("Größe: %.2fx%.2f, A: %.2f", entity.width, entity.height, entity.getEyeHeight()) + "\n" + - // if(!this.debugHideInfo) { String.format("Bewegung: %.3f %.3f %.3f", entity.motionX, entity.motionY, entity.motionZ) + "\n" + String.format("Drehung: %.1f %.1f, K: %.1f", entity.rotYaw, entity.rotPitch, entity.getRotationYawHead()) + "\n" + - // } (entity instanceof EntityLiving ? String.format("Leben: %d/%d, A: %d", ((EntityLiving)entity).getHealth(), ((EntityLiving)entity).getMaxHealth(), ((EntityLiving)entity).getAbsorptionAmount()) : "Leben: n/a") + "\n" + - "Schaden: " + entity.hurtResistance + "t" + (showPlayerInfo ? String.format(", Fallh.: %.3f", entity.fallDistance) : "") + "\n" + // + ", Luft: " + entity.getAir()); + "Schaden: " + entity.hurtResistance + "t" + (showPlayerInfo ? String.format(", Fallh.: %.3f", entity.fallDistance) : "") + "\n" + (entity instanceof EntityLiving ? (((EntityLiving)entity).deathTime != 0 ? "Tod: " + ((EntityLiving)entity).deathTime + "t, " : "") + "Rüstung: " + ((EntityLiving)entity).getTotalArmorValue() + ", Pfeile: " + ((EntityLiving)entity).getArrowCountInEntity() : "Rüstung: n/a, Pfeile: n/a") + "\n" + -// ItemStack held = ((EntityLiving)entity).getHeldItem(); (held != null ? - "Gegens.: " + ItemRegistry.REGISTRY.getNameForObject(held.getItem()) + " x" + held.stackSize + " (" + held.getMetadata() + ")" : "Gegens.: n/a") + "\n" + - "Eigens.: " + (entity.dead ? "D" : " ") + (entity.noClip ? "N" : " ") + (entity.onGround ? "G" : " ") - + (entity.canBeCollidedWith() ? "C" : " ") + (entity.canBePushed() ? "P" : " ") - + (entity.isBurning() ? "B" : " ") // + (entity.isInvisible() ? "I" : " ") // + (entity.isSilent() ? "S" : " ") - + (entity.isWet() ? "W" : " ") + (entity.canAttackWithItem() ? "A" : " ") - + (entity.passenger != null ? "H" : " ") + (entity.vehicle != null ? "R" : " ") + (entity instanceof EntityLiving ? - ("+" /* + (((EntityLivingBase)entity).isEntityUndead() ? "U" : " ") */ // + (((EntityLivingBase)entity).isChild() ? "C" : " ") - + (((EntityLiving)entity).doesEntityNotTriggerPressurePlate() ? "P" : " ")) : "") + "\n" + - // list.add("UUID: " + entity.getUniqueID().toString()); + "Gegens.: " + ItemRegistry.getNameFromItem(held.getItem()) + " x" + held.size + " (" + held.getMetadata() + ")" : "Gegens.: n/a") + "\n" + + "Eigens.: " + (entity.dead ? "D" : "") + (entity.noClip ? "N" : "") + (entity.onGround ? "G" : "") + + (entity.canBeCollidedWith() ? "C" : "") + (entity.canBePushed() ? "P" : "") + + (entity.isBurning() ? "B" : "") + (entity.isPlayer() ? "S" : "") + + (entity.isWet() ? "W" : "") + (entity.canAttackWithItem() ? "A" : "") + + (entity.passenger != null ? "H" : "") + (entity.vehicle != null ? "R" : "") + + (entity.doesEntityNotTriggerPressurePlate() ? "L" : "") + "\n" + (entity.hasCustomName() ? "Name: '" + TextColor.stripCodes(entity.getCustomNameTag()) + "'" : "Name: n/a") ; } @@ -1852,13 +1986,9 @@ public class Game implements IThreadListener { private void fbsize(int x, int y) { GL11.glViewport(0, 0, x, y); - fb_x = x; - fb_y = y; - if(this.open != null) { - this.refreshing = true; - this.displayGuiScreen(this.open); - this.refreshing = false; - } + fb_raw_x = x; + fb_raw_y = y; + this.rescale(); if(!fullscreen) { xsize = x; ysize = y; @@ -1874,9 +2004,11 @@ public class Game implements IThreadListener { private void mouse(int x, int y) { if(!mouseFirst && open == null) - this.moveCamera((float)(x - mouse_x) * sensitivity, (float)(mouse_y - y) * sensitivity); - mouse_x = x; - mouse_y = y; + this.moveCamera((float)(x - mouse_raw_x) * sensitivity, (float)(mouse_raw_y - y) * sensitivity); + mouse_raw_x = x; + mouse_raw_y = y; + mouse_x = x / this.scale; + mouse_y = y / this.scale; mouseFirst = false; if(open != null && Bind.isInputEnabled() && Button.isMouseDown() /* && !(win->mouse & 0xfc) */ && !ctrl()) { // if(mouse_clickx < 0 || mouse_clicky < 0) { @@ -1959,7 +2091,13 @@ public class Game implements IThreadListener { // open.restyle(); } - private void redraw() { + private void rescale() { + this.scale = this.scaleVar; + while(this.scale > 1 && (this.fb_raw_x / this.scale < MIN_WIDTH || this.fb_raw_y / this.scale < MIN_HEIGHT)) { + this.scale--; + } + this.fb_x = Math.max(this.fb_raw_x / this.scale, MIN_WIDTH); + this.fb_y = Math.max(this.fb_raw_y / this.scale, MIN_HEIGHT); if(this.open != null) { this.refreshing = true; this.displayGuiScreen(this.open); @@ -1973,40 +2111,40 @@ public class Game implements IThreadListener { public void poll() { for(WindowEvent event : Window.poll()) { - switch(event.action) { + switch(event.action()) { case BUTTON: - if(event.param1 >= 0 && event.param1 < Button.values().length) - button(Button.values()[event.param1], event.param2 != 0); + if(event.param1() >= 0 && event.param1() < Button.values().length) + button(Button.values()[event.param1()], event.param2() != 0); break; case CHARACTER: - if(event.param1 >= (int)Log.CHR_SPC && event.param1 <= (int)Character.MAX_VALUE) - character((char)event.param1); + if(event.param1() >= (int)Log.CHR_SPC && event.param1() <= (int)Character.MAX_VALUE) + character((char)event.param1()); break; case CLOSED: closed(); break; case CURSOR: - mouse(event.param1, event.param2); + mouse(event.param1(), event.param2()); break; case FOCUS: - focus(event.param1 != 0); + focus(event.param1() != 0); break; case KEY: - if(event.param1 >= 0 && event.param1 < Keysym.values().length) - key(Keysym.values()[event.param1], KeyEvent.values()[event.param2 % KeyEvent.values().length]); + if(event.param1() >= 0 && event.param1() < Keysym.values().length) + key(Keysym.values()[event.param1()], KeyEvent.values()[event.param2() % KeyEvent.values().length]); break; case POSITION: - pos(event.param1, event.param2); + pos(event.param1(), event.param2()); break; case REDRAW: - redraw(); + // redraw(); disable as it is pretty useless break; case RESIZE: - fbsize(event.param1, event.param2); + fbsize(event.param1(), event.param2()); break; case SCROLL: - if(event.param1 != 0 || event.param2 != 0) - scroll(event.param1, event.param2); + if(event.param1() != 0 || event.param2() != 0) + scroll(event.param1(), event.param2()); break; } } @@ -2022,7 +2160,7 @@ public class Game implements IThreadListener { public void full(boolean full) { if((full != fullscreen || full) && (!full || vidMode != null)) { if(full) { - Window.setFullscreen(vidMode.width, vidMode.height, vidMode.refresh); + Window.setFullscreen(vidMode.width(), vidMode.height(), vidMode.refresh()); } else { Window.setWindowed(saved_xpos, saved_ypos, xsize, ysize); @@ -2040,7 +2178,7 @@ public class Game implements IThreadListener { } else { DisplayMode mode = Window.getDisplayMode(); - syncLimit = mode != null ? mode.refresh : 60; + syncLimit = mode != null ? mode.refresh() : 60; } Window.setVSync(vsync); } @@ -2053,10 +2191,16 @@ public class Game implements IThreadListener { GL11.glClear(256); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); - GL11.glOrtho(0.0D, (double)this.fb_x, (double)this.fb_y, 0.0D, 1000.0D, 3000.0D); + GL11.glOrtho(0.0D, (double)this.fb_raw_x, (double)this.fb_raw_y, 0.0D, 1000.0D, 3000.0D); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); GL11.glTranslatef(0.0F, 0.0F, -2000.0F); + if(this.scale != 1) + GL11.glScalef((float)this.scale, (float)this.scale, 1.0f); + } + + public void scissor(int x, int y, int width, int height) { + GL11.glScissor(x * this.scale, y * this.scale, width * this.scale, height * this.scale); } private void addFrame(long runningTime) @@ -2092,10 +2236,8 @@ public class Game implements IThreadListener { } } - public void run() { - Log.SYSTEM.info("Java " + System.getProperty("java.version")); - Log.SYSTEM.info(Config.VERSION); - if(!Window.createWindow(Config.VERSION, System.getProperty("opengl.debug") != null)) + public void run(long time) { + if(!Window.createWindow(VERSION, System.getProperty("opengl.debug") != null)) System.exit(1); Log.SYSTEM.info("OpenGL %s", GL11.glGetString(GL11.GL_VERSION)); Log.SYSTEM.info("GL_VENDOR: %s", GL11.glGetString(GL11.GL_VENDOR)); @@ -2106,30 +2248,33 @@ public class Game implements IThreadListener { this.registerDebug(); System.gc(); System.gc(); - Font.load(); + Font.load(false); GlState.enableBlend(); GlState.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); this.initConsole(); this.startSound(true); this.vidMode = Window.getDisplayMode(); - Window.initWindow(this.saved_xpos, this.saved_ypos, this.xsize, this.ysize); + if(this.vidMode != null && (this.vidMode.width() < MIN_WIDTH || this.vidMode.height() < MIN_HEIGHT)) + this.vidMode = null; + Window.initWindow(this.saved_xpos, this.saved_ypos, this.xsize, this.ysize, MIN_WIDTH, MIN_HEIGHT); Window.setIcon(genTriwave(64, 64, 0x00000000, 0xffff0000, 0xff00ff00, 0xff0000ff, 0xff7f00ff, 0xff000000), 64, 64); this.sync(this.sync); // this.startSound(true); this.getVar("tic_target").setDefault(); this.displayGuiScreen(GuiMenu.INSTANCE); + Log.SYSTEM.info("Client gestartet in " + String.format("%.1f", (double)(System.currentTimeMillis() - time) / 1000.0) + " Sekunden"); while(!this.interrupted) { PerfSection.swap(); PerfSection.TIMING.enter(); - Timing.tmr_current = Util.rtime(); - Timing.tmr_delta = Timing.tmr_current - Timing.tmr_last; - Timing.tmr_last = Timing.tmr_current; - Timing.fdelta = ((float)Timing.tmr_delta) / 1000000.0f; - if((Timing.tmr_current - Timing.tmr_update) >= 1000000L) { - Timing.framerate = ((float)Timing.tmr_frames) * 1000000.0f / ((float)(long)(Timing.tmr_current - Timing.tmr_update)); - Timing.tmr_frames = 0L; - Timing.tmr_update = Timing.tmr_current; + this.tmr_current = Util.rtime(); + this.tmr_delta = this.tmr_current - this.tmr_last; + this.tmr_last = this.tmr_current; + this.fdelta = ((float)this.tmr_delta) / 1000000.0f; + if((this.tmr_current - this.tmr_update) >= 1000000L) { + this.framerate = ((float)this.tmr_frames) * 1000000.0f / ((float)(long)(this.tmr_current - this.tmr_update)); + this.tmr_frames = 0L; + this.tmr_update = this.tmr_current; } this.start(); PerfSection.INPUT.enter(); @@ -2162,16 +2307,15 @@ public class Game implements IThreadListener { long now = System.nanoTime(); this.addFrame(now - this.startNanoTime); this.startNanoTime = now; - while(this.syncLimited && (Util.rtime() - Timing.tmr_current) < (1000000L / this.syncLimit)) { + while(this.syncLimited && (Util.rtime() - this.tmr_current) < (1000000L / this.syncLimit)) { ; } - Timing.tmr_frames += 1L; + this.tmr_frames += 1L; } Log.SYSTEM.info("Beende ..."); unload(false); this.getSoundManager().unload(); - Region.killIO(); this.renderGlobal.stopChunkBuilders(); if(audio.end()) Log.SOUND.info("Audiogerät geschlossen"); @@ -2192,7 +2336,7 @@ public class Game implements IThreadListener { // } public void disconnected(String msg) { - Log.SYSTEM.info("Getrennt: %s", msg); + Log.NETWORK.info("Getrennt: %s", msg); this.unload(true); this.displayGuiScreen(new GuiInfo("Von Server getrennt", TextColor.RED + "Verbindung zum Server wurde getrennt\n\n" + TextColor.RESET + msg)); } @@ -2217,24 +2361,24 @@ public class Game implements IThreadListener { // if(this.theWorld != null && this.open == null && Bind.COMMAND.isPressed()) { // this.displayGuiScreen(GuiChat.INSTANCE); // } - if(this.theWorld != null && Bind.MENU.isPressed()) { + if(this.world != null && Bind.MENU.isPressed()) { if(this.open != (this.charEditor ? GuiChar.INSTANCE : null)) this.displayGuiScreen(this.charEditor ? GuiChar.INSTANCE : null); else this.displayGuiScreen(GuiMenu.INSTANCE); } - else if(this.theWorld == null && !(this.open instanceof GuiMenu) && Bind.MENU.isPressed()) { + else if(this.world == null && !(this.open instanceof GuiMenu) && Bind.MENU.isPressed()) { this.displayGuiScreen(GuiMenu.INSTANCE); } - if(this.theWorld != null && !this.charEditor && Bind.INVENTORY.isPressed()) { + if(this.world != null && !this.charEditor && Bind.INVENTORY.isPressed()) { if(this.open instanceof GuiContainer) { this.displayGuiScreen(null); } else if(this.open == null) { - if(this.thePlayer.isRiding() && this.thePlayer.vehicle instanceof EntityHorse) - this.thePlayer.sendHorseInventory(); + if(this.player.isRiding() && this.player.vehicle instanceof EntityHorse) + this.player.sendHorseInventory(); else - this.displayGuiScreen(/* this.itemCheat ? new GuiCheat() : */ new GuiInventory(this.thePlayer)); + this.displayGuiScreen(/* this.itemCheat ? new GuiCheat() : */ new GuiInventory(this.player)); } } } @@ -2254,23 +2398,23 @@ public class Game implements IThreadListener { if(this.saving) return; this.saving = true; - final int stride = ((this.fb_x * 3) & 3) != 0 ? 4 + ((this.fb_x * 3) & ~3) : (this.fb_x * 3); - final ByteBuffer data = ByteBuffer.allocateDirect(stride * this.fb_y).order(ByteOrder.nativeOrder()); - GL11.glReadPixels(0, 0, this.fb_x, this.fb_y, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, data); + final int stride = ((this.fb_raw_x * 3) & 3) != 0 ? 4 + ((this.fb_raw_x * 3) & ~3) : (this.fb_raw_x * 3); + final ByteBuffer data = ByteBuffer.allocateDirect(stride * this.fb_raw_y).order(ByteOrder.nativeOrder()); + GL11.glReadPixels(0, 0, this.fb_raw_x, this.fb_raw_y, GL11.GL_RGB, GL11.GL_UNSIGNED_BYTE, data); new Thread(new Runnable() { public void run() { - byte[] pixels = new byte[stride * Game.this.fb_y]; + byte[] pixels = new byte[stride * Client.this.fb_raw_y]; data.get(pixels); - byte[] conv = new byte[Game.this.fb_x * Game.this.fb_y * 3]; - for(int l = 0; l < Game.this.fb_y; l++) { - System.arraycopy(pixels, l * stride, conv, (Game.this.fb_y - 1 - l) * Game.this.fb_x * 3, Game.this.fb_x * 3); + byte[] conv = new byte[Client.this.fb_raw_x * Client.this.fb_raw_y * 3]; + for(int l = 0; l < Client.this.fb_raw_y; l++) { + System.arraycopy(pixels, l * stride, conv, (Client.this.fb_raw_y - 1 - l) * Client.this.fb_raw_x * 3, Client.this.fb_raw_x * 3); } - BufferedImage image = new BufferedImage(Game.this.fb_x, Game.this.fb_y, BufferedImage.TYPE_INT_ARGB); - int[] img = new int[Game.this.fb_x * Game.this.fb_y]; + BufferedImage image = new BufferedImage(Client.this.fb_raw_x, Client.this.fb_raw_y, BufferedImage.TYPE_INT_ARGB); + int[] img = new int[Client.this.fb_raw_x * Client.this.fb_raw_y]; for(int z = 0; z < img.length; z++) { img[z] = (int)(conv[(z * 3) + 2] & 0xff) | ((int)(conv[(z * 3) + 1] & 0xff) << 8) | ((int)(conv[(z * 3) + 0] & 0xff) << 16) | 0xff000000; } - image.setRGB(0, 0, Game.this.fb_x, Game.this.fb_y, img, 0, Game.this.fb_x); + image.setRGB(0, 0, Client.this.fb_raw_x, Client.this.fb_raw_y, img, 0, Client.this.fb_raw_x); File dir = new File("screenshots"); dir.mkdirs(); @@ -2287,18 +2431,18 @@ public class Game implements IThreadListener { ImageIO.write(image, "png", file); } catch(IOException e) { - Game.this.schedule(new Runnable() { + Client.this.schedule(new Runnable() { public void run() { - Game.this.saving = false; + Client.this.saving = false; Log.IO.error(e, "Konnte Textur '" + saved + "' nicht speichern"); } }); return; } - Game.this.schedule(new Runnable() { + Client.this.schedule(new Runnable() { public void run() { - Game.this.saving = false; - Game.this.logFeed("Bildschirmfoto als '%s' gespeichert", saved.getName()); + Client.this.saving = false; + Client.this.logFeed("Bildschirmfoto als '%s' gespeichert", saved.getName()); } }); } @@ -2306,60 +2450,58 @@ public class Game implements IThreadListener { } public TextColor framecode() { - return (Timing.framerate >= 59.0f) ? TextColor.GREEN : ((Timing.framerate >= 29.0f) ? TextColor.YELLOW : ((Timing.framerate >= 14.0f) ? TextColor.ORANGE : TextColor.RED)); + return (this.framerate >= 59.0f) ? TextColor.GREEN : ((this.framerate >= 29.0f) ? TextColor.YELLOW : ((this.framerate >= 14.0f) ? TextColor.ORANGE : TextColor.RED)); } public TextColor tpscode() { - return (Timing.tickrate >= (((float)Timing.tickTarget / 1000.0f) - 1.0f)) ? TextColor.GREEN : ((Timing.tickrate >= (((float)Timing.tickTarget / 1000.0f) / 2.0f - 1.0f)) ? TextColor.YELLOW : - ((Timing.tickrate >= (((float)Timing.tickTarget / 1000.0f) / 4.0f - 1.0f)) ? TextColor.ORANGE : TextColor.RED)); + return (this.tickrate >= (((float)this.tickTarget / 1000.0f) - 1.0f)) ? TextColor.GREEN : ((this.tickrate >= (((float)this.tickTarget / 1000.0f) / 2.0f - 1.0f)) ? TextColor.YELLOW : + ((this.tickrate >= (((float)this.tickTarget / 1000.0f) / 4.0f - 1.0f)) ? TextColor.ORANGE : TextColor.RED)); } private void doTicks() { - Timing.tick_stime = Util.rtime(); - if((Timing.tick_stime - Timing.tick_update) >= 1000000L) { - Timing.tickrate = ((float)Timing.tick_done) * 1000000.0f / ((float)(long)(Timing.tick_stime - Timing.tick_update)); - Timing.tick_done = 0; - Timing.tick_update = Timing.tick_stime; + this.tick_stime = Util.rtime(); + if((this.tick_stime - this.tick_update) >= 1000000L) { + this.tickrate = ((float)this.tick_done) * 1000000.0f / ((float)(long)(this.tick_stime - this.tick_update)); + this.tick_done = 0; + this.tick_update = this.tick_stime; } - Timing.tick_torun += (((long)Timing.tickTarget) * Timing.tmr_delta) / 1000L; - Timing.tickFrame = 0; - Timing.tick_torun = Timing.tick_torun > 2000000L ? 1000000L : Timing.tick_torun; - while(Timing.tick_torun >= 1000000L) { + this.tick_torun += (((long)this.tickTarget) * this.tmr_delta) / 1000L; + this.tickFrame = 0; + this.tick_torun = this.tick_torun > 2000000L ? 1000000L : this.tick_torun; + while(this.tick_torun >= 1000000L) { this.tick(); - Timing.tick_done += 1L; - Timing.tickFrame += 1; - Timing.tick_total += 1L; - Timing.tick_torun -= 1000000L; - if((Timing.tick_ftime = (Util.rtime() - Timing.tick_stime)) >= (((long)this.tickTimeout) * 1000L)) { - Log.TICK.warn("Ticks benötigten %d ms dieses Frame (maximal %d ms), überspringe %d Ticks", Timing.tick_ftime / 1000L, this.tickTimeout, Timing.tick_torun / 1000000L); - Timing.tick_torun = 0L; + this.tick_done += 1L; + this.tickFrame += 1; + this.tick_total += 1L; + this.tick_torun -= 1000000L; + if((this.tick_ftime = (Util.rtime() - this.tick_stime)) >= (((long)this.tickTimeout) * 1000L)) { + Log.TICK.warn("Ticks benötigten %d ms dieses Frame (maximal %d ms), überspringe %d Ticks", this.tick_ftime / 1000L, this.tickTimeout, this.tick_torun / 1000000L); + this.tick_torun = 0L; break; } } - Timing.tick_fraction = ((double)Timing.tick_torun) / 1000000.0; - Timing.tick_ttime += Timing.tick_ftime; - Timing.tick_time = Timing.tickFrame != 0 ? (Timing.tick_ftime / (long)Timing.tickFrame) : 0L; + this.tick_fraction = ((double)this.tick_torun) / 1000000.0; + this.tick_ttime += this.tick_ftime; + this.tick_time = this.tickFrame != 0 ? (this.tick_ftime / (long)this.tickFrame) : 0L; } public void tick_target(float tps) { - Timing.tickTarget = (int)(tps * 1000.0f); - Timing.tick_torun = 0L; - Timing.tick_done = 0L; - Timing.tick_update = Util.rtime(); + this.tickTarget = (int)(tps * 1000.0f); + this.tick_torun = 0L; + this.tick_done = 0L; + this.tick_update = Util.rtime(); } public void unload(boolean loading) { - if(this.theWorld != null) { - if(this.getNetHandler() != null) - this.getNetHandler().getNetworkManager().closeChannel("Quitting"); - this.unloadWorld(); - } + if(this.world != null && this.getNetHandler() != null) + this.getNetHandler().getConnection().closeChannel("Quitting"); + this.unloadWorld(); this.displayGuiScreen(GuiMenu.INSTANCE); } private void startSound(boolean load) { if(load) - SoundEvent.loadSounds(); + SoundManager.loadSounds(); audio = new AudioInterface(this.soundFrameSize, this.soundBufferSize, !this.soundEnabled); boolean started = audio.start(); Log.flushLog(); @@ -2373,12 +2515,12 @@ public class Game implements IThreadListener { } public void restartSound(boolean load) { - Game.this.logFeed("Lade Sound-System neu"); + Client.this.logFeed("Lade Sound-System neu"); this.soundManager.unload(); if(audio.end()) Log.SOUND.info("Audiogerät geschlossen"); this.startSound(load); - Game.this.logFeed("Das Sound-System wurde neu geladen"); + Client.this.logFeed("Das Sound-System wurde neu geladen"); } public AudioInterface getAudioInterface() { @@ -2400,124 +2542,124 @@ public class Game implements IThreadListener { this.registerDebug(Keysym.H, "Hilfe zu Tastenkombinationen anzeigen", new DebugRunner() { public void execute(Keysym key) { String bind = Bind.CHEAT.getInput() == null ? "n/a" : Bind.CHEAT.getInput().getDisplay(); - Game.this.displayGuiScreen(new GuiInfo("Hilfe zu Tastenkombinationen", TextColor.DGREEN + "" + Game.this.debug.size() + " Tastenkombinationen stehen zur Verfügung:\n" + + Client.this.displayGuiScreen(new GuiInfo("Hilfe zu Tastenkombinationen", TextColor.DGREEN + "" + Client.this.debug.size() + " Tastenkombinationen stehen zur Verfügung:\n" + Util.buildLines(new Function() { public String apply(DebugFunction func) { return TextColor.CYAN + bind + TextColor.RED + "+" + TextColor.GREEN + func.key.getDisplay() + TextColor.GRAY + " - " + TextColor.YELLOW + func.help; } - }, Game.this.debug.values()))); + }, Client.this.debug.values()))); } }); this.registerDebug(Keysym.N, "NoClip umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.performAction(Action.NOCLIP); + Client.this.performAction(Action.NOCLIP); } }); this.registerDebug(Keysym.G, "Unsterblichkeit umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.performAction(Action.GOD); + Client.this.performAction(Action.GOD); } }); this.registerDebug(Keysym.F, "Geschwindigkeit umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.performAction(Action.SPEED); + Client.this.performAction(Action.SPEED); } }); this.registerDebug(Keysym.R, "Gegenstand reparieren und Stapel auffüllen", new DebugRunner() { public void execute(Keysym key) { - Game.this.performAction(Action.REPAIR); + Client.this.performAction(Action.REPAIR); } }); this.registerDebug(Keysym.E, "Gegenstands-Cheat-Menü umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.logFeed("Cheat-Menü: %s", (Game.this.itemCheat ^= true) ? "an" : "aus"); - if(Game.this.open instanceof GuiContainer) - Game.this.open.init(); + Client.this.logFeed("Cheat-Menü: %s", (Client.this.itemCheat ^= true) ? "an" : "aus"); + if(Client.this.open instanceof GuiContainer) + Client.this.open.init(); } }); this.registerDebug(Keysym.L, "Maximale Helligkeit umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.logFeed("Maximale Helligkeit: %s", (Game.this.setGamma ^= true) ? "an" : "aus"); + Client.this.logFeed("Maximale Helligkeit: %s", (Client.this.setGamma ^= true) ? "an" : "aus"); } }); this.registerDebug(Keysym.J, "JVM GC ausführen", new DebugRunner() { public void execute(Keysym key) { - Game.this.logFeed("Führe JVM GC aus"); + Client.this.logFeed("Führe JVM GC aus"); long mem = Runtime.getRuntime().freeMemory(); System.gc(); System.gc(); mem = Runtime.getRuntime().freeMemory() - mem; mem = mem < 0L ? 0L : mem; - Game.this.logFeed("JVM GC ausgeführt: %d MB freigegeben", (int)(mem / 1024L / 1024L)); + Client.this.logFeed("JVM GC ausgeführt: %d MB freigegeben", (int)(mem / 1024L / 1024L)); } }); this.registerDebug(Keysym.B, "Hitbox-Overlay umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.getRenderManager().setDebugBoundingBox(!Game.this.getRenderManager().isDebugBoundingBox()); - Game.this.logFeed("Objekt-Grenzen: %s", Game.this.getRenderManager().isDebugBoundingBox() ? "an" : "aus"); + Client.this.getRenderManager().setDebugBoundingBox(!Client.this.getRenderManager().isDebugBoundingBox()); + Client.this.logFeed("Objekt-Grenzen: %s", Client.this.getRenderManager().isDebugBoundingBox() ? "an" : "aus"); } }); this.registerDebug(Keysym.K, "Debug-Kamera in 3. Person umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.logFeed("Debug-Kamera 3. Person: %s", (Game.this.debugCamEnable ^= true) ? "an" : "aus"); + Client.this.logFeed("Debug-Kamera 3. Person: %s", (Client.this.debugCamEnable ^= true) ? "an" : "aus"); } }); this.registerDebug(Keysym.X, "Röntgenblick umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.xrayActive ^= true; - Game.this.renderGlobal.loadRenderers(); - Game.this.logFeed("Röntgenblick: %s", Game.this.xrayActive ? "an" : "aus"); + Client.this.xrayActive ^= true; + Client.this.renderGlobal.loadRenderers(); + Client.this.logFeed("Röntgenblick: %s", Client.this.xrayActive ? "an" : "aus"); } }); this.registerDebug(Keysym.O, "Objekt-Overlay umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.logFeed("Objekt-Umrahmung: %s", (Game.this.renderOutlines ^= true) ? "an" : "aus"); + Client.this.logFeed("Objekt-Umrahmung: %s", (Client.this.renderOutlines ^= true) ? "an" : "aus"); } }); this.registerDebug(Keysym.I, "Block-Objekt-Overlay umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.logFeed("Block-Objekte anzeigen: %s", (Game.this.tileOverlay ^= true) ? "an" : "aus"); + Client.this.logFeed("Block-Objekte anzeigen: %s", (Client.this.tileOverlay ^= true) ? "an" : "aus"); } }); this.registerDebug(Keysym.Y, "Alle Chunks neu kompilieren", new DebugRunner() { public void execute(Keysym key) { - Game.this.logFeed("Kompiliere alle Chunks neu"); - Game.this.renderGlobal.loadRenderers(); - Game.this.logFeed("Alle Chunks wurden neu kompiliert"); + Client.this.logFeed("Kompiliere alle Chunks neu"); + Client.this.renderGlobal.loadRenderers(); + Client.this.logFeed("Alle Chunks wurden neu kompiliert"); } }); this.registerDebug(Keysym.T, "Alle Texturen neu laden", new DebugRunner() { public void execute(Keysym key) { - Game.this.logFeed("Lade Texturen neu"); - Game.this.refreshResources(); - Game.this.logFeed("Texturen wurden neu geladen"); + Client.this.logFeed("Lade Texturen neu"); + Client.this.refreshResources(); + Client.this.logFeed("Texturen wurden neu geladen"); } }); this.registerDebug(Keysym.S, "Alle Sounds neu laden", new DebugRunner() { public void execute(Keysym key) { - Game.this.logFeed("Lade Sounds neu"); - Game.this.restartSound(true); - Game.this.logFeed("Sounds wurden neu geladen"); + Client.this.logFeed("Lade Sounds neu"); + Client.this.restartSound(true); + Client.this.logFeed("Sounds wurden neu geladen"); } }); this.registerDebug(Keysym.W, "Server-Tick-Limit umschalten (Welt beschleunigen / Warpmodus)", new DebugRunner() { public void execute(Keysym key) { - Game.this.performAction(Action.WARP_MODE); + Client.this.performAction(Action.WARP_MODE); } }); this.registerDebug(Keysym.M, "Alle Gegenstände herbei ziehen (Magnetmodus)", new DebugRunner() { public void execute(Keysym key) { - Game.this.performAction(Action.MAGNET); + Client.this.performAction(Action.MAGNET); } }); this.registerDebug(Keysym.Z, "Den Spieler heilen", new DebugRunner() { public void execute(Keysym key) { - Game.this.performAction(Action.HEAL); + Client.this.performAction(Action.HEAL); } }); this.registerDebug(Keysym.P, "Server Performance-Anfrage senden", new DebugRunner() { public void execute(Keysym key) { - Game.this.performAction(Action.PERF); + Client.this.performAction(Action.PERF); } }); this.registerDebug(Keysym.C, "Debug-Crash auslösen (2x schnell hintereinander)", new DebugRunner() { @@ -2529,55 +2671,75 @@ public class Game implements IThreadListener { } else { this.lastUsed = System.currentTimeMillis(); - Game.this.logFeed(TextColor.RED + "VORSICHT: Debug-Absturz nach mehrmaligem Drücken innerhalb einer Sekunde"); + Client.this.logFeed(TextColor.RED + "VORSICHT: Debug-Absturz nach mehrmaligem Drücken innerhalb einer Sekunde"); } } }); this.registerDebug(Keysym.V, "Alle Sounds stoppen", new DebugRunner() { public void execute(Keysym key) { - Game.this.soundManager.stopSounds(); + Client.this.soundManager.stopSounds(); } }); - this.registerDebug(Keysym.Q, "Programm sofort beenden und speichern", new DebugRunner() { + this.registerDebug(Keysym.Q, "Programm sofort beenden und trennen", new DebugRunner() { public void execute(Keysym key) { - Game.this.interrupted = true; + Client.this.interrupted = true; } }); this.registerDebug(Keysym.A, "Bild-Synchonisation umschalten (VSync - begrenzt - unbegrenzt)", new DebugRunner() { public void execute(Keysym key) { - Game.this.getVar("win_sync").parse("" + (Game.this.vsync ? Game.this.syncLimit : (Game.this.syncLimited ? -1 : 0))); - Game.this.setDirty(); + Client.this.getVar("win_sync").parse("" + (Client.this.vsync ? Client.this.syncLimit : (Client.this.syncLimited ? -1 : 0))); + Client.this.setDirty(); } }); this.registerDebug(Keysym.D, "Konsole und Chat leeren", new DebugRunner() { public void execute(Keysym key) { GuiConsole.INSTANCE.reset(); - if(Game.this.open instanceof GuiConsole) - ((GuiConsole)Game.this.open).setLog(Game.this.buffer); + if(Client.this.open instanceof GuiConsole) + ((GuiConsole)Client.this.open).setLog(Client.this.buffer); } }); this.registerDebug(Keysym.U, "HUD umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.showHud ^= true; + Client.this.showHud ^= true; } }); this.registerDebug(Keysym.UE, "Spieler in Overlay umschalten", new DebugRunner() { public void execute(Keysym key) { - Game.this.logFeed("Spieler-Info in Overlay: %s", (Game.this.debugPlayer ^= true) ? "an" : "aus"); + Client.this.logFeed("Spieler-Info in Overlay: %s", (Client.this.debugPlayer ^= true) ? "an" : "aus"); } }); this.registerDebug(Keysym.OE, "Tick-Profiler umschalten", new DebugRunner() { public void execute(Keysym key) { - if(Game.this.lastTickTime >= 0) { - Game.this.performAction(Action.STOP_PROFILING); - Game.this.lastTickTime = -1; + if(Client.this.lastTickTime >= 0) { + Client.this.performAction(Action.STOP_PROFILING); + Client.this.lastTickTime = -1; } else { - Game.this.performAction(Action.START_PROFILING); - Game.this.lastTickTime = 0; + Client.this.performAction(Action.START_PROFILING); + Client.this.lastTickTime = 0; } } }); + if(Util.DEVMODE) + this.registerDebug(Keysym.AE, "Programm sofort beenden und server beenden", new DebugRunner() { + public void execute(Keysym key) { + if(Client.this.getNetHandler() != null) { + Client.this.getNetHandler().getConnection().sendPacket(new CPacketMessage(CPacketMessage.Type.COMMAND, "shutdown"), new GenericFutureListener>() { + public void operationComplete(Future u) throws Exception { + try { + Thread.sleep(1000L); + } + catch(InterruptedException e) { + } + Client.this.interrupted = true; + } + }); + } + else { + Client.this.interrupted = true; + } + } + }); } private boolean handleDebugKey(Keysym key) { @@ -2585,7 +2747,7 @@ public class Game implements IThreadListener { if(func != null) { Bind.disableInput(key); if(!(this.open instanceof GuiLoading)) { - this.soundManager.playSound(new PositionedSound(SoundEvent.CLICK, Volume.GUI)); + this.soundManager.playSound(new PositionedSound(SoundEvent.CLICK, EventType.UI_INTERFACE)); func.runner.execute(key); } } @@ -2595,11 +2757,22 @@ public class Game implements IThreadListener { public static void main(String[] args) { - Util.checkOs(); - Log.init(INSTANCE); + long time = System.currentTimeMillis(); + Util.checkPlatform(); + Thread.currentThread().setName("Render thread"); + Locale.setDefault(Locale.ROOT); + Util.setupHandlers(); + Log.init(); + Log.SYSTEM.info("Java " + System.getProperty("java.version")); + Log.SYSTEM.info("Starte " + VERSION + " (Protokoll #" + Util.PROTOCOL + ")"); + if(Util.DEVMODE) + Log.SYSTEM.warn("Entwicklungsmodus aktiv - Debugging-Features sind verfügbar"); Window.init(); - Registry.setup("Render thread"); - INSTANCE.run(); + ModelBlock.setAsProvider(); + Registry.register(); + UniverseRegistry.register(); + Log.setSync(CLIENT); + CLIENT.run(time); Window.end(); } @@ -2659,26 +2832,6 @@ public class Game implements IThreadListener { return data; } - // plr_play("/home/sen/Musik/midi50k/Video_Games/ff/ff2cecil.mid", 0); - public static void meltdown() { - Random rand = new Random(); - Log.SYSTEM.error("CORE_MELTDOWN: Nuclear processor core meltdown imminent\n\n" + - " ************************ CAUTION ************************\n" + - " KCTL: Processor core #%02d has reached a critical\n" + - " temperature, system explosion is imminent! \n" + - " According to the general core density \n" + - " calculation routine defined by the SKC \n" + - " (Hard) Warfare Testing Facility (SKC-WTF) \n" + - " your processor will cause a detonation with \n" + - " a radius of (roughly) %d.%d kilometers. \n" + - " In addition, it will release appoximately \n" + - " %d megajoules of ionizing radiation. \n" + - " You have an estimate time of %d minutes and \n" + - " %d seconds left to clear the detonation area. \n" + - " ************************ CAUTION ************************\n" - , rand.range(1, 64), rand.range(1, 9), rand.range(0, 9), rand.range(10000, 39999), rand.range(3, 9), rand.range(2, 59)); - } - public T getVar(String name) { return (T)cvars.get(name); } @@ -2699,6 +2852,14 @@ public class Game implements IThreadListener { return buffer; } + public float getTickFraction() { + return (float)this.tick_fraction; + } + + public long getPassedTime() { + return this.tmr_delta; + } + private void regVar(CVar cv) { if(cvars.containsKey(cv.getCVarName())) throw new IllegalArgumentException("Variable " + cv.getCVarName() + " existiert bereits!"); @@ -2783,7 +2944,7 @@ public class Game implements IThreadListener { data = FileUtils.read(config); } catch(IOException e) { - Log.CONSOLE.error(e, "Konnte Konfigurationsdatei nicht laden"); + Log.IO.error(e, "Konnte Konfigurationsdatei nicht laden"); return; } if(data == null) @@ -2820,7 +2981,7 @@ public class Game implements IThreadListener { FileUtils.write(config, sb.toString()); } catch(IOException e) { - Log.CONSOLE.error(e, "Konnte Konfigurationsdatei nicht speichern"); + Log.IO.error(e, "Konnte Konfigurationsdatei nicht speichern"); } } @@ -2860,14 +3021,14 @@ public class Game implements IThreadListener { return; } } - if(this.thePlayer != null && this.getNetHandler() != null) + if(this.player != null && this.getNetHandler() != null) this.getNetHandler().addToSendQueue(new CPacketMessage(line.startsWith("/") ? CPacketMessage.Type.COMMAND : CPacketMessage.Type.CHAT, line.startsWith("/") ? line.substring(1) : line)); // Log.CONSOLE.user("%s", line); // this.command(line); } public void reset() { - this.buffer = TextColor.NEON + "*** " + Config.VERSION + " ***"; + this.buffer = TextColor.NEON + "*** " + VERSION + " ***"; this.console.clear(); this.chat.clear(); this.feed.clear(); @@ -2914,7 +3075,7 @@ public class Game implements IThreadListener { Log.CONSOLE.user(msg); if(size > 0) { for(String line : msg.split("\n")) { - Message lmsg = new Message(line, Timing.tmr_current); + Message lmsg = new Message(line, this.tmr_current); while(log.size() >= size) { log.remove(log.size() - 1); } @@ -2962,13 +3123,13 @@ public class Game implements IThreadListener { y = up ? y - Font.YGLYPH : y; for(Iterator iter = log.iterator(); iter.hasNext();) { Message msg = iter.next(); - if((Timing.tmr_current - msg.time) <= fade || (log == this.chat && this.chatPermanent)) { + if((this.tmr_current - msg.time()) <= fade || (log == this.chat && this.chatPermanent)) { if(align > 0) - Drawing.drawTextbox(msg.message, x, y, bg); + Drawing.drawTextbox(msg.message(), x, y, bg); else if(align < 0) - Drawing.drawTextboxRight(msg.message, x, y, bg); + Drawing.drawTextboxRight(msg.message(), x, y, bg); else - Drawing.drawTextboxCentered(msg.message, x, y, bg); + Drawing.drawTextboxCentered(msg.message(), x, y, bg); y += up ? -(Font.YGLYPH) : Font.YGLYPH; } else { @@ -3041,18 +3202,17 @@ public class Game implements IThreadListener { public void drawInfo() { ClientPlayer netHandler = this.getNetHandler(); if(netHandler != null) { - Set> list = netHandler.getPlayerList(); - int size = list.size(); + int size = this.playerList.size(); int w = size > 80 ? 4 : (size > 40 ? 3 : (size > 10 ? 2 : 1)); w = Math.min(w, Math.max(1, this.fb_x / 300)); int bx = 0; int by = 0; - for(Entry elem : list) { + for(Entry elem : this.playerList.entrySet()) { int x = this.fb_x / 2 - (w * 300) / 2 + bx * 300; - int y = 10 + by * Font.YGLYPH; - Drawing.drawGradient(x, y, 300, Font.YGLYPH, 0x7f404040, 0x7f000000); - Drawing.drawText(elem.getKey(), x + 4, y, 0xffffffff); - Drawing.drawTextRight(formatPing(elem.getValue()), x + 300 - 4, y, 0xffffffff); + int y = 10 + by * (Font.YGLYPH + 2); + Drawing.drawGradient(x, y, 300, Font.YGLYPH + 2, 0x7f404040, 0x7f000000); + Drawing.drawText(elem.getKey(), x + 4, y + 1, 0xffffffff); + Drawing.drawTextRight(formatPing(elem.getValue()), x + 300 - 4, y + 1, 0xffffffff); if(++bx >= w) { bx = 0; ++by; @@ -3170,8 +3330,11 @@ public class Game implements IThreadListener { this.waitingForFile = true; new Thread(new Runnable() { public void run() { - String output; + String output = null; + JFileChooser chooser = null; try { + if(Util.WINDOWS) + throw new RuntimeException("Windows wird von Zenity nicht unterstützt"); List list = Lists.newArrayList("zenity", "--file-selection"); switch(mode) { case DIRECTORY_SAVE: @@ -3205,74 +3368,93 @@ public class Game implements IThreadListener { } } catch(Throwable e) { - Log.SYSTEM.error(e, "Konnte Zenity nicht starten"); - Game.this.logFeed(TextColor.RED + "Konnte Dateibrowser nicht öffnen"); - Game.this.waitingForFile = false; - return; + Log.SYSTEM.error(e, "Konnte Dateibrowser nicht starten"); + chooser = new JFileChooser(def.isDirectory() ? def : def.getParentFile()); + chooser.setDialogTitle(title); + chooser.setMultiSelectionEnabled(mode == FileMode.FILE_LOAD_MULTI); + chooser.setFileSelectionMode(mode == FileMode.DIRECTORY_LOAD || mode == FileMode.DIRECTORY_SAVE ? JFileChooser.DIRECTORIES_ONLY : JFileChooser.FILES_ONLY); + int result; + if(mode == FileMode.FILE_SAVE || mode == FileMode.DIRECTORY_SAVE) + result = chooser.showSaveDialog(null); + else + result = chooser.showOpenDialog(null); + if(result != JFileChooser.APPROVE_OPTION) { +// Client.this.logFeed(TextColor.RED + "Konnte Dateibrowser nicht öffnen"); + Client.this.waitingForFile = false; + return; + } } - if(output == null) { - Game.this.waitingForFile = false; + if(output == null && chooser == null) { + Client.this.waitingForFile = false; return; } if(mode == FileMode.FILE_LOAD_MULTI) { final List files = Lists.newArrayList(); - for(String out : output.split(":")) { - File file = new File(out); - if(file.isFile()) - files.add(file); + if(chooser != null) { + for(File file : chooser.getSelectedFiles()) { + if(file.isFile()) + files.add(file); + } + } + else { + for(String out : output.split(":")) { + File file = new File(out); + if(file.isFile()) + files.add(file); + } } if(files.isEmpty()) { - Game.this.waitingForFile = false; + Client.this.waitingForFile = false; return; } - Game.this.schedule(new Runnable() { + Client.this.schedule(new Runnable() { public void run() { - if(Game.this.waitingForFile) { + if(Client.this.waitingForFile) { for(File file : files) { callback.selected(file); } } - Game.this.waitingForFile = false; + Client.this.waitingForFile = false; } }); } else { - File file = new File(output); + File file = chooser != null ? chooser.getSelectedFile() : new File(output); switch(mode) { case DIRECTORY_LOAD: if(!file.isDirectory()) { - Game.this.waitingForFile = false; + Client.this.waitingForFile = false; return; } break; case DIRECTORY_SAVE: if(file.exists() && !file.isDirectory()) { - Game.this.waitingForFile = false; + Client.this.waitingForFile = false; return; } break; case FILE_LOAD: if(!file.isFile()) { - Game.this.waitingForFile = false; + Client.this.waitingForFile = false; return; } break; case FILE_SAVE: if(file.exists() && !file.isFile()) { - Game.this.waitingForFile = false; + Client.this.waitingForFile = false; return; } break; } - Game.this.schedule(new Runnable() { + Client.this.schedule(new Runnable() { public void run() { - if(Game.this.waitingForFile) + if(Client.this.waitingForFile) callback.selected(file); - Game.this.waitingForFile = false; + Client.this.waitingForFile = false; } }); } } - }, "Zenity listener").start(); + }, "File Browser listener").start(); } } diff --git a/java/src/game/audio/AudioInterface.java b/client/src/main/java/client/audio/AudioInterface.java similarity index 96% rename from java/src/game/audio/AudioInterface.java rename to client/src/main/java/client/audio/AudioInterface.java index 1631cb7..47dbefd 100644 --- a/java/src/game/audio/AudioInterface.java +++ b/client/src/main/java/client/audio/AudioInterface.java @@ -1,4 +1,4 @@ -package game.audio; +package client.audio; import java.util.Arrays; import java.util.List; @@ -7,13 +7,12 @@ import javax.sound.sampled.AudioFormat; import javax.sound.sampled.AudioFormat.Encoding; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.DataLine.Info; -import javax.sound.sampled.LineUnavailableException; + +import common.collect.Lists; +import common.log.Log; + import javax.sound.sampled.SourceDataLine; -import game.collect.Lists; - -import game.log.Log; - public class AudioInterface implements Runnable { private static class Channel { short[] buffer; @@ -138,12 +137,12 @@ public class AudioInterface implements Runnable { public void run() { AudioFormat format = new AudioFormat(Encoding.PCM_SIGNED, 48000, 16, 2, 2 * 2, 48000, false); - Info info = new Info(SourceDataLine.class, format, this.devbufsize); + Info info = new Info(SourceDataLine.class, format, this.devbufsize == 0 ? AudioSystem.NOT_SPECIFIED : this.devbufsize); try { this.line = (SourceDataLine)AudioSystem.getLine(info); - this.line.open(format, this.devbufsize); + this.line.open(format, this.devbufsize == 0 ? AudioSystem.NOT_SPECIFIED : this.devbufsize); } - catch(LineUnavailableException e) { + catch(Exception e) { this.line = null; Log.SOUND.error(e, "Konnte Audiogerät nicht öffnen"); } diff --git a/java/src/game/audio/CodecJOrbis.java b/client/src/main/java/client/audio/CodecJOrbis.java similarity index 98% rename from java/src/game/audio/CodecJOrbis.java rename to client/src/main/java/client/audio/CodecJOrbis.java index 19a92cf..aa1bfe6 100644 --- a/java/src/game/audio/CodecJOrbis.java +++ b/client/src/main/java/client/audio/CodecJOrbis.java @@ -1,15 +1,16 @@ -package game.audio; +package client.audio; import java.io.IOException; import java.io.InputStream; -import game.audio.jogg.Packet; -import game.audio.jogg.Page; -import game.audio.jogg.StreamState; -import game.audio.jogg.SyncState; -import game.audio.jorbis.Block; -import game.audio.jorbis.Comment; -import game.audio.jorbis.DspState; -import game.audio.jorbis.Info; + +import client.audio.jogg.Packet; +import client.audio.jogg.Page; +import client.audio.jogg.StreamState; +import client.audio.jogg.SyncState; +import client.audio.jorbis.Block; +import client.audio.jorbis.Comment; +import client.audio.jorbis.DspState; +import client.audio.jorbis.Info; public class CodecJOrbis { diff --git a/java/src/game/audio/SoundManager.java b/client/src/main/java/client/audio/SoundManager.java similarity index 75% rename from java/src/game/audio/SoundManager.java rename to client/src/main/java/client/audio/SoundManager.java index d6d3f86..b37eb87 100755 --- a/java/src/game/audio/SoundManager.java +++ b/client/src/main/java/client/audio/SoundManager.java @@ -1,19 +1,28 @@ -package game.audio; +package client.audio; +import java.io.BufferedInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import game.collect.BiMap; -import game.collect.HashBiMap; -import game.collect.Lists; -import game.collect.Maps; - -import game.Game; -import game.entity.npc.EntityNPC; -import game.util.ExtMath; +import client.Client; +import client.util.FileUtils; +import common.collect.BiMap; +import common.collect.HashBiMap; +import common.collect.Lists; +import common.collect.Maps; +import common.entity.npc.EntityNPC; +import common.init.SoundEvent; +import common.log.Log; +import common.rng.Random; +import common.sound.MovingSound; +import common.sound.Sound; +import common.util.ExtMath; public class SoundManager { private class Source { @@ -67,13 +76,16 @@ public class SoundManager { } } + private static final Random RANDOM = new Random(); + private static final Map BUFFERS = Maps.newEnumMap(SoundEvent.class); + private final Map playingSounds = HashBiMap.create(); private final Map invPlayingSounds = ((BiMap)this.playingSounds).inverse(); private final List tickableSounds = Lists.newArrayList(); private final Map playingSoundsStopTime = Maps.newHashMap(); private final Map sources = new HashMap(); private final String[] channels = new String[28]; - private final Game gm; + private final Client gm; private float listenerX; private float listenerY; @@ -82,9 +94,49 @@ public class SoundManager { private int playTime = 0; private int eventId = 0; - public SoundManager(Game gm) { + public SoundManager(Client gm) { this.gm = gm; } + + public static void loadSounds() { + for(SoundEvent entry : SoundEvent.values()) { + short[][] buffers = new short[entry.getSounds().length][]; + for(int z = 0; z < entry.getSounds().length; z++) { + String sound = entry.getSounds()[z]; + Log.SOUND.trace("Lade Sound %s", sound); + buffers[z] = readOgg("sounds/" + sound + ".ogg"); + } + BUFFERS.put(entry, buffers); + } + } + + private static short[] readOgg(String filename) { + InputStream in = null; + try { + in = new BufferedInputStream(FileUtils.getResource(filename)); + return CodecJOrbis.readAll(in); + } + catch(FileNotFoundException e) { + Log.IO.error("Fehler beim Lesen von OPUS-Datei '%s': Datei nicht gefunden", filename); + return null; + } + catch(Exception e) { + Log.IO.error("Fehler beim Lesen von OPUS-Datei '%s': %s", filename, e.getMessage()); + return null; + } + finally { + try { + if(in != null) + in.close(); + } + catch(IOException e) { + } + } + } + + private static short[] getBuffer(SoundEvent event) { + return RANDOM.pick(BUFFERS.get(event)); + } public void unload() { @@ -183,11 +235,11 @@ public class SoundManager { if (volume > 0.0F) { String s = String.format("snd-%016x", this.eventId++); - this.sources.put(s, new Source(sound.getSoundLocation().getBuffer(), sound.getChannelType(), sound.canRepeat(), s, sound.getXPosF(), sound.getYPosF(), sound.getZPosF(), sound.getAttenuationType(), attn, volume)); + this.sources.put(s, new Source(getBuffer(sound.getSoundLocation()), Volume.getByType(sound.getChannelType()), sound.canRepeat(), s, sound.getXPosF(), sound.getYPosF(), sound.getZPosF(), sound.getAttenuationType(), attn, volume)); this.playingSoundsStopTime.put(s, this.playTime + 20); this.playingSounds.put(s, sound); - if (sound instanceof MovingSound) - this.tickableSounds.add((MovingSound)sound); + if (sound instanceof MovingSound moving) + this.tickableSounds.add(moving); } } diff --git a/java/src/game/audio/Volume.java b/client/src/main/java/client/audio/Volume.java similarity index 57% rename from java/src/game/audio/Volume.java rename to client/src/main/java/client/audio/Volume.java index 794ab45..5d400b7 100644 --- a/java/src/game/audio/Volume.java +++ b/client/src/main/java/client/audio/Volume.java @@ -1,25 +1,46 @@ -package game.audio; +package client.audio; -import game.Game; -import game.color.TextColor; -import game.gui.element.Slider; -import game.vars.CVar; -import game.vars.CVarCategory; +import client.Client; +import client.gui.element.Slider; +import client.gui.element.SliderCallback; +import client.vars.CVar; +import client.vars.CVarCategory; +import common.color.TextColor; +import common.sound.EventType; public enum Volume implements CVar { MASTER("master", "Gesamt"), MUSIC("music", "Musik"), - SFX("sfx", "Geräusche"), - GUI("gui", "Oberfläche"); + SFX("sfx", "Geräusche", EventType.SOUND_EFFECT), + GUI("gui", "Oberfläche", EventType.UI_INTERFACE); + + private static final Volume[] LOOKUP = new Volume[EventType.values().length]; public final String id; public final String name; + public final EventType type; private int value = 100; - private Volume(String id, String name) { + private Volume(String id, String name, EventType type) { this.id = id; this.name = name; + this.type = type; + } + + private Volume(String id, String name) { + this(id, name, null); + } + + static { + for(Volume volume : values()) { + if(volume.type != null) + LOOKUP[volume.type.ordinal()] = volume; + } + } + + public static Volume getByType(EventType type) { + return LOOKUP[type.ordinal()]; } public String getDisplay() { @@ -71,12 +92,12 @@ public enum Volume implements CVar { } public void apply() { - if(Game.getGame().getAudioInterface() != null) - Game.getGame().getAudioInterface().alSetVolume(this, (short)(((float)this.value) / 100.0f * 32767.0f)); + if(Client.CLIENT.getAudioInterface() != null) + Client.CLIENT.getAudioInterface().alSetVolume(this, (short)(((float)this.value) / 100.0f * 32767.0f)); } public Slider selector(int x, int y, int w, int h) { - return new Slider(x, y, w, h, 0, 0, 100, 100, this.value, new Slider.Callback() { + return new Slider(x, y, w, h, 0, 0, 100, 100, this.value, new SliderCallback() { public void use(Slider elem, int value) { Volume.this.value = value; Volume.this.apply(); diff --git a/java/src/game/audio/jogg/Buffer.java b/client/src/main/java/client/audio/jogg/Buffer.java similarity index 99% rename from java/src/game/audio/jogg/Buffer.java rename to client/src/main/java/client/audio/jogg/Buffer.java index 761e609..68fe0fc 100644 --- a/java/src/game/audio/jogg/Buffer.java +++ b/client/src/main/java/client/audio/jogg/Buffer.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jogg; +package client.audio.jogg; public class Buffer{ private static final int BUFFER_INCREMENT=256; diff --git a/java/src/game/audio/jogg/Packet.java b/client/src/main/java/client/audio/jogg/Packet.java similarity index 98% rename from java/src/game/audio/jogg/Packet.java rename to client/src/main/java/client/audio/jogg/Packet.java index 0ede86d..67c8e13 100644 --- a/java/src/game/audio/jogg/Packet.java +++ b/client/src/main/java/client/audio/jogg/Packet.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jogg; +package client.audio.jogg; public class Packet{ public byte[] packet_base; diff --git a/java/src/game/audio/jogg/Page.java b/client/src/main/java/client/audio/jogg/Page.java similarity index 99% rename from java/src/game/audio/jogg/Page.java rename to client/src/main/java/client/audio/jogg/Page.java index a05a403..1b73823 100644 --- a/java/src/game/audio/jogg/Page.java +++ b/client/src/main/java/client/audio/jogg/Page.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jogg; +package client.audio.jogg; public class Page{ private static int[] crc_lookup=new int[256]; diff --git a/java/src/game/audio/jogg/StreamState.java b/client/src/main/java/client/audio/jogg/StreamState.java similarity index 99% rename from java/src/game/audio/jogg/StreamState.java rename to client/src/main/java/client/audio/jogg/StreamState.java index 3339bb3..cc6452b 100644 --- a/java/src/game/audio/jogg/StreamState.java +++ b/client/src/main/java/client/audio/jogg/StreamState.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jogg; +package client.audio.jogg; public class StreamState{ byte[] body_data; /* bytes from packet bodies */ diff --git a/java/src/game/audio/jogg/SyncState.java b/client/src/main/java/client/audio/jogg/SyncState.java similarity index 99% rename from java/src/game/audio/jogg/SyncState.java rename to client/src/main/java/client/audio/jogg/SyncState.java index 58e3743..10c86ea 100644 --- a/java/src/game/audio/jogg/SyncState.java +++ b/client/src/main/java/client/audio/jogg/SyncState.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jogg; +package client.audio.jogg; // DECODING PRIMITIVES: packet streaming layer diff --git a/java/src/game/audio/jorbis/Block.java b/client/src/main/java/client/audio/jorbis/Block.java similarity index 97% rename from java/src/game/audio/jorbis/Block.java rename to client/src/main/java/client/audio/jorbis/Block.java index a96d2e2..249d4d6 100644 --- a/java/src/game/audio/jorbis/Block.java +++ b/client/src/main/java/client/audio/jorbis/Block.java @@ -24,9 +24,10 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; +import client.audio.jogg.Packet; public class Block{ ///necessary stream state for linking to the framing abstraction diff --git a/java/src/game/audio/jorbis/ChainingExample.java b/client/src/main/java/client/audio/jorbis/ChainingExample.java similarity index 98% rename from java/src/game/audio/jorbis/ChainingExample.java rename to client/src/main/java/client/audio/jorbis/ChainingExample.java index 1270c05..c1d9f3d 100644 --- a/java/src/game/audio/jorbis/ChainingExample.java +++ b/client/src/main/java/client/audio/jorbis/ChainingExample.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; class ChainingExample{ public static void main(String[] arg){ diff --git a/java/src/game/audio/jorbis/CodeBook.java b/client/src/main/java/client/audio/jorbis/CodeBook.java similarity index 99% rename from java/src/game/audio/jorbis/CodeBook.java rename to client/src/main/java/client/audio/jorbis/CodeBook.java index 40ce7eb..1a85d95 100644 --- a/java/src/game/audio/jorbis/CodeBook.java +++ b/client/src/main/java/client/audio/jorbis/CodeBook.java @@ -24,9 +24,9 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; class CodeBook{ int dim; // codebook dimensions (elements per vector) diff --git a/java/src/game/audio/jorbis/Comment.java b/client/src/main/java/client/audio/jorbis/Comment.java similarity index 98% rename from java/src/game/audio/jorbis/Comment.java rename to client/src/main/java/client/audio/jorbis/Comment.java index 9ec44c8..85a2a92 100644 --- a/java/src/game/audio/jorbis/Comment.java +++ b/client/src/main/java/client/audio/jorbis/Comment.java @@ -24,9 +24,10 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; +import client.audio.jogg.Packet; // the comments are not part of vorbis_info so that vorbis_info can be // static storage diff --git a/java/src/game/audio/jorbis/DecodeExample.java b/client/src/main/java/client/audio/jorbis/DecodeExample.java similarity index 98% rename from java/src/game/audio/jorbis/DecodeExample.java rename to client/src/main/java/client/audio/jorbis/DecodeExample.java index 0d5e999..a96c14f 100644 --- a/java/src/game/audio/jorbis/DecodeExample.java +++ b/client/src/main/java/client/audio/jorbis/DecodeExample.java @@ -24,9 +24,12 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Packet; +import client.audio.jogg.Page; +import client.audio.jogg.StreamState; +import client.audio.jogg.SyncState; // Takes a vorbis bitstream from stdin and writes raw stereo PCM to // stdout. Decodes simple and chained OggVorbis files from beginning diff --git a/java/src/game/audio/jorbis/Drft.java b/client/src/main/java/client/audio/jorbis/Drft.java similarity index 99% rename from java/src/game/audio/jorbis/Drft.java rename to client/src/main/java/client/audio/jorbis/Drft.java index 052faea..1bdd82f 100644 --- a/java/src/game/audio/jorbis/Drft.java +++ b/client/src/main/java/client/audio/jorbis/Drft.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; class Drft{ int n; diff --git a/java/src/game/audio/jorbis/DspState.java b/client/src/main/java/client/audio/jorbis/DspState.java similarity index 99% rename from java/src/game/audio/jorbis/DspState.java rename to client/src/main/java/client/audio/jorbis/DspState.java index 1115570..5ff952c 100644 --- a/java/src/game/audio/jorbis/DspState.java +++ b/client/src/main/java/client/audio/jorbis/DspState.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; public class DspState{ static final float M_PI=3.1415926539f; diff --git a/java/src/game/audio/jorbis/Floor0.java b/client/src/main/java/client/audio/jorbis/Floor0.java similarity index 99% rename from java/src/game/audio/jorbis/Floor0.java rename to client/src/main/java/client/audio/jorbis/Floor0.java index 7a37aa7..17ab1fd 100644 --- a/java/src/game/audio/jorbis/Floor0.java +++ b/client/src/main/java/client/audio/jorbis/Floor0.java @@ -24,9 +24,9 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; class Floor0 extends FuncFloor{ diff --git a/java/src/game/audio/jorbis/Floor1.java b/client/src/main/java/client/audio/jorbis/Floor1.java similarity index 99% rename from java/src/game/audio/jorbis/Floor1.java rename to client/src/main/java/client/audio/jorbis/Floor1.java index 70bc6d6..1d7c0ce 100644 --- a/java/src/game/audio/jorbis/Floor1.java +++ b/client/src/main/java/client/audio/jorbis/Floor1.java @@ -24,9 +24,9 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; class Floor1 extends FuncFloor{ static final int floor1_rangedb=140; diff --git a/java/src/game/audio/jorbis/FuncFloor.java b/client/src/main/java/client/audio/jorbis/FuncFloor.java similarity index 96% rename from java/src/game/audio/jorbis/FuncFloor.java rename to client/src/main/java/client/audio/jorbis/FuncFloor.java index 81b1cc1..1abc43c 100644 --- a/java/src/game/audio/jorbis/FuncFloor.java +++ b/client/src/main/java/client/audio/jorbis/FuncFloor.java @@ -24,9 +24,9 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; abstract class FuncFloor{ diff --git a/java/src/game/audio/jorbis/FuncMapping.java b/client/src/main/java/client/audio/jorbis/FuncMapping.java similarity index 95% rename from java/src/game/audio/jorbis/FuncMapping.java rename to client/src/main/java/client/audio/jorbis/FuncMapping.java index 2d94876..aa18945 100644 --- a/java/src/game/audio/jorbis/FuncMapping.java +++ b/client/src/main/java/client/audio/jorbis/FuncMapping.java @@ -24,9 +24,9 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; abstract class FuncMapping{ public static FuncMapping[] mapping_P= {new Mapping0()}; diff --git a/java/src/game/audio/jorbis/FuncResidue.java b/client/src/main/java/client/audio/jorbis/FuncResidue.java similarity index 96% rename from java/src/game/audio/jorbis/FuncResidue.java rename to client/src/main/java/client/audio/jorbis/FuncResidue.java index d0b7aaf..2c405ba 100644 --- a/java/src/game/audio/jorbis/FuncResidue.java +++ b/client/src/main/java/client/audio/jorbis/FuncResidue.java @@ -24,9 +24,9 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; abstract class FuncResidue{ public static FuncResidue[] residue_P= {new Residue0(), new Residue1(), diff --git a/java/src/game/audio/jorbis/FuncTime.java b/client/src/main/java/client/audio/jorbis/FuncTime.java similarity index 95% rename from java/src/game/audio/jorbis/FuncTime.java rename to client/src/main/java/client/audio/jorbis/FuncTime.java index f0ea437..7ba4a6b 100644 --- a/java/src/game/audio/jorbis/FuncTime.java +++ b/client/src/main/java/client/audio/jorbis/FuncTime.java @@ -24,9 +24,9 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; abstract class FuncTime{ public static FuncTime[] time_P= {new Time0()}; diff --git a/java/src/game/audio/jorbis/Info.java b/client/src/main/java/client/audio/jorbis/Info.java similarity index 99% rename from java/src/game/audio/jorbis/Info.java rename to client/src/main/java/client/audio/jorbis/Info.java index e37fac2..077ec0e 100644 --- a/java/src/game/audio/jorbis/Info.java +++ b/client/src/main/java/client/audio/jorbis/Info.java @@ -24,9 +24,10 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; +import client.audio.jogg.Packet; public class Info{ private static final int OV_EBADPACKET=-136; diff --git a/java/src/game/audio/jorbis/InfoMode.java b/client/src/main/java/client/audio/jorbis/InfoMode.java similarity index 97% rename from java/src/game/audio/jorbis/InfoMode.java rename to client/src/main/java/client/audio/jorbis/InfoMode.java index 2125bc5..3945476 100644 --- a/java/src/game/audio/jorbis/InfoMode.java +++ b/client/src/main/java/client/audio/jorbis/InfoMode.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; class InfoMode{ int blockflag; diff --git a/java/src/game/audio/jorbis/JOrbisException.java b/client/src/main/java/client/audio/jorbis/JOrbisException.java similarity index 97% rename from java/src/game/audio/jorbis/JOrbisException.java rename to client/src/main/java/client/audio/jorbis/JOrbisException.java index a6a2433..a58a772 100644 --- a/java/src/game/audio/jorbis/JOrbisException.java +++ b/client/src/main/java/client/audio/jorbis/JOrbisException.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; public class JOrbisException extends Exception{ diff --git a/java/src/game/audio/jorbis/Lookup.java b/client/src/main/java/client/audio/jorbis/Lookup.java similarity index 99% rename from java/src/game/audio/jorbis/Lookup.java rename to client/src/main/java/client/audio/jorbis/Lookup.java index b539615..4838f08 100644 --- a/java/src/game/audio/jorbis/Lookup.java +++ b/client/src/main/java/client/audio/jorbis/Lookup.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; class Lookup{ static final int COS_LOOKUP_SZ=128; diff --git a/java/src/game/audio/jorbis/Lpc.java b/client/src/main/java/client/audio/jorbis/Lpc.java similarity index 99% rename from java/src/game/audio/jorbis/Lpc.java rename to client/src/main/java/client/audio/jorbis/Lpc.java index 5a456f0..58e0e76 100644 --- a/java/src/game/audio/jorbis/Lpc.java +++ b/client/src/main/java/client/audio/jorbis/Lpc.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; class Lpc{ // en/decode lookups diff --git a/java/src/game/audio/jorbis/Lsp.java b/client/src/main/java/client/audio/jorbis/Lsp.java similarity index 99% rename from java/src/game/audio/jorbis/Lsp.java rename to client/src/main/java/client/audio/jorbis/Lsp.java index 182e693..8a2c002 100644 --- a/java/src/game/audio/jorbis/Lsp.java +++ b/client/src/main/java/client/audio/jorbis/Lsp.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; /* function: LSP (also called LSF) conversion routines diff --git a/java/src/game/audio/jorbis/Mapping0.java b/client/src/main/java/client/audio/jorbis/Mapping0.java similarity index 99% rename from java/src/game/audio/jorbis/Mapping0.java rename to client/src/main/java/client/audio/jorbis/Mapping0.java index b679be9..808970f 100644 --- a/java/src/game/audio/jorbis/Mapping0.java +++ b/client/src/main/java/client/audio/jorbis/Mapping0.java @@ -24,9 +24,9 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; class Mapping0 extends FuncMapping{ static int seq=0; diff --git a/java/src/game/audio/jorbis/Mdct.java b/client/src/main/java/client/audio/jorbis/Mdct.java similarity index 99% rename from java/src/game/audio/jorbis/Mdct.java rename to client/src/main/java/client/audio/jorbis/Mdct.java index 1a82a68..390fc22 100644 --- a/java/src/game/audio/jorbis/Mdct.java +++ b/client/src/main/java/client/audio/jorbis/Mdct.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; class Mdct{ diff --git a/java/src/game/audio/jorbis/PsyInfo.java b/client/src/main/java/client/audio/jorbis/PsyInfo.java similarity index 98% rename from java/src/game/audio/jorbis/PsyInfo.java rename to client/src/main/java/client/audio/jorbis/PsyInfo.java index cedd892..f5e8665 100644 --- a/java/src/game/audio/jorbis/PsyInfo.java +++ b/client/src/main/java/client/audio/jorbis/PsyInfo.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; // psychoacoustic setup class PsyInfo{ diff --git a/java/src/game/audio/jorbis/PsyLook.java b/client/src/main/java/client/audio/jorbis/PsyLook.java similarity index 97% rename from java/src/game/audio/jorbis/PsyLook.java rename to client/src/main/java/client/audio/jorbis/PsyLook.java index 70285ef..5fa57ad 100644 --- a/java/src/game/audio/jorbis/PsyLook.java +++ b/client/src/main/java/client/audio/jorbis/PsyLook.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; class PsyLook{ int n; diff --git a/java/src/game/audio/jorbis/Residue0.java b/client/src/main/java/client/audio/jorbis/Residue0.java similarity index 99% rename from java/src/game/audio/jorbis/Residue0.java rename to client/src/main/java/client/audio/jorbis/Residue0.java index 6ba0e90..6af8a9c 100644 --- a/java/src/game/audio/jorbis/Residue0.java +++ b/client/src/main/java/client/audio/jorbis/Residue0.java @@ -24,9 +24,9 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; class Residue0 extends FuncResidue{ void pack(Object vr, Buffer opb){ diff --git a/java/src/game/audio/jorbis/Residue1.java b/client/src/main/java/client/audio/jorbis/Residue1.java similarity index 97% rename from java/src/game/audio/jorbis/Residue1.java rename to client/src/main/java/client/audio/jorbis/Residue1.java index d0ac707..8072ce6 100644 --- a/java/src/game/audio/jorbis/Residue1.java +++ b/client/src/main/java/client/audio/jorbis/Residue1.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; class Residue1 extends Residue0{ diff --git a/java/src/game/audio/jorbis/Residue2.java b/client/src/main/java/client/audio/jorbis/Residue2.java similarity index 97% rename from java/src/game/audio/jorbis/Residue2.java rename to client/src/main/java/client/audio/jorbis/Residue2.java index 6c19867..b1875da 100644 --- a/java/src/game/audio/jorbis/Residue2.java +++ b/client/src/main/java/client/audio/jorbis/Residue2.java @@ -24,7 +24,7 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; class Residue2 extends Residue0{ diff --git a/java/src/game/audio/jorbis/StaticCodeBook.java b/client/src/main/java/client/audio/jorbis/StaticCodeBook.java similarity index 99% rename from java/src/game/audio/jorbis/StaticCodeBook.java rename to client/src/main/java/client/audio/jorbis/StaticCodeBook.java index a32e458..9452a85 100644 --- a/java/src/game/audio/jorbis/StaticCodeBook.java +++ b/client/src/main/java/client/audio/jorbis/StaticCodeBook.java @@ -24,9 +24,9 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; class StaticCodeBook{ int dim; // codebook dimensions (elements per vector) diff --git a/java/src/game/audio/jorbis/Time0.java b/client/src/main/java/client/audio/jorbis/Time0.java similarity index 95% rename from java/src/game/audio/jorbis/Time0.java rename to client/src/main/java/client/audio/jorbis/Time0.java index 6c64b3e..af2b2fb 100644 --- a/java/src/game/audio/jorbis/Time0.java +++ b/client/src/main/java/client/audio/jorbis/Time0.java @@ -24,9 +24,9 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; +package client.audio.jorbis; -import game.audio.jogg.*; +import client.audio.jogg.Buffer; class Time0 extends FuncTime{ void pack(Object i, Buffer opb){ diff --git a/java/src/game/audio/jorbis/Util.java b/client/src/main/java/client/audio/jorbis/Util.java similarity index 92% rename from java/src/game/audio/jorbis/Util.java rename to client/src/main/java/client/audio/jorbis/Util.java index ce82e07..5fd283b 100644 --- a/java/src/game/audio/jorbis/Util.java +++ b/client/src/main/java/client/audio/jorbis/Util.java @@ -1,4 +1,4 @@ -package game.audio.jorbis; +package client.audio.jorbis; class Util{ static int ilog(int v){ diff --git a/java/src/game/audio/jorbis/VorbisFile.java b/client/src/main/java/client/audio/jorbis/VorbisFile.java similarity index 99% rename from java/src/game/audio/jorbis/VorbisFile.java rename to client/src/main/java/client/audio/jorbis/VorbisFile.java index 0d5cbf7..54dade8 100644 --- a/java/src/game/audio/jorbis/VorbisFile.java +++ b/client/src/main/java/client/audio/jorbis/VorbisFile.java @@ -25,13 +25,15 @@ * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ -package game.audio.jorbis; - -import java.io.InputStream; - -import game.audio.jogg.*; +package client.audio.jorbis; import java.io.IOException; +import java.io.InputStream; + +import client.audio.jogg.Packet; +import client.audio.jogg.Page; +import client.audio.jogg.StreamState; +import client.audio.jogg.SyncState; public class VorbisFile{ static final int CHUNKSIZE=8500; diff --git a/java/src/game/util/FileCallback.java b/client/src/main/java/client/gui/FileCallback.java similarity index 79% rename from java/src/game/util/FileCallback.java rename to client/src/main/java/client/gui/FileCallback.java index 0c840c7..82f57d5 100644 --- a/java/src/game/util/FileCallback.java +++ b/client/src/main/java/client/gui/FileCallback.java @@ -1,4 +1,4 @@ -package game.util; +package client.gui; import java.io.File; diff --git a/java/src/game/gui/Font.java b/client/src/main/java/client/gui/Font.java similarity index 88% rename from java/src/game/gui/Font.java rename to client/src/main/java/client/gui/Font.java index f72e210..2ddfabe 100644 --- a/java/src/game/gui/Font.java +++ b/client/src/main/java/client/gui/Font.java @@ -1,4 +1,4 @@ -package game.gui; +package client.gui; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; @@ -6,15 +6,16 @@ import java.io.IOException; import org.lwjgl.opengl.GL11; -import game.log.Log; -import game.renderer.GlState; -import game.renderer.texture.TextureUtil; -import game.util.FileUtils; +import client.renderer.GlState; +import client.renderer.texture.TextureUtil; +import client.util.FileUtils; +import common.log.Log; public class Font { public static final FontChar[] SIZES = new FontChar[256]; - public static final int XGLYPH = 12; - public static final int YGLYPH = 18; + + public static int XGLYPH = 12; + public static int YGLYPH = 14; private static int texture; @@ -72,10 +73,12 @@ public class Font { } } - public static void load() { + public static void load(boolean tiny) { + XGLYPH = tiny ? 6 : 12; + YGLYPH = tiny ? 7 : 14; BufferedImage img = null; try { - img = TextureUtil.readImage(FileUtils.getResource("textures/font.png")); + img = TextureUtil.readImage(FileUtils.getResource("textures/font" + (tiny ? "_tiny" : "") + ".png")); } catch(FileNotFoundException e) { Log.IO.error("Konnte Font-Textur nicht laden: Datei nicht vorhanden"); diff --git a/java/src/game/gui/FontChar.java b/client/src/main/java/client/gui/FontChar.java similarity index 91% rename from java/src/game/gui/FontChar.java rename to client/src/main/java/client/gui/FontChar.java index 74a4d7e..1d39db4 100644 --- a/java/src/game/gui/FontChar.java +++ b/client/src/main/java/client/gui/FontChar.java @@ -1,4 +1,4 @@ -package game.gui; +package client.gui; public class FontChar { public final byte s; diff --git a/java/src/game/util/Formatter.java b/client/src/main/java/client/gui/Formatter.java similarity index 57% rename from java/src/game/util/Formatter.java rename to client/src/main/java/client/gui/Formatter.java index d14563e..a551198 100644 --- a/java/src/game/util/Formatter.java +++ b/client/src/main/java/client/gui/Formatter.java @@ -1,6 +1,6 @@ -package game.util; +package client.gui; -import game.gui.element.Element; +import client.gui.element.Element; public interface Formatter { String use(T elem); diff --git a/java/src/game/gui/Gui.java b/client/src/main/java/client/gui/Gui.java similarity index 94% rename from java/src/game/gui/Gui.java rename to client/src/main/java/client/gui/Gui.java index a719e0a..b8e4fbf 100644 --- a/java/src/game/gui/Gui.java +++ b/client/src/main/java/client/gui/Gui.java @@ -1,27 +1,26 @@ -package game.gui; +package client.gui; import java.util.List; import org.lwjgl.opengl.GL13; -import game.collect.Lists; - -import game.Game; -import game.gui.element.Dropdown; -import game.gui.element.Dropdown.Handle; -import game.gui.element.Element; -import game.renderer.Drawing; -import game.renderer.GlState; -import game.window.Bind; -import game.window.Button; -import game.window.Keysym; +import client.Client; +import client.gui.element.Dropdown; +import client.gui.element.Dropdown.Handle; +import client.gui.element.Element; +import client.renderer.Drawing; +import client.renderer.GlState; +import client.window.Bind; +import client.window.Button; +import client.window.Keysym; +import common.collect.Lists; public abstract class Gui { - public static final String DIRT_BACKGROUND = "textures/background.png"; + public static final String BACKGROUND = "textures/background.png"; public static final int HOVER_COLOR = 0x288080ff; public static final int PRESS_COLOR = 0x30afafff; - protected final Game gm = Game.getGame(); + protected final Client gm = Client.CLIENT; public Element selected; private int min_x; @@ -177,8 +176,8 @@ public abstract class Gui { this.min_y = Math.min(this.min_y, elem.getY()); this.max_x = Math.max(this.max_x, elem.getX() + elem.getWidth()); this.max_y = Math.max(this.max_y, elem.getY() + elem.getHeight()); - if(elem instanceof Dropdown) - this.add(((Dropdown)elem).getHandle()); + if(elem instanceof Dropdown drop) + this.add(drop.getHandle()); return elem; } @@ -302,13 +301,13 @@ public abstract class Gui { // } public void drawMainBackground() { - if(this.gm.theWorld != null && !this.gm.charEditor) { + if(this.gm.world != null && !this.gm.charEditor) { // Drawing.drawGradient(0, 0, this.fb_x, this.fb_y, this.theWorld == null ? this.style.bg_top : 0x3f202020, // this.theWorld == null ? this.style.bg_btm : 0x3f000000); Drawing.drawGradient(0, 0, this.gm.fb_x, this.gm.fb_y, 0xc0101010, 0xd0101010); } else { - Drawing.drawScaled(this.gm, DIRT_BACKGROUND); + Drawing.drawScaled(this.gm, BACKGROUND); } } diff --git a/client/src/main/java/client/gui/GuiConfirm.java b/client/src/main/java/client/gui/GuiConfirm.java new file mode 100755 index 0000000..6e0d288 --- /dev/null +++ b/client/src/main/java/client/gui/GuiConfirm.java @@ -0,0 +1,46 @@ +package client.gui; + +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.Label; +import client.gui.element.MultiLabel; +import client.gui.element.PressType; + +public class GuiConfirm extends Gui implements ButtonCallback { + public static interface Callback { + void confirm(boolean confirmed); + } + + private final Callback callback; + private final String messageLine1; + private final String messageLine2; + private final String confirmButtonText; + private final String cancelButtonText; + + private ActButton confirmBtn; + private ActButton cancelBtn; + + public GuiConfirm(Callback callback, String msg1, String msg2, String msgConfirm, String msgCancel) { + this.callback = callback; + this.messageLine1 = msg1; + this.messageLine2 = msg2; + this.confirmButtonText = msgConfirm; + this.cancelButtonText = msgCancel; + } + + public void init(int width, int height) { + this.add(new Label(0, 0, 700, 0, this.messageLine1)); + this.add(new MultiLabel(0, 40, 700, 300, this.messageLine2, true)); + this.confirmBtn = this.add(new ActButton(100, 400, 245, 0, this, this.confirmButtonText)); + this.cancelBtn = this.add(new ActButton(355, 400, 245, 0, this, this.cancelButtonText)); + this.shift(); + } + + public String getTitle() { + return "Aktion bestätigen"; + } + + public void use(ActButton btn, PressType mode) { + this.callback.confirm(btn == this.confirmBtn); + } +} diff --git a/client/src/main/java/client/gui/GuiConnect.java b/client/src/main/java/client/gui/GuiConnect.java new file mode 100644 index 0000000..a744c40 --- /dev/null +++ b/client/src/main/java/client/gui/GuiConnect.java @@ -0,0 +1,379 @@ +package client.gui; + +import java.io.File; +import java.security.KeyPair; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.text.SimpleDateFormat; +import java.util.Collections; +import java.util.Date; + +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.GuiList; +import client.gui.element.ListEntry; +import client.gui.element.NavButton; +import client.gui.element.PressType; +import client.renderer.Drawing; +import client.util.FileUtils; +import common.color.TextColor; +import common.log.Log; +import common.network.IPlayer; +import common.util.EncryptUtil; +import common.util.Pair; +import common.util.Util; + +public class GuiConnect extends GuiList implements ButtonCallback { + public class ServerInfo implements Comparable, ListEntry { + private final boolean direct; + + private String name; + private String address; + private int port; + private String user; + private String password; + private String access; + private KeyPair keypair; + private String keyDigest; + private PublicKey serverKey; + private String serverDigest; + private boolean enforceEncryption; + private long lastConnected; + + public ServerInfo(String address, int port, String user, String password, String access) { + this.direct = true; + this.name = DIRECT_NAME; + this.address = address; + this.port = port; + this.user = user; + this.password = password; + this.access = access; + this.lastConnected = -1L; + } + + public ServerInfo(String name, String address, int port, String user, String password, String access, KeyPair keypair, long lastConnected, PublicKey serverKey, boolean enforceEnc) { + this.direct = false; + this.name = name; + this.address = address; + this.port = port; + this.user = user; + this.password = password; + this.access = access; + this.keypair = keypair; + this.lastConnected = lastConnected; + this.serverKey = serverKey; + this.enforceEncryption = enforceEnc; + if(this.keypair != null) + this.keyDigest = EncryptUtil.getXorSha512Hash(this.keypair.getPublic().getEncoded()); + if(this.serverKey != null) + this.serverDigest = EncryptUtil.getXorSha512Hash(this.serverKey.getEncoded()); + } + + public boolean isDirect() { + return this.direct; + } + + public String getName() { + return this.name; + } + + public String getAddress() { + return this.address; + } + + public int getPort() { + return this.port; + } + + public String getUser() { + return this.user; + } + + public String getPassword() { + return this.password; + } + + public String getAccess() { + return this.access; + } + + public KeyPair getKeypair() { + return this.keypair; + } + + public PublicKey getServerKey() { + return this.serverKey; + } + + public boolean requiresEncryption() { + return this.enforceEncryption; + } + + public long getLastConnected() { + return this.lastConnected; + } + + public void setData(String name, String address, int port, String user, String password, String access, KeyPair keypair, PublicKey serverKey, boolean encryptReq) { + this.name = name; + this.address = address; + this.port = port; + this.user = user; + this.password = password; + this.access = access; + this.keypair = keypair; + this.serverKey = serverKey; + this.enforceEncryption = encryptReq; + this.keyDigest = this.keypair != null ? EncryptUtil.getXorSha512Hash(this.keypair.getPublic().getEncoded()) : null; + this.serverDigest = this.serverKey != null ? EncryptUtil.getXorSha512Hash(this.serverKey.getEncoded()) : null; + } + + public void setLastConnected() { + this.lastConnected = System.currentTimeMillis(); + } + + public void setServerKey(PublicKey key) { + this.serverKey = key; + this.serverDigest = this.serverKey != null ? EncryptUtil.getXorSha512Hash(this.serverKey.getEncoded()) : null; + } + + public int compareTo(ServerInfo comp) { + return this.lastConnected < comp.lastConnected ? 1 : (this.lastConnected > comp.lastConnected ? -1 : this.name.compareTo(comp.name)); + } + + public void select(boolean isDoubleClick, int mouseX, int mouseY) { + GuiConnect.this.selectButton.enabled = true; + GuiConnect.this.deleteButton.enabled = true; + GuiConnect.this.editButton.enabled = true; + GuiConnect.this.copyButton.enabled = true; + + if(isDoubleClick) { + GuiConnect.this.use(GuiConnect.this.selectButton, PressType.PRIMARY); + } + } + + public void draw(int x, int y, int width, int height, int mouseXIn, int mouseYIn, boolean hover) { + Drawing.drawText(this.name + TextColor.GRAY + " - " + TextColor.RESET + this.user, x + 2, y, 0xffffffff); + if(this.keypair != null || !this.password.isEmpty()) + Drawing.drawTextRight( + (this.keypair != null ? "Pubkey " + this.keyDigest : "") + (this.keypair != null && !this.password.isEmpty() ? " + " : "") + (!this.password.isEmpty() ? "Passwort" : ""), + x + width - 2, y, 0xffffffff); + Drawing.drawText(this.address + TextColor.GRAY + " Port " + TextColor.RESET + this.port + (this.enforceEncryption ? TextColor.GRAY + ", nur verschlüsselt" : ""), + x + 2, y + height - Font.YGLYPH * 2, 0xffb0b0b0); + if(!this.access.isEmpty()) + Drawing.drawTextRight((this.keypair != null || !this.password.isEmpty() ? "+ " : "") + "Server-Passwort", x + width - 2, y + height - Font.YGLYPH * 2, 0xffb0b0b0); + Drawing.drawText("Zuletzt verbunden: " + (this.lastConnected == -1L ? "nie" : DATE_FORMAT.format(new Date(this.lastConnected))), x + 2, y + height - Font.YGLYPH, 0xffb0b0b0); + if(this.serverDigest != null) + Drawing.drawTextRight("Server-ID: " + this.serverDigest, x + width - 2, y + height - Font.YGLYPH, 0xffb0b0b0); + } + } + + public static final GuiConnect INSTANCE = new GuiConnect(); + private static final String DIRECT_NAME = ""; + private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); + private static final File SERVERS_FILE = new File("servers.cfg"); + + private ActButton deleteButton; + private ActButton selectButton; + private ActButton copyButton; + private ActButton editButton; + private ActButton createButton; + + private GuiConnect() { + } + + public void init(int width, int height) { + super.init(width, height); + this.setDimensions(width, height, 32, height - 32); + this.elements.clear(); + if(SERVERS_FILE.exists()) { + try { + String[] lines = FileUtils.read(SERVERS_FILE).split("\n"); + String name = ""; + String address = ""; + int port = -1; + String user = ""; + String password = ""; + String access = ""; + byte[] key = null; + byte[] pubkey = null; + byte[] serverKey = null; + boolean enforceEnc = false; + long time = -1L; + for(int z = 0; z <= lines.length; z++) { + String line = z == lines.length ? null : lines[z]; + if(line == null || (line.startsWith("[") && line.endsWith("]"))) { + if(!name.isEmpty() && !address.isEmpty() && !user.isEmpty() && user.length() < IPlayer.MAX_USER_LENGTH && IPlayer.isValidUser(user) && + password.length() < IPlayer.MAX_PASS_LENGTH && access.length() < IPlayer.MAX_PASS_LENGTH && address.length() < 128 && name.length() < 128 && + port >= 1024 && port <= 32767 && (password.length() >= 8 || password.isEmpty()) && (access.length() >= 8 || access.isEmpty()) && !this.isNameTaken(name)) { + PrivateKey priv = key == null ? null : EncryptUtil.decodePrivateKey(key); + PublicKey pub = pubkey == null ? null : EncryptUtil.decodePublicKey(pubkey); + PublicKey serv = serverKey == null ? null : EncryptUtil.decodePublicKey(serverKey); + this.elements.add(new ServerInfo(name, address, port, user, password, access, priv == null || pub == null ? null : new KeyPair(pub, priv), time, serv, enforceEnc)); + } + if(line != null) { + address = ""; + port = -1; + user = ""; + password = ""; + access = ""; + key = null; + pubkey = null; + serverKey = null; + enforceEnc = false; + time = -1L; + name = line.substring(1, line.length() - 1); + } + } + else { + Pair value = Util.getKeyValue(line); + if(value.first().equals("address")) + address = value.second(); + else if(value.first().equals("port")) + try { + port = Integer.parseInt(value.second()); + } + catch(NumberFormatException e) { + } + else if(value.first().equals("user")) + user = value.second(); + else if(value.first().equals("password")) + password = value.second(); + else if(value.first().equals("access")) + access = value.second(); + else if(value.first().equals("connected")) + try { + time = Long.parseLong(value.second()); + } + catch(NumberFormatException e) { + } + else if(value.first().equals("encryption_enforced")) + enforceEnc = true; + else if(value.first().equals("serverkey")) + serverKey = Util.fromHexString(value.second()); + else if(value.first().equals("key")) + key = Util.fromHexString(value.second()); + else if(value.first().equals("pubkey")) + pubkey = Util.fromHexString(value.second()); + } + } + Collections.sort(this.elements); + } + catch(Exception e) { + Log.IO.error("Konnte Serverliste nicht laden", e); + this.elements.clear(); + } + } + + this.add(this.selectButton = new ActButton(width / 2 - 379, height - 30, 150, 0, this, "Verbinden")); + this.add(this.createButton = new ActButton(width - 202, 12, 200, 0, this, "Server hinzufügen ...")); + this.add(this.deleteButton = new ActButton(width / 2 - 75, height - 30, 150, 0, this, "Löschen")); + this.add(this.editButton = new ActButton(width / 2 + 77, height - 30, 150, 0, this, "Bearbeiten")); + this.add(this.copyButton = new ActButton(width / 2 - 227, height - 30, 150, 0, this, "Kopieren")); + this.add(new NavButton(width / 2 + 229, height - 30, 150, 0, GuiMenu.INSTANCE, "Abbrechen")); + + this.selectButton.enabled = false; + this.deleteButton.enabled = false; + this.editButton.enabled = false; + this.copyButton.enabled = false; + } + + public void onGuiClosed() { + this.save(); + } + + public void applyServer(ServerInfo server) { + if(this.selectedElement < 0) + this.elements.add(server); + this.save(); + this.gm.displayGuiScreen(this); + } + + public boolean isNameTaken(String name) { + for(int z = 0; z < this.elements.size(); z++) { + if(this.selectedElement != z && this.elements.get(z).getName().equals(name)) + return true; + } + return DIRECT_NAME.equals(name); + } + + public void editServer(ServerInfo server) { + if(!server.isDirect()) + this.save(); + } + + public void connect(String address, int port, String user, String pass, String access) { + this.gm.connect(new ServerInfo(address, port, user, pass, access)); + } + + private void save() { + try { + StringBuilder sb = new StringBuilder(); + for(ServerInfo server : this.elements) { + if(sb.length() > 0) + sb.append("\n"); + sb.append("[" + server.getName() + "]"); + sb.append("\naddress " + server.getAddress()); + sb.append("\nport " + server.getPort()); + sb.append("\nuser " + server.getUser()); + if(!server.getPassword().isEmpty()) + sb.append("\npassword " + server.getPassword()); + if(!server.getAccess().isEmpty()) + sb.append("\naccess " + server.getAccess()); + if(server.getKeypair() != null) { + sb.append("\nkey " + Util.getHexString(server.getKeypair().getPrivate().getEncoded())); + sb.append("\npubkey " + Util.getHexString(server.getKeypair().getPublic().getEncoded())); + } + if(server.requiresEncryption()) + sb.append("\nencryption_enforced"); + if(server.getLastConnected() != -1L) + sb.append("\nconnected " + server.getLastConnected()); + if(server.getServerKey() != null) + sb.append("\nserverkey " + Util.getHexString(server.getServerKey().getEncoded())); + } + FileUtils.write(SERVERS_FILE, sb.toString()); + } + catch(Exception e) { + Log.IO.error("Konnte Serverliste nicht speichern", e); + } + } + + public String getTitle() { + return "Server auswählen"; + } + + public int getSlotHeight() { + return 56; + } + + public void use(ActButton button, PressType mode) { + if(button == this.deleteButton) { + if(this.selectedElement >= 0) { + this.elements.remove(this.selectedElement); + this.gm.displayGuiScreen(this); + } + } + else if(button == this.selectButton) { + ServerInfo server = this.getSelected(); + if(server != null) { + server.setLastConnected(); + this.gm.connect(server); + } + } + else if(button == this.createButton) { + this.setSelected(-1); + this.gm.displayGuiScreen(new GuiServer(new ServerInfo("", "", -1, "", "", "", null, -1L, null, false))); + } + else if(button == this.editButton) { + ServerInfo server = this.getSelected(); + if(server != null) + this.gm.displayGuiScreen(new GuiServer(server)); + } + else if(button == this.copyButton) { + ServerInfo server = this.getSelected(); + if(server != null) { + this.setSelected(-1); + this.gm.displayGuiScreen(new GuiServer(new ServerInfo(server.name, server.address, server.port, server.user, server.password, server.access, server.keypair, -1L, null, server.enforceEncryption))); + } + } + } +} diff --git a/java/src/game/gui/GuiConsole.java b/client/src/main/java/client/gui/GuiConsole.java similarity index 80% rename from java/src/game/gui/GuiConsole.java rename to client/src/main/java/client/gui/GuiConsole.java index 28e776c..673d90b 100644 --- a/java/src/game/gui/GuiConsole.java +++ b/client/src/main/java/client/gui/GuiConsole.java @@ -1,26 +1,29 @@ -package game.gui; +package client.gui; import java.util.List; -import game.collect.Lists; +import client.Client; +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.Element; +import client.gui.element.Fill; +import client.gui.element.PressType; +import client.gui.element.FieldAction; +import client.gui.element.Field; +import client.gui.element.FieldCallback; +import client.vars.BoolVar; +import client.vars.CVar; +import client.gui.element.TransparentArea; +import client.window.Keysym; +import common.collect.Lists; +import common.color.TextColor; +import common.network.IPlayer; +import common.packet.CPacketComplete; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.HitPosition; -import game.Game; -import game.color.TextColor; -import game.gui.element.ActButton; -import game.gui.element.Fill; -import game.gui.element.Textbox; -import game.gui.element.Textbox.Action; -import game.gui.element.TransparentBox; -import game.network.Player; -import game.packet.CPacketComplete; -import game.util.ExtMath; -import game.vars.BoolVar; -import game.vars.CVar; -import game.window.Keysym; -import game.world.BlockPos; -import game.world.HitPosition; - -public class GuiConsole extends Gui implements Textbox.Callback { +public class GuiConsole extends Gui implements FieldCallback { public static final GuiConsole INSTANCE = new GuiConsole(); private final List sentMessages = Lists.newArrayList(); @@ -35,8 +38,8 @@ public class GuiConsole extends Gui implements Textbox.Callback { private String prefixFirst; private int autocompleteIndex; private List foundPlayerNames = Lists.newArrayList(); - private Textbox inputField; - private TransparentBox logBox; + private Field inputField; + private TransparentArea logBox; public GuiConsole setFull(boolean full) { this.full = full; @@ -45,20 +48,20 @@ public class GuiConsole extends Gui implements Textbox.Callback { public void init(int width, int height) { if(this.full) { - this.addSelector("con_autoclose", 0, 0, 160, 24); - this.addSelector("con_timestamps", 160, 0, 160, 24); - this.addSelector("con_loglevel", 320, 0, 160, 24); - this.add(new ActButton(480, 0, 160, 24, new ActButton.Callback() { - public void use(ActButton elem, ActButton.Mode action) { + this.addSelector("con_autoclose", 0, 0, 160, 0); + this.addSelector("con_timestamps", 160, 0, 160, 0); + this.addSelector("con_loglevel", 320, 0, 160, 0); + this.add(new ActButton(480, 0, 160, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { GuiConsole.this.reset(); GuiConsole.this.setLog(GuiConsole.this.gm.getBuffer()); } }, "Löschen")); } - this.logBox = this.add(new TransparentBox(0, this.full ? 24 : 0, width, height - (this.full ? 48 : 24), this.gm.getBuffer(), this.gm.theWorld != null && !this.gm.charEditor)); + this.logBox = this.add(new TransparentArea(0, this.full ? Element.BASE_HEIGHT : 0, width, height - Element.BASE_HEIGHT * (this.full ? 2 : 1), this.gm.getBuffer(), this.gm.world != null && !this.gm.charEditor)); if(this.full) - this.add(new Fill(640, 0, width - 640, 24)); - this.inputField = this.add(new Textbox(0, height - 24, width, 24, Player.MAX_CMD_LENGTH, true, this, "")); + this.add(new Fill(640, 0, width - 640, 0)); + this.inputField = this.add(new Field(0, height - Element.BASE_HEIGHT, width, 0, IPlayer.MAX_CMD_LENGTH, this, "")); this.inputField.setSelected(); this.sentHistoryCursor = this.sentMessages.size(); } @@ -79,7 +82,7 @@ public class GuiConsole extends Gui implements Textbox.Callback { } public void drawMainBackground() { - if(this.gm.theWorld == null || this.gm.charEditor) + if(this.gm.world == null || this.gm.charEditor) super.drawMainBackground(); } @@ -90,13 +93,13 @@ public class GuiConsole extends Gui implements Textbox.Callback { this.playerNamesFound = false; } - public void use(Textbox elem, Action value) + public void use(Field elem, FieldAction value) { this.waitingOnAutocomplete = false; - if (value == Action.FORWARD || value == Action.BACKWARD) + if (value == FieldAction.FORWARD || value == FieldAction.BACKWARD) { - this.reverse = value == Action.BACKWARD; + this.reverse = value == FieldAction.BACKWARD; this.autocompletePlayerNames(); } else @@ -104,11 +107,11 @@ public class GuiConsole extends Gui implements Textbox.Callback { this.playerNamesFound = false; } - if(value == Action.PREVIOUS) + if(value == FieldAction.PREVIOUS) this.getSentHistory(-1); - else if (value == Action.NEXT) + else if (value == FieldAction.NEXT) this.getSentHistory(1); - if(value == Action.SEND) + if(value == FieldAction.SEND) { String s = this.inputField.getText().trim(); @@ -123,7 +126,7 @@ public class GuiConsole extends Gui implements Textbox.Callback { } this.inputField.setText(""); - if((this.gm.conAutoclose || !this.full) && this.gm.theWorld != null) + if((this.gm.conAutoclose || !this.full) && this.gm.world != null) this.gm.displayGuiScreen(null); } } @@ -142,7 +145,7 @@ public class GuiConsole extends Gui implements Textbox.Callback { private void addMessage(String msg) { String buffer = this.gm.getBuffer(); - if((buffer.length() + msg.length() + 2) > Game.LOG_BUFFER) { + if((buffer.length() + msg.length() + 2) > Client.LOG_BUFFER) { int offset = (msg.length() + 2) > 1024 ? (msg.length() + 2) : 1024; int nl = buffer.indexOf('\n', offset); buffer = nl >= 0 ? buffer.substring(nl + 1) : ""; @@ -154,7 +157,7 @@ public class GuiConsole extends Gui implements Textbox.Callback { { if (this.playerNamesFound) { - this.inputField.deleteFromCursor(); + this.inputField.deleteSpaceToCur(); if (this.autocompleteIndex >= this.foundPlayerNames.size()) { @@ -167,11 +170,11 @@ public class GuiConsole extends Gui implements Textbox.Callback { } else { - int i = this.inputField.getNthCharFromPos(); + int i = this.inputField.getSpaceBeforeCur(); this.foundPlayerNames.clear(); this.autocompleteIndex = 0; // String s = this.inputField.getText().substring(i).toLowerCase(); - String s1 = this.inputField.getText().substring(0, this.inputField.getCursorPosition()); + String s1 = this.inputField.getText().substring(0, this.inputField.getCursorPos()); String[] localMatches = this.sendAutocompleteRequest(s1); if(localMatches != null) { this.onAutocompleteResponse(localMatches); @@ -184,7 +187,7 @@ public class GuiConsole extends Gui implements Textbox.Callback { } this.playerNamesFound = true; - this.inputField.deleteFromCursor(); + this.inputField.deleteSpaceToCur(); } if (this.foundPlayerNames.size() > 1) @@ -215,7 +218,7 @@ public class GuiConsole extends Gui implements Textbox.Callback { s = argv[argv.length - 1]; Iterable res = pre.startsWith("#") ? (argv.length == 1 ? this.gm.getVars() : (argv.length == 2 ? getVarCompletion(argv[0].substring(1)) : Lists.newArrayList())) : - (this.gm.thePlayer == null ? Lists.newArrayList() : this.gm.thePlayer.sendQueue.getPlayerNames()); + (this.gm.player == null ? Lists.newArrayList() : this.gm.playerList.keySet()); if(argv.length == 1 && pre.startsWith("#")) s = s.substring(1); for(String s1 : res) { @@ -252,10 +255,10 @@ public class GuiConsole extends Gui implements Textbox.Callback { blockpos = new BlockPos(this.gm.pointed.entity); } if(currentText.startsWith("/")) { - if(this.gm.thePlayer != null) { + if(this.gm.player != null) { currentText = currentText.substring(1); this.prefixFirst = currentText.split(" ", -1).length == 1 ? "/" : null; - this.gm.thePlayer.sendQueue.addToSendQueue(new CPacketComplete(currentText, eid, blockpos)); + this.gm.player.client.addToSendQueue(new CPacketComplete(currentText, eid, blockpos)); this.waitingOnAutocomplete = true; } } @@ -314,12 +317,12 @@ public class GuiConsole extends Gui implements Textbox.Callback { } } - String s1 = this.inputField.getText().substring(this.inputField.getNthCharFromPos()); + String s1 = this.inputField.getText().substring(this.inputField.getSpaceBeforeCur()); String s2 = getCommonPrefix(choices); if (s2.length() > 0 && !s1.equalsIgnoreCase(s2)) { - this.inputField.deleteFromCursor(); + this.inputField.deleteSpaceToCur(); this.inputField.insertText(s2); } else if (this.foundPlayerNames.size() > 0) diff --git a/java/src/game/gui/GuiInfo.java b/client/src/main/java/client/gui/GuiInfo.java similarity index 60% rename from java/src/game/gui/GuiInfo.java rename to client/src/main/java/client/gui/GuiInfo.java index 904620d..98f1b94 100644 --- a/java/src/game/gui/GuiInfo.java +++ b/client/src/main/java/client/gui/GuiInfo.java @@ -1,32 +1,35 @@ -package game.gui; +package client.gui; -import game.color.TextColor; -import game.gui.element.NavButton; -import game.gui.element.TransparentBox; -import game.init.Config; -import game.log.Log; +import client.Client; +import client.gui.element.MultiLabel; +import client.gui.element.NavButton; +import common.Version; +import common.color.TextColor; +import common.log.Log; +import common.util.Util; public class GuiInfo extends Gui { private static final String VER = - TextColor.GREEN + "" + TextColor.BUG + "" + TextColor.BUG + "" + TextColor.BUG + " " + TextColor.VIOLET + "" + Config.VERSION + "" + - TextColor.GREEN + " " + TextColor.BUG + "" + TextColor.BUG + "" + TextColor.BUG; + TextColor.GREEN + "" + Util.repeatString(TextColor.BUG, Version.RELEASE.getId()) + TextColor.DVIOLET + "|-| " + TextColor.VIOLET + Client.VERSION + TextColor.DVIOLET + " |-|" + + TextColor.GREEN + Util.repeatString(TextColor.BUG, Version.RELEASE.getId()); private static final String INFO = "Ein Spiel zur Simulation, zum Testen, für Rollenspiele, Mehrspieler und vieles mehr." + "\n" + "Optimiert für Geschwindigkeit, Stabilität und" + TextColor.UNKNOWN + "" + TextColor.UNKNOWN + " [Speicherzugriffsfehler]"; - private static final String HACKED = "Ein weiterer Release von WAAAAAAAAAAAAAAAAAAAAAAAAAAAAGHDRIVE!!!1!!!ONEoneOnetyone!1!!!" + "\n" + + private static final String HACKED = "Ein weiterer Release von WAAAAAAAAAAAAGHDRIVE!!!1!!!ONEoneOnetyone!1!!!" + "\n" + "Update 0.2 - Läuft jetzt auch mit nur 512KB Fast-RAM!"; private static final String[] LIBRARIES = { - "LWJGL 3.3.6+1 (GLFW + OpenGL)", - "Netty 4.1.119-Final" + "LWJGL 3.3.6", + "LWJGL-GLFW 3.3.6", + "LWJGL-OpenGL 3.3.6" }; private static final String[] CODE = { "Albert Pham - WorldEdit (Snippets)", "Joonas Vali - NameGenerator", "LWJGL 2.9.4-nightly-20150209 - Project, Vector*, Matrix*", "Guava 17.0 - collect, future, Predicates", - "JOrbis 20101023 (JCraft) - jogg, jorbis, CodecJOrbis", - "MC 1.8.9" + "Netty 4.0.23-Final - net.*", + "JOrbis 20101023 (JCraft) - jogg, jorbis, CodecJOrbis" }; public static final GuiInfo INSTANCE = new GuiInfo("Über dieses Programm", getFormat(false)); @@ -36,12 +39,12 @@ public class GuiInfo extends Gui { private final String info; private static String getFormat(boolean hax) { - return getInfo(hax) + "\n\n" + getCredits(hax) + "\n\n" + getLibraries(hax) + "\n\n" + getCode(hax) + "\n\n" + getOldCredits(hax) + "\n\n" + getColors(); + return getInfo(hax) + "\n\n" + getCredits(hax) + "\n\n" + getLibraries(hax) + "\n\n" + getCode(hax) + "\n\n" + getColors(); } private static String getHeader(boolean hax, String normal, String hacked) { return (hax ? TextColor.RED : TextColor.YELLOW) + (hax ? hacked : normal) + "\n" + - (hax ? TextColor.CYAN : TextColor.WHITE) + "==========================================+=========================================="; + (hax ? TextColor.CYAN : TextColor.WHITE) + "==========================+=========================="; } private static void addLines(StringBuilder sb, boolean hax, String alternate, String category, String... authors) { @@ -61,7 +64,7 @@ public class GuiInfo extends Gui { private static String getLibraries(boolean hax) { StringBuilder sb = new StringBuilder(getHeader(hax, "Verwendete Programmbibliotheken", "U$3d 3xpl0its")); for(String lib : LIBRARIES) { - sb.append("\n" + TextColor.LGRAY + "-> " + TextColor.NEON + lib); + sb.append("\n" + TextColor.NEON + lib); } return sb.toString(); } @@ -69,7 +72,7 @@ public class GuiInfo extends Gui { private static String getCode(boolean hax) { StringBuilder sb = new StringBuilder(getHeader(hax, "Zusätzlicher Quellcode", "M0ar 3xpl01ts")); for(String lib : CODE) { - sb.append("\n" + TextColor.LGRAY + "-> " + TextColor.NEON + lib); + sb.append("\n" + TextColor.NEON + lib); } return sb.toString(); } @@ -78,37 +81,16 @@ public class GuiInfo extends Gui { StringBuilder sb = new StringBuilder(); int num = 0; for(TextColor color : TextColor.values()) { - if(num > 0) - sb.append(' '); + if(num == 14) + sb.append('\n'); if((color.code >= Log.CHR_COLORS1 && color.code <= Log.CHR_COLORE1) || (color.code >= Log.CHR_COLORS2 && color.code <= Log.CHR_COLORE2)) { - sb.append(color + "#" + (char)(num < 10 ? ('0' + num) : ('A' + (num - 10)))); + sb.append(color + "#" + (char)(num < 10 ? ('0' + num) : ('A' + (num - 10))) + ' '); num++; } } return sb.toString(); } - private static String getOldCredits(boolean hax) { - StringBuilder sb = new StringBuilder(getHeader(hax, "Ursprüngliche Mitwirkende", "Das Team -- Nicht TCQ")); - - addLines(sb, hax, "Absolut größter Lamer des Universums", "Spielidee und ursprüngliche Umsetzung", - "Markus Persson"); - addLines(sb, hax, "Crack und weitere Programmierung", "Spiel-Design, Programmierung und Grafiken", - "Jens Bergensten", "Nathan Adams", "Ryan Holtz", "Michael Stoyke"); - addLines(sb, hax, "Entschlüsselung von Ressourcen", "Programmierung", - "Erik Broes", "Paul Spooner", "Ryan Hitchman", "Elliot Segal"); - addLines(sb, hax, "Cracktro, Grafiken und Intromusik", "Töne und Geräusche", - "Daniel Rosenfeld", "freesound.org"); - addLines(sb, hax, "Packing und Verbreitung", "Management, Administration und Spaß", - "Carl Manneh", "Daniel Kaplan", "Lydia Winters"); - addLines(sb, hax, "Server und Hosting", "Zahlen und Statistiken", - "Patrick Geuder"); - addLines(sb, hax, "Weiterer Dank und Grüße", "Entwickler von Mo' Creatures (Pferde usw.)", - "John Olarte", "Kent Christian Jensen", "Dan Roque"); - - return sb.toString(); - } - private static String getCredits(boolean hax) { StringBuilder sb = new StringBuilder(getHeader(hax, "Mitwirkende dieses Programms", "Das Team -- TCQ")); @@ -125,8 +107,8 @@ public class GuiInfo extends Gui { } public void init(int width, int height) { - this.add(new TransparentBox(10, 10, width - 20, height - 44, this.info, this.gm.theWorld != null && !this.gm.charEditor)); - this.add(new NavButton(0, height - 24, width, 24, GuiMenu.INSTANCE, "Zurück")); + this.add(new MultiLabel(10, 10, width - 20, height - 44, this.info, false)); + this.add(new NavButton((width - 280) / 2, height - 20, 280, 0, GuiMenu.INSTANCE, "Zurück")); } public String getTitle() { diff --git a/java/src/game/gui/GuiLoading.java b/client/src/main/java/client/gui/GuiLoading.java similarity index 83% rename from java/src/game/gui/GuiLoading.java rename to client/src/main/java/client/gui/GuiLoading.java index 60120f9..26f5b8a 100644 --- a/java/src/game/gui/GuiLoading.java +++ b/client/src/main/java/client/gui/GuiLoading.java @@ -1,12 +1,12 @@ -package game.gui; +package client.gui; -import game.Game; -import game.gui.element.Bar; -import game.gui.element.Label; +import client.Client; +import client.gui.element.Bar; +import client.gui.element.Label; public class GuiLoading extends Gui { public static interface Callback { - void poll(Game gm, GuiLoading gui); + void poll(Client gm, GuiLoading gui); } private final String message; @@ -19,7 +19,7 @@ public class GuiLoading extends Gui { public static GuiLoading makeServerTask(String message) { return new GuiLoading(message, new Callback() { - public void poll(Game gm, GuiLoading gui) { + public void poll(Client gm, GuiLoading gui) { int progress = gm.progress; if(progress < 0) { gui.resetBar(); @@ -35,7 +35,7 @@ public class GuiLoading extends Gui { public static GuiLoading makeWaitTask(String message) { return new GuiLoading(message, new Callback() { - public void poll(Game gm, GuiLoading gui) { + public void poll(Client gm, GuiLoading gui) { } }); } @@ -46,11 +46,11 @@ public class GuiLoading extends Gui { } public void init(int width, int height) { - this.taskLabel = this.add(new Label(0, 40, 500, 20, "")); - this.progressBar1 = this.add(new Bar(0, 80, 500, 24)); - this.progressBar2 = this.add(new Bar(0, 120, 500, 24)); + this.taskLabel = this.add(new Label(0, 40, 500, 0, "")); + this.progressBar1 = this.add(new Bar(0, 80, 500, 0)); + this.progressBar2 = this.add(new Bar(0, 120, 500, 0)); this.shift(); - this.headerLabel = this.add(new Label(0, 40, width, 20, this.message)); + this.headerLabel = this.add(new Label(0, 40, width, 0, this.message)); this.progressBar1.visible = false; this.progressBar2.visible = false; } diff --git a/java/src/game/gui/GuiMenu.java b/client/src/main/java/client/gui/GuiMenu.java similarity index 72% rename from java/src/game/gui/GuiMenu.java rename to client/src/main/java/client/gui/GuiMenu.java index 88cd839..51fda9b 100644 --- a/java/src/game/gui/GuiMenu.java +++ b/client/src/main/java/client/gui/GuiMenu.java @@ -1,21 +1,19 @@ -package game.gui; +package client.gui; -import game.color.TextColor; -import game.gui.character.GuiChar; -import game.gui.character.GuiCharacters; -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; -import game.gui.element.Label; -import game.gui.element.NavButton; -import game.gui.element.Textbox; -import game.gui.options.GuiOptions; -import game.init.Config; -import game.renderer.Drawing; -import game.rng.Random; -import game.util.ExtMath; -import game.util.Splashes; -import game.util.Timing; -import game.window.Keysym; +import client.Client; +import client.gui.character.GuiChar; +import client.gui.character.GuiCharacters; +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.Label; +import client.gui.element.NavButton; +import client.gui.element.PressType; +import client.gui.options.GuiOptions; +import client.renderer.Drawing; +import client.window.Keysym; +import common.color.TextColor; +import common.rng.Random; +import common.util.ExtMath; public class GuiMenu extends Gui { public static final GuiMenu INSTANCE = new GuiMenu(); @@ -24,10 +22,10 @@ public class GuiMenu extends Gui { } public void drawMainBackground() { - if(this.gm.theWorld != null) + if(this.gm.world != null) super.drawMainBackground(); else - this.gm.renderGlobal.renderStarField(this.gm.fb_x, this.gm.fb_y, 0x000000, 0xffffff, (float)this.ticks + (float)Timing.tick_fraction, this.rand); + this.gm.renderGlobal.renderStarField(this.gm.fb_x, this.gm.fb_y, 0x000000, 0xffffff, (float)this.ticks + this.gm.getTickFraction(), this.rand); } private final Random rand = new Random(); @@ -49,12 +47,16 @@ public class GuiMenu extends Gui { private boolean animStep; public void init(int width, int height) { - if(this.gm.theWorld == null) { + if(this.gm.world == null) { this.ticks = 0; this.hacked = 0; this.resetAnimation(); - this.add(new ActButton(0, 0, 400, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { + this.add(new ActButton(0, 0, 180, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + if(action == PressType.SECONDARY) { + GuiMenu.this.gm.joinDebugWorld(); + return; + } if(GuiMenu.this.hacked == 9) { GuiMenu.this.hacked++; GuiMenu.this.splashLabel.setText(TextColor.VIOLET + "Hax!"); @@ -64,19 +66,20 @@ public class GuiMenu extends Gui { } } }, "Server beitreten")); - this.add(new ActButton(0, 28, 400, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { + this.add(new ActButton(0, 20, 180, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { if(GuiMenu.this.hacked == 8) GuiMenu.this.hacked++; else - GuiMenu.this.gm.displayGuiScreen(GuiOptions.getPage()); + GuiMenu.this.gm.displayGuiScreen(GuiServer.INSTANCE); } - }, "Einstellungen")); - this.infoButton = this.add(new ActButton(0, 56, 400, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { + }, "Schnellverbindung")); + this.add(new NavButton(0, 40, 180, 0, GuiOptions.getPage(), "Einstellungen")); + this.infoButton = this.add(new ActButton(0, 60, 180, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { GuiMenu.this.gm.displayGuiScreen(GuiMenu.this.hacked == 10 ? GuiInfo.HAX : GuiInfo.INSTANCE); } - }, "Info / Über / Mitwirkende") { + }, "Info / Mitwirkende") { public void drawHover() { if(GuiMenu.this.hacked == 10) { Drawing.drawRect(this.pos_x, this.pos_y, this.size_x, this.size_y, 0x287f00ff); @@ -84,9 +87,9 @@ public class GuiMenu extends Gui { int width = Drawing.getWidth("Hax!"); for(int z = 0; z < 64; z++) { Drawing.drawText("Hax!", GuiMenu.this.rand.zrange(Math.max(1, this.gm.fb_x - width)) + - (int)(ExtMath.sin(((float)(GuiMenu.this.ticks + GuiMenu.this.rand.zrange(256)) + (float)Timing.tick_fraction) / 100.0f * (float)Math.PI * 2.0f) * 16.0f), + (int)(ExtMath.sin(((float)(GuiMenu.this.ticks + GuiMenu.this.rand.zrange(256)) + this.gm.getTickFraction()) / 100.0f * (float)Math.PI * 2.0f) * 16.0f), GuiMenu.this.rand.zrange(Math.max(1, this.gm.fb_y - Font.YGLYPH)) + - (int)(ExtMath.sin(((float)(GuiMenu.this.ticks + GuiMenu.this.rand.zrange(256)) + (float)Timing.tick_fraction) / 100.0f * (float)Math.PI * 2.0f) * 16.0f), + (int)(ExtMath.sin(((float)(GuiMenu.this.ticks + GuiMenu.this.rand.zrange(256)) + this.gm.getTickFraction()) / 100.0f * (float)Math.PI * 2.0f) * 16.0f), 0xff0000ff | (GuiMenu.this.rand.zrange(256) << 16)); } } @@ -95,34 +98,33 @@ public class GuiMenu extends Gui { } } }); - this.add(new NavButton(0, 102, 196, 24, GuiConvert.INSTANCE, "Welt konvertieren")); - this.add(new ActButton(204, 102, 196, 24, new ActButton.Callback() { - public void use(ActButton elem, ActButton.Mode action) { + this.add(new ActButton(0, 90, 180, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { GuiMenu.this.gm.interrupted = true; } - }, "Spiel beenden")); + }, "Client schließen")); this.shift(); - this.add(new Label(4, /* this.gm.fb_y - 2 */ 0, 200, 20, TextColor.VIOLET + Config.VERSION, true)); - this.splashLabel = this.add(new Label(0, 160, width, 24, "")); + this.add(new Label(4, 4, 200, 0, TextColor.VIOLET + Client.VERSION, true)); + this.splashLabel = this.add(new Label(0, 100, width, 0, "")); this.pickSplash(); } else { - this.add(new NavButton(0, 0, 400, 24, this.gm.charEditor ? GuiChar.INSTANCE : null, this.gm.charEditor ? "Zurück zum Charakter-Editor" : "Zurück zum Spiel")); - this.add(new NavButton(0, 28, this.gm.charEditor ? 400 : 198, 24, GuiOptions.getPage(), "Einstellungen")); + this.add(new NavButton(0, 0, 180, 0, this.gm.charEditor ? GuiChar.INSTANCE : null, this.gm.charEditor ? "Zurück zum Editor" : "Zurück zum Spiel")); + this.add(new NavButton(0, 20, 180, 0, GuiOptions.getPage(), "Einstellungen")); if(!this.gm.charEditor) - this.add(new NavButton(202, 28, 198, 24, GuiCharacters.INSTANCE, "Charakter")); - this.add(new ActButton(0, 102, 400, 24, new ActButton.Callback() { - public void use(ActButton elem, ActButton.Mode action) { + this.add(new NavButton(0, 40, 180, 0, GuiCharacters.INSTANCE, "Charakter")); + this.add(new ActButton(0, this.gm.charEditor ? 50 : 70, 180, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { GuiMenu.this.gm.unload(true); // GuiMenu.this.gm.displayGuiScreen(INSTANCE); } - }, "Server verlassen und Verbindung trennen")); + }, "Server verlassen")); this.shift(); } } public String getTitle() { - return this.gm.theWorld == null ? "Hauptmenü" : "Menü"; + return this.gm.world == null ? "Hauptmenü" : "Menü"; } private void pickSplash() { @@ -225,9 +227,9 @@ public class GuiMenu extends Gui { } public void updateScreen() { - if(this.gm.theWorld == null) { + if(this.gm.world == null) { this.ticks++; - if(this.gm.shift() && !(this.selected instanceof Textbox)) + if(this.gm.shift()) this.pickSplash(); this.updateAnimation(); } @@ -235,7 +237,7 @@ public class GuiMenu extends Gui { public void key(Keysym key, boolean ctrl, boolean shift) { super.key(key, ctrl, shift); - if(this.gm.theWorld == null) { + if(this.gm.world == null) { if((key == Keysym.UP || key == Keysym.W) && (this.hacked == 0 || this.hacked == 1)) this.hacked++; else if((key == Keysym.DOWN || key == Keysym.S) && (this.hacked == 2 || this.hacked == 3)) @@ -289,8 +291,8 @@ public class GuiMenu extends Gui { public void drawOverlays() { super.drawOverlays(); - if(this.gm.theWorld == null) { - int y = 164; + if(this.gm.world == null) { + int y = 99; int h = 16; int n = Drawing.getWidth(this.splashLabel.getText()); Drawing.drawRect(0, y, this.gm.fb_x / 2 - n / 2 - 10, h, 0x7f7f00ff); diff --git a/client/src/main/java/client/gui/GuiServer.java b/client/src/main/java/client/gui/GuiServer.java new file mode 100644 index 0000000..a15b796 --- /dev/null +++ b/client/src/main/java/client/gui/GuiServer.java @@ -0,0 +1,279 @@ +package client.gui; + +import java.security.KeyPair; +import java.security.PublicKey; +import client.gui.GuiConnect.ServerInfo; +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.Element; +import client.gui.element.Label; +import client.gui.element.NavButton; +import client.gui.element.PasswordField; +import client.gui.element.PressType; +import client.gui.element.Toggle; +import client.gui.element.FieldAction; +import client.gui.element.Field; +import client.gui.element.FieldCallback; +import client.vars.CVarCategory; +import client.vars.Variable; +import client.window.Window; +import common.color.TextColor; +import common.network.IPlayer; +import common.util.EncryptUtil; + +public class GuiServer extends Gui implements FieldCallback { + public static final GuiServer INSTANCE = new GuiServer(null); + + private final ServerInfo server; + + private Field nameBox; + private Field addrBox; + private Field portBox; + private Field userBox; + private PasswordField passBox; + private PasswordField accBox; + private Label nameLabel; + private Label addrLabel; + private Label portLabel; + private Label rangeLabel; + private Label userLabel; + private Label passLabel; + private Label accLabel; + private Label keyLabel; + private Label idLabel; + private Toggle encToggle; + private ActButton keyButton; + private ActButton resetButton; + private ActButton copyKeyButton; + private ActButton copyIdButton; + private KeyPair keypair; + private String keyDigest; + private PublicKey serverKey; + private String serverDigest; + + public GuiServer(ServerInfo server) { + this.server = server; + } + + @Variable(name = "srv_last_address", category = CVarCategory.SYSTEM, min = 1, max = 128, display = "Letzte Server-Adresse") + private String lastAddr = ""; + @Variable(name = "srv_last_port", category = CVarCategory.SYSTEM, min = 1024, max = 32767, display = "Letzter Server-Port") + private int lastPort = -1; + @Variable(name = "srv_last_user", category = CVarCategory.SYSTEM, max = IPlayer.MAX_USER_LENGTH, display = "Letzter Server-Nutzer", validator = IPlayer.UserValidator.class) + private String lastUser = ""; + @Variable(name = "srv_last_password", category = CVarCategory.SYSTEM, max = IPlayer.MAX_PASS_LENGTH, display = "Letztes Server-Passwort") + private String lastPass = ""; + @Variable(name = "srv_last_access", category = CVarCategory.SYSTEM, max = IPlayer.MAX_PASS_LENGTH, display = "Letzter Server-Zugang") + private String lastAcc = ""; + + public void init(int width, int height) { + if(this.server != null) { + this.nameBox = this.add(new Field(0, 0, 400, 0, 128, this, this.server.getName())); + this.nameLabel = this.add(new Label(0, 0, 410, "Name in der Liste", true)); + this.keypair = this.server.getKeypair(); + this.keyDigest = this.keypair == null ? null : EncryptUtil.getXorSha512Hash(this.keypair.getPublic().getEncoded()); + } + this.addrBox = this.add(new Field(0, 34, 400, 0, 128, this, this.server == null ? this.lastAddr : this.server.getAddress())); + this.addrLabel = this.add(new Label(0, 34, 410, "Adresse / Hostname", true)); + int port = this.server == null ? this.lastPort : this.server.getPort(); + this.portBox = this.add(new Field(404, 34, 76, 0, 5, this, port < 0 ? "" : "" + port)); + this.portLabel = this.add(new Label(404, 34, 76, "Port", true)); + this.rangeLabel = this.add(new Label(370, 34 + Element.BASE_HEIGHT, 110, 0, "[1024..32767]", true)); + this.userBox = this.add(new Field(0, 68, 220, 0, IPlayer.MAX_USER_LENGTH, this, IPlayer.VALID_USER, this.server == null ? this.lastUser : this.server.getUser())); + this.userLabel = this.add(new Label(0, 68, 220, "Benutzername", true)); + this.passBox = this.add(new PasswordField(0, this.server == null ? 102 : 136, 480, 0, IPlayer.MAX_PASS_LENGTH, this, this.server == null ? this.lastPass : this.server.getPassword())); + this.passLabel = this.add(new Label(0, this.server == null ? 102 : 136, 480, (this.keypair == null ? "Anmelde" : "Ersatz") + "-Passwort (mind. 8 Zeichen)", true)); + this.accBox = this.add(new PasswordField(0, this.server == null ? 136 : 170, 480, 0, IPlayer.MAX_PASS_LENGTH, this, this.server == null ? this.lastAcc : this.server.getAccess())); + this.accLabel = this.add(new Label(0, this.server == null ? 136 : 170, 480, "Server-Passwort (mind. 8 Zeichen)", true)); + this.add(new ActButton(241, this.server == null ? 166 : 254, 239, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + GuiServer.this.connect(); + } + }, this.server == null ? "Verbinden" : (this.server.getName().isEmpty() ? "Hinzufügen" : "Übernehmen"))); + this.add(new NavButton(0, this.server == null ? 166 : 254, 239, 0, this.server != null ? GuiConnect.INSTANCE : GuiMenu.INSTANCE, "Zurück")); + if(this.server != null) { + this.keyButton = this.add(new ActButton(0, 102, 391, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + if(GuiServer.this.keypair == null) { + GuiServer.this.keypair = EncryptUtil.createKeypair(); + GuiServer.this.keyDigest = EncryptUtil.getXorSha512Hash(GuiServer.this.keypair.getPublic().getEncoded()); + GuiServer.this.keyLabel.setText("Anmelde-Pubkey: " + EncryptUtil.KEY_ALGO_DISPLAY + " " + GuiServer.this.keyDigest); + GuiServer.this.keyButton.setText("Schlüsselpaar entfernen"); + GuiServer.this.passLabel.setText("Ersatz-Passwort (mind. 8 Zeichen)"); + GuiServer.this.copyKeyButton.enabled = true; + } + else { + final String name = GuiServer.this.nameBox.getText(); + final String addr = GuiServer.this.addrBox.getText(); + final String port = GuiServer.this.portBox.getText(); + final String pass = GuiServer.this.passBox.getText(); + final String acc = GuiServer.this.accBox.getText(); + final boolean reqEnc = GuiServer.this.encToggle.getValue(); + final KeyPair keys = GuiServer.this.keypair; + final PublicKey key = GuiServer.this.serverKey; + final String digest = GuiServer.this.keyDigest; + final String sdigest = GuiServer.this.serverDigest; + GuiServer.this.gm.displayGuiScreen(new GuiConfirm(new GuiConfirm.Callback() { + public void confirm(boolean confirmed) { + GuiServer.this.gm.displayGuiScreen(GuiServer.this); + GuiServer.this.nameBox.setText(name); + GuiServer.this.addrBox.setText(addr); + GuiServer.this.portBox.setText(port); + GuiServer.this.passBox.setText(pass); + GuiServer.this.accBox.setText(acc); + GuiServer.this.encToggle.setValue(reqEnc); + GuiServer.this.serverKey = key; + GuiServer.this.serverDigest = sdigest; + GuiServer.this.idLabel.setText("Server-Pubkey: " + (key != null ? EncryptUtil.KEY_ALGO_DISPLAY + " " + GuiServer.this.serverDigest : "nicht vorhanden")); + GuiServer.this.resetButton.enabled = key != null; + GuiServer.this.copyIdButton.enabled = key != null; + GuiServer.this.copyKeyButton.enabled = !confirmed; + if(confirmed) { + GuiServer.this.keypair = null; + GuiServer.this.keyDigest = null; + GuiServer.this.keyLabel.setText("Anmelde-Pubkey: nicht vorhanden"); + GuiServer.this.keyButton.setText("Neues Schlüsselpaar generieren"); + GuiServer.this.passLabel.setText("Anmelde-Passwort (mind. 8 Zeichen)"); + } + else { + GuiServer.this.keypair = keys; + GuiServer.this.keyDigest = digest; + GuiServer.this.keyLabel.setText("Anmelde-Pubkey: " + EncryptUtil.KEY_ALGO_DISPLAY + " " + GuiServer.this.keyDigest); + GuiServer.this.keyButton.setText("Schlüsselpaar entfernen"); + GuiServer.this.passLabel.setText("Ersatz-Passwort (mind. 8 Zeichen)"); + } + } + }, "Schlüsselpaar wirklich entfernen?", "Wenn das Schlüsselpaar gelöscht wird, ist es nicht mehr möglich, sich damit\nauf dem Server zu identifizieren und sich anzumelden.\nDamit könnte der Zugriff auf den Server unmöglich werden.", "Schlüsselpaar löschen", "Abbrechen")); + } + } + }, this.keypair == null ? "Neues Schlüsselpaar generieren" : "Schlüsselpaar entfernen")); + this.copyKeyButton = this.add(new ActButton(395, 102, 85, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + if(GuiServer.this.keypair != null) + Window.setClipboard(EncryptUtil.getArmoredPubkey(GuiServer.this.keypair.getPublic(), GuiServer.this.userBox.getText())); + } + }, "Kopieren")); + this.copyKeyButton.enabled = this.keypair != null; + this.keyLabel = this.add(new Label(0, 102, 480, "Anmelde-Pubkey: " + (this.keypair != null ? EncryptUtil.KEY_ALGO_DISPLAY + " " + this.keyDigest : "nicht vorhanden"), true)); + this.encToggle = this.add(new Toggle(0, 190, 480, 0, false, this.server.requiresEncryption(), null, "Nur Verschlüsselte Verbindung akzeptieren")); + this.serverKey = this.server.getServerKey(); + this.serverDigest = this.serverKey == null ? null : EncryptUtil.getXorSha512Hash(this.serverKey.getEncoded()); + this.resetButton = this.add(new ActButton(0, 224, 391, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + if(GuiServer.this.serverKey != null) { + GuiServer.this.serverKey = null; + GuiServer.this.serverDigest = null; + GuiServer.this.idLabel.setText("Server-Pubkey: nicht vorhanden"); + GuiServer.this.resetButton.enabled = false; + GuiServer.this.copyIdButton.enabled = false; + } + } + }, "Server-Identifizierung / Pubkey zurücksetzen")); + this.resetButton.enabled = this.serverKey != null; + this.copyIdButton = this.add(new ActButton(395, 224, 85, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + if(GuiServer.this.serverKey != null) + Window.setClipboard(EncryptUtil.getArmoredPubkey(GuiServer.this.serverKey, GuiServer.this.nameBox.getText())); + } + }, "Kopieren")); + this.copyIdButton.enabled = this.serverKey != null; + this.idLabel = this.add(new Label(0, 224, 480, "Server-Pubkey: " + (this.serverKey != null ? EncryptUtil.KEY_ALGO_DISPLAY + " " + this.serverDigest : "nicht vorhanden"), true)); + } + this.shift(); + } + + public String getTitle() { + return this.server == null ? "Mit Server verbinden" : (this.server.getName().isEmpty() ? "Server hinzufügen" : "Server bearbeiten"); + } + + private void connect() { + if(this.gm.world != null) + return; + String name = null; + if(this.server != null) { + name = this.nameBox.getText(); + if(name.isEmpty()) { + this.nameLabel.setText(TextColor.RED + "Name in der Liste"); + return; + } + if(GuiConnect.INSTANCE.isNameTaken(name)) { + this.nameLabel.setText("Name in der Liste - " + TextColor.RED + "Bereits vorhanden"); + return; + } + } + String addr = this.addrBox.getText(); + if(addr.isEmpty()) { + this.addrLabel.setText(TextColor.RED + "Adresse / Hostname"); + return; + } + int port = -1; + if(this.portBox.getText().isEmpty()) { + this.portLabel.setText(TextColor.RED + "Port"); + return; + } + else { + try { + port = Integer.parseInt(this.portBox.getText()); + } + catch(NumberFormatException e) { + this.rangeLabel.setText("[" + TextColor.RED + "1024..32767" + TextColor.RESET + "]"); + return; + } + if(port < 1024 || port > 32767) { + this.rangeLabel.setText("[" + (port < 1024 ? TextColor.RED + "1024" + TextColor.RESET + "..32767" : "1024.." + TextColor.RED + "32767" + TextColor.RESET) + "]"); + return; + } + } + String user = this.userBox.getText(); + if(user.isEmpty()) { + this.userLabel.setText(TextColor.RED + "Benutzername"); + return; + } + String pass = this.passBox.getText(); + if(!pass.isEmpty() && pass.length() < 8) { + this.passLabel.setText((this.keypair == null ? "Anmelde" : "Ersatz") + "-Passwort (" + TextColor.RED + "mind. 8 Zeichen" + TextColor.RESET + ")"); + return; + } + String acc = this.accBox.getText(); + if(!acc.isEmpty() && acc.length() < 8) { + this.accLabel.setText("Zugang (" + TextColor.RED + "mind. 8 Zeichen" + TextColor.RESET + ")"); + return; + } + if(this.server == null) { + this.lastAddr = addr; + this.lastPort = port; + this.lastUser = user; + this.lastPass = pass; + this.lastAcc = acc; + this.gm.setDirty(); + GuiConnect.INSTANCE.connect(addr, port, user, pass, acc); + } + else { + this.server.setData(name, addr, port, user, pass, acc, this.keypair, this.serverKey, this.encToggle.getValue()); + GuiConnect.INSTANCE.applyServer(this.server); + } + } + + public void use(Field elem, FieldAction value) { + if(value == FieldAction.SEND) { + elem.setDeselected(); + this.connect(); + } + else if(value == FieldAction.FOCUS) { + if(elem == this.addrBox) + this.addrLabel.setText("Adresse / Hostname"); + else if(elem == this.portBox) { + this.portLabel.setText("Port"); + this.rangeLabel.setText("[1024..32767]"); + } + else if(elem == this.userBox) + this.userLabel.setText("Benutzername"); + else if(elem == this.passBox) + this.passLabel.setText((this.keypair == null ? "Anmelde" : "Ersatz") + "-Passwort (mind. 8 Zeichen)"); + else if(elem == this.accBox) + this.accLabel.setText("Server-Passwort (mind. 8 Zeichen)"); + else if(this.server != null && elem == this.nameBox) + this.nameLabel.setText("Name in der Liste"); + } + } +} diff --git a/java/src/game/util/Splashes.java b/client/src/main/java/client/gui/Splashes.java similarity index 75% rename from java/src/game/util/Splashes.java rename to client/src/main/java/client/gui/Splashes.java index 47a33c6..de6257e 100644 --- a/java/src/game/util/Splashes.java +++ b/client/src/main/java/client/gui/Splashes.java @@ -1,36 +1,35 @@ -package game.util; +package client.gui; public abstract class Splashes { public static final String[] SPLASHES = { - "Aus der TV-Werbung!", - "Toll!", + "Aus der Toiletten-Werbung!", "0% pur!", "Kann Nüsse enthalten!", - "Besser als Crysis!", + "Kann *.,-#+~ enthalten!", "Mehr Polygone!", "Sexy!", "Limitierte Edition!", "Blinkende Buchstaben!", - "Erstellt von Notch!", - "Es ist hier!", - "Das Beste seiner Klasse!", - "Es ist vollendet!", + "Erstellt von Satan!", + "Er ist hier!", + "Das Schlimmste seiner Klasse!", + "Es ist vollendet (nicht)!", "Mehr oder weniger frei von Drachen!", "Aufregung!", "Weniger als -5 verkauft!", "Einzigartig!", "Einen Haufen Scheiße auf YouTube!", - "Indev!", + "Dev!", + "Alpha!", + "Beta!", "Spinnen überall!", "Schau es dir an!", "Heilige Kuh, mann!", "Es ist ein Spiel!", - "Hergestellt in Schweden!", + "Hergestellt im Schattenland!", "Benutzt LWJGL!", "Retikulierende Splinen!", - "Meine Kraft!", "Hurraaa!", - "Einzelspieler!", "Tastatur ist kompatibel!", "Undokumentiert!", "Barren!", @@ -41,17 +40,14 @@ public abstract class Splashes { "Überlebe!", "Verlies!", "Exklusiv!", - "Die Knie der Biene!", - "Weg mit O.P.P.!", "Mit Quellcode (mehr oder weniger)!", "Mit Klasse(n)!", "Wow!", - "Immer noch nicht auf Steam - und das ist auch gut so!", + "Niemals auf Steam - und das ist auch gut so!", "Oh, mann!", "Grauenvolle Community!", "Pixel!", - "Teetsuuuuoooo!", - "Kaaneeeedaaaa!", + "Garfiiieeeeeeeld!", "Jetzt ohne Schwierigkeit!", "Verbessert!", "9% frei von Bugs!", @@ -59,31 +55,26 @@ public abstract class Splashes { "13 Kräuter und Gewürze!", "Fettfrei!", "Absolut keine Memes!", - "Kostenlose Zähne!", + "Kostenlose Vampirzähne!", "Fragen Sie Ihnen Arzt oder Apotheker!", "Alle Bergleute sind willkommen!", "Cloud-Computing!", - "Legal in Finnland!", + "Frei von \"\"KI\"\"!", + "Legal in Norwegen!", + "Illegal in China!", "Schwer zu beschreiben!", "Technisch gesehen gut!", - "Bringe den Speck nach Hause!", "Indie!", - "GOTY!", - "Ceci n'est pas une title screen!", "Euklidisch!", - "Jetzt in 3D!", + "Jetzt in 4D?!", "Bietet Inspiration!", - "Herregud!", - "Komplexe Zellvorgänge!", "Ja, Sir!", - "Von Cowboys gespielt!", + "Ja, Miss!", + "Von Trollen gespielt!", "OpenGL 1.5 oder höher!", - "Tausende von Farben!", + "Millionen von Farben!", "Probiere es!", - "Age of Wonders ist besser!", - "Probiere die Pilzsuppe!", "Sensationell!", - "Heiße Tamale, heiße heiße Tamale!", "Spiele ihn runter, Klavierkatze!", "Garantiert!", "Makroskopisch!", @@ -94,27 +85,22 @@ public abstract class Splashes { "Von Melonen geliebt!", "Ultimative Edition!", "Merkwürdig!", - "Du hast einen nagelneuen Schlüssel bekommen!", "Wasserfest!", "Nicht brennbar!", "Oha, du!", "Alles inklusive!", "Sag es deinen Freunden!", "NP ist nicht in P!", - "Musik von C418 (DLC)!", - "Viel zu oft live gestreamt!", "Heimgesucht!", "Polynomial!", "Terrestrisch!", "Alles ist voller Zerstörung!", "Voll mit Sternen, Planeten und Monden!", "Wissenschaftlich!", - "Nicht so cool wie Spock!", "Trage nix bei und höre weg!", "Grabe niemals nach unten, wenn du keine Erze brauchst!", "Mache nie Pause!", "Nicht linear!", - "Han hat zuerst geschossen!", "Schön dich zu sehen!", "Eimer mit Lava!", "Reite auf dem Schwein!", @@ -124,25 +110,18 @@ public abstract class Splashes { "Holz schlagen!", "Von Klippen fallen!", "0% Zucker!", - "150% hyperbol!", - "Synecdoche!", + "180% Alkohol!", "Lasst uns tanzne!", - "Geheeimes Freitags-Update!", "Referenz-Implementation!", "Frei mit zwei.. äähhh fünf Typen mit Essen!", "Küsse den Himmel!", "20 GOTO 10!", - "Verlet-Intregration!", - "Peter Griffin!", "Verteile die Erde gut!", - "Cogito ergo sum!", - "4815162342 Zeilen Quellcode (287228 am 30.7.)!", + "8263273626252622872652 Zeilen Quellcode (287228 am 30.7.)!", "Ein Skelett fiel heraus!", - "Das Werk von Notch!", + "Das Werk von Luzifer!", "Die Summe seiner Teile!", - "BTAF war mal gut!", - "Ich vermisse ADOM!", - "umop-apisdn!", + "mureh srednA!", "GTX750Ti!", "Bringe mir Mentos und Cola!", "Finger-leckend!", @@ -162,25 +141,16 @@ public abstract class Splashes { "Doppelt gepuffert!", "Fan-Fiction!", "Flaxkikare!", - "Jason! Jason! Jason!", "Heißer als die Sonne!", "Internet-Funktionalität!", "Autonom!", "Engagiere!", "Fantasie!", - "DRR! DRR! DRR!", + "Mau! Mau! Mau!", "Stoß es Wurzel runter!", "Regionale Ressourcen!", - "Jaa, facepunch!", - "Jaa, somethingawful!", - "Jaa, /v/!", - "Jaa, tigsource!", - "Jaa, weinkraftforum!", - "Jaa, worldofweinkraft!", - "Buu, reddit!", - "Jaa, 2pp!", "Goggle anllyticsed:DD :DDD:D!", - "Unterstützt jetzt äöü!", + "Unterstützt jetzt äöüß!", "Gebt uns Gordon!", "Gib deinem Kellner Trinkgeld!", "Macht viel Spaß!", @@ -191,15 +161,12 @@ public abstract class Splashes { "Allmächtig!", "Huch!", "...!", - "Bienen, Bienen, Bienen, Bienen!", - "Jag känner en bot!", + "Bienen, Mienen, Minen, W-!", "Dieser Text ist schwer bei der Standard-Auflösung zu lesen, aber auf 1080p ist es in Ordnung!", "Haha, LOL!", "Hampsterdance!", "Schalter und Erze!", "Menger-Schwamm!", - "idspispopd!", - "Eple (originale Version)!", "So frisch, so sauber!", "Schnell reagierende Portale!", "Probiere den Warp aus!", @@ -207,10 +174,9 @@ public abstract class Splashes { "Oh, ok, NPCs!", "Endlich mit Leitern!", "Gruselig!", - "Spiele Minenkraft, schaue Topgear, bekomme Schwein!", "Darüber gewittert!", "Spring hoch, spring hoch, und komme runter!", - "Joel ist klasse!", + "Strahlung ist klasse!", "Ein Rätsel, in einen Mythos verwoben!", "Riesige Landeszüge voll mit TNT!", "Willkommen zu deinem Ende! Muahahahahahaha!", @@ -222,23 +188,21 @@ public abstract class Splashes { "\"Fast nie\" ist ein interessantes Konzept!", "Eine Menge Wahrheitigkeit!", "Der TNT-Block ist ein Spion!", - "Turing-vollständig!", + "Turing-unvollständig!", "Es ist bahnbrechend!", "Lasst unsere Schlachten beginnen!", "Der Himmel ist die Grenze - oder auch nicht!", - "Jeb hat tolle Haare!", - "Ryan hat auch tolle Haare!", + "Dein PC hat tolle Haare, mach das Ding mal sauber!", + "Shen hat auch tolle Haare!", "Gelegentliches Spielen!", "Unbesiegt!", "Ein Bisschen wie Lemmings!", "Folge dem Zug, CJ!", "Macht von Synergie Verwendung!", - "Diese Nachricht wird niemals als Splash-Text erscheinen, ist das nicht komisch?", - "DungeonQuest ist unfair!", + "Diese Nachricht sollte niemals als Splash-Text erscheinen, oder etwa doch? Trololololol!", "0815!", "666!", "Geh zu den fernen Ländern und weiter!", - "Tyrion würde es lieben!", "Probiere auch Stellaris!", "Probiere auch Garry's Mod!", "Probiere auch GZDoom!", @@ -252,52 +216,43 @@ public abstract class Splashes { "Brot ist Schmerz!", "Lese mehr Bücher!", "Khaaaaaaaaan!", - "Weniger süchtig machend als TV Tropes!", + "Weniger süchtig machend als [zensiert da NSFW]!", "Mehr süchtig machend als Limonade!", "Größer als eine Brotkiste!", "Millionen von Pfirsichen!", - "Fnord!", "Dies ist meine echte Gestalt! Muahahahaha!", - "Habe Dre vollkommen vergessen!", - "Verschwende keine Zeit mit den Klonen!", - "Kürbiskopf!", - "Hobo humping slobo babe!", - "Erstellt von Jeb!", + "Verschwende keine Zeit mit \"\"KI\"\"!", + "Erstellt von einer Katze!", "Hat kein Ende!", "Endlich vollständig!", "Voll mit Features!", "Stiefel mit dem Fell!", "Stop, hammertime!", - "Testificates!", + "Test!", "Nicht konventionell!", - "Homeomorphisch zu einer 3-Kugel!", + "Nicht kommerziell!", "Vermeidet nicht doppelte Verneinung!", "Platziere ALL die Blöcke!", "Macht Walzen!", "Erfüllt Erwartungen!", - "Spielen am PC seit 1873!", - "Ghoughpteighbteau tchoghs!", + "Spielen am PC seit 1992!", "Deja vu!", "Deja vu!", "Hab deine Nase!", - "Haley liebt Elan!", "Hat keine Angst vor der großen, schwarzen Fledermaus!", "Benutzt nicht das U-Wort!", "Nicht wirklich leicht!", "Bis nächsten Freitag oder so!", - "Von den Straßen von Södermalm!", - "150 BPM für 400000 Minuten!", + "Von den Straßen von Nibelheim!", "Technologisch!", - "Funk Soul Bruder!", - "Pumpa kungen!", - "Hallo Japan!", + "Hallo Japan!", "Hallo Korea!", "Hallo Wales!", "Hallo Polen!", - "Hallo China!", + "Hallo China!", "Hallo Russland!", "Hallo Griechenland!", - "Mein Leben für Aiur!", + "Mein Leben für Aiur (warte mal..)!", "Lenny lenny = new Lenny(\"(°^°)\");", "Ich sehe dein Wortschatz hat sich verbessert!", "Wer hat es dort hin getan?", @@ -305,14 +260,14 @@ public abstract class Splashes { "if not ok then return end", "Mehrfarbig!", "FUNKY LOL", - "SOPA bedeutet LOSER in Schwedisch!", + "Copyright bedeutet LOSER in allen Sprachen!", "Große Spitze Zähne!", "Mein Shizun bewacht das Tor!", "Mmmph, mmph!", - "Füttere keine Avocados an Papageien!", + "Füttere keine Landminen an Piranhas!", "Schwerter für alle!", "Bitteee antworte meinem Tweet! (Nutzer wurde gebannt)", - ".party()!", + ".party().crash().commitWarcrimes().forTheEmperor()!", "Nehme ihr Kissen!", "Lege diesen Keks weg!", "Extrem gruselig!", @@ -320,26 +275,21 @@ public abstract class Splashes { "Jetzt mit extra Sprengstoff!", "Nicht kompatibel zu Java 6!", "Oha.", - "HURNERJSGER?", "Was'n los, Doc?", "Enthält jetzt 0 zufällige tägliche Katzen!", - "Das ist Numberwang!", "((pls rt)) -- Der Vogel ist tot!", "Willst du meinem Server beitreten?", "Mach einen großen Zaun drum herum! Oder du wirst v-", "Lege eine Landmine drüber!", - "Eines Tages, irgendwann in der Zukunft, wird mein Werk zitiert werden!", + "Eines Tages, irgendwann in der Zukunft, wird mein Werk r3- ÄÄHHH kopiert werden!", "Jetzt mit zusätzlichem Zeug!", "Zusätzliche Dinge!", "Hurra, Atombomben für alle!", - "So süß, wie ein schöner Bon-Bon!", - "Poppende Tags!", + "So süß, wie ein schöner ****!", "Sehr einflussreich in seinem Kreis!", "Jetzt mit Mehrspieler!", "Stehe aus deinem Grab auf!", "Warnung! Ein großes Kampfschiff \"SHEN\" nähert sich schnell!", - "Der blaue Krieger hat das Essen beschossen!", - "Renn, Feigling! Ich hunger!", "Geschmack ohne Würze!", "Seltsam, aber nicht fremd!", "Härter als Diamanten, Reich wie Creme!", @@ -355,14 +305,13 @@ public abstract class Splashes { "Bau mir einen Tisch, einen funkigen Tisch!", "Nehm den Aufzug in die Hölle!", "Hör auf vernünftig zu sein, das hier ist das Internet!", - "/give @a tnt 67108864 7", + "/give * tnt 67108864 7", "Das ist gut für 3D Realms.", "Jeder Computer ist ein Laptop, wenn du tapfer genug bist!", "Mach es alles, jede Sache!", "Wo ist kein Licht, da kann Spinne!", "GNU Terry Pratchett", - "Jetzt Java 8!", - "MeinKraft!", + "Jetzt Java 21!", "Immer noch zu viele Bugs!", "Wird nicht laggen!", "Er hat es ruiniert!", @@ -370,7 +319,6 @@ public abstract class Splashes { "OpenGL 2.0+ (definitiv nicht unterstützt)!", "Keine Segfaults (nicht) möglich!", "Keine Abstürze (un)möglich!", - "Alpha!", "Enthält Bugs!", "Enthält Mäuse!", "Enthält Gewalt!", @@ -379,6 +327,7 @@ public abstract class Splashes { "Du hattest eine. aufgabe.", "Spinnen können TNT1 A 0 sein!", "RTFM!", + "Hex, nur mit mehr Ameisen!", "Vorherrschaft des Imperiums!", "Vorherrschaft der Eldar!", "Vorherrschaft der Drukhari!", @@ -409,6 +358,11 @@ public abstract class Splashes { "Eimer mit Wasser!", "Hergestellt in Deutschland!", "Hergestellt in China!", - "Jetzt mit Einzelspieler!" + "Jetzt ohne Einzelspieler!", + "Jetzt mit tieferen Schluchten!", + "Was bist du denn für ein hübsches Ding?", + "[TEXT ZENSIERT]", + "Mehr Energie!", + "Maximale Energie!" }; } diff --git a/java/src/game/gui/Style.java b/client/src/main/java/client/gui/Style.java similarity index 89% rename from java/src/game/gui/Style.java rename to client/src/main/java/client/gui/Style.java index cd69dd2..f9a2753 100644 --- a/java/src/game/gui/Style.java +++ b/client/src/main/java/client/gui/Style.java @@ -1,12 +1,12 @@ -package game.gui; +package client.gui; -import game.properties.IStringSerializable; -import game.util.Displayable; -import game.vars.CVarCategory; -import game.vars.Variable; -import game.vars.Variable.IntType; +import client.vars.CVarCategory; +import client.vars.Variable; +import client.vars.Variable.IntType; +import common.util.Displayable; +import common.util.Identifyable; -public enum Style implements IStringSerializable, Displayable { +public enum Style implements Identifyable, Displayable { DEFAULT("default", "Standard"), SHINY("shiny", "Glänzend"), GRAY("gray", "Grau"), BLUE("blue", "Blau"), CUSTOM("custom", "Angepasst"); public final String id; @@ -17,9 +17,9 @@ public enum Style implements IStringSerializable, Displayable { this.name = name; } - @Variable(type = IntType.COLOR, name = "color_border_top", category = CVarCategory.GUI, display = "Umrahmung oben / l.") + @Variable(type = IntType.COLOR, name = "color_border_top", category = CVarCategory.GUI, display = "Umrahmung A") public int brdr_top; - @Variable(type = IntType.COLOR, name = "color_border_btm", category = CVarCategory.GUI, display = "Umrahmung unten / r.") + @Variable(type = IntType.COLOR, name = "color_border_btm", category = CVarCategory.GUI, display = "Umrahmung B") public int brdr_btm; @Variable(type = IntType.COLOR, name = "color_button_top", category = CVarCategory.GUI, display = "Knopf oben") diff --git a/java/src/game/gui/character/GuiChar.java b/client/src/main/java/client/gui/character/GuiChar.java similarity index 64% rename from java/src/game/gui/character/GuiChar.java rename to client/src/main/java/client/gui/character/GuiChar.java index b2d9b5a..33cc771 100755 --- a/java/src/game/gui/character/GuiChar.java +++ b/client/src/main/java/client/gui/character/GuiChar.java @@ -1,4 +1,4 @@ -package game.gui.character; +package client.gui.character; import java.awt.image.BufferedImage; import java.io.File; @@ -8,61 +8,67 @@ import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.util.Arrays; + import javax.imageio.ImageIO; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import game.Game; -import game.Game.FileMode; -import game.collect.Lists; -import game.dimension.DimType; -import game.dimension.Dimension; -import game.entity.npc.Alignment; -import game.entity.npc.CharacterInfo; -import game.entity.npc.EntityHuman; -import game.entity.npc.EntityNPC; -import game.entity.npc.SpeciesInfo; -import game.entity.types.EntityLiving; -import game.gui.GuiLoading; -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; -import game.gui.element.Element; -import game.gui.element.GuiList; -import game.gui.element.Label; -import game.gui.element.ListEntry; -import game.gui.element.NavButton; -import game.gui.element.Slider; -import game.gui.element.Textbox; -import game.gui.element.TransparentBox; -import game.gui.element.Textbox.Action; -import game.init.EntityEggInfo; -import game.init.EntityRegistry; -import game.init.SpeciesRegistry; -import game.init.UniverseRegistry; -import game.init.SpeciesRegistry.ModelType; -import game.log.Log; -import game.network.Player; -import game.packet.CPacketAction; -import game.packet.CPacketMessage; -import game.packet.CPacketSkin; -import game.properties.IStringSerializable; -import game.renderer.Drawing; -import game.renderer.GlState; -import game.renderer.ItemRenderer; -import game.renderer.entity.RenderManager; -import game.renderer.texture.EntityTexManager; -import game.rng.Random; -import game.util.Displayable; -import game.util.FileCallback; -import game.util.FileUtils; -import game.util.SkinConverter; -import game.util.Util; -import game.vars.CVarCategory; -import game.vars.EnumVar; -import game.vars.EnumVar.EnumFunction; -import game.vars.Variable; -import game.window.Button; +import client.Client; +import client.Client.FileMode; +import client.gui.FileCallback; +import client.gui.Font; +import client.gui.GuiLoading; +import client.gui.element.ActButton; +import client.gui.element.Element; +import client.gui.element.GuiList; +import client.gui.element.Label; +import client.gui.element.ListEntry; +import client.gui.element.MultiLabel; +import client.gui.element.NavButton; +import client.gui.element.PressType; +import client.gui.element.Slider; +import client.gui.element.SliderCallback; +import client.gui.element.FieldAction; +import client.gui.element.Area; +import client.gui.element.ButtonCallback; +import client.gui.element.Field; +import client.gui.element.FieldCallback; +import client.renderer.Drawing; +import client.renderer.GlState; +import client.renderer.ItemRenderer; +import client.renderer.entity.RenderManager; +import client.renderer.texture.EntityTexManager; +import client.util.FileUtils; +import client.util.SkinConverter; +import client.vars.CVarCategory; +import client.vars.EnumVar; +import client.vars.Variable; +import client.vars.EnumVar.EnumFunction; +import client.window.Button; +import common.collect.Lists; +import common.dimension.DimType; +import common.dimension.Dimension; +import common.entity.npc.Alignment; +import common.entity.npc.CharacterInfo; +import common.entity.npc.EntityHuman; +import common.entity.npc.EntityNPC; +import common.entity.npc.SpeciesInfo; +import common.entity.types.EntityLiving; +import common.init.EntityInfo; +import common.init.EntityRegistry; +import common.init.SpeciesRegistry; +import common.init.UniverseRegistry; +import common.init.SpeciesRegistry.ModelType; +import common.log.Log; +import common.network.IPlayer; +import common.packet.CPacketAction; +import common.packet.CPacketMessage; +import common.packet.CPacketSkin; +import common.rng.Random; +import common.util.Displayable; +import common.util.Identifyable; +import common.util.Util; public class GuiChar extends GuiList { @@ -96,7 +102,7 @@ public class GuiChar extends GuiList } } - public void draw(int x, int y, int mouseX, int mouseY, boolean hovered) + public void draw(int x, int y, int width, int height, int mouseX, int mouseY, boolean hovered) { String str = (this.skinFile != null ? this.skinFile.getName() : ( @@ -108,7 +114,7 @@ public class GuiChar extends GuiList Drawing.drawText(str, x + 64 + 3, y, 0xff000000 | (this.charinfo == null ? 0xffffff : this.charinfo.color1 | this.charinfo.color2)); if(this.charinfo != null) - Drawing.drawText(this.charinfo.skin, x + 64 + 3, y + 18, 0xffc0c0c0); + Drawing.drawTextRight(this.charinfo.skin, x + width - 2, y + height - Font.YGLYPH, 0xffc0c0c0); GlState.color(1.0F, 1.0F, 1.0F, 1.0F); @@ -128,7 +134,7 @@ public class GuiChar extends GuiList EntityTexManager.altLayer = this.dynId; EntityTexManager.altNpcLayer = this.dynId == -1 && this.charinfo != null ? this.charinfo.skin : null; drawEntity(x + 32, y + 60, 28.0f - * Math.min(1.8f / GuiChar.this.gm.thePlayer.height, 1.5f / GuiChar.this.gm.thePlayer.width), -45.0f, -20.0f, GuiChar.this.gm.thePlayer); + * Math.min(1.8f / GuiChar.this.gm.player.height, 1.5f / GuiChar.this.gm.player.width), -45.0f, -20.0f, GuiChar.this.gm.player); GuiChar.this.gm.cameraUsed = flag; EntityTexManager.altTexture = null; EntityTexManager.altLayer = -1; @@ -161,7 +167,15 @@ public class GuiChar extends GuiList // } // } GuiChar.this.templateButton.enabled = this.charinfo != null; - GuiChar.this.gm.getNetHandler().addToSendQueue(new CPacketSkin(this.skinImage, this.skinImage != null ? null : this.charinfo.skin, this.model)); + if(this.skinImage == null) { + GuiChar.this.gm.getNetHandler().addToSendQueue(new CPacketSkin(null, this.charinfo.skin)); + } + else { + int[] img = new int[this.model.texWidth * this.model.texHeight]; + this.skinImage.getRGB(0, 0, this.skinImage.getWidth(), this.skinImage.getHeight(), img, 0, this.skinImage.getWidth()); + GuiChar.this.gm.getNetHandler().addToSendQueue(new CPacketSkin(EntityTexManager.imageToComp(img, this.model), null)); + } +// GuiChar.this.gm.getNetHandler().addToSendQueue(new CPacketSkin(this.skinImage, this.skinImage != null ? null : this.charinfo.skin, this.model)); GuiChar.this.currentSkin = this.skinFile != null ? this.skinFile.getName() : this.charinfo.skin; GuiChar.this.waiting = false; } @@ -206,7 +220,7 @@ public class GuiChar extends GuiList } } - public static enum FilterType implements IStringSerializable, Displayable { + public static enum FilterType implements Identifyable, Displayable { ALL("all", "Alle anzeigen"), CUSTOM("custom", "Nur eigene"), NPC("preset", "Nur vorgegebene"), SPECIES("species", "Nur Spezies"), SPECIES_CUSTOM("species_custom", "Spezies und eigene"); private final String name; @@ -228,8 +242,8 @@ public class GuiChar extends GuiList public static class FilterFunction implements EnumFunction { public void apply(EnumVar cv, FilterType value) { - if(Game.getGame().open instanceof GuiChar) - Game.getGame().displayGuiScreen(Game.getGame().open); + if(Client.CLIENT.open instanceof GuiChar) + Client.CLIENT.displayGuiScreen(Client.CLIENT.open); } } @@ -239,7 +253,8 @@ public class GuiChar extends GuiList private ActButton templateButton; private DragAdjust adjust; private ActButton dimButton; - private TransparentBox descLines; + private MultiLabel descLines; + private ActButton cancelButton; private float yaw = -15.0f; private float pitch = -15.0f; private boolean waiting = true; @@ -256,16 +271,16 @@ public class GuiChar extends GuiList { super.init(width, height); this.waiting = true; - this.setDimensions(400, height, 32, height - 32); + this.setDimensions(390, height, 32, height - 32); if(this.gm.getRenderManager().gm == null) { this.unload(); this.adjust = null; return; } - this.currentSkin = this.gm.thePlayer != null && !EntityTexManager.hasCustomSkin(this.gm.thePlayer.getId()) ? this.gm.thePlayer.getChar() : null; - this.load(this.gm.thePlayer == null ? ModelType.HUMANOID : this.gm.thePlayer.getModel(), this.gm.thePlayer != null ? this.gm.thePlayer.getSpecies() : SpeciesRegistry.CLASSES.get(EntityHuman.class)); - this.add(new ActButton(4, 4, 194, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { + this.currentSkin = this.gm.player != null && !EntityTexManager.hasCustomSkin(this.gm.player.getId()) ? this.gm.player.getChar() : null; + this.load(this.gm.player == null ? ModelType.HUMANOID : this.gm.player.getModel(), this.gm.player != null ? this.gm.player.getSpecies() : SpeciesRegistry.CLASSES.get(EntityHuman.class)); + this.add(new ActButton(2, 12, 193, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { GuiChar.this.gm.showFileDialog(FileMode.FILE_LOAD_MULTI, "Skin konvertieren", TEXTURE_FOLDER, new FileCallback() { public void selected(File file) { if(SkinConverter.convertSkin(file, TEXTURE_FOLDER, false)) @@ -274,8 +289,8 @@ public class GuiChar extends GuiList }); } }, "Importieren: Standard")); - this.add(new ActButton(202, 4, 194, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { + this.add(new ActButton(197, 12, 193, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { GuiChar.this.gm.showFileDialog(FileMode.FILE_LOAD_MULTI, "Skin konvertieren (schlank)", TEXTURE_FOLDER, new FileCallback() { public void selected(File file) { if(SkinConverter.convertSkin(file, TEXTURE_FOLDER, true)) @@ -284,14 +299,14 @@ public class GuiChar extends GuiList }); } }, "Importieren: Schlank")); - this.addSelector("char_filter_species", 400, 4, 300, 24); - this.add(new ActButton(4, height - 28, 194, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { + this.addSelector("char_filter_species", 392, 12, 250, 0); + this.add(new ActButton(2, height - 30, 193, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { GuiChar.this.gm.displayGuiScreen(GuiChar.this); } }, "Neu laden")); - this.templateButton = this.add(new ActButton(202, height - 28, 194, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { + this.templateButton = this.add(new ActButton(197, height - 30, 193, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { SkinEntry skin = GuiChar.this.getSelected(); if(skin != null && skin.getLocation() != null) { String loc = skin.getLocation(); @@ -307,9 +322,9 @@ public class GuiChar extends GuiList } catch(Exception e) { if(e instanceof FileNotFoundException) - Log.JNI.warn("Textur ist nicht zum Kopieren vorhanden: " + EntityNPC.getSkinTexture(loc)); + Log.IO.warn("Textur ist nicht zum Kopieren vorhanden: " + EntityNPC.getSkinTexture(loc)); else - Log.JNI.error(e, "Konnte Textur nicht kopieren"); + Log.IO.error(e, "Konnte Textur nicht kopieren"); } finally { if(in != null) { @@ -324,74 +339,81 @@ public class GuiChar extends GuiList } } }, "Vorlage kopieren")); - this.adjust = this.add(new DragAdjust(width / 2 - 230, height - 64 - 640, 460, 640)); + if(width >= 784 + 460 && height >= 128 + 640) + this.adjust = this.add(new DragAdjust(width / 2 - 230, height - 64 - 640, 460, 640)); + else + this.adjust = this.add(new DragAdjust(390 - 115 - 4, height - 32 - 160 - 4, 115, 160)); - this.add(new Label(width - 396, 36, 392, 20, "Spezies: " + (this.gm.thePlayer == null ? "" : this.gm.thePlayer.getSpecies().name), true)); - this.add(new NavButton(width - 396, 56, 392, 24, GuiSpecies.INSTANCE, "Spezies ändern")); - this.add(new Label(width - 396, 36 + 92, 392, 20, "Klasse: " + (this.gm.thePlayer == null || this.gm.thePlayer.getSpecies().classEnum == null || this.gm.thePlayer.getNpcClass() == null || this.gm.thePlayer.getNpcClass().toString().isEmpty() ? "" : this.gm.thePlayer.getNpcClass().toString()), true)) - .enabled = this.gm.thePlayer != null && this.gm.thePlayer.getSpecies().classEnum != null; - this.add(new NavButton(width - 396, 56 + 92, 392, 24, GuiClass.INSTANCE, "Klasse ändern")) - .enabled = this.gm.thePlayer != null && this.gm.thePlayer.getSpecies().classEnum != null; + this.add(new Label(width - 390, 48, 388, "Spezies: " + (this.gm.player == null ? "" : this.gm.player.getSpecies().name), true)); + this.add(new NavButton(width - 390, 48, 388, 0, GuiSpecies.INSTANCE, "Spezies ändern")); + this.add(new Label(width - 390, 82, 388, "Klasse: " + (this.gm.player == null || this.gm.player.getSpecies().classEnum == null || this.gm.player.getNpcClass() == null || this.gm.player.getNpcClass().toString().isEmpty() ? "" : this.gm.player.getNpcClass().toString()), true)) + .enabled = this.gm.player != null && this.gm.player.getSpecies().classEnum != null; + this.add(new NavButton(width - 390, 82, 388, 0, GuiClass.INSTANCE, "Klasse ändern")) + .enabled = this.gm.player != null && this.gm.player.getSpecies().classEnum != null; final ActButton[] alignBtns = new ActButton[Alignment.values().length]; for (int z = 0; z < Alignment.values().length; z++) { final Alignment align = Alignment.values()[z]; - alignBtns[z] = this.add(new ActButton(width - 396 + (z % 3) * 132, height - 32 - 28 * 3 + 28 * (z / 3), 128, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { - if(GuiChar.this.gm.thePlayer != null) { + alignBtns[z] = this.add(new ActButton(width - 390 + (z % 3) * 130, height - 32 - 20 * 3 + 20 * (z / 3), 128, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + if(GuiChar.this.gm.player != null) { GuiChar.this.waiting = false; - GuiChar.this.gm.thePlayer.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_ALIGN, align.ordinal())); + GuiChar.this.gm.player.client.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_ALIGN, align.ordinal())); for(ActButton btn : alignBtns) { btn.enabled = btn != elem; } } } }, align.color + align.display)); - alignBtns[z].enabled = this.gm.thePlayer == null || this.gm.thePlayer.getAlignment() != align; + alignBtns[z].enabled = this.gm.player == null || this.gm.player.getAlignment() != align; } - this.add(new Slider(width / 2 - 200, height - 28, 400, 24, 1, this.gm.thePlayer == null ? 120 : this.gm.thePlayer.getMinSize(), this.gm.thePlayer == null ? 320 : this.gm.thePlayer.getMaxSize(), this.gm.thePlayer == null ? 180 : this.gm.thePlayer.getDefaultSize(), this.gm.thePlayer == null ? 180 : this.gm.thePlayer.getCurrentSize(), new Slider.Callback() { + this.add(new Slider(width - 390, 136, 388, 0, 1, this.gm.player == null ? 120 : this.gm.player.getMinSize(), this.gm.player == null ? 320 : this.gm.player.getMaxSize(), this.gm.player == null ? 180 : this.gm.player.getDefaultSize(), this.gm.player == null ? 180 : this.gm.player.getCurrentSize(), new SliderCallback() { public void use(Slider elem, int value) { - if(GuiChar.this.gm.thePlayer != null) { + if(GuiChar.this.gm.player != null) { GuiChar.this.waiting = false; - GuiChar.this.gm.thePlayer.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_HEIGHT, value)); + GuiChar.this.gm.player.client.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_HEIGHT, value)); } } - }, "Spieler-Größe", "cm")).enabled = this.gm.thePlayer == null || this.gm.thePlayer.getMinSize() != this.gm.thePlayer.getMaxSize(); - this.add(new Label(width / 2 - 200, 36, 400, 20, "Name", true)); - this.add(new Label(width - 396, height - 384, 392, 20, "Beschreibung", true)); - final Textbox descField = this.add(new Textbox(width - 396, height - 364, 392, 130, Player.MAX_INFO_LENGTH, new Textbox.Callback() { - public void use(Textbox elem, Action value) { - } - }, "")); - this.add(new ActButton(width - 198, height - 28, 194, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { - if(GuiChar.this.gm.thePlayer != null) { + }, "Spieler-Größe", "cm")).enabled = this.gm.player == null || this.gm.player.getMinSize() != this.gm.player.getMaxSize(); + this.add(new Label(width - 390, 116, 388, "Name", true)); + this.add(new Label(width - 390, 170, 388, "Beschreibung", true)); + final Area descField = this.add(new Area(width - 390, 170, 388, height - 328, IPlayer.MAX_INFO_LENGTH, "")); + this.add(new ActButton(width - 195, height - 30, 193, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + if(GuiChar.this.gm.player != null) { GuiChar.this.gm.displayGuiScreen(GuiLoading.makeWaitTask("Lade Welt ...")); Dimension dim = UniverseRegistry.getBaseDimensions().get(GuiChar.this.dimension); - GuiChar.this.gm.thePlayer.sendQueue.addToSendQueue(new CPacketMessage(CPacketMessage.Type.INFO, descField.getText())); - GuiChar.this.gm.thePlayer.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.CLOSE_EDITOR, dim.getDimensionId())); + GuiChar.this.gm.player.client.addToSendQueue(new CPacketMessage(CPacketMessage.Type.INFO, descField.getText())); + GuiChar.this.gm.player.client.addToSendQueue(new CPacketAction(CPacketAction.Action.CLOSE_EDITOR, dim.getDimensionId())); } } }, "Charakter erstellen")); - this.add(new Textbox(width / 2 - 200, 36 + 20, 400, 24, Player.MAX_NICK_LENGTH, true, new Textbox.Callback() { - public void use(Textbox elem, Action value) { - if(value == Action.SEND || value == Action.UNFOCUS) { + this.cancelButton = this.add(new ActButton(width - 390, height - 30, 193, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + if(GuiChar.this.gm.player != null) + GuiChar.this.gm.displayGuiScreen(GuiCharacters.INSTANCE); + } + }, "Abbrechen")); + this.setCharsAvailable(); + this.add(new Field(width - 390, 116, 388, 0, IPlayer.MAX_NICK_LENGTH, new FieldCallback() { + public void use(Field elem, FieldAction value) { + if(value == FieldAction.SEND || value == FieldAction.UNFOCUS) { String name = elem.getText(); if(name.isEmpty()) - elem.setText(GuiChar.this.gm.thePlayer == null ? "..." : GuiChar.this.gm.thePlayer.getCustomNameTag()); - else if(GuiChar.this.gm.thePlayer != null) { + elem.setText(GuiChar.this.gm.player == null ? "..." : GuiChar.this.gm.player.getCustomNameTag()); + else if(GuiChar.this.gm.player != null) { GuiChar.this.waiting = false; - GuiChar.this.gm.thePlayer.sendQueue.addToSendQueue(new CPacketMessage(CPacketMessage.Type.DISPLAY, name)); + GuiChar.this.gm.player.client.addToSendQueue(new CPacketMessage(CPacketMessage.Type.DISPLAY, name)); } } } - }, Player.VALID_NICK, this.gm.thePlayer == null ? "" : this.gm.thePlayer.getCustomNameTag())); + }, IPlayer.VALID_NICK, this.gm.player == null ? "" : this.gm.player.getCustomNameTag())); this.templateButton.enabled = false; this.dimension = new Random().zrange(UniverseRegistry.getBaseDimensions().size()); - EntityEggInfo egg = EntityRegistry.SPAWN_EGGS.get(this.gm.thePlayer == null ? EntityRegistry.getEntityString(EntityHuman.class) : EntityRegistry.getEntityString(this.gm.thePlayer)); - if(egg != null && egg.origin != null) { - Dimension dim = UniverseRegistry.getDimension(egg.origin); + EntityInfo egg = EntityRegistry.SPAWN_EGGS.get(this.gm.player == null ? EntityRegistry.getEntityString(EntityHuman.class) : EntityRegistry.getEntityString(this.gm.player)); + if(egg != null && egg.origin() != null) { + Dimension dim = UniverseRegistry.getDimension(egg.origin()); if(dim != null) { for(int z = 0; z < UniverseRegistry.getBaseDimensions().size(); z++) { if(UniverseRegistry.getBaseDimensions().get(z).getDimensionId() == dim.getDimensionId()) { @@ -401,12 +423,12 @@ public class GuiChar extends GuiList } } } - this.dimButton = this.add(new ActButton(width - 396, height - 220, 392, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode mode) { - if(mode == Mode.TERTIARY) { + this.dimButton = this.add(new ActButton(width - 390, height - 156, 388, 0, new ButtonCallback() { + public void use(ActButton elem, PressType mode) { + if(mode == PressType.TERTIARY) { GuiChar.this.dimension = new Random().zrange(UniverseRegistry.getBaseDimensions().size()); } - else if(mode == Mode.SECONDARY) { + else if(mode == PressType.SECONDARY) { if(--GuiChar.this.dimension < 0) GuiChar.this.dimension = UniverseRegistry.getBaseDimensions().size() - 1; } @@ -417,7 +439,7 @@ public class GuiChar extends GuiList GuiChar.this.setDimButton(); } }, "")); - this.descLines = this.add(new TransparentBox(width - 396, height - 220 + 24, 392, 66, "", false)); + this.descLines = this.add(new MultiLabel(width - 390, height - 156 + Element.BASE_HEIGHT, 388, 42, "", true)); this.setDimButton(); } @@ -437,10 +459,12 @@ public class GuiChar extends GuiList public void drawOverlays() { if(this.adjust != null) { - float factor = this.gm.thePlayer.width > 2.15f ? 2.15f / this.gm.thePlayer.width : 1.0f; - factor = this.gm.thePlayer.height > 3.0f && 3.0f / this.gm.thePlayer.height < factor ? 3.0f / this.gm.thePlayer.height : factor; - drawEntity(400 + (this.gm.fb_x - 400 - 400) / 2, this.gm.fb_y - 160, 160.0f * factor - , this.yaw, this.pitch, this.gm.thePlayer); + float factor = this.gm.player.width > 2.15f ? 2.15f / this.gm.player.width : 1.0f; + factor = this.gm.player.height > 3.0f && 3.0f / this.gm.player.height < factor ? 3.0f / this.gm.player.height : factor; + if(this.gm.fb_x >= 784 + 460 && this.gm.fb_y >= 128 + 640) + drawEntity(400 + (this.gm.fb_x - 400 - 400) / 2, this.gm.fb_y - 160, 160.0f * factor, this.yaw, this.pitch, this.gm.player); + else + drawEntity(390 - 4 - 115 / 2, this.gm.fb_y - 60, 40.0f * factor, this.yaw, this.pitch, this.gm.player); } } @@ -460,6 +484,11 @@ public class GuiChar extends GuiList return "Charakter anpassen"; } + public void setCharsAvailable() { + if(this.cancelButton != null) + this.cancelButton.enabled = !this.gm.characterList.isEmpty(); + } + public static BufferedImage loadSkin(File file) { BufferedImage img = null; @@ -527,11 +556,6 @@ public class GuiChar extends GuiList this.elements.clear(); } - - public int getListWidth() - { - return 400 - 20; - } public int getSlotHeight() { @@ -604,7 +628,7 @@ public class GuiChar extends GuiList ent.headYaw = ent.rotYaw; ent.prevHeadYaw = ent.rotYaw; GL11.glTranslatef(0.0F, -(ent.height / 2), 0.0F); - RenderManager rendermanager = Game.getGame().getRenderManager(); + RenderManager rendermanager = Client.CLIENT.getRenderManager(); rendermanager.setPlayerViewY(180.0F); rendermanager.renderEntity(ent, 0.0D, 0.0D, 0.0D, 1.0F); // GL11.glTranslatef(0.0F, 0.0F, 0.0F); diff --git a/client/src/main/java/client/gui/character/GuiCharacters.java b/client/src/main/java/client/gui/character/GuiCharacters.java new file mode 100644 index 0000000..9d53d9e --- /dev/null +++ b/client/src/main/java/client/gui/character/GuiCharacters.java @@ -0,0 +1,120 @@ +package client.gui.character; + +import client.gui.Font; +import client.gui.GuiConfirm; +import client.gui.GuiMenu; +import client.gui.element.ActButton; +import client.gui.element.Area; +import client.gui.element.ButtonCallback; +import client.gui.element.GuiList; +import client.gui.element.ListEntry; +import client.gui.element.NavButton; +import client.gui.element.PressType; +import client.renderer.Drawing; +import common.color.TextColor; +import common.entity.npc.PlayerCharacter; +import common.packet.CPacketAction; +import common.packet.CPacketAction.Action; +import common.util.ExtMath; + +public class GuiCharacters extends GuiList implements ButtonCallback +{ + protected class CharacterEntry implements ListEntry + { + private final PlayerCharacter character; + private final boolean initial; + + protected CharacterEntry(PlayerCharacter character, boolean initial) + { + this.character = character; + this.initial = initial; + } + + public void draw(int x, int y, int width, int height, int mouseX, int mouseY, boolean hovered) + { + if(this.initial) + Drawing.drawRect(x, y, 1, 36, 0xffaf0000); + String str = this.character == null ? TextColor.BLUE + "[" + TextColor.CYAN + "+" + TextColor.BLUE + "]" : + String.format(TextColor.GREEN + "Level " + TextColor.DGREEN + "%d " + TextColor.YELLOW + "%s " + TextColor.VIOLET + "%s", + character.level(), character.type(), character.name()); + String pos = this.character == null ? TextColor.BROWN + "Neuen Charakter erstellen" : + String.format(TextColor.NEON + "%s " + TextColor.GRAY + "bei " + TextColor.ACID + "%d" + TextColor.GRAY + ", " + TextColor.ACID + "%d" + TextColor.GRAY + ", " + TextColor.ACID + "%d", + character.dim(), character.pos().getX(), character.pos().getY(), character.pos().getZ()); + Drawing.drawText(str, x + 3, y, 0xffffffff); + Drawing.drawText(pos, x + 3, y + height - Font.YGLYPH, 0xffffffff); + } + + public void select(boolean dclick, int mx, int my) + { + if(dclick) + GuiCharacters.this.use(GuiCharacters.this.actionButtom, PressType.PRIMARY); + GuiCharacters.this.updateButtons(); + } + } + + public static final GuiCharacters INSTANCE = new GuiCharacters(); + + private Area descField; + private ActButton actionButtom; + private ActButton deleteButtom; + + private GuiCharacters() { + } + + private void updateButtons() { + CharacterEntry entry = this.getSelected(); + this.descField.setText(entry == null ? "" : (entry.character == null ? "*neuer Charakter*" : String.format(TextColor.GRAY + "[%s%s" + TextColor.GRAY + "]\n" + TextColor.RESET + "%s", entry.character.align().color, entry.character.align().display, entry.character.info() == null ? "*keine Beschreibung vorhanden*" : this.getSelected().character.info()))); + this.actionButtom.setText(entry != null && entry.character == null ? "Charakter erstellen" : "Charakter spielen"); + this.actionButtom.enabled = entry != null && !entry.initial; + this.deleteButtom.enabled = !this.gm.charEditor && entry != null && entry.character != null && !entry.initial; + } + + public void init(int width, int height) + { + super.init(width, height); + this.setDimensions(width - 300, height, 32, height - 32); + this.elements.clear(); + int selected = this.gm.selectedCharacter; + for(PlayerCharacter character : this.gm.characterList) { + this.elements.add(new CharacterEntry(selected == this.elements.size() ? new PlayerCharacter(character.name(), character.info(), character.align(), this.gm.player.worldObj.dimension.getFormattedName(false), this.gm.player.getPosition(), character.type(), this.gm.player.experienceLevel) : character, selected == this.elements.size())); + } + if(!this.gm.charEditor) + this.elements.add(new CharacterEntry(null, false)); + this.setSelected(ExtMath.clampi(selected, -1, this.elements.size() - 1)); + this.descField = this.add(new Area(width - 300, 32, 300, height - 64, "")); + this.deleteButtom = this.add(new ActButton(width / 2 - 302, height - 30, 200, 0, this, "Charakter löschen")); + this.actionButtom = this.add(new ActButton(width / 2 - 100, height - 30, 200, 0, this, "")); + this.add(new NavButton(width / 2 + 102, height - 30, 200, 0, this.gm.charEditor ? GuiChar.INSTANCE : GuiMenu.INSTANCE, this.gm.charEditor ? "Zurück" : "Abbrechen")); + this.updateButtons(); + } + + public String getTitle() { + return "Charakter auswählen"; + } + + public int getSlotHeight() + { + return 36 + 4; + } + + public void use(ActButton elem, PressType action) { + CharacterEntry entry = GuiCharacters.this.getSelected(); + if(entry != null && GuiCharacters.this.gm.getNetHandler() != null) { + if(elem == this.actionButtom) { + if(entry.character == null) + this.gm.getNetHandler().addToSendQueue(new CPacketAction(CPacketAction.Action.OPEN_EDITOR)); + else + this.gm.getNetHandler().addToSendQueue(new CPacketAction(GuiCharacters.this.gm.charEditor ? Action.CANCEL_EDITOR : CPacketAction.Action.SELECT_CHARACTER, this.selectedElement)); + } + else if(elem == this.deleteButtom && entry.character != null) { + this.gm.displayGuiScreen(new GuiConfirm(new GuiConfirm.Callback() { + public void confirm(boolean confirmed) { + if(confirmed) + GuiCharacters.this.gm.getNetHandler().addToSendQueue(new CPacketAction(CPacketAction.Action.DELETE_CHARACTER, GuiCharacters.this.selectedElement)); + GuiCharacters.this.gm.displayGuiScreen(GuiCharacters.this); + } + }, "Möchtest du diesen Charakter wirklich löschen?", "Der Fortschritt, die Gegenstände und die Historie\nvon \"" + entry.character.name() + "\" werden für immer verloren sein!", "Löschen", "Abbrechen")); + } + } + } +} diff --git a/client/src/main/java/client/gui/character/GuiClass.java b/client/src/main/java/client/gui/character/GuiClass.java new file mode 100644 index 0000000..775a266 --- /dev/null +++ b/client/src/main/java/client/gui/character/GuiClass.java @@ -0,0 +1,73 @@ +package client.gui.character; + +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.GuiList; +import client.gui.element.ListEntry; +import client.gui.element.NavButton; +import client.gui.element.PressType; +import client.renderer.Drawing; +import common.packet.CPacketAction; + +public class GuiClass extends GuiList implements ButtonCallback +{ + protected class ClassEntry implements ListEntry + { + private final Enum clazz; + + protected ClassEntry(Enum clazz) + { + this.clazz = clazz; + } + + public void draw(int x, int y, int width, int height, int mouseX, int mouseY, boolean hovered) + { + if(GuiClass.this.gm.player != null && this.clazz == GuiClass.this.gm.player.getNpcClass()) + Drawing.drawRect(x, y, 1, 44, 0xffaf0000); + Drawing.drawText(this.clazz.toString().isEmpty() ? "" : this.clazz.toString(), x + 3, y, 0xffffffff); + } + + public void select(boolean dclick, int mx, int my) + { + if((GuiClass.this.selectButton.enabled = GuiClass.this.gm.player == null || this.clazz != GuiClass.this.gm.player.getNpcClass()) && dclick) + GuiClass.this.use(GuiClass.this.selectButton, PressType.PRIMARY); + } + } + + public static final GuiClass INSTANCE = new GuiClass(); + + private ActButton selectButton; + + private GuiClass() { + } + + public void init(int width, int height) + { + super.init(width, height); + this.setDimensions(width, height, 32, height - 32); + this.elements.clear(); + if(this.gm.player != null && this.gm.player.getSpecies().classEnum != null) + for(Enum clazz : this.gm.player.getSpecies().classEnum.getEnumConstants()) { + this.elements.add(new ClassEntry(clazz)); + } + this.add(new NavButton(width / 2 - 195, height - 30, 194, 0, GuiChar.INSTANCE, "Zurück")); + this.selectButton = this.add(new ActButton(width / 2 + 1, height - 30, 194, 0, this, "Klasse ändern")); + } + + public String getTitle() { + return "Klasse wählen"; + } + + public int getSlotHeight() + { + return 44 + 4; + } + + public void use(ActButton elem, PressType action) { + ClassEntry entry = this.getSelected(); + if(entry != null && GuiClass.this.gm.player != null) { + GuiClass.this.gm.player.client.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_CLASS, entry.clazz.ordinal())); + this.gm.displayGuiScreen(GuiChar.INSTANCE); + } + } +} diff --git a/client/src/main/java/client/gui/character/GuiSpecies.java b/client/src/main/java/client/gui/character/GuiSpecies.java new file mode 100644 index 0000000..6f190db --- /dev/null +++ b/client/src/main/java/client/gui/character/GuiSpecies.java @@ -0,0 +1,75 @@ +package client.gui.character; + +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.GuiList; +import client.gui.element.ListEntry; +import client.gui.element.NavButton; +import client.gui.element.PressType; +import client.renderer.Drawing; +import common.entity.npc.SpeciesInfo; +import common.init.EntityRegistry; +import common.init.SpeciesRegistry; +import common.packet.CPacketAction; + +public class GuiSpecies extends GuiList implements ButtonCallback +{ + protected class SpeciesEntry implements ListEntry + { + private final SpeciesInfo species; + + protected SpeciesEntry(SpeciesInfo species) + { + this.species = species; + } + + public void draw(int x, int y, int width, int height, int mouseX, int mouseY, boolean hovered) + { + if(GuiSpecies.this.gm.player != null && this.species == GuiSpecies.this.gm.player.getSpecies()) + Drawing.drawRect(x, y, 1, 44, 0xffaf0000); + Drawing.drawText(this.species.name, x + 3, y, 0xff000000 | this.species.color1 | this.species.color2); + if(this.species.classEnum != null) + Drawing.drawText(this.species.classEnum.getEnumConstants().length + " Klassen", x + 3, y + 18, 0xffc0c0c0); + } + + public void select(boolean dclick, int mx, int my) + { + if((GuiSpecies.this.selectButton.enabled = GuiSpecies.this.gm.player == null || this.species != GuiSpecies.this.gm.player.getSpecies()) && dclick) + GuiSpecies.this.use(GuiSpecies.this.selectButton, PressType.PRIMARY); + } + } + + public static final GuiSpecies INSTANCE = new GuiSpecies(); + + private ActButton selectButton; + + private GuiSpecies() { + } + + public void init(int width, int height) + { + super.init(width, height); + this.setDimensions(width, height, 32, height - 32); + this.elements.clear(); + for(SpeciesInfo species : SpeciesRegistry.SPECIMEN) { + this.elements.add(new SpeciesEntry(species)); + } + this.add(new NavButton(width / 2 - 195, height - 30, 194, 0, GuiChar.INSTANCE, "Zurück")); + this.selectButton = this.add(new ActButton(width / 2 + 1, height - 30, 194, 0, this, "Spezies ändern")); + } + + public String getTitle() { + return "Spezies wählen"; + } + + public int getSlotHeight() + { + return 44 + 4; + } + + public void use(ActButton elem, PressType action) { + SpeciesEntry entry = this.getSelected(); + if(entry != null && GuiSpecies.this.gm.player != null) + GuiSpecies.this.gm.player.client.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_SPECIES, EntityRegistry.getEntityID(entry.species.clazz))); + } +} diff --git a/java/src/game/gui/container/GuiBrewing.java b/client/src/main/java/client/gui/container/GuiBrewing.java similarity index 89% rename from java/src/game/gui/container/GuiBrewing.java rename to client/src/main/java/client/gui/container/GuiBrewing.java index 93530ba..45690d6 100755 --- a/java/src/game/gui/container/GuiBrewing.java +++ b/client/src/main/java/client/gui/container/GuiBrewing.java @@ -1,8 +1,8 @@ -package game.gui.container; +package client.gui.container; -import game.inventory.ContainerBrewingStand; -import game.inventory.IInventory; -import game.inventory.InventoryPlayer; +import common.inventory.ContainerBrewingStand; +import common.inventory.IInventory; +import common.inventory.InventoryPlayer; public class GuiBrewing extends GuiContainer diff --git a/java/src/game/gui/container/GuiChest.java b/client/src/main/java/client/gui/container/GuiChest.java similarity index 89% rename from java/src/game/gui/container/GuiChest.java rename to client/src/main/java/client/gui/container/GuiChest.java index 6adb0d9..c9a56be 100755 --- a/java/src/game/gui/container/GuiChest.java +++ b/client/src/main/java/client/gui/container/GuiChest.java @@ -1,8 +1,8 @@ -package game.gui.container; +package client.gui.container; -import game.Game; -import game.inventory.ContainerChest; -import game.inventory.IInventory; +import client.Client; +import common.inventory.ContainerChest; +import common.inventory.IInventory; public class GuiChest extends GuiContainer @@ -19,7 +19,7 @@ public class GuiChest extends GuiContainer public GuiChest(IInventory upperInv, IInventory lowerInv) { - super(new ContainerChest(upperInv, lowerInv, Game.getGame().thePlayer)); + super(new ContainerChest(upperInv, lowerInv, Client.CLIENT.player)); this.upperChestInventory = upperInv; this.lowerChestInventory = lowerInv; // this.allowUserInput = false; diff --git a/java/src/game/gui/container/GuiContainer.java b/client/src/main/java/client/gui/container/GuiContainer.java similarity index 90% rename from java/src/game/gui/container/GuiContainer.java rename to client/src/main/java/client/gui/container/GuiContainer.java index d4bc825..967dfa5 100755 --- a/java/src/game/gui/container/GuiContainer.java +++ b/client/src/main/java/client/gui/container/GuiContainer.java @@ -1,4 +1,4 @@ -package game.gui.container; +package client.gui.container; import java.util.List; import java.util.Set; @@ -6,24 +6,24 @@ import java.util.Set; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import game.collect.Lists; -import game.collect.Sets; - -import game.color.TextColor; -import game.gui.Gui; -import game.gui.element.InventoryButton; -import game.inventory.Container; -import game.inventory.InventoryPlayer; -import game.inventory.Slot; -import game.item.CheatTab; -import game.item.ItemStack; -import game.packet.CPacketCheat; -import game.renderer.Drawing; -import game.renderer.GlState; -import game.renderer.ItemRenderer; -import game.renderer.entity.RenderItem; -import game.util.ExtMath; -import game.window.Button; +import client.gui.Font; +import client.gui.Gui; +import client.gui.element.InventoryButton; +import client.renderer.Drawing; +import client.renderer.GlState; +import client.renderer.ItemRenderer; +import client.renderer.entity.RenderItem; +import client.window.Button; +import common.collect.Lists; +import common.collect.Sets; +import common.color.TextColor; +import common.inventory.Container; +import common.inventory.InventoryPlayer; +import common.inventory.Slot; +import common.item.CheatTab; +import common.item.ItemStack; +import common.packet.CPacketCheat; +import common.util.ExtMath; public abstract class GuiContainer extends Gui { @@ -43,7 +43,7 @@ public abstract class GuiContainer extends Gui private static final List ITEM_LIST = Lists.newArrayList(); - private static CheatTab selectedTab = CheatTab.tabBlocks; + private static CheatTab selectedTab = CheatTab.BLOCKS; // /** The location of the inventory background texture */ // protected static final String inventoryBackground = "textures/gui/inventory.png"; @@ -214,7 +214,7 @@ public abstract class GuiContainer extends Gui */ public void initGui() { - this.gm.thePlayer.openContainer = this.inventorySlots; + this.gm.player.openContainer = this.inventorySlots; // this.guiLeft = (this.width - this.xSize) / 2; // this.guiTop = (this.height - this.ySize) / 2; // this.addButtons(); @@ -361,7 +361,7 @@ public abstract class GuiContainer extends Gui ItemRenderer.disableStandardItemLighting(); // this.drawGuiContainerForegroundLayer(mouseX, mouseY); ItemRenderer.enableGUIStandardItemLighting(); - InventoryPlayer inventoryplayer = this.gm.thePlayer.inventory; + InventoryPlayer inventoryplayer = this.gm.player.inventory; ItemStack itemstack = this.draggedStack == null ? inventoryplayer.getItemStack() : this.draggedStack; if(this.gm.itemCheat) itemstack = itemstack == null ? this.cheatStack : itemstack; @@ -375,20 +375,20 @@ public abstract class GuiContainer extends Gui if (this.draggedStack != null && this.isRightMouseClick) { itemstack = itemstack.copy(); - itemstack.stackSize = ExtMath.ceilf((float)itemstack.stackSize / 2.0F); + itemstack.size = ExtMath.ceilf((float)itemstack.size / 2.0F); } else if (this.dragSplitting && this.dragSplittingSlots.size() > 1) { itemstack = itemstack.copy(); - itemstack.stackSize = this.dragSplittingRemnant; + itemstack.size = this.dragSplittingRemnant; - if (itemstack.stackSize == 0) + if (itemstack.size == 0) { s = "" + TextColor.YELLOW + "0"; } } else if(itemstack == this.cheatStack) { - s = TextColor.DGREEN + "+" + TextColor.GREEN + ItemStack.formatAmount(itemstack.stackSize); + s = TextColor.DGREEN + "+" + TextColor.GREEN + ItemStack.formatAmount(itemstack.size); } this.drawItemStack(itemstack, mouseX - j2, mouseY - k2, s); @@ -452,7 +452,7 @@ public abstract class GuiContainer extends Gui } protected void renderToolTip(ItemStack stack, int x, int y) { - List list = stack.getTooltip(this.gm.thePlayer); + List list = stack.getTooltip(this.gm.player); StringBuilder sb = new StringBuilder(); for(int i = 0; i < list.size(); ++i) { if(i != 0) @@ -513,13 +513,13 @@ public abstract class GuiContainer extends Gui ItemStack itemstack = slotIn.getStack(); boolean flag = false; boolean flag1 = slotIn == this.clickedSlot && this.draggedStack != null && !this.isRightMouseClick; - ItemStack itemstack1 = this.gm.thePlayer.inventory.getItemStack(); + ItemStack itemstack1 = this.gm.player.inventory.getItemStack(); String s = null; if (slotIn == this.clickedSlot && this.draggedStack != null && this.isRightMouseClick && itemstack != null) { itemstack = itemstack.copy(); - itemstack.stackSize /= 2; + itemstack.size /= 2; } else if (this.dragSplitting && this.dragSplittingSlots.contains(slotIn) && itemstack1 != null) { @@ -532,18 +532,18 @@ public abstract class GuiContainer extends Gui { itemstack = itemstack1.copy(); flag = true; - Container.computeStackSize(this.dragSplittingSlots, this.dragSplittingLimit, itemstack, slotIn.getStack() == null ? 0 : slotIn.getStack().stackSize); + Container.computeStackSize(this.dragSplittingSlots, this.dragSplittingLimit, itemstack, slotIn.getStack() == null ? 0 : slotIn.getStack().size); - if (itemstack.stackSize > itemstack.getMaxStackSize()) + if (itemstack.size > itemstack.getMaxStackSize()) { s = TextColor.YELLOW + ItemStack.formatAmount(itemstack.getMaxStackSize()); - itemstack.stackSize = itemstack.getMaxStackSize(); + itemstack.size = itemstack.getMaxStackSize(); } - if (itemstack.stackSize > slotIn.getItemStackLimit(itemstack)) + if (itemstack.size > slotIn.getItemStackLimit(itemstack)) { s = TextColor.YELLOW + ItemStack.formatAmount(slotIn.getItemStackLimit(itemstack)); - itemstack.stackSize = slotIn.getItemStackLimit(itemstack); + itemstack.size = slotIn.getItemStackLimit(itemstack); } } else @@ -590,29 +590,29 @@ public abstract class GuiContainer extends Gui private void updateDragSplitting() { - ItemStack itemstack = this.gm.thePlayer.inventory.getItemStack(); + ItemStack itemstack = this.gm.player.inventory.getItemStack(); if (itemstack != null && this.dragSplitting) { - this.dragSplittingRemnant = itemstack.stackSize; + this.dragSplittingRemnant = itemstack.size; for (Slot slot : this.dragSplittingSlots) { ItemStack itemstack1 = itemstack.copy(); - int i = slot.getStack() == null ? 0 : slot.getStack().stackSize; + int i = slot.getStack() == null ? 0 : slot.getStack().size; Container.computeStackSize(this.dragSplittingSlots, this.dragSplittingLimit, itemstack1, i); - if (itemstack1.stackSize > itemstack1.getMaxStackSize()) + if (itemstack1.size > itemstack1.getMaxStackSize()) { - itemstack1.stackSize = itemstack1.getMaxStackSize(); + itemstack1.size = itemstack1.getMaxStackSize(); } - if (itemstack1.stackSize > slot.getItemStackLimit(itemstack1)) + if (itemstack1.size > slot.getItemStackLimit(itemstack1)) { - itemstack1.stackSize = slot.getItemStackLimit(itemstack1); + itemstack1.size = slot.getItemStackLimit(itemstack1); } - this.dragSplittingRemnant -= itemstack1.stackSize - i; + this.dragSplittingRemnant -= itemstack1.size - i; } } } @@ -644,8 +644,8 @@ public abstract class GuiContainer extends Gui return; if(this.cheatStack != null) { Slot slot = this.getSlotAtPosition(mouseX, mouseY); - if((mouseButton == 0 || mouseButton == 1) && slot != null && this.gm.thePlayer != null && slot.inventory == this.gm.thePlayer.inventory) - this.gm.thePlayer.sendQueue.addToSendQueue(new CPacketCheat(this.cheatStack, slot.getIndex(), mouseButton == 0 && this.cheatStack.stackSize > 1)); + if((mouseButton == 0 || mouseButton == 1) && slot != null && this.gm.player != null && slot.inventory == this.gm.player.inventory) + this.gm.player.client.addToSendQueue(new CPacketCheat(this.cheatStack, slot.getIndex(), mouseButton == 0 && this.cheatStack.size > 1)); if(mouseButton != 1 && !this.gm.ctrl()) this.cheatStack = null; return; @@ -653,7 +653,7 @@ public abstract class GuiContainer extends Gui if((mouseButton == 0 || mouseButton == 1 || mouseButton == 2) && this.clickSide(mouseX, mouseY, -1, this.gm.shift() || mouseButton == 1, this.gm.ctrl() || mouseButton == 2)) return; if(mouseButton == 0) { - if(this.gm.itemCheat && this.gm.thePlayer != null && this.gm.thePlayer.inventory.getItemStack() == null) { + if(this.gm.itemCheat && this.gm.player != null && this.gm.player.inventory.getItemStack() == null) { for (CheatTab tab : CheatTab.values()) { if (this.isInsideTab(tab, mouseX, mouseY)) @@ -712,7 +712,7 @@ public abstract class GuiContainer extends Gui // else if (!this.dragSplitting) { - if (this.gm.thePlayer.inventory.getItemStack() == null) + if (this.gm.player.inventory.getItemStack() == null) { // if (mouseButton == this.gm.bindTertiary.getKeyCode() + 100) // { @@ -775,7 +775,7 @@ public abstract class GuiContainer extends Gui if(this.gm == null || this.cheatStack != null) return; Slot slot = this.getSlotAtPosition(mouseX, mouseY); - ItemStack itemstack = this.gm.thePlayer.inventory.getItemStack(); + ItemStack itemstack = this.gm.player.inventory.getItemStack(); // if (this.clickedSlot != null && this.gm.touchscreen) // { @@ -812,7 +812,7 @@ public abstract class GuiContainer extends Gui // } // } // else - if (this.dragSplitting && slot != null && itemstack != null && itemstack.stackSize > this.dragSplittingSlots.size() && Container.canAddItemToSlot(slot, itemstack, true) && slot.isItemValid(itemstack) && this.inventorySlots.canDragIntoSlot(slot)) + if (this.dragSplitting && slot != null && itemstack != null && itemstack.size > this.dragSplittingSlots.size() && Container.canAddItemToSlot(slot, itemstack, true) && slot.isItemValid(itemstack) && this.inventorySlots.canDragIntoSlot(slot)) { this.dragSplittingSlots.add(slot); this.updateDragSplitting(); @@ -850,7 +850,7 @@ public abstract class GuiContainer extends Gui { for (Slot slot2 : this.inventorySlots.inventorySlots) { - if (slot2 != null && slot2.canTakeStack(this.gm.thePlayer) && slot2.getHasStack() && slot2.inventory == slot.inventory && Container.canAddItemToSlot(slot2, this.shiftClickedSlot, true)) + if (slot2 != null && slot2.canTakeStack(this.gm.player) && slot2.getHasStack() && slot2.inventory == slot.inventory && Container.canAddItemToSlot(slot2, this.shiftClickedSlot, true)) { this.handleMouseClick(slot2, slot2.slotNumber, state, 1); } @@ -936,7 +936,7 @@ public abstract class GuiContainer extends Gui this.handleMouseClick((Slot)null, -999, Container.getDragCode(2, this.dragSplittingLimit), 5); } - else if (this.gm.thePlayer.inventory.getItemStack() != null) + else if (this.gm.player.inventory.getItemStack() != null) { // if (state == this.gm.bindTertiary.getKeyCode() + 100) // { @@ -956,7 +956,7 @@ public abstract class GuiContainer extends Gui } } - if (this.gm.thePlayer.inventory.getItemStack() == null) + if (this.gm.player.inventory.getItemStack() == null) { this.lastClickTime = 0L; } @@ -995,11 +995,11 @@ public abstract class GuiContainer extends Gui slotId = slotIn.slotNumber; } - this.gm.controller.windowClick(this.inventorySlots.windowId, slotId, clickedButton, clickType, this.gm.thePlayer); + this.gm.controller.windowClick(this.inventorySlots.windowId, slotId, clickedButton, clickType, this.gm.player); } public void dropItem() { - if (this.gm != null && this.gm.thePlayer != null && this.theSlot != null && this.theSlot.getHasStack()) + if (this.gm != null && this.gm.player != null && this.theSlot != null && this.theSlot.getHasStack()) { // if (keyCode == this.gm.bindTertiary.getKeyCode()) // { @@ -1035,7 +1035,7 @@ public abstract class GuiContainer extends Gui */ public void useHotbar(int slot) { - if (!this.clickSide((this.gm.mouse_x - this.container_x) / 2, (this.gm.mouse_y - this.container_y) / 2, slot, this.gm.shift(), this.gm.ctrl()) && this.gm != null && this.gm.thePlayer != null && this.gm.thePlayer.inventory.getItemStack() == null && this.cheatStack == null && this.theSlot != null) + if (!this.clickSide((this.gm.mouse_x - this.container_x) / 2, (this.gm.mouse_y - this.container_y) / 2, slot, this.gm.shift(), this.gm.ctrl()) && this.gm != null && this.gm.player != null && this.gm.player.inventory.getItemStack() == null && this.cheatStack == null && this.theSlot != null) { // for (int i = 0; i < 9; ++i) // { @@ -1055,9 +1055,9 @@ public abstract class GuiContainer extends Gui */ public void onGuiClosed() { - if (this.gm != null && this.gm.thePlayer != null) + if (this.gm != null && this.gm.player != null) { - this.inventorySlots.onContainerClosed(this.gm.thePlayer); + this.inventorySlots.onContainerClosed(this.gm.player); } } @@ -1076,9 +1076,9 @@ public abstract class GuiContainer extends Gui { // super.updateScreen(); - if (this.gm != null && this.gm.thePlayer != null && (!this.gm.thePlayer.isEntityAlive() || this.gm.thePlayer.dead)) + if (this.gm != null && this.gm.player != null && (!this.gm.player.isEntityAlive() || this.gm.player.dead)) { - this.gm.thePlayer.closeScreen(); + this.gm.displayGuiScreen(null); } } @@ -1091,13 +1091,13 @@ public abstract class GuiContainer extends Gui { if (stack != null) { - if (stack.stackSize != 1 || text != null) + if (stack.size != 1 || text != null) { - String s = text == null ? ItemStack.formatAmount(stack.stackSize) : text; + String s = text == null ? ItemStack.formatAmount(stack.size) : text; - if (text == null && stack.stackSize < 1) + if (text == null && stack.size < 1) { - s = TextColor.RED + ItemStack.formatAmount(stack.stackSize); + s = TextColor.RED + ItemStack.formatAmount(stack.size); } // this.drawString(s, , ); // Vec2i size = Drawing.txt_size(0, 0, 0, 0, 65536, 65536, s); @@ -1105,7 +1105,7 @@ public abstract class GuiContainer extends Gui // int y = ; // x = x * 2 + this.container_x; // y = y * 2 + this.container_y; - Drawing.drawTextRight(s, xPosition + 32, yPosition + 17, 0xffffffff); + Drawing.drawTextRight(s, xPosition + 32, yPosition + 33 - Font.YGLYPH, 0xffffffff); } if (stack.isItemDamaged()) @@ -1152,7 +1152,7 @@ public abstract class GuiContainer extends Gui protected void drawTab(CheatTab tab) { this.itemRender.zLevel = 100.0F; - ItemStack itemstack = tab.getIconItemStack(); + ItemStack itemstack = tab.getIcon(); GlState.enableDepth(); this.itemRender.renderItemAndEffectIntoGUI(itemstack, this.xSize + 2 + 18 * tab.getHorizontal() + 1, 9 * 18 + 4 + 20 * tab.getVertical() + 1); this.itemRender.zLevel = 0.0F; @@ -1177,13 +1177,13 @@ public abstract class GuiContainer extends Gui selectedTab = tab; this.dragSplittingSlots.clear(); ITEM_LIST.clear(); - tab.displayAllReleventItems(ITEM_LIST); + tab.filter(ITEM_LIST); this.currentScroll = 0.0F; } private boolean clickSide(int mouseX, int mouseY, int slot, boolean instant, boolean full) { - if(this.gm.itemCheat && this.isPointInRegion(this.xSize + 2, 0, 18 * 12, 18 * 9, mouseX, mouseY) && this.gm.thePlayer != null && this.gm.thePlayer.inventory.getItemStack() == null && this.cheatStack == null) { + if(this.gm.itemCheat && this.isPointInRegion(this.xSize + 2, 0, 18 * 12, 18 * 9, mouseX, mouseY) && this.gm.player != null && this.gm.player.inventory.getItemStack() == null && this.cheatStack == null) { int i = (ITEM_LIST.size() + 12 - 1) / 12 - 9; int j = (int)((double)(this.currentScroll * (float)i) + 0.5D); @@ -1198,11 +1198,11 @@ public abstract class GuiContainer extends Gui if(i1 >= 0 && i1 < ITEM_LIST.size()) { if(slot >= 0 || instant) { - this.gm.thePlayer.sendQueue.addToSendQueue(new CPacketCheat(ITEM_LIST.get(i1), slot, full)); + this.gm.player.client.addToSendQueue(new CPacketCheat(ITEM_LIST.get(i1), slot, full)); } else { this.cheatStack = ITEM_LIST.get(i1).copy(); - this.cheatStack.stackSize = full ? this.cheatStack.getMaxStackSize() : 1; + this.cheatStack.size = full ? this.cheatStack.getMaxStackSize() : 1; } return true; } diff --git a/client/src/main/java/client/gui/container/GuiCrafting.java b/client/src/main/java/client/gui/container/GuiCrafting.java new file mode 100755 index 0000000..36b3eb5 --- /dev/null +++ b/client/src/main/java/client/gui/container/GuiCrafting.java @@ -0,0 +1,22 @@ +package client.gui.container; + +import common.block.tech.BlockWorkbench; +import common.inventory.ContainerWorkbench; +import common.inventory.InventoryPlayer; +import common.util.BlockPos; +import common.world.World; + +public class GuiCrafting extends GuiContainer { + private final BlockWorkbench type; + + public GuiCrafting(InventoryPlayer playerInv, World worldIn, BlockWorkbench type) { + super(new ContainerWorkbench(playerInv, worldIn, BlockPos.ORIGIN, type)); + this.type = type; + this.ySize = 112 + 18 * this.type.getSize(); + } + + public void drawGuiContainerForegroundLayer() { + this.drawString("Handwerk (" + this.type.getDisplay() + ")", 26, 6); + this.drawString("Inventar", 8, this.ySize - 96 + 2); + } +} diff --git a/java/src/game/gui/container/GuiDispenser.java b/client/src/main/java/client/gui/container/GuiDispenser.java similarity index 90% rename from java/src/game/gui/container/GuiDispenser.java rename to client/src/main/java/client/gui/container/GuiDispenser.java index c65e983..00184b5 100755 --- a/java/src/game/gui/container/GuiDispenser.java +++ b/client/src/main/java/client/gui/container/GuiDispenser.java @@ -1,8 +1,8 @@ -package game.gui.container; +package client.gui.container; -import game.inventory.ContainerDispenser; -import game.inventory.IInventory; -import game.inventory.InventoryPlayer; +import common.inventory.ContainerDispenser; +import common.inventory.IInventory; +import common.inventory.InventoryPlayer; public class GuiDispenser extends GuiContainer diff --git a/java/src/game/gui/container/GuiEnchant.java b/client/src/main/java/client/gui/container/GuiEnchant.java similarity index 85% rename from java/src/game/gui/container/GuiEnchant.java rename to client/src/main/java/client/gui/container/GuiEnchant.java index dcf2632..b9a7181 100755 --- a/java/src/game/gui/container/GuiEnchant.java +++ b/client/src/main/java/client/gui/container/GuiEnchant.java @@ -1,12 +1,12 @@ -package game.gui.container; +package client.gui.container; -import game.color.TextColor; -import game.enchantment.Enchantment; -import game.inventory.ContainerEnchantment; -import game.inventory.InventoryPlayer; -import game.rng.Random; -import game.tileentity.IWorldNameable; -import game.world.World; +import common.color.TextColor; +import common.enchantment.Enchantment; +import common.inventory.ContainerEnchantment; +import common.inventory.InventoryPlayer; +import common.rng.Random; +import common.util.Pair; +import common.world.World; public class GuiEnchant extends GuiContainer { @@ -19,7 +19,7 @@ public class GuiEnchant extends GuiContainer private final Random nameRand = new Random(); private final Random random = new Random(); private final ContainerEnchantment container; - private final IWorldNameable table; + private final String title; // public int field_147073_u; // public float field_147071_v; @@ -30,12 +30,12 @@ public class GuiEnchant extends GuiContainer // public float field_147076_A; // ItemStack field_147077_B; - public GuiEnchant(InventoryPlayer inventory, World worldIn, IWorldNameable table) + public GuiEnchant(InventoryPlayer inventory, World worldIn, String title) { super(new ContainerEnchantment(inventory, worldIn)); this.playerInventory = inventory; this.container = (ContainerEnchantment)this.inventorySlots; - this.table = table; + this.title = title; } /** @@ -43,7 +43,7 @@ public class GuiEnchant extends GuiContainer */ public void drawGuiContainerForegroundLayer() { - this.drawString(this.table.getCommandName(), 12, 5); + this.drawString(this.title, 12, 5); this.drawString(this.playerInventory.getCommandName(), 8, this.ySize - 96 + 2); } @@ -70,7 +70,7 @@ public class GuiEnchant extends GuiContainer int l = mouseX - 60; int i1 = mouseY - (14 + 19 * k); - if (l >= 0 && i1 >= 0 && l < 108 && i1 < 19 && this.container.enchantItem(this.gm.thePlayer, k)) + if (l >= 0 && i1 >= 0 && l < 108 && i1 < 19 && this.container.enchantItem(this.gm.player, k)) { this.gm.controller.sendEnchantPacket(this.container.windowId, k); } @@ -89,14 +89,14 @@ public class GuiEnchant extends GuiContainer */ public void drawGuiContainerBackgroundLayer() { - this.nameRand.setSeed((long)this.container.xpSeed); + this.nameRand.setSeed((long)this.container.seed); for (int l = 0; l < 3; ++l) { int i1 = 60; int j1 = i1 + 20; String s = this.getRandomName(); - int l1 = this.container.enchantLevels[l]; + int l1 = this.container.mana[l]; if (l1 == 0) { @@ -107,7 +107,7 @@ public class GuiEnchant extends GuiContainer String s1 = "" + l1; int i2 = 6839882; - if (/* (k < l + 1 || */ this.gm.thePlayer.experienceLevel < l1) // && !this.gm.thePlayer.creative) + if (/* (k < l + 1 || */ this.gm.player.getManaPoints() < l1) // && !this.gm.thePlayer.creative) { this.rect(i1, 14 + 19 * l, 108, 19, 0x400000); this.rect(i1 + 1, 15 + 19 * l, 16, 16, 0x200000); @@ -150,19 +150,16 @@ public class GuiEnchant extends GuiContainer for (int j = 0; j < 3; ++j) { - int k = this.container.enchantLevels[j]; - int l = this.container.enchantmentIds[j]; + int k = this.container.mana[j]; + Pair l = this.container.ench[j]; int i1 = j + 1; - if (this.isPointInRegion(60, 14 + 19 * j, 108, 17, mouseX, mouseY) && k > 0 && l >= 0) + if (this.isPointInRegion(60, 14 + 19 * j, 108, 17, mouseX, mouseY) && k > 0 && l != null) { StringBuilder sb = new StringBuilder(); - if (l >= 0 && Enchantment.getEnchantmentById(l & 255) != null) - { - String s = Enchantment.getEnchantmentById(l & 255).getFormattedName((l & 65280) >> 8); - sb.append(TextColor.WHITE + s + " . . . ?"); - } + String s = l.first().getFormattedName(l.second()); + sb.append(TextColor.WHITE + s + " . . . ?"); // if (!flag) // { @@ -171,9 +168,9 @@ public class GuiEnchant extends GuiContainer // sb.append("\n"); // } - if (this.gm.thePlayer.experienceLevel < k) + if (this.gm.player.getManaPoints() < k) { - sb.append((sb.length() != 0 ? "\n" : "") + TextColor.RED + String.format("Erfahrungsstufe %d erforderlich", this.container.enchantLevels[j])); + sb.append((sb.length() != 0 ? "\n" : "") + TextColor.RED + String.format("%d Mana erforderlich", this.container.mana[j])); } else { @@ -199,11 +196,11 @@ public class GuiEnchant extends GuiContainer if (i1 == 1) { - s1 = "1 Erfahrungsstufe"; + s1 = "1 Manapunkt"; } else { - s1 = String.format("%d Erfahrungsstufen", i1); + s1 = String.format("%d Manapunkte", i1); } sb.append((sb.length() != 0 ? "\n" : "") + TextColor.LGRAY.toString() + "" + s1); diff --git a/java/src/game/gui/container/GuiHorse.java b/client/src/main/java/client/gui/container/GuiEntity.java similarity index 53% rename from java/src/game/gui/container/GuiHorse.java rename to client/src/main/java/client/gui/container/GuiEntity.java index 6d620b4..a4aa4bb 100755 --- a/java/src/game/gui/container/GuiHorse.java +++ b/client/src/main/java/client/gui/container/GuiEntity.java @@ -1,45 +1,26 @@ -package game.gui.container; +package client.gui.container; -import game.Game; -import game.entity.animal.EntityHorse; -import game.inventory.ContainerHorseInventory; -import game.inventory.IInventory; +import client.Client; +import common.entity.Entity; +import common.inventory.ContainerEntityInventory; +import common.inventory.IInventory; -public class GuiHorse extends GuiContainer +public class GuiEntity extends GuiContainer { -// private static final String horseGuiTextures = "textures/gui/horse.png"; - - /** The player inventory bound to this GUI. */ private IInventory playerInventory; + private IInventory entityInventory; - /** The horse inventory bound to this GUI. */ - private IInventory horseInventory; - -// /** The EntityHorse whose inventory is currently being accessed. */ -// private EntityHorse horseEntity; - -// /** The mouse x-position recorded during the last rendered frame. */ -// private float mousePosx; -// -// /** The mouse y-position recorded during the last renderered frame. */ -// private float mousePosY; - - public GuiHorse(IInventory playerInv, IInventory horseInv, EntityHorse horse) + public GuiEntity(IInventory playerInv, IInventory entityInv, Entity entity) { - super(new ContainerHorseInventory(playerInv, horseInv, horse, Game.getGame().thePlayer)); + super(new ContainerEntityInventory(playerInv, entityInv, entity, Client.CLIENT.player)); this.playerInventory = playerInv; - this.horseInventory = horseInv; -// this.horseEntity = horse; -// this.allowUserInput = false; + this.entityInventory = entityInv; } - /** - * Draw the foreground layer for the GuiContainer (everything in front of the items). Args : mouseX, mouseY - */ public void drawGuiContainerForegroundLayer() { - this.drawString(this.horseInventory.getCommandName(), 8, 6); + this.drawString(this.entityInventory.getCommandName(), 8, 6); this.drawString(this.playerInventory.getCommandName(), 8, this.ySize - 96 + 2); } diff --git a/java/src/game/gui/container/GuiFurnace.java b/client/src/main/java/client/gui/container/GuiFurnace.java similarity index 90% rename from java/src/game/gui/container/GuiFurnace.java rename to client/src/main/java/client/gui/container/GuiFurnace.java index f8f31a3..c3aad9a 100755 --- a/java/src/game/gui/container/GuiFurnace.java +++ b/client/src/main/java/client/gui/container/GuiFurnace.java @@ -1,9 +1,9 @@ -package game.gui.container; +package client.gui.container; -import game.inventory.ContainerFurnace; -import game.inventory.IInventory; -import game.inventory.InventoryPlayer; -import game.tileentity.TileEntityFurnace; +import common.inventory.ContainerFurnace; +import common.inventory.IInventory; +import common.inventory.InventoryPlayer; +import common.tileentity.TileEntityFurnace; public class GuiFurnace extends GuiContainer diff --git a/java/src/game/gui/container/GuiHopper.java b/client/src/main/java/client/gui/container/GuiHopper.java similarity index 85% rename from java/src/game/gui/container/GuiHopper.java rename to client/src/main/java/client/gui/container/GuiHopper.java index 9923d08..c11362a 100755 --- a/java/src/game/gui/container/GuiHopper.java +++ b/client/src/main/java/client/gui/container/GuiHopper.java @@ -1,9 +1,9 @@ -package game.gui.container; +package client.gui.container; -import game.Game; -import game.inventory.ContainerHopper; -import game.inventory.IInventory; -import game.inventory.InventoryPlayer; +import client.Client; +import common.inventory.ContainerHopper; +import common.inventory.IInventory; +import common.inventory.InventoryPlayer; public class GuiHopper extends GuiContainer @@ -19,7 +19,7 @@ public class GuiHopper extends GuiContainer public GuiHopper(InventoryPlayer playerInv, IInventory hopperInv) { - super(new ContainerHopper(playerInv, hopperInv, Game.getGame().thePlayer)); + super(new ContainerHopper(playerInv, hopperInv, Client.CLIENT.player)); this.playerInventory = playerInv; this.hopperInventory = hopperInv; // this.allowUserInput = false; diff --git a/java/src/game/gui/container/GuiInventory.java b/client/src/main/java/client/gui/container/GuiInventory.java similarity index 96% rename from java/src/game/gui/container/GuiInventory.java rename to client/src/main/java/client/gui/container/GuiInventory.java index 71a4473..3dd33f0 100755 --- a/java/src/game/gui/container/GuiInventory.java +++ b/client/src/main/java/client/gui/container/GuiInventory.java @@ -1,6 +1,6 @@ -package game.gui.container; +package client.gui.container; -import game.entity.npc.EntityNPC; +import common.entity.npc.EntityNPC; public class GuiInventory extends GuiContainer { diff --git a/java/src/game/gui/container/GuiMerchant.java b/client/src/main/java/client/gui/container/GuiMerchant.java similarity index 93% rename from java/src/game/gui/container/GuiMerchant.java rename to client/src/main/java/client/gui/container/GuiMerchant.java index dc9e4ac..f76faa9 100755 --- a/java/src/game/gui/container/GuiMerchant.java +++ b/client/src/main/java/client/gui/container/GuiMerchant.java @@ -1,16 +1,16 @@ -package game.gui.container; +package client.gui.container; import org.lwjgl.opengl.GL11; -import game.inventory.ContainerMerchant; -import game.inventory.InventoryPlayer; -import game.item.ItemStack; -import game.packet.CPacketAction; -import game.renderer.GlState; -import game.renderer.ItemRenderer; -import game.village.MerchantRecipe; -import game.village.MerchantRecipeList; -import game.world.World; +import client.renderer.GlState; +import client.renderer.ItemRenderer; +import common.inventory.ContainerMerchant; +import common.inventory.InventoryPlayer; +import common.item.ItemStack; +import common.packet.CPacketAction; +import common.village.MerchantRecipe; +import common.village.MerchantRecipeList; +import common.world.World; public class GuiMerchant extends GuiContainer { @@ -81,9 +81,9 @@ public class GuiMerchant extends GuiContainer if (merchantrecipelist != null && !merchantrecipelist.isEmpty()) { int k = this.selectedMerchantRecipe; MerchantRecipe merchantrecipe = (MerchantRecipe)merchantrecipelist.get(k); - ItemStack itemstack = merchantrecipe.getItemToBuy(); - ItemStack itemstack1 = merchantrecipe.getSecondItemToBuy(); - ItemStack itemstack2 = merchantrecipe.getItemToSell(); + ItemStack itemstack = merchantrecipe.first(); + ItemStack itemstack1 = merchantrecipe.second(); + ItemStack itemstack2 = merchantrecipe.result(); this.renderItemOverlayIntoGUI(itemstack, 36, 24, null); if(itemstack1 != null) this.renderItemOverlayIntoGUI(itemstack1, 62, 24, null); @@ -180,9 +180,9 @@ public class GuiMerchant extends GuiContainer // int j = (this.height - this.ySize) / 2; int k = this.selectedMerchantRecipe; MerchantRecipe merchantrecipe = (MerchantRecipe)merchantrecipelist.get(k); - ItemStack itemstack = merchantrecipe.getItemToBuy(); - ItemStack itemstack1 = merchantrecipe.getSecondItemToBuy(); - ItemStack itemstack2 = merchantrecipe.getItemToSell(); + ItemStack itemstack = merchantrecipe.first(); + ItemStack itemstack1 = merchantrecipe.second(); + ItemStack itemstack2 = merchantrecipe.result(); GL11.glPushMatrix(); ItemRenderer.enableGUIStandardItemLighting(); GlState.disableLighting(); diff --git a/java/src/game/gui/container/GuiRepair.java b/client/src/main/java/client/gui/container/GuiRepair.java similarity index 93% rename from java/src/game/gui/container/GuiRepair.java rename to client/src/main/java/client/gui/container/GuiRepair.java index c8e1ba4..b8257bc 100755 --- a/java/src/game/gui/container/GuiRepair.java +++ b/client/src/main/java/client/gui/container/GuiRepair.java @@ -1,15 +1,15 @@ -package game.gui.container; +package client.gui.container; import java.util.List; -import game.Game; -import game.inventory.Container; -import game.inventory.ContainerRepair; -import game.inventory.ICrafting; -import game.inventory.IInventory; -import game.inventory.InventoryPlayer; -import game.item.ItemStack; -import game.world.World; +import client.Client; +import common.inventory.Container; +import common.inventory.ContainerRepair; +import common.inventory.ICrafting; +import common.inventory.IInventory; +import common.inventory.InventoryPlayer; +import common.item.ItemStack; +import common.world.World; public class GuiRepair extends GuiContainer implements ICrafting { @@ -21,7 +21,7 @@ public class GuiRepair extends GuiContainer implements ICrafting public GuiRepair(InventoryPlayer inventoryIn, World worldIn) { - super(new ContainerRepair(inventoryIn, worldIn, Game.getGame().thePlayer)); + super(new ContainerRepair(inventoryIn, worldIn, Client.CLIENT.player)); this.playerInventory = inventoryIn; this.anvil = (ContainerRepair)this.inventorySlots; } @@ -68,7 +68,7 @@ public class GuiRepair extends GuiContainer implements ICrafting { int i = 8453920; boolean flag = true; - String s = String.format("Erfahrungskosten: %d", this.anvil.maximumCost); + String s = String.format("Manakosten: %d", this.anvil.maximumCost); if (this.anvil.maximumCost >= 40) // && !this.gm.thePlayer.creative) { diff --git a/client/src/main/java/client/gui/container/GuiTile.java b/client/src/main/java/client/gui/container/GuiTile.java new file mode 100755 index 0000000..018826d --- /dev/null +++ b/client/src/main/java/client/gui/container/GuiTile.java @@ -0,0 +1,32 @@ +package client.gui.container; + +import client.Client; +import common.inventory.ContainerTile; +import common.inventory.IInventory; +import common.inventory.InventoryPlayer; +import common.tileentity.TileEntityDevice; + + +public class GuiTile extends GuiContainer +{ + private final IInventory playerInv; + private final IInventory tileInv; + private final TileEntityDevice tile; + + public GuiTile(InventoryPlayer player, IInventory inv, TileEntityDevice tile) + { + super(new ContainerTile(player, tile, inv, Client.CLIENT.player)); + this.playerInv = player; + this.tileInv = tile; + this.ySize = 153; + this.tile = tile; + } + + public void drawGuiContainerForegroundLayer() + { + this.drawString(this.tile.getStatus().color + this.tileInv.getCommandName() + " - " + this.tile.getStatus().name, 8, 6); + this.drawString(this.playerInv.getCommandName(), 8, this.ySize - 96 + 2); + this.drawString(String.format("Temperatur: %d °", this.tile.getTemperature()), 8, 18); + this.drawString(this.tile.formatDisplay((ContainerTile)this.inventorySlots), 8, 28); + } +} diff --git a/client/src/main/java/client/gui/element/ActButton.java b/client/src/main/java/client/gui/element/ActButton.java new file mode 100644 index 0000000..d4d32b6 --- /dev/null +++ b/client/src/main/java/client/gui/element/ActButton.java @@ -0,0 +1,26 @@ +package client.gui.element; + +import client.gui.Formatter; +import client.window.Button; + +public class ActButton extends Element { + private final ButtonCallback func; + + public ActButton(int x, int y, int w, int h, ButtonCallback callback, Formatter formatter) { + super(x, y, w, h, formatter); + this.func = callback; + this.formatText(); + } + + public ActButton(int x, int y, int w, int h, ButtonCallback callback, String text) { + super(x, y, w, h, null); + this.func = callback; + this.setText(text); + } + + public void mouse(Button btn, int x, int y, boolean ctrl, boolean shift) { + this.func.use(this, (ctrl || (btn == Button.MOUSE_MIDDLE)) ? PressType.TERTIARY : ((shift || (btn == Button.MOUSE_RIGHT)) ? PressType.SECONDARY : PressType.PRIMARY)); + this.formatText(); + this.playSound(); + } +} diff --git a/client/src/main/java/client/gui/element/Area.java b/client/src/main/java/client/gui/element/Area.java new file mode 100644 index 0000000..d93c6b7 --- /dev/null +++ b/client/src/main/java/client/gui/element/Area.java @@ -0,0 +1,159 @@ +package client.gui.element; + +import client.gui.Font; +import client.renderer.Drawing; +import client.renderer.Drawing.Offset; +import client.renderer.Drawing.Vec2i; +import common.util.CharValidator; +import common.util.ExtMath; +import common.util.Util; + +public class Area extends Textbox { + private int textHeight; + private int scrollPos; + private int cursorX; + private int cursorY; + + private Area(int x, int y, int w, int h, int cap, boolean editable, CharValidator validator, String text) { + super(x, y, w, h, cap, editable, null, validator); + this.setText(text); + } + + public Area(int x, int y, int w, int h, int cap, CharValidator validator, String text) { + this(x, y, w, h, cap, true, validator, text); + } + + public Area(int x, int y, int w, int h, int cap, String text) { + this(x, y, w, h, cap, true, null, text); + } + + public Area(int x, int y, int w, int h, String text) { + this(x, y, w, h, Integer.MAX_VALUE, false, null, text); + } + + public void updateText() { + this.textHeight = Drawing.txt_size(this.pos_x + this.margin_x1, this.pos_y + this.margin_y1, + this.pos_x + this.margin_x1, this.pos_y + this.margin_y1, + this.pos_x + (this.size_x - (this.margin_x1 + this.margin_x2)), Integer.MAX_VALUE, this.text).ypos; + } + + public void scroll(int scr_x, int scr_y, int x, int y, boolean ctrl, boolean shift) { + if(scr_y != 0) { + int limit = Font.YGLYPH + this.textHeight - (this.size_y - (this.margin_y1 + this.margin_y2)); + limit = ExtMath.clampi(limit, 0, 0x7fffffff); + int prev = this.text_y; + this.text_y += (scr_y < 0 ? -1 : 1) * (ctrl ? 1 : Font.YGLYPH) * this.gm.scrollLines * (shift ? 10 : 1); + this.text_y = ExtMath.clampi(this.text_y, -limit, 0); + if(this.sel_start >= 0) + this.cursorY += (this.text_y - prev); + } + } + + public void mouserel() { + this.scrollPos = 0; + } + + public void onReturn(boolean shift) { + insertText("\n"); + } + + public void onSelection(boolean up) { + if(!up && this.sel_start != this.sel_end) { + this.sel_start = this.sel_drag = this.sel_end; + } + else if(up && this.sel_start != this.sel_end) { + this.sel_end = this.sel_drag = this.sel_start; + } + if(!up && this.sel_start >= 0) { + if(this.sel_end < this.text.length()) { + int nl = this.text.indexOf('\n', this.sel_end); + this.sel_end = nl >= 0 ? nl + 1 : this.text.length(); + this.sel_start = this.sel_drag = this.sel_end; + } + else { + this.sel_end = this.sel_drag = this.sel_start; + } + gui_text_update_cur(this.sel_end, true); + } + else if(up && this.sel_start >= 0) { + if(this.sel_start > 0) { + int nl = this.text.lastIndexOf('\n', this.sel_start); + this.sel_start = nl >= 0 ? nl : 0; + } + this.sel_end = this.sel_drag = this.sel_start; + gui_text_update_cur(this.sel_end, true); + } + } + + public void update() { + if(this.scrollPos != 0) { + int n = this.updateScroll(this.scrollPos); + this.text_y += n; + if(n != 0) + gui_text_clamp_scroll(); + } + } + + public void shift(int shift_x, int shift_y) { + super.shift(shift_x, shift_y); + this.cursorX += shift_x; + this.cursorY += shift_y; + } + + protected void gui_text_clamp_scroll() { + int limit = Font.YGLYPH + this.textHeight - (this.size_y - (this.margin_y1 + this.margin_y2)); + limit = ExtMath.clampi(limit, 0, 0x7fffffff); + this.text_y = ExtMath.clampi(this.text_y, -limit, 0); + } + + protected void updateCursor(int offset, boolean shift, int x1, int y1, int x2, int y2) { + Vec2i coord = Drawing.txt_coord(offset, x1, y1 + this.text_y, + x1 + this.text_x, y1 + this.text_y, this.pos_x + x2, 0x7fffffff, this.text); + this.cursorX = coord.xpos; + this.cursorY = coord.ypos; + if(shift) { + if(this.cursorY < y1) + this.text_y += y1 - this.cursorY; + else if((this.cursorY + Font.YGLYPH) >= (y1 + y2)) + this.text_y -= (this.cursorY + Font.YGLYPH) - (y1 + y2); + gui_text_update_cur(offset, false); + } + } + + protected int onCursorOffset(int x, int y, int x1, int y1, int x2, int y2) { + Offset off = Drawing.txt_offset(x, y, x1, y1 + this.text_y, + x1 + this.text_x, y1 + this.text_y, this.pos_x + x2, 0x7fffffff, this.text); + if(off != null) { + this.cursorX = off.xpos; + this.cursorY = off.ypos; + } + int offset = off == null ? 0 : off.offset; + if(y < y1) + this.scrollPos = y1 - y; + else if(y >= (y1 + y2)) + this.scrollPos = -(y - (y1 + y2)); + return offset; + } + + protected void drawForeground(int x1, int y1, int x2, int y2) { + Drawing.txt_draw(x1, y1 + this.text_y, + x1 + this.text_x, y1 + this.text_y, + this.pos_x + x2, Integer.MAX_VALUE, this.enabled ? this.gm.style.text_field : Util.mulColor(this.gm.style.text_field, 0.5f), this.text); + if(this.sel_start >= 0 && this.sel_end != this.sel_start) + Drawing.txt_overlay(this.sel_start, this.sel_end, x1, y1 + this.text_y, + x1 + this.text_x, y1 + this.text_y, + this.pos_x + x2, Integer.MAX_VALUE, this.enabled ? 0x808080ff : 0x80404040, this.text); + } + + protected char getNewline() { + return '\n'; + } + + protected int getCursorX(int x1, int x2) { + return this.cursorX; + } + + protected int getCursorY(int y1, int y2) { + return this.cursorY; + } +} diff --git a/java/src/game/gui/element/Bar.java b/client/src/main/java/client/gui/element/Bar.java similarity index 96% rename from java/src/game/gui/element/Bar.java rename to client/src/main/java/client/gui/element/Bar.java index b8d3f8d..649fb21 100644 --- a/java/src/game/gui/element/Bar.java +++ b/client/src/main/java/client/gui/element/Bar.java @@ -1,8 +1,8 @@ -package game.gui.element; +package client.gui.element; -import game.renderer.Drawing; -import game.util.ExtMath; -import game.util.Util; +import client.renderer.Drawing; +import common.util.ExtMath; +import common.util.Util; public class Bar extends Fill { private int color = 0x00ff00; diff --git a/client/src/main/java/client/gui/element/ButtonCallback.java b/client/src/main/java/client/gui/element/ButtonCallback.java new file mode 100644 index 0000000..b22d24e --- /dev/null +++ b/client/src/main/java/client/gui/element/ButtonCallback.java @@ -0,0 +1,5 @@ +package client.gui.element; + +public interface ButtonCallback { + void use(ActButton elem, PressType action); +} \ No newline at end of file diff --git a/java/src/game/gui/element/Dropdown.java b/client/src/main/java/client/gui/element/Dropdown.java similarity index 78% rename from java/src/game/gui/element/Dropdown.java rename to client/src/main/java/client/gui/element/Dropdown.java index 33280de..773cda0 100644 --- a/java/src/game/gui/element/Dropdown.java +++ b/client/src/main/java/client/gui/element/Dropdown.java @@ -1,13 +1,13 @@ -package game.gui.element; +package client.gui.element; -import game.gui.Font; -import game.gui.Gui; -import game.renderer.Drawing; -import game.util.Displayable; -import game.util.ExtMath; -import game.util.Formatter; -import game.util.Util; -import game.window.Button; +import client.gui.Font; +import client.gui.Formatter; +import client.gui.Gui; +import client.renderer.Drawing; +import client.window.Button; +import common.util.Displayable; +import common.util.ExtMath; +import common.util.Util; public class Dropdown extends Element { public class Handle extends Element { @@ -17,7 +17,7 @@ public class Dropdown extends Element { for(T value : Dropdown.this.values) { if(sb.length() > 0) sb.append('\n'); - sb.append(value instanceof Displayable ? ((Displayable)value).getDisplay() : value.toString()); + sb.append(value instanceof Displayable disp ? disp.getDisplay() : value.toString()); } this.setText(sb.toString()); this.visible = /* this.r_dirty = */ false; @@ -64,18 +64,14 @@ public class Dropdown extends Element { } } - public static interface Callback { - void use(Dropdown elem, T value); - } - - private final Callback func; + private final DropdownCallback func; private final T[] values; private final Handle handle; private final int def; private int value; - public Dropdown(int x, int y, int w, int h, boolean up, T[] values, T def, T init, Callback callback, Formatter> formatter) { + public Dropdown(int x, int y, int w, int h, boolean up, T[] values, T def, T init, DropdownCallback callback, Formatter> formatter) { super(x, y, w, h, formatter); this.func = callback; this.values = values; @@ -85,11 +81,16 @@ public class Dropdown extends Element { this.formatText(); } - public Dropdown(int x, int y, int w, int h, boolean up, T[] values, T def, T init, Callback callback, final String text) { - this(x, y, w, h, up, values, def, init, callback, new Formatter>() { + public Dropdown(int x, int y, int w, int h, boolean up, T[] values, T def, T init, DropdownCallback callback, final String text) { + this(x, y, w, h, up, values, def, init, callback, text == null ? new Formatter>() { public String use(Dropdown elem) { T value = elem.getValue(); - return String.format("%s: %s", text, value instanceof Displayable ? ((Displayable)value).getDisplay() : value.toString()); + return value instanceof Displayable disp ? disp.getDisplay() : value.toString(); + } + } : new Formatter>() { + public String use(Dropdown elem) { + T value = elem.getValue(); + return String.format("%s: %s", text, value instanceof Displayable disp ? disp.getDisplay() : value.toString()); } }); } diff --git a/client/src/main/java/client/gui/element/DropdownCallback.java b/client/src/main/java/client/gui/element/DropdownCallback.java new file mode 100644 index 0000000..4161d31 --- /dev/null +++ b/client/src/main/java/client/gui/element/DropdownCallback.java @@ -0,0 +1,5 @@ +package client.gui.element; + +public interface DropdownCallback { + void use(Dropdown elem, T value); +} \ No newline at end of file diff --git a/java/src/game/gui/element/Element.java b/client/src/main/java/client/gui/element/Element.java similarity index 89% rename from java/src/game/gui/element/Element.java rename to client/src/main/java/client/gui/element/Element.java index 9f7e6ce..f670156 100644 --- a/java/src/game/gui/element/Element.java +++ b/client/src/main/java/client/gui/element/Element.java @@ -1,21 +1,23 @@ -package game.gui.element; +package client.gui.element; import org.lwjgl.opengl.GL11; -import game.Game; -import game.audio.PositionedSound; -import game.audio.Volume; -import game.gui.Gui; -import game.init.SoundEvent; -import game.renderer.Drawing; -import game.renderer.Drawing.Vec2i; -import game.util.Formatter; -import game.util.Util; -import game.window.Button; -import game.window.Keysym; +import client.Client; +import client.gui.Formatter; +import client.gui.Gui; +import client.renderer.Drawing; +import client.renderer.Drawing.Vec2i; +import client.window.Button; +import client.window.Keysym; +import common.init.SoundEvent; +import common.sound.EventType; +import common.sound.PositionedSound; +import common.util.Util; public abstract class Element { - protected final Game gm = Game.getGame(); + public static final int BASE_HEIGHT = 18; + + protected final Client gm = Client.CLIENT; protected Gui gui; protected Formatter format; @@ -36,12 +38,11 @@ public abstract class Element { public boolean visible = true; public boolean enabled = true; - public Element(int x, int y, int w, int h, Formatter formatter) { this.pos_x = x; this.pos_y = y; this.size_x = w; - this.size_y = h; + this.size_y = h <= 0 ? BASE_HEIGHT : h; this.format = formatter; // gui_update_style(this, 1); // if(type != ElemType.SLIDER) { @@ -112,8 +113,8 @@ public abstract class Element { public void updateText() { Vec2i size = Drawing.getSize(this.text); - this.text_x = (this.size_x - size.xpos) / 2; - this.text_y = (this.size_y - size.ypos) / 2; + this.text_x = ((this.size_x - (this.margin_x1 + this.margin_x2)) - size.xpos) / 2; + this.text_y = ((this.size_y - (this.margin_y1 + this.margin_y2)) - size.ypos + 1) / 2; } public void setText(String str) { @@ -220,7 +221,7 @@ public abstract class Element { int x2 = this.size_x - (this.margin_x1 + this.margin_x2); int y2 = this.size_y - (this.margin_y1 + this.margin_y2); // if(elem.type == ElemType.FIELD) { - GL11.glScissor(x1 < 0 ? 0 : x1, (this.gm.fb_y - (y1 + y2)) < 0 ? 0 : (this.gm.fb_y - (y1 + y2)), x2 < 0 ? 0 : x2, y2 < 0 ? 0 : y2); + this.gm.scissor(x1 < 0 ? 0 : x1, (this.gm.fb_y - (y1 + y2)) < 0 ? 0 : (this.gm.fb_y - (y1 + y2)), x2 < 0 ? 0 : x2, y2 < 0 ? 0 : y2); GL11.glEnable(GL11.GL_SCISSOR_TEST); // } // if(this.type == ElemType.CUSTOM) @@ -266,6 +267,6 @@ public abstract class Element { } public void playSound() { - this.gm.getSoundManager().playSound(new PositionedSound(SoundEvent.CLICK, Volume.GUI)); + this.gm.getSoundManager().playSound(new PositionedSound(SoundEvent.CLICK, EventType.UI_INTERFACE)); } } diff --git a/client/src/main/java/client/gui/element/Field.java b/client/src/main/java/client/gui/element/Field.java new file mode 100644 index 0000000..78340d0 --- /dev/null +++ b/client/src/main/java/client/gui/element/Field.java @@ -0,0 +1,198 @@ +package client.gui.element; + +import client.gui.Font; +import client.renderer.Drawing; +import client.renderer.Drawing.Offset; +import client.renderer.Drawing.Vec2i; +import common.util.CharValidator; +import common.util.ExtMath; +import common.util.Util; + +public class Field extends Textbox { + private int textWidth; + private int scrollPos; + private int cursorPos; + + private Field(int x, int y, int w, int h, int cap, boolean editable, FieldCallback callback, CharValidator validator, String text) { + super(x, y, w, h, cap, editable, callback, validator); + this.text_y = (this.size_y - (this.margin_y1 + this.margin_y2 + Font.YGLYPH)) / 2; + this.setText(text); + } + + public Field(int x, int y, int w, int h, int cap, FieldCallback callback, CharValidator validator, String text) { + this(x, y, w, h, cap, true, callback, validator, text); + } + + public Field(int x, int y, int w, int h, int cap, FieldCallback callback, String text) { + this(x, y, w, h, cap, true, callback, null, text); + } + + public Field(int x, int y, int w, int h, String text) { + this(x, y, w, h, Integer.MAX_VALUE, false, null, null, text); + } + + public void updateText() { + this.textWidth = Drawing.txt_size(this.pos_x + this.margin_x1, this.pos_y + this.margin_y1, + this.pos_x + this.margin_x1, this.pos_y + this.margin_y1, + Integer.MAX_VALUE, Integer.MAX_VALUE, this.getDrawnText()).xpos; + } + + public void mouserel() { + this.scrollPos = 0; + } + + public void onReturn(boolean shift) { + if(this.func != null) { + this.func.use(this, shift ? FieldAction.LINE : FieldAction.SEND); + } + } + + public void onSelection(boolean up) { + if(this.func != null) { + this.func.use(this, up ? FieldAction.PREVIOUS : FieldAction.NEXT); + } + } + + public void update() { + if(this.scrollPos != 0) { + int n = this.updateScroll(this.scrollPos); + this.text_x += n; + if(n != 0) + gui_text_clamp_scroll(); + } + } + + public void shift(int shift_x, int shift_y) { + super.shift(shift_x, shift_y); + this.cursorPos += shift_x; + } + + public void scroll(int scr_x, int scr_y, int x, int y, boolean ctrl, boolean shift) { + if(scr_y != 0 || scr_x != 0) { + int limit = Font.XGLYPH + this.textWidth - (this.size_x - (this.margin_x1 + this.margin_x2)); + limit = ExtMath.clampi(limit, 0, 0x7fffffff); + int prev = this.text_x; + this.text_x += ((scr_y != 0 ? scr_y : (-scr_x)) < 0 ? -1 : 1) * (ctrl ? 1 : Font.XGLYPH) * this.gm.scrollLines * (shift ? 10 : 1); + this.text_x = ExtMath.clampi(this.text_x, -limit, 0); + if(this.sel_start >= 0) + this.cursorPos += (this.text_x - prev); + } + } + + protected int getCursorX(int x1, int x2) { + return this.cursorPos; + } + + protected int getCursorY(int y1, int y2) { + return y1 + (y2 - Font.YGLYPH) / 2; + } + + protected void gui_text_clamp_scroll() { + int limit = Font.XGLYPH + this.textWidth - (this.size_x - (this.margin_x1 + this.margin_x2)); + limit = ExtMath.clampi(limit, 0, 0x7fffffff); + this.text_x = ExtMath.clampi(this.text_x, -limit, 0); + } + + protected void updateCursor(int offset, boolean shift, int x1, int y1, int x2, int y2) { + Vec2i coord = Drawing.txt_coord(offset, x1 + this.text_x, y1 + this.text_y, + x1 + this.text_x, y1 + this.text_y, 0x7fffffff, 0x7fffffff, this.getDrawnText()); + this.cursorPos = coord.xpos; + if(shift) { + if(this.cursorPos < x1) + this.text_x += x1 - this.cursorPos; + else if((this.cursorPos + Font.XGLYPH) >= (x1 + x2)) + this.text_x -= (this.cursorPos + Font.XGLYPH) - (x1 + x2); + gui_text_update_cur(offset, false); + } + } + + protected int onCursorOffset(int x, int y, int x1, int y1, int x2, int y2) { + Offset off = Drawing.txt_offset(x, y, x1 + this.text_x, y1 + this.text_y, + x1 + this.text_x, y1 + this.text_y, 0x7fffffff, 0x7fffffff, this.getDrawnText()); + if(off != null) { + this.cursorPos = off.xpos; + } + int offset = off == null ? 0 : off.offset; + if(x < x1) + this.scrollPos = x1 - x; + else if(x >= (x1 + x2)) + this.scrollPos = -(x - (x1 + x2)); + return offset; + } + + protected void drawBackground() { + if(this.enabled) + Drawing.drawGradientBorder(this.pos_x, this.pos_y, this.size_x, this.size_y, this.gm.style.field_top, this.gm.style.field_btm, 0xff000000, this.gm.style.brdr_top, this.gm.style.brdr_btm); + else + Drawing.drawGradientBorder(this.pos_x, this.pos_y, this.size_x, this.size_y, Util.mulColor(this.gm.style.field_top, 0.5f), Util.mulColor(this.gm.style.field_btm, 0.5f), 0xff000000, Util.mulColor(this.gm.style.brdr_top, 0.5f), Util.mulColor(this.gm.style.brdr_btm, 0.5f)); + } + + protected void drawForeground(int x1, int y1, int x2, int y2) { + Drawing.txt_draw(x1 + this.text_x, y1 + this.text_y, + x1 + this.text_x, y1 + this.text_y, + Integer.MAX_VALUE, Integer.MAX_VALUE, this.enabled ? this.gm.style.text_field : Util.mulColor(this.gm.style.text_field, 0.5f), this.getDrawnText()); + if(this.sel_start >= 0 && this.sel_end != this.sel_start) + Drawing.txt_overlay(this.sel_start, this.sel_end, x1 + this.text_x, y1 + this.text_y, + x1 + this.text_x, y1 + this.text_y, + Integer.MAX_VALUE, Integer.MAX_VALUE, this.enabled ? 0x808080ff : 0x80404040, this.getDrawnText()); + } + + protected char getNewline() { + return ' '; + } + + protected String getDrawnText() { + return this.text; + } + + + + + + + + public void deleteSpaceToCur() { + int num = this.getSpaceBeforeCur() - this.sel_start; + if(this.text.length() != 0) { + if(this.sel_start != this.sel_end) { + this.insertText(""); + } + else { +// boolean flag = num < 0; + int i = this.sel_start + num; // flag ? this.sel_start + num : this.sel_start; + int j = this.sel_start; // flag ? this.sel_start : this.sel_start + num; + String s = ""; + + if(i >= 0) { + s = this.text.substring(0, i); + } + + if(j < this.text.length()) { + s = s + this.text.substring(j); + } + +// this.setText(s); + this.text = s; + this.updateText(); + this.sel_start = this.sel_end = this.sel_drag = i; + gui_text_update_cur(this.sel_start, true); +// +// if(flag) { +// this.moveCursorBy(num); +// } + } + } + } + + public int getSpaceBeforeCur() { + int i = this.sel_start; + while(i > 0 && this.text.charAt(i - 1) != ' ') { + --i; + } + return i; + } + + public int getCursorPos() { + return this.sel_start == this.sel_end ? this.sel_start : -1; + } +} diff --git a/client/src/main/java/client/gui/element/FieldAction.java b/client/src/main/java/client/gui/element/FieldAction.java new file mode 100644 index 0000000..e28413d --- /dev/null +++ b/client/src/main/java/client/gui/element/FieldAction.java @@ -0,0 +1,5 @@ +package client.gui.element; + +public enum FieldAction { + FOCUS, UNFOCUS, PREVIOUS, NEXT, FUNCTION, SEND, LINE, FORWARD, BACKWARD; +} \ No newline at end of file diff --git a/client/src/main/java/client/gui/element/FieldCallback.java b/client/src/main/java/client/gui/element/FieldCallback.java new file mode 100644 index 0000000..09d2ada --- /dev/null +++ b/client/src/main/java/client/gui/element/FieldCallback.java @@ -0,0 +1,5 @@ +package client.gui.element; + +public interface FieldCallback extends TextCallback { + void use(Field elem, FieldAction value); +} \ No newline at end of file diff --git a/java/src/game/gui/element/Fill.java b/client/src/main/java/client/gui/element/Fill.java similarity index 79% rename from java/src/game/gui/element/Fill.java rename to client/src/main/java/client/gui/element/Fill.java index 7a9a90b..7067dcf 100644 --- a/java/src/game/gui/element/Fill.java +++ b/client/src/main/java/client/gui/element/Fill.java @@ -1,7 +1,7 @@ -package game.gui.element; +package client.gui.element; -import game.renderer.Drawing; -import game.renderer.Drawing.Vec2i; +import client.renderer.Drawing; +import client.renderer.Drawing.Vec2i; public class Fill extends Element { private final boolean left; @@ -50,8 +50,8 @@ public class Fill extends Element { public void updateText() { Vec2i size = Drawing.getSize(this.text); if(!this.left) - this.text_x = (this.size_x - size.xpos) / 2; + this.text_x = ((this.size_x - (this.margin_x1 + this.margin_x2)) - size.xpos) / 2; if(!this.top) - this.text_y = (this.size_y - size.ypos) / 2; + this.text_y = ((this.size_y - (this.margin_y1 + this.margin_y2)) - size.ypos + 1) / 2; } } diff --git a/client/src/main/java/client/gui/element/GuiList.java b/client/src/main/java/client/gui/element/GuiList.java new file mode 100755 index 0000000..0727984 --- /dev/null +++ b/client/src/main/java/client/gui/element/GuiList.java @@ -0,0 +1,292 @@ +package client.gui.element; + +import java.util.List; + +import client.gui.Gui; +import client.renderer.Drawing; +import client.window.Button; +import common.collect.Lists; +import common.util.ExtMath; + +public abstract class GuiList extends Gui +{ + public static final int SCROLLBAR_WIDTH = 6; + + protected final List elements = Lists.newArrayList(); + + protected int width; + protected int height; + + protected int top; + protected int bottom; + protected int right; + protected int left; + protected int mouseX; + protected int mouseY; + protected int initialClickY = -2; + protected float scrollMultiplier; + protected float amountScrolled; + protected int selectedElement = -1; + protected long lastClicked; + + public abstract int getSlotHeight(); + + protected boolean isScrollbarRight() + { + return false; + } + + public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn) + { + this.width = widthIn; + this.height = heightIn; + this.top = topIn; + this.bottom = bottomIn; + this.left = 0; + this.right = widthIn; + } + + public void init(int width, int height) { + + this.selectedElement = -1; + } + + public void setSlotXBoundsFromLeft(int leftIn) + { + this.left = leftIn; + this.right = leftIn + this.width; + } + + public final T getListEntry(int index) { + return this.elements.get(index); + } + + public final T getSelected() { + return this.selectedElement < 0 ? null : this.elements.get(this.selectedElement); + } + + public final int getSize() { + return this.elements.size(); + } + + public final void setSelected(int index) { + this.selectedElement = index; + } + + protected int getContentHeight() + { + return this.getSize() * this.getSlotHeight(); + } + + public int getSlotIndexFromScreenCoords(int x, int y) + { + int x1 = this.left + (this.isScrollbarRight() ? 0 : SCROLLBAR_WIDTH); + int x2 = this.left + (this.isScrollbarRight() ? this.width - SCROLLBAR_WIDTH : this.width); + int y1 = y - this.top + (int)this.amountScrolled - 4; + int idx = y1 / this.getSlotHeight(); + return this.isInList(x, y) && x >= x1 && x <= x2 && idx >= 0 && y1 >= 0 && idx < this.getSize() ? idx : -1; + } + + protected boolean isInList(int x, int y) + { + return this.isScrollbarRight() ? x < this.width - SCROLLBAR_WIDTH : x >= SCROLLBAR_WIDTH; + } + + protected final boolean isSelected(int slotIndex) + { + return slotIndex == this.selectedElement; + } + + protected void bindAmountScrolled() + { + this.amountScrolled = ExtMath.clampf(this.amountScrolled, 0.0F, (float)this.getMaxScroll()); + } + + public int getMaxScroll() + { + return Math.max(0, this.getContentHeight() - (this.bottom - this.top - 4)); + } + + public int getAmountScrolled() + { + return (int)this.amountScrolled; + } + + public boolean isMouseYWithinSlotBounds(int y) + { + return y >= this.top && y <= this.bottom && this.mouseX >= this.left && this.mouseX <= this.right; + } + + public void scrollBy(int amount) + { + this.amountScrolled += (float)amount; + this.bindAmountScrolled(); + this.initialClickY = -2; + } + + public void draw() + { + int mouseXIn = this.gm.mouse_x; + int mouseYIn = this.gm.mouse_y; + this.mouseX = mouseXIn; + this.mouseY = mouseYIn; + this.drawBackground(); + this.bindAmountScrolled(); + + Drawing.drawScaled(this.gm, Gui.BACKGROUND, 0, this.top, this.gm.fb_x, this.bottom - this.top, 0xff7f7f7f); + + int x = this.left + (this.isScrollbarRight() ? 0 : SCROLLBAR_WIDTH); + int y = this.top + 4 - (int)this.amountScrolled; + + int size = this.getSize(); + boolean canHover = this.clicked(mouseXIn, mouseYIn) == null; + + for (int z = 0; z < size; z++) + { + int y1 = y + z * this.getSlotHeight(); + int h = this.getSlotHeight() - 4; + + Drawing.drawRectBorder(x, y1 - 2, this.width - SCROLLBAR_WIDTH, this.getSlotHeight(), this.isSelected(z) ? this.gm.style.fill_btm : this.gm.style.fill_top, this.isSelected(z) ? 0xffffffff : 0xff000000, this.gm.style.brdr_top, this.gm.style.brdr_btm); + + boolean hover = canHover && this.getSlotIndexFromScreenCoords(mouseXIn, mouseYIn) == z; + this.getListEntry(z).draw(x + 2, y1, this.width - SCROLLBAR_WIDTH - 4, this.getSlotHeight() - 4, mouseXIn - x - 2, mouseYIn - y1, hover); + if(hover) + Drawing.drawRect(x, y1 - 2, this.width - SCROLLBAR_WIDTH, this.getSlotHeight(), Gui.HOVER_COLOR); + } + + Drawing.drawScaled(this.gm, Gui.BACKGROUND, 0, 0, this.gm.fb_x, this.top, 0xffffffff); + Drawing.drawScaled(this.gm, Gui.BACKGROUND, 0, this.bottom, this.gm.fb_x, this.height - this.bottom, 0xffffffff); + Drawing.drawRect(-1, -1, this.gm.fb_x + 2, this.top + 1, 0, this.gm.style.brdr_top, this.gm.style.brdr_btm); + Drawing.drawRect(-1, this.bottom, this.gm.fb_x + 2, this.height - this.bottom + 1, 0, this.gm.style.brdr_top, this.gm.style.brdr_btm); + + int edge = 2; + Drawing.drawGradient(0, this.top, this.gm.fb_x, edge, 0xff000000, 0x00000000); + Drawing.drawGradient(0, this.bottom - edge, this.gm.fb_x, edge, 0x00000000, 0xff000000); + + int max = this.getMaxScroll(); + + if (max > 0) + { + int barHeight = (this.bottom - this.top) * (this.bottom - this.top) / this.getContentHeight(); + barHeight = ExtMath.clampi(barHeight, 32, this.bottom - this.top - 8); + int scrollX = this.isScrollbarRight() ? this.width - SCROLLBAR_WIDTH : 0; + int scrollY = (int)this.amountScrolled * (this.bottom - this.top - barHeight) / max + this.top; + if(scrollY < this.top) + scrollY = this.top; + Drawing.drawRect(scrollX, this.top, SCROLLBAR_WIDTH, this.bottom - this.top, 0xff000000); + Drawing.drawGradient(scrollX, scrollY, SCROLLBAR_WIDTH, barHeight, this.gm.style.fill_top, this.gm.style.fill_btm, this.gm.style.brdr_top, this.gm.style.brdr_btm); + } + + super.draw(); + } + + public void handleMouseInput() + { + if (this.isMouseYWithinSlotBounds(this.mouseY)) + { + if (this.initialClickY == -1) + { + boolean flag1 = true; + + if (this.mouseY >= this.top && this.mouseY <= this.bottom) + { + int j2 = (this.isScrollbarRight() ? 0 : SCROLLBAR_WIDTH); + int k2 = (this.isScrollbarRight() ? this.width - SCROLLBAR_WIDTH : this.width); + int l2 = this.mouseY - this.top + (int)this.amountScrolled - 4; + int i1 = l2 / this.getSlotHeight(); + + if (i1 < this.getSize() && this.mouseX >= j2 && this.mouseX <= k2 && i1 >= 0 && l2 >= 0) + { + } + else if (this.mouseX >= j2 && this.mouseX <= k2 && l2 < 0) + { + flag1 = false; + } + + int i3 = this.isScrollbarRight() ? this.width - SCROLLBAR_WIDTH : 0; + int j1 = i3 + SCROLLBAR_WIDTH; + + if (this.mouseX >= i3 && this.mouseX <= j1) + { + this.scrollMultiplier = -1.0F; + int k1 = this.getMaxScroll(); + + if (k1 < 1) + { + k1 = 1; + } + + int l1 = (int)((float)((this.bottom - this.top) * (this.bottom - this.top)) / (float)this.getContentHeight()); + l1 = ExtMath.clampi(l1, 32, this.bottom - this.top - 8); + this.scrollMultiplier /= (float)(this.bottom - this.top - l1) / (float)k1; + } + else + { + this.scrollMultiplier = 1.0F; + } + + if (flag1) + { + this.initialClickY = this.mouseY; + } + else + { + this.initialClickY = -2; + } + } + else + { + this.initialClickY = -2; + } + } + else if (this.initialClickY >= 0) + { + this.amountScrolled -= (float)(this.mouseY - this.initialClickY) * this.scrollMultiplier; + this.initialClickY = this.mouseY; + } + } + } + + public void mouse(Button btn, int x, int y, boolean ctrl, boolean shift) + { + super.mouse(btn, x, y, ctrl, shift); + if (this.isMouseYWithinSlotBounds(y) && this.clicked(x, y) == null) + { + int i = this.getSlotIndexFromScreenCoords(x, y); + + if (i >= 0) + { + int x1 = this.left + (this.isScrollbarRight() ? 0 : SCROLLBAR_WIDTH) + 2; + int y1 = this.top + 4 - this.getAmountScrolled() + i * this.getSlotHeight(); + int mx = x - x1; + int my = y - y1; + + boolean flag = i == this.selectedElement && System.currentTimeMillis() - this.lastClicked < (long)this.gm.dclickDelay; + this.selectedElement = i; + this.lastClicked = System.currentTimeMillis(); + + this.getListEntry(i).select(flag, mx, my); + } + } + if(btn == Button.MOUSE_LEFT && this.clicked(x, y) == null) + this.handleMouseInput(); + } + + public void mouserel(Button btn, int x, int y) { + super.mouserel(btn, x, y); + if(btn == Button.MOUSE_LEFT) + this.initialClickY = -1; + } + + public void scroll(int scr_x, int scr_y, int x, int y, boolean ctrl, boolean shift) { + super.scroll(scr_x, scr_y, x, y, ctrl, shift); + if(scr_y != 0 && this.clicked(x, y) == null) + this.amountScrolled -= (float)(ExtMath.clampi(scr_y, -1, 1) * this.getSlotHeight() / 2); + } + + public void drag(int x, int y) { + super.drag(x, y); + if(this.selected == null && Button.MOUSE_LEFT.isDown() && (this.initialClickY != -1 || this.clicked(x, y) == null)) + this.handleMouseInput(); + } +} diff --git a/java/src/game/gui/element/InventoryButton.java b/client/src/main/java/client/gui/element/InventoryButton.java similarity index 88% rename from java/src/game/gui/element/InventoryButton.java rename to client/src/main/java/client/gui/element/InventoryButton.java index 6027422..7a71464 100644 --- a/java/src/game/gui/element/InventoryButton.java +++ b/client/src/main/java/client/gui/element/InventoryButton.java @@ -1,6 +1,6 @@ -package game.gui.element; +package client.gui.element; -import game.renderer.Drawing; +import client.renderer.Drawing; public class InventoryButton extends Element { public InventoryButton(int x, int y, int w, int h) { diff --git a/client/src/main/java/client/gui/element/Label.java b/client/src/main/java/client/gui/element/Label.java new file mode 100644 index 0000000..b371741 --- /dev/null +++ b/client/src/main/java/client/gui/element/Label.java @@ -0,0 +1,47 @@ +package client.gui.element; + +import client.renderer.Drawing; +import common.util.Util; + +public class Label extends Fill { + public static final int LABEL_HEIGHT = 14; + + public Label(int x, int y, int w, int h, String text, boolean top, boolean left) { + super(x, y, w, h <= 0 ? LABEL_HEIGHT : h, text, top, left); + } + + public Label(int x, int y, int w, int h, String text, boolean left) { + super(x, y, w, h <= 0 ? LABEL_HEIGHT : h, text, left); + } + + public Label(int x, int y, int w, int h, String text) { + super(x, y, w, h <= 0 ? LABEL_HEIGHT : h, text); + } + + public Label(int x, int y, int w, String text, boolean top, boolean left) { + super(x, y - LABEL_HEIGHT, w, LABEL_HEIGHT, text, top, left); + } + + public Label(int x, int y, int w, String text, boolean left) { + super(x, y - LABEL_HEIGHT, w, LABEL_HEIGHT, text, left); + } + + public Label(int x, int y, int w, String text) { + super(x, y - LABEL_HEIGHT, w, LABEL_HEIGHT, text); + } + + protected void drawBackground() { + } + + protected void drawForeground(int x1, int y1, int x2, int y2) { + Drawing.drawText(this.text, x1 + this.text_x, y1 + this.text_y, this.enabled ? this.gm.style.text_label : Util.mulColor(this.gm.style.text_label, 0.5f)); + } + + protected int getMarginX() { + return 0; + } + + protected int getMarginY() { + return 0; + } +} diff --git a/client/src/main/java/client/gui/element/ListEntry.java b/client/src/main/java/client/gui/element/ListEntry.java new file mode 100644 index 0000000..1360285 --- /dev/null +++ b/client/src/main/java/client/gui/element/ListEntry.java @@ -0,0 +1,7 @@ +package client.gui.element; + +public interface ListEntry +{ + void draw(int x, int y, int width, int height, int mouseX, int mouseY, boolean hovered); + void select(boolean dclick, int mx, int my); +} \ No newline at end of file diff --git a/client/src/main/java/client/gui/element/MultiLabel.java b/client/src/main/java/client/gui/element/MultiLabel.java new file mode 100644 index 0000000..3eb64a8 --- /dev/null +++ b/client/src/main/java/client/gui/element/MultiLabel.java @@ -0,0 +1,40 @@ +package client.gui.element; + +import client.gui.Font; +import client.renderer.Drawing; +import common.util.Util; + +public class MultiLabel extends Fill { + private String[] lines; + + public MultiLabel(int x, int y, int w, int h, String text, boolean top) { + super(x, y, w, h, text, top, true); + } + + public MultiLabel(int x, int y, int w, int h, String text) { + super(x, y, w, h, text, false, true); + } + + public void setText(String str) { + super.setText(str); + this.lines = str.split("\n", -1); + } + + protected void drawBackground() { + } + + protected void drawForeground(int x1, int y1, int x2, int y2) { + int color = this.enabled ? this.gm.style.text_label : Util.mulColor(this.gm.style.text_label, 0.5f); + for(int z = 0; z < this.lines.length; z++) { + Drawing.drawTextCentered(this.lines[z], x1 + x2 / 2, y1 + this.text_y + z * Font.YGLYPH, color); + } + } + + protected int getMarginX() { + return 0; + } + + protected int getMarginY() { + return 0; + } +} diff --git a/java/src/game/gui/element/NavButton.java b/client/src/main/java/client/gui/element/NavButton.java similarity index 74% rename from java/src/game/gui/element/NavButton.java rename to client/src/main/java/client/gui/element/NavButton.java index f9cc66c..a80d9c4 100644 --- a/java/src/game/gui/element/NavButton.java +++ b/client/src/main/java/client/gui/element/NavButton.java @@ -1,17 +1,17 @@ -package game.gui.element; +package client.gui.element; -import game.Game; -import game.gui.Gui; -import game.renderer.Drawing; -import game.util.Util; +import client.Client; +import client.gui.Gui; +import client.renderer.Drawing; +import common.util.Util; public class NavButton extends ActButton { private final Gui navGui; public NavButton(int x, int y, int w, int h, Gui gui, String text) { - super(x, y, w, h, new Callback() { - public void use(ActButton elem, Mode action) { - Game.getGame().displayGuiScreen(gui); + super(x, y, w, h, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + Client.CLIENT.displayGuiScreen(gui); } }, text); this.navGui = gui; diff --git a/client/src/main/java/client/gui/element/PasswordField.java b/client/src/main/java/client/gui/element/PasswordField.java new file mode 100644 index 0000000..a125e03 --- /dev/null +++ b/client/src/main/java/client/gui/element/PasswordField.java @@ -0,0 +1,17 @@ +package client.gui.element; + +import common.util.Util; + +public class PasswordField extends Field { + public PasswordField(int x, int y, int w, int h, int cap, FieldCallback callback, String text) { + super(x, y, w, h, cap, callback, text); + } + + protected String getDrawnText() { + return Util.repeatString("*", this.text.length()); + } + + protected boolean canCopy() { + return false; + } +} diff --git a/client/src/main/java/client/gui/element/PressType.java b/client/src/main/java/client/gui/element/PressType.java new file mode 100644 index 0000000..4424611 --- /dev/null +++ b/client/src/main/java/client/gui/element/PressType.java @@ -0,0 +1,5 @@ +package client.gui.element; + +public enum PressType { + PRIMARY, SECONDARY, TERTIARY; +} \ No newline at end of file diff --git a/java/src/game/gui/element/SelectableButton.java b/client/src/main/java/client/gui/element/SelectableButton.java similarity index 80% rename from java/src/game/gui/element/SelectableButton.java rename to client/src/main/java/client/gui/element/SelectableButton.java index 4dc7995..b9888a2 100644 --- a/java/src/game/gui/element/SelectableButton.java +++ b/client/src/main/java/client/gui/element/SelectableButton.java @@ -1,12 +1,12 @@ -package game.gui.element; +package client.gui.element; -import game.renderer.Drawing; -import game.util.Util; +import client.renderer.Drawing; +import common.util.Util; public class SelectableButton extends ActButton { private boolean selected; - public SelectableButton(int x, int y, int w, int h, Callback callback, String text, boolean selected) { + public SelectableButton(int x, int y, int w, int h, ButtonCallback callback, String text, boolean selected) { super(x, y, w, h, callback, text); this.selected = selected; } diff --git a/java/src/game/gui/element/Slider.java b/client/src/main/java/client/gui/element/Slider.java similarity index 85% rename from java/src/game/gui/element/Slider.java rename to client/src/main/java/client/gui/element/Slider.java index f994c33..5df5d99 100644 --- a/java/src/game/gui/element/Slider.java +++ b/client/src/main/java/client/gui/element/Slider.java @@ -1,23 +1,15 @@ -package game.gui.element; +package client.gui.element; -import game.renderer.Drawing; -import game.util.ExtMath; -import game.util.Formatter; -import game.util.Util; -import game.window.Button; +import client.gui.Formatter; +import client.renderer.Drawing; +import client.window.Button; +import common.util.ExtMath; +import common.util.Util; public class Slider extends Element { - public static interface Callback { - void use(Slider elem, int value); - } - - public static interface FloatCallback { - void use(Slider elem, float value); - } + private static final int SLIDER_WIDTH = 8; - private static final int SLIDER_WIDTH = 10; - - private final Callback func; + private final SliderCallback func; private final int def; private final int min; private final int max; @@ -27,9 +19,9 @@ public class Slider extends Element { private int value; private int position; - public Slider(int x, int y, int w, int h, int prec, int min, int max, int def, int init, Callback callback, Formatter formatter) { + public Slider(int x, int y, int w, int h, int prec, int min, int max, int def, int init, SliderCallback callback, Formatter formatter) { super(x, y, w, h, formatter); - this.handle = ((this.size_y * SLIDER_WIDTH) / 24) & ~1; + this.handle = ((this.size_y * SLIDER_WIDTH) / BASE_HEIGHT) & ~1; this.func = callback; this.precision = prec; this.min = min; @@ -40,7 +32,7 @@ public class Slider extends Element { this.formatText(); } - public Slider(int x, int y, int w, int h, int prec, int min, int max, int def, int init, Callback callback, final String text) { + public Slider(int x, int y, int w, int h, int prec, int min, int max, int def, int init, SliderCallback callback, final String text) { this(x, y, w, h, prec, min, max, def, init, callback, new Formatter() { public String use(Slider elem) { return String.format("%s: %d", text, elem.value); @@ -48,7 +40,7 @@ public class Slider extends Element { }); } - public Slider(int x, int y, int w, int h, int prec, int min, int max, int def, int init, Callback callback, final String text, final String unit) { + public Slider(int x, int y, int w, int h, int prec, int min, int max, int def, int init, SliderCallback callback, final String text, final String unit) { this(x, y, w, h, prec, min, max, def, init, callback, new Formatter() { private final String format = unit.isEmpty() ? "%s: %d" : "%s: %d %s"; @@ -58,15 +50,15 @@ public class Slider extends Element { }); } - public Slider(int x, int y, int w, int h, int prec, float min, float max, float def, float init, final FloatCallback callback, Formatter formatter) { - this(x, y, w, h, prec, (int)(min * 1000.0f), (int)(max * 1000.0f), (int)(def * 1000.0f), (int)(init * 1000.0f), new Callback() { + public Slider(int x, int y, int w, int h, int prec, float min, float max, float def, float init, final SliderFloatCallback callback, Formatter formatter) { + this(x, y, w, h, prec, (int)(min * 1000.0f), (int)(max * 1000.0f), (int)(def * 1000.0f), (int)(init * 1000.0f), new SliderCallback() { public void use(Slider elem, int value) { callback.use(elem, (float)value / 1000.0f); } }, formatter); } - public Slider(int x, int y, int w, int h, final int prec, float min, float max, float def, float init, FloatCallback callback, final String text, final String unit) { + public Slider(int x, int y, int w, int h, final int prec, float min, float max, float def, float init, SliderFloatCallback callback, final String text, final String unit) { this(x, y, w, h, prec < 0 ? 0 : prec, min, max, def, init, callback, new Formatter() { private final String format = "%s: " + (prec <= 0 ? "%d" : ("%." + prec + "f")) + (unit.isEmpty() ? "" : " %s"); diff --git a/client/src/main/java/client/gui/element/SliderCallback.java b/client/src/main/java/client/gui/element/SliderCallback.java new file mode 100644 index 0000000..4ed60b0 --- /dev/null +++ b/client/src/main/java/client/gui/element/SliderCallback.java @@ -0,0 +1,5 @@ +package client.gui.element; + +public interface SliderCallback { + void use(Slider elem, int value); +} \ No newline at end of file diff --git a/client/src/main/java/client/gui/element/SliderFloatCallback.java b/client/src/main/java/client/gui/element/SliderFloatCallback.java new file mode 100644 index 0000000..ca24df3 --- /dev/null +++ b/client/src/main/java/client/gui/element/SliderFloatCallback.java @@ -0,0 +1,5 @@ +package client.gui.element; + +public interface SliderFloatCallback { + void use(Slider elem, float value); +} \ No newline at end of file diff --git a/java/src/game/gui/element/Switch.java b/client/src/main/java/client/gui/element/Switch.java similarity index 75% rename from java/src/game/gui/element/Switch.java rename to client/src/main/java/client/gui/element/Switch.java index 77249c2..02449a8 100644 --- a/java/src/game/gui/element/Switch.java +++ b/client/src/main/java/client/gui/element/Switch.java @@ -1,22 +1,18 @@ -package game.gui.element; +package client.gui.element; -import game.util.Displayable; -import game.util.Formatter; -import game.util.Util; -import game.window.Button; +import client.gui.Formatter; +import client.window.Button; +import common.util.Displayable; +import common.util.Util; public class Switch extends Element { - public static interface Callback { - void use(Switch elem, T value); - } - - private final Callback func; + private final SwitchCallback func; private final T[] values; private final int def; private int value; - public Switch(int x, int y, int w, int h, T[] values, T def, T init, Callback callback, Formatter> formatter) { + public Switch(int x, int y, int w, int h, T[] values, T def, T init, SwitchCallback callback, Formatter> formatter) { super(x, y, w, h, formatter); this.func = callback; this.values = values; @@ -25,11 +21,11 @@ public class Switch extends Element { this.formatText(); } - public Switch(int x, int y, int w, int h, T[] values, T def, T init, Callback callback, final String text) { + public Switch(int x, int y, int w, int h, T[] values, T def, T init, SwitchCallback callback, final String text) { this(x, y, w, h, values, def, init, callback, new Formatter>() { public String use(Switch elem) { T value = elem.getValue(); - return String.format("%s: %s", text, value instanceof Displayable ? ((Displayable)value).getDisplay() : value.toString()); + return String.format("%s: %s", text, value instanceof Displayable disp ? disp.getDisplay() : value.toString()); } }); } diff --git a/client/src/main/java/client/gui/element/SwitchCallback.java b/client/src/main/java/client/gui/element/SwitchCallback.java new file mode 100644 index 0000000..2893e44 --- /dev/null +++ b/client/src/main/java/client/gui/element/SwitchCallback.java @@ -0,0 +1,5 @@ +package client.gui.element; + +public interface SwitchCallback { + void use(Switch elem, T value); +} \ No newline at end of file diff --git a/client/src/main/java/client/gui/element/TextCallback.java b/client/src/main/java/client/gui/element/TextCallback.java new file mode 100644 index 0000000..c014c89 --- /dev/null +++ b/client/src/main/java/client/gui/element/TextCallback.java @@ -0,0 +1,5 @@ +package client.gui.element; + +interface TextCallback { + void use(T elem, FieldAction value); +} \ No newline at end of file diff --git a/client/src/main/java/client/gui/element/Textbox.java b/client/src/main/java/client/gui/element/Textbox.java new file mode 100644 index 0000000..dd69674 --- /dev/null +++ b/client/src/main/java/client/gui/element/Textbox.java @@ -0,0 +1,251 @@ +package client.gui.element; + +import org.lwjgl.opengl.GL11; + +import client.gui.Font; +import client.renderer.Drawing; +import client.window.Button; +import client.window.Keysym; +import client.window.Window; +import common.util.CharValidator; +import common.util.Util; + +abstract class Textbox extends Element { + protected final TextCallback func; + protected final CharValidator validator; + protected final int capacity; + protected final boolean editable; + + protected long tmr_scroll; + protected long tmr_leftmb; + protected int sel_start = -1; + protected int sel_end = -1; + protected int sel_drag = -1; + + protected Textbox(int x, int y, int w, int h, int cap, boolean editable, TextCallback callback, CharValidator validator) { + super(x, y, w, h, null); + this.func = callback; + this.validator = validator; + this.capacity = cap; + this.editable = editable; + } + + public abstract void updateText(); + protected abstract void onReturn(boolean shift); + protected abstract void onSelection(boolean up); + public abstract void scroll(int scr_x, int scr_y, int x, int y, boolean ctrl, boolean shift); + public abstract void update(); + protected abstract void gui_text_clamp_scroll(); + protected abstract void updateCursor(int offset, boolean shift, int x1, int y1, int x2, int y2); + protected abstract char getNewline(); + protected abstract int getCursorX(int x1, int x2); + protected abstract int getCursorY(int y1, int y2); + protected abstract int onCursorOffset(int x, int y, int x1, int y1, int x2, int y2); + protected abstract void drawForeground(int x1, int y1, int x2, int y2); + + public boolean canHover() { + return false; + } + + protected int getMarginX() { + return 4; + } + + protected boolean canCopy() { + return true; + } + + public void setText(String str) { + if(this.validator != null) + str = this.validator.filter(str); + this.text = str.length() > this.capacity ? str.substring(0, this.capacity) : str; + this.updateText(); + this.sel_start = this.sel_end = this.sel_drag = this.text.length(); + gui_text_update_cur(this.sel_start, true); + } + + public void mouse(Button btn, int x, int y, boolean ctrl, boolean shift) { + if(btn == Button.MOUSE_LEFT) { + if(!shift && ((System.currentTimeMillis() - this.tmr_leftmb) <= (long)this.gm.dclickDelay)) { + this.sel_start = this.sel_drag = 0; + this.sel_end = this.text.length(); + } + else { + gui_text_select(x, y, shift); + } + this.tmr_leftmb = System.currentTimeMillis(); + } + else if((btn == Button.MOUSE_MIDDLE) && this.func != null) { + this.func.use(this, FieldAction.FUNCTION); + } + } + + public void drag(int x, int y) { + gui_text_select(x, y, true); + } + + public void character(char code) { + if(this.editable) + insertText(Character.toString(code)); + } + + public void key(Keysym key, boolean ctrl, boolean shift) { + if(ctrl && key == Keysym.A) { + this.sel_start = this.sel_drag = 0; + this.sel_end = this.text.length(); + } + else if(ctrl && (key == Keysym.C) || (this.editable && (key == Keysym.X))) { + if(this.canCopy() && this.sel_start >= 0 && this.sel_start != this.sel_end) { // fix empty + String str = Util.strip(this.text, this.sel_start, this.sel_end - this.sel_start, '\n', (char)0, '?'); + Window.setClipboard(str); + if(key == Keysym.X) + insertText(""); + } + } + else if(this.editable && ctrl && key == Keysym.V) { + insertText(Window.getClipboard()); + } + else if(this.editable && !ctrl && key == Keysym.RETURN) { + this.onReturn(shift); + } + else if(this.editable && (!ctrl) && (key == Keysym.BACKSPACE || key == Keysym.DELETE)) { + if(this.sel_start != this.sel_end) { + insertText(""); + } + else if(key == Keysym.DELETE && this.sel_start >= 0) { + if(this.sel_end < this.text.length()) { + this.sel_end += 1; + insertText(""); + } + else { + this.sel_end = this.sel_start; + } + } + else if(key == Keysym.BACKSPACE && this.sel_start > 0) { + this.sel_start -= 1; + insertText(""); + } + } + else if(!ctrl && (key == Keysym.RIGHT || key == Keysym.LEFT)) { + if(key == Keysym.RIGHT && this.sel_start != this.sel_end) { + this.sel_start = this.sel_drag = this.sel_end; + } + else if(key == Keysym.LEFT && this.sel_start != this.sel_end) { + this.sel_end = this.sel_drag = this.sel_start; + } + if(key == Keysym.RIGHT && this.sel_start >= 0) { + if(this.sel_end < this.text.length()) { + this.sel_start = this.sel_drag = this.sel_end += 1; + } + else { + this.sel_end = this.sel_drag = this.sel_start; + } + gui_text_update_cur(this.sel_end, true); + } + else if(key == Keysym.LEFT && this.sel_start >= 0) { + if(this.sel_start > 0) + this.sel_start -= 1; + this.sel_end = this.sel_drag = this.sel_start; + gui_text_update_cur(this.sel_end, true); + } + } + else if(!ctrl && (key == Keysym.DOWN || key == Keysym.UP)) { + this.onSelection(key == Keysym.UP); + } + else if((!ctrl) && key == Keysym.TAB) { + if(this.func != null) { + this.func.use(this, shift ? FieldAction.BACKWARD : FieldAction.FORWARD); + } + } + } + + public void select() { + if(this.func != null) { + this.func.use(this, FieldAction.FOCUS); + } + } + + public void deselect() { + this.sel_start = this.sel_end = this.sel_drag = -1; + this.tmr_leftmb = 0L; + if(this.func != null) { + this.func.use(this, FieldAction.UNFOCUS); + } + } + + protected int updateScroll(int value) { + if(value != 0) { + int n = (int)((float)((float)this.tmr_scroll) / 1000000.0f * 4.0f * ((float)value)); + if((((long)n) * 1000000L) <= this.tmr_scroll) + this.tmr_scroll -= ((long)n) * 1000000L; + else + this.tmr_scroll = 0L; + this.tmr_scroll += this.gm.getPassedTime(); + return n; + } + return 0; + } + + protected void gui_text_update_cur(int offset, boolean shift) { + int x1 = this.pos_x + this.margin_x1; + int y1 = this.pos_y + this.margin_y1; + int x2 = this.size_x - (this.margin_x1 + this.margin_x2); + int y2 = this.size_y - (this.margin_y1 + this.margin_y2); + gui_text_clamp_scroll(); + this.updateCursor(offset, shift, x1, y1, x2, y2); + } + + public void insertText(String str) { + if(str == null || (this.sel_start == -1)) + return; + str = Util.strip(str, 0, str.length(), this.getNewline(), ' ', (char)0); + if(this.validator != null) + str = this.validator.filter(str); + if((str.length() + this.text.length() - (this.sel_end - this.sel_start)) > this.capacity) + return; + this.text = this.text.substring(0, this.sel_start) + str + this.text.substring(this.sel_end); + this.sel_start += str.length(); + this.sel_end = this.sel_drag = this.sel_start; + this.updateText(); + gui_text_update_cur(this.sel_end, true); + } + + private void gui_text_select(int x, int y, boolean drag) { + int x1 = this.pos_x + this.margin_x1; + int y1 = this.pos_y + this.margin_y1; + int x2 = this.size_x - (this.margin_x1 + this.margin_x2); + int y2 = this.size_y - (this.margin_y1 + this.margin_y2); + int offset = this.onCursorOffset(x, y, x1, y1, x2, y2); + if(!drag) { + this.sel_drag = this.sel_start = this.sel_end = offset; + } + else if(drag && this.sel_drag >= 0 && offset >= this.sel_drag) { + this.sel_start = this.sel_drag; + this.sel_end = offset; + } + else if(drag && this.sel_drag >= 0 && offset < this.sel_drag) { + this.sel_start = offset; + this.sel_end = this.sel_drag; + } + } + + protected void drawBackground() { + if(this.enabled) + Drawing.drawGradientBorder(this.pos_x, this.pos_y, this.size_x, this.size_y, this.gm.style.field_top, this.gm.style.field_btm, 0xff000000, this.gm.style.brdr_top, this.gm.style.brdr_btm); + else + Drawing.drawGradientBorder(this.pos_x, this.pos_y, this.size_x, this.size_y, Util.mulColor(this.gm.style.field_top, 0.5f), Util.mulColor(this.gm.style.field_btm, 0.5f), 0xff000000, Util.mulColor(this.gm.style.brdr_top, 0.5f), Util.mulColor(this.gm.style.brdr_btm, 0.5f)); + } + + public void drawOverlay() { + if(this.editable && this.sel_start >= 0 && this.sel_end == this.sel_start && Util.ftime() % 1.0f < 0.5f) { + int x1 = this.pos_x + this.margin_x1; + int y1 = this.pos_y + this.margin_y1; + int x2 = this.size_x - (this.margin_x1 + this.margin_x2); + int y2 = this.size_y - (this.margin_y1 + this.margin_y2); + this.gm.scissor(x1 < 0 ? 0 : x1, (this.gm.fb_y - (y1 + y2)) < 0 ? 0 : (this.gm.fb_y - (y1 + y2)), x2 < 0 ? 0 : x2, y2 < 0 ? 0 : y2); + GL11.glEnable(GL11.GL_SCISSOR_TEST); + Drawing.drawRect(this.getCursorX(x1, x2), this.getCursorY(y1, y2), 1, Font.YGLYPH, 0xff000000 | (~Util.mixColor(this.gm.style.field_top, this.gm.style.field_btm))); + GL11.glDisable(GL11.GL_SCISSOR_TEST); + } + } +} diff --git a/java/src/game/gui/element/Toggle.java b/client/src/main/java/client/gui/element/Toggle.java similarity index 74% rename from java/src/game/gui/element/Toggle.java rename to client/src/main/java/client/gui/element/Toggle.java index 568f2b2..ea0467d 100644 --- a/java/src/game/gui/element/Toggle.java +++ b/client/src/main/java/client/gui/element/Toggle.java @@ -1,21 +1,17 @@ -package game.gui.element; +package client.gui.element; -import game.renderer.Drawing; -import game.util.Formatter; -import game.util.Util; -import game.window.Button; +import client.gui.Formatter; +import client.renderer.Drawing; +import client.window.Button; +import common.util.Util; public class Toggle extends Element { - public static interface Callback { - void use(Toggle elem, boolean value); - } - - private final Callback func; + private final ToggleCallback func; private final boolean def; private boolean value; - public Toggle(int x, int y, int w, int h, boolean def, boolean init, Callback callback, Formatter formatter) { + public Toggle(int x, int y, int w, int h, boolean def, boolean init, ToggleCallback callback, Formatter formatter) { super(x, y, w, h, formatter); this.func = callback; this.def = def; @@ -23,7 +19,7 @@ public class Toggle extends Element { this.formatText(); } - public Toggle(int x, int y, int w, int h, boolean def, boolean init, Callback callback, final String text) { + public Toggle(int x, int y, int w, int h, boolean def, boolean init, ToggleCallback callback, final String text) { this(x, y, w, h, def, init, callback, new Formatter() { public String use(Toggle elem) { return String.format("%s: %s", text, elem.value ? "An" : "Aus"); @@ -38,7 +34,8 @@ public class Toggle extends Element { // this.type = this.value != 0 ? ElemType.TOGGLE_ON : ElemType.TOGGLE_OFF; // gui_update_style(this, 1); // this.r_dirty = true; - this.func.use(this, this.value); + if(this.func != null) + this.func.use(this, this.value); this.formatText(); this.playSound(); } @@ -54,4 +51,15 @@ public class Toggle extends Element { else super.drawBackground(); } + + public void setValue(boolean value) { + if(this.value != value) { + this.value = value; + this.formatText(); + } + } + + public boolean getValue() { + return this.value; + } } diff --git a/client/src/main/java/client/gui/element/ToggleCallback.java b/client/src/main/java/client/gui/element/ToggleCallback.java new file mode 100644 index 0000000..8aa374b --- /dev/null +++ b/client/src/main/java/client/gui/element/ToggleCallback.java @@ -0,0 +1,5 @@ +package client.gui.element; + +public interface ToggleCallback { + void use(Toggle elem, boolean value); +} \ No newline at end of file diff --git a/java/src/game/gui/element/TransparentBox.java b/client/src/main/java/client/gui/element/TransparentArea.java similarity index 56% rename from java/src/game/gui/element/TransparentBox.java rename to client/src/main/java/client/gui/element/TransparentArea.java index b7f66d9..d9da822 100644 --- a/java/src/game/gui/element/TransparentBox.java +++ b/client/src/main/java/client/gui/element/TransparentArea.java @@ -1,11 +1,11 @@ -package game.gui.element; +package client.gui.element; -import game.renderer.Drawing; +import client.renderer.Drawing; -public class TransparentBox extends Textbox { +public class TransparentArea extends Area { private final boolean background; - public TransparentBox(int x, int y, int w, int h, String text, boolean background) { + public TransparentArea(int x, int y, int w, int h, String text, boolean background) { super(x, y, w, h, text); this.background = background; } diff --git a/client/src/main/java/client/gui/ingame/GuiForm.java b/client/src/main/java/client/gui/ingame/GuiForm.java new file mode 100644 index 0000000..510de33 --- /dev/null +++ b/client/src/main/java/client/gui/ingame/GuiForm.java @@ -0,0 +1,124 @@ +package client.gui.ingame; + +import client.gui.Gui; +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.Element; +import client.gui.element.Label; +import client.gui.element.NavButton; +import client.gui.element.PasswordField; +import client.gui.element.PressType; +import client.gui.element.Switch; +import client.gui.element.SwitchCallback; +import client.gui.element.FieldAction; +import client.gui.element.Field; +import client.gui.element.FieldCallback; +import client.gui.element.Toggle; +import client.gui.element.ToggleCallback; +import client.network.ClientPlayer; +import common.color.TextColor; +import common.packet.CPacketForm; +import common.util.ExtMath; +import common.util.Triplet; + +public class GuiForm extends Gui implements ButtonCallback { + private final int id; + private final String title; + private final Element[] inputs; + private final Label[] labels; + private final Triplet[] inputData; + private final Object[] outputData; + + private boolean sent; + + public void init(int width, int height) { + this.add(new Label(0, -100, 300, 0, this.title)); + for(int z = 0; z < this.inputs.length; z++) { + final int index = z; + final String name = this.inputData[z].first(); + Object obj = this.inputData[z].second(); + int param = this.inputData[z].third(); + if(obj instanceof Boolean bool) { + this.inputs[z] = this.add(new Toggle(0, 50 * z, 300, 0, bool, bool, new ToggleCallback() { + public void use(Toggle elem, boolean value) { + GuiForm.this.outputData[index] = value; + } + }, name)); + } + else if(obj instanceof String[] strs) { + param = ExtMath.clampi(param, 0, strs.length - 1); + this.inputs[z] = this.add(new Switch(0, 50 * z, 300, 0, strs, strs[param], strs[param], new SwitchCallback() { + public void use(Switch elem, String value) { + for(int n = 0; n < strs.length; n++) { + if(value == strs[n]) { + GuiForm.this.outputData[index] = n; + break; + } + } + } + }, name)); + } + else { + this.labels[z] = this.add(new Label(0, 50 * z, 300, name, true)); + FieldCallback callback = new FieldCallback() { + public void use(Field elem, FieldAction value) { + if(value == FieldAction.FOCUS) + GuiForm.this.labels[index].setText(name); + } + }; + this.inputs[z] = this.add((param & 0x80000000) != 0 ? new PasswordField(0, 50 * z, 300, 0, Math.min(param & 0xffff, 1024), callback, (String)obj) : + new Field(0, 50 * z, 300, 0, Math.min(param & 0xffff, 1024), callback, (String)obj)); + } + } + this.add(new NavButton(0, 50 * (this.inputs.length + 1), 148, 0, null, "Abbrechen")); + this.add(new ActButton(152, 50 * (this.inputs.length + 1), 148, 0, this, "Senden")); + this.shift(); + } + + public String getTitle() { + return this.title; + } + + public void onGuiClosed() { + if(!this.sent) { + ClientPlayer nethandler = this.gm.getNetHandler(); + if(nethandler != null) { + nethandler.addToSendQueue(new CPacketForm(this.id, null)); + } + } + } + + public GuiForm(int id, String title, Triplet[] data) { + this.id = id; + this.title = title; + this.inputs = new Element[data.length]; + this.labels = new Label[data.length]; + this.inputData = data; + this.outputData = new Object[data.length]; + for(int z = 0; z < data.length; z++) { + Object obj = data[z].second(); + this.outputData[z] = obj instanceof String[] ? data[z].third() : obj; + } + } + + public void use(ActButton elem, PressType action) { + for(int z = 0; z < this.inputs.length; z++) { + if(this.inputs[z] instanceof Field) { + int min = (this.inputData[z].third() & 0x7fffffff) >> 16; + String text = this.inputs[z].getText(); + if(text.length() < min) { + if(!GuiForm.this.labels[z].getText().startsWith("" + TextColor.RED)) + GuiForm.this.labels[z].setText(TextColor.RED + GuiForm.this.labels[z].getText()); + return; + } + this.outputData[z] = text; + } + } + this.sent = true; + ClientPlayer nethandler = this.gm.getNetHandler(); + if(nethandler != null) { + nethandler.addToSendQueue(new CPacketForm(this.id, this.outputData)); + } + this.gm.displayGuiScreen(null); + } +} diff --git a/client/src/main/java/client/gui/ingame/GuiGameOver.java b/client/src/main/java/client/gui/ingame/GuiGameOver.java new file mode 100755 index 0000000..5fec815 --- /dev/null +++ b/client/src/main/java/client/gui/ingame/GuiGameOver.java @@ -0,0 +1,43 @@ +package client.gui.ingame; + +import client.gui.Gui; +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import common.color.TextColor; +import common.util.ExtMath; +import client.gui.element.Label; +import client.gui.element.MultiLabel; +import client.gui.element.PressType; + +public class GuiGameOver extends Gui { + public static final GuiGameOver INSTANCE = new GuiGameOver(); + + private ActButton button; + private int timer; + + private GuiGameOver() { + } + + public void init(int width, int height) { + this.timer = 0; + this.add(new Label(0, 0, 400, 0, TextColor.DRED + "Du bist gestorben!")); + this.add(new MultiLabel(0, 32, 400, 42, String.format(TextColor.GREEN + "Letzte Position" + TextColor.GRAY + ":\n" + TextColor.YELLOW + "%d, %d, %d\n" + TextColor.YELLOW + "%s", ExtMath.floord(this.gm.player.posX), ExtMath.floord(this.gm.player.posY), ExtMath.floord(this.gm.player.posZ), this.gm.player.worldObj.dimension.getFormattedName(false)))); + this.button = this.add(new ActButton(100, 100, 200, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + GuiGameOver.this.gm.player.respawnPlayer(); + GuiGameOver.this.gm.displayGuiScreen(null); + } + }, "Wiederbeleben")); + this.shift(); + this.button.enabled = false; + } + + public String getTitle() { + return "Game over - Wiederbeleben?"; + } + + public void updateScreen() { + if(++this.timer >= 20) + this.button.enabled = true; + } +} diff --git a/client/src/main/java/client/gui/ingame/GuiSign.java b/client/src/main/java/client/gui/ingame/GuiSign.java new file mode 100644 index 0000000..1e3d59d --- /dev/null +++ b/client/src/main/java/client/gui/ingame/GuiSign.java @@ -0,0 +1,54 @@ +package client.gui.ingame; + +import client.gui.Gui; +import client.gui.element.Label; +import client.gui.element.NavButton; +import client.gui.element.FieldAction; +import client.gui.element.Field; +import client.gui.element.FieldCallback; +import client.network.ClientPlayer; +import common.packet.CPacketSign; +import common.util.BlockPos; + +public class GuiSign extends Gui implements FieldCallback { + private final BlockPos position; + private final Field[] lines; + private final String[] tempLines; + + public void init(int width, int height) { + this.add(new Label(0, -140, 300, 0, "Bearbeite Schild")); + this.add(new Label(0, -80, 300, 0, String.format("%d, %d, %d", this.position.getX(), this.position.getY(), this.position.getZ()))); + this.add(new Label(0, -50, 300, 0, this.gm.world == null ? "" : this.gm.world.dimension.getFormattedName(false))); + for(int z = 0; z < this.lines.length; z++) { + this.lines[z] = this.add(new Field(0, 40 * z, 300, 0, 50, this, this.tempLines[z] == null ? "" : this.tempLines[z])); + } + this.add(new NavButton(0, 40 * (this.lines.length + 1), 300, 0, null, "Fertig")); + this.shift(); + } + + public String getTitle() { + return "Schild bearbeiten"; + } + + public void onGuiClosed() { + ClientPlayer nethandler = this.gm.getNetHandler(); + if(nethandler != null) { + for(int z = 0; z < this.lines.length; z++) { + this.tempLines[z] = this.lines[z].getText(); + } + nethandler.addToSendQueue(new CPacketSign(this.position, this.tempLines)); + } + } + + public GuiSign(BlockPos sign, String[] lines) { + this.position = sign; + this.lines = new Field[lines.length]; + this.tempLines = new String[lines.length]; + System.arraycopy(lines, 0, this.tempLines, 0, lines.length); + } + + public void use(Field elem, FieldAction value) { + if(value == FieldAction.SEND) + this.gm.displayGuiScreen(null); + } +} diff --git a/java/src/game/gui/options/GuiBinds.java b/client/src/main/java/client/gui/options/GuiBinds.java similarity index 59% rename from java/src/game/gui/options/GuiBinds.java rename to client/src/main/java/client/gui/options/GuiBinds.java index 5f0b7d4..2face9d 100644 --- a/java/src/game/gui/options/GuiBinds.java +++ b/client/src/main/java/client/gui/options/GuiBinds.java @@ -1,11 +1,12 @@ -package game.gui.options; +package client.gui.options; -import game.color.TextColor; -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; -import game.gui.element.Label; -import game.util.Formatter; -import game.window.Bind; +import client.gui.Formatter; +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.Label; +import client.gui.element.PressType; +import client.window.Bind; +import common.color.TextColor; public class GuiBinds extends GuiOptions { protected GuiBinds() { @@ -15,17 +16,17 @@ public class GuiBinds extends GuiOptions { int y = 0; int x = 0; for(Bind bind : Bind.values()) { - this.add(new Label(10 + x * 190, 80 + y * 50, 180, 20, bind.getDisplay())); - this.add(new ActButton(10 + x * 190, 100 + y * 50, 180, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { - if(action == Mode.SECONDARY) { + this.add(new Label(x * 152, 100 + y * 34, 150, bind.getDisplay())); + this.add(new ActButton(x * 152, 100 + y * 34, 150, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + if(action == PressType.SECONDARY) { if(!bind.isDefault()) { bind.setDefault(); GuiBinds.this.gm.setDirty(); GuiBinds.this.reformat(); } } - else if(action == Mode.TERTIARY) { + else if(action == PressType.TERTIARY) { if(bind.getInput() != null) { bind.setInput(null); GuiBinds.this.gm.setDirty(); @@ -44,14 +45,14 @@ public class GuiBinds extends GuiOptions { return (bind.isDupe() ? TextColor.RED : TextColor.YELLOW) + (bind.getInput() == null ? "---" : bind.getInput().getDisplay()); } })); - if(++x == 5) { + if(++x == 4) { x = 0; y++; } } y += x != 0 ? 1 : 0; - this.add(new ActButton(200, 100 + y * 50, 560, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { + this.add(new ActButton(0, 100 + y * 34, 150 * 4 + 2 * 3, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { boolean flag = false; for(Bind bind : Bind.values()) { flag |= !bind.isDefault(); @@ -63,8 +64,8 @@ public class GuiBinds extends GuiOptions { } } }, "Zurücksetzen")); - this.addSelector("phy_sensitivity", 30, 160 + y * 50, 440, 24); - this.addSelector("gui_dclick_delay", 490, 160 + y * 50, 440, 24); + this.addSelector("phy_sensitivity", 0, 140 + y * 34, 302, 0); + this.addSelector("gui_dclick_delay", 304, 140 + y * 34, 302, 0); super.init(width, height); } diff --git a/client/src/main/java/client/gui/options/GuiDisplay.java b/client/src/main/java/client/gui/options/GuiDisplay.java new file mode 100644 index 0000000..abbebf8 --- /dev/null +++ b/client/src/main/java/client/gui/options/GuiDisplay.java @@ -0,0 +1,115 @@ +package client.gui.options; + +import java.util.List; + +import client.Client; +import client.gui.Font; +import client.gui.Formatter; +import client.gui.element.Dropdown; +import client.gui.element.DropdownCallback; +import client.gui.element.Element; +import client.gui.element.Fill; +import client.gui.element.Slider; +import client.gui.element.SliderCallback; +import client.gui.element.Toggle; +import client.gui.element.ToggleCallback; +import client.window.Button; +import client.window.DisplayMode; +import client.window.Window; +import common.collect.Lists; +import common.color.TextColor; +import common.util.ExtMath; + +public class GuiDisplay extends GuiOptions { + private static final String[] DISTANCES = new String[] {"Gruselig", "Winzig", "Gering", "Normal", "Weit"}; + + private Element distanceSlider; + + protected GuiDisplay() { + } + + public void init(int width, int height) { + this.add(new Toggle(0, 0, 240, 0, false, GuiDisplay.this.gm.fullscreen, new ToggleCallback() { + public void use(Toggle elem, boolean value) { + GuiDisplay.this.gm.full(value); + } + }, "Vollbild")); + int maxModes = ExtMath.clampi((height - 120) / Font.YGLYPH, 4, 28); + DisplayMode[] dmodes = Window.getDisplayModes(); + if(dmodes != null) { + List modes = Lists.newArrayList(); + for(int z = dmodes.length - 1; z >= 0 && modes.size() < maxModes; z--) { + DisplayMode mode = dmodes[z]; + if(mode.width() >= Client.MIN_WIDTH && mode.height() >= Client.MIN_HEIGHT) + modes.add(0, mode); + } + if(modes.isEmpty()) { + dmodes = null; + } + else { + DisplayMode selected = modes.get(modes.size() - 1); + for(DisplayMode mode : modes) { + if(mode.equals(this.gm.vidMode)) + selected = mode; + } + this.add(new Dropdown(242, 0, 240, 0, false, modes.toArray(new DisplayMode[modes.size()]), modes.get(modes.size() - 1), selected, new DropdownCallback() { + public void use(Dropdown elem, DisplayMode value) { + GuiDisplay.this.gm.vidMode = value; + GuiDisplay.this.gm.full(true); + } + }, (String)null)); + } + } + if(dmodes == null) + this.add(new Fill(242, 0, 240, 0, TextColor.RED + "")); + + this.add(new Slider(0, 20, 240, 0, 0, 0, 360 - 8, 0, (this.gm.sync < 0) ? (360 - 8) : (this.gm.sync != 0 ? ((this.gm.sync < 10) ? 1 : (this.gm.sync - 9)) : 0), new SliderCallback() { + public void use(Slider elem, int value) { + GuiDisplay.this.gm.getVar("win_sync").parse("" + ((value > 0 && value < 360 - 8) ? (value + 9) : (value != 0 ? -1 : 0))); + GuiDisplay.this.gm.setDirty(); + } + }, new Formatter() { + public String use(Slider elem) { + int value = elem.getValue(); + return "Max. Bildrate: " + (value > 0 && value < (360 - 8) ? (value + 9) + " FPS" : (value != 0 ? "Unbegrenzt" : "VSync")); + } + })); + this.addSelector("gl_vsync_flush", 242, 20, 240, 0); + + this.addSelector("overlay_enabled", 0, 50, 240, 0); + this.addSelector("overlay_opacity", 242, 50, 240, 0); + + this.addSelector("overlay_fadeout", 0, 70, 240, 0); + this.addSelector("chat_permanent", 242, 70, 240, 0); + + this.addSelector("console_size", 0, 90, 240, 0); + this.addSelector("chat_size", 242, 90, 240, 0); + + this.addSelector("feed_size", 0, 110, 240, 0); + this.addSelector("hotbar_size", 242, 110, 240, 0); + + this.addSelector("gl_fov", 0, 140, 240, 0); + + this.distanceSlider = this.addSelector("chunk_view_distance", 0, 160, 240, 0); + this.addSelector("chunk_build_time", 242, 160, 240, 0); + super.init(width, height); + } + + public String getTitle() { + return "Grafik und Anzeige"; + } + + private String getDistanceName() { + int distance = this.gm.renderDistance; + distance = distance > 16 ? 16 : distance; + String str = distance < 0 ? DISTANCES[0] : DISTANCES[(distance + 1) / 4]; + if(distance > 2 && (((distance + 1) / 2) & 1) == 1) + str = str + "+"; + return String.format("Sichtweite: %d [%d, %s]", this.gm.renderDistance, this.gm.renderDistance * 16, str); + } + + public void updateScreen() { + if(!Button.isMouseDown()) + this.distanceSlider.setText(this.getDistanceName()); + } +} diff --git a/client/src/main/java/client/gui/options/GuiOptions.java b/client/src/main/java/client/gui/options/GuiOptions.java new file mode 100644 index 0000000..57bfdac --- /dev/null +++ b/client/src/main/java/client/gui/options/GuiOptions.java @@ -0,0 +1,25 @@ +package client.gui.options; + +import client.gui.Gui; +import client.gui.GuiMenu; +import client.gui.element.NavButton; + +public abstract class GuiOptions extends Gui { + private static final GuiOptions[] PAGES = {lastPage = new GuiBinds(), new GuiStyle(), new GuiDisplay(), new GuiSound()}; + + private static GuiOptions lastPage; + + public static GuiOptions getPage() { + return lastPage; + } + + public void init(int width, int height) { + lastPage = this; + this.shift(); + for(int z = 0; z < PAGES.length; z++) { + GuiOptions gui = PAGES[z]; + this.add(new NavButton(z % 2 == 1 ? width - 212 : 2, 2 + 20 * (z / 2), 210, 0, gui, gui.getTitle())); + } + this.add(new NavButton((width - 280) / 2, height - 20, 280, 0, GuiMenu.INSTANCE, "Zurück")); + } +} diff --git a/client/src/main/java/client/gui/options/GuiSound.java b/client/src/main/java/client/gui/options/GuiSound.java new file mode 100644 index 0000000..9e49c02 --- /dev/null +++ b/client/src/main/java/client/gui/options/GuiSound.java @@ -0,0 +1,39 @@ +package client.gui.options; + +import client.audio.Volume; +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.PressType; + +public class GuiSound extends GuiOptions { + protected GuiSound() { + } + + public void init(int width, int height) { + int x = 0; + int y = 0; + for(Volume volume : Volume.values()) { + this.addSelector(volume.getCVarName(), x, y, 150, 0); + x = (x == 0) ? 152 : 0; + if(x == 0) + y += 20; + } + + this.addSelector("snd_enabled", 0, 50, 150, 0); + + this.addSelector("snd_buffer_size", 0, 70, 150, 0); + this.addSelector("snd_frame_size", 152, 70, 150, 0); + + this.add(new ActButton(0, 100, 302, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + GuiSound.this.gm.restartSound(false); + } + }, "Übernehmen und Audio neu starten")); + + super.init(width, height); + } + + public String getTitle() { + return "Audio und Ton"; + } +} diff --git a/client/src/main/java/client/gui/options/GuiStyle.java b/client/src/main/java/client/gui/options/GuiStyle.java new file mode 100644 index 0000000..c322e25 --- /dev/null +++ b/client/src/main/java/client/gui/options/GuiStyle.java @@ -0,0 +1,121 @@ +package client.gui.options; + +import client.gui.Style; +import client.gui.element.ActButton; +import client.gui.element.ButtonCallback; +import client.gui.element.Dropdown; +import client.gui.element.DropdownCallback; +import client.gui.element.Element; +import client.gui.element.SelectableButton; +import client.gui.element.Slider; +import client.gui.element.SliderCallback; +import client.gui.element.Switch; +import client.gui.element.SwitchCallback; +import client.gui.element.FieldAction; +import client.gui.element.Field; +import client.gui.element.FieldCallback; +import client.gui.element.PressType; +import client.vars.CVar; +import client.vars.ColorVar; +import client.gui.element.Toggle; +import client.gui.element.ToggleCallback; + +public class GuiStyle extends GuiOptions implements DropdownCallback, ButtonCallback, ToggleCallback, SwitchCallback, SliderCallback, FieldCallback { + private static final String[] STYLE_CVARS = { + "color_button_top", + "color_textbox_top", + "color_border_top", + + "color_button_btm", + "color_textbox_btm", + "color_border_btm", + + "color_button_text", + "color_textbox_text", + "color_label_text" + }; + + protected GuiStyle() { + } + + protected Element addSelector(String cvar, int x, int y, int w, int h) { + CVar cv = this.gm.getVar(cvar); + if(cv instanceof ColorVar color) { + if(!color.getDisplay().isEmpty()) + this.add(color.label(x, y, w)); + if(this.gm.style != Style.CUSTOM) + return this.add(new Field(x, y, w, h, color.getFieldValue(this.gm.style))); + else + return this.add(color.editor(x, y, w, h)); + } + return super.addSelector(cvar, x, y, w, h); + } + + public void init(int width, int height) { + int z; + for(z = 0; z < STYLE_CVARS.length; z++) { + this.addSelector(STYLE_CVARS[z], (z % 3) * 122, z / 3 * 34, 120, 0); + } + z = 0; + for(Style theme : Style.values()) { + ButtonCallback callback = new ButtonCallback() { + public void use(ActButton elem, PressType action) { + if(GuiStyle.this.gm.style != theme) { + GuiStyle.this.gm.style = theme; + GuiStyle.this.gm.setDirty(); + GuiStyle.this.gm.displayGuiScreen(GuiStyle.this); + } + } + }; + this.add( // theme == this.gm.style ? new SelectedButton(10 + (z % 3) * 320, 360 + (z / 3) * 40, 300, 0, callback, theme.name) : + new SelectableButton((z % 3) * 122, 4 * 34 + (z / 3) * 20, 120, 0, callback, theme.name, theme == this.gm.style)); + z++; + } + + this.addSelector("gui_scale", 0, 5 * 34 + (Style.values().length / 3) * 20, 181, 0); + this.addSelector("gui_font_tiny", 183, 5 * 34 + (Style.values().length / 3) * 20, 181, 0); + + if(this.gm.style != Style.CUSTOM) { + this.add(new ActButton(0, 3 * 34, 364, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + if(GuiStyle.this.gm.style != Style.CUSTOM) { + GuiStyle.this.gm.style.copyToCustom(); + GuiStyle.this.gm.style = Style.CUSTOM; + GuiStyle.this.gm.setDirty(); + GuiStyle.this.gm.displayGuiScreen(GuiStyle.this); + } + } + }, "In angepasstes Design kopieren")); + } + else { + this.add(new ActButton(0, 3 * 34, 364, 0, new ButtonCallback() { + public void use(ActButton elem, PressType action) { + GuiStyle.this.gm.style = Style.CUSTOM; + for(String cvar : STYLE_CVARS) { + GuiStyle.this.gm.getVar(cvar).setDefault(); + } + GuiStyle.this.gm.setDirty(); + GuiStyle.this.gm.displayGuiScreen(GuiStyle.this); + } + }, "Angepasstes Design zurücksetzen")); + } + super.init(width, height); + } + + public String getTitle() { + return "Benutzeroberfläche"; + } + + public void use(Field elem, FieldAction value) { + } + public void use(Slider elem, int value) { + } + public void use(Switch elem, String value) { + } + public void use(Toggle elem, boolean value) { + } + public void use(ActButton elem, PressType action) { + } + public void use(Dropdown elem, String value) { + } +} diff --git a/client/src/main/java/client/init/RenderRegistry.java b/client/src/main/java/client/init/RenderRegistry.java new file mode 100644 index 0000000..254989d --- /dev/null +++ b/client/src/main/java/client/init/RenderRegistry.java @@ -0,0 +1,181 @@ +package client.init; + +import java.util.Map; + +import client.renderer.entity.Render; +import client.renderer.entity.RenderArachnoid; +import client.renderer.entity.RenderArrow; +import client.renderer.entity.RenderBat; +import client.renderer.entity.RenderBlockEntity; +import client.renderer.entity.RenderBoat; +import client.renderer.entity.RenderBullet; +import client.renderer.entity.RenderChicken; +import client.renderer.entity.RenderCow; +import client.renderer.entity.RenderCrystal; +import client.renderer.entity.RenderDie; +import client.renderer.entity.RenderDragon; +import client.renderer.entity.RenderDynamite; +import client.renderer.entity.RenderEntity; +import client.renderer.entity.RenderEntityItem; +import client.renderer.entity.RenderFallingBlock; +import client.renderer.entity.RenderFireball; +import client.renderer.entity.RenderFish; +import client.renderer.entity.RenderFlyingBox; +import client.renderer.entity.RenderFox; +import client.renderer.entity.RenderHorse; +import client.renderer.entity.RenderHumanoid; +import client.renderer.entity.RenderItem; +import client.renderer.entity.RenderItemEntity; +import client.renderer.entity.RenderLeashKnot; +import client.renderer.entity.RenderLightning; +import client.renderer.entity.RenderManager; +import client.renderer.entity.RenderMinecart; +import client.renderer.entity.RenderMooshroom; +import client.renderer.entity.RenderMouse; +import client.renderer.entity.RenderNpc; +import client.renderer.entity.RenderOcelot; +import client.renderer.entity.RenderPig; +import client.renderer.entity.RenderPotion; +import client.renderer.entity.RenderRabbit; +import client.renderer.entity.RenderSheep; +import client.renderer.entity.RenderSlime; +import client.renderer.entity.RenderSpaceMarine; +import client.renderer.entity.RenderSquid; +import client.renderer.entity.RenderTntMinecart; +import client.renderer.entity.RenderTntPrimed; +import client.renderer.entity.RenderWolf; +import client.renderer.entity.RenderXpOrb; +import client.renderer.model.ModelChicken; +import client.renderer.model.ModelCow; +import client.renderer.model.ModelFox; +import client.renderer.model.ModelHorse; +import client.renderer.model.ModelMouse; +import client.renderer.model.ModelOcelot; +import client.renderer.model.ModelPig; +import client.renderer.model.ModelRabbit; +import client.renderer.model.ModelSheep2; +import client.renderer.model.ModelSquid; +import client.renderer.model.ModelWolf; +import client.renderer.texture.TextureTicked; +import client.renderer.ticked.TextureFlamesFX1; +import client.renderer.ticked.TextureFlamesFX2; +import client.renderer.ticked.TextureFlamesFXMono1; +import client.renderer.ticked.TextureFlamesFXMono2; +import client.renderer.ticked.TextureLavaFX; +import client.renderer.ticked.TextureLavaFlowFX; +import client.renderer.ticked.TextureWaterFX; +import client.renderer.ticked.TextureWaterFlowFX; +import common.entity.Entity; +import common.entity.animal.EntityBat; +import common.entity.animal.EntityChicken; +import common.entity.animal.EntityCow; +import common.entity.animal.EntityDragon; +import common.entity.animal.EntityFox; +import common.entity.animal.EntityHorse; +import common.entity.animal.EntityMooshroom; +import common.entity.animal.EntityMouse; +import common.entity.animal.EntityOcelot; +import common.entity.animal.EntityPig; +import common.entity.animal.EntityRabbit; +import common.entity.animal.EntitySheep; +import common.entity.animal.EntitySquid; +import common.entity.animal.EntityWolf; +import common.entity.effect.EntityLightning; +import common.entity.item.EntityBoat; +import common.entity.item.EntityCart; +import common.entity.item.EntityCrystal; +import common.entity.item.EntityFalling; +import common.entity.item.EntityFireworks; +import common.entity.item.EntityItem; +import common.entity.item.EntityLeashKnot; +import common.entity.item.EntityNuke; +import common.entity.item.EntityOrb; +import common.entity.item.EntityTnt; +import common.entity.item.EntityTntCart; +import common.entity.item.EntityXp; +import common.entity.item.EntityXpBottle; +import common.entity.npc.SpeciesInfo; +import common.entity.projectile.EntityArrow; +import common.entity.projectile.EntityBox; +import common.entity.projectile.EntityBullet; +import common.entity.projectile.EntityDie; +import common.entity.projectile.EntityDynamite; +import common.entity.projectile.EntityEgg; +import common.entity.projectile.EntityFireCharge; +import common.entity.projectile.EntityFireball; +import common.entity.projectile.EntityHook; +import common.entity.projectile.EntityPotion; +import common.entity.projectile.EntitySnowball; +import common.init.Blocks; +import common.init.Items; +import common.init.SpeciesRegistry; +import common.init.SpeciesRegistry.ModelType; + +public abstract class RenderRegistry { + public static void registerRenderers(Map, Render> map, + Map models, RenderManager mgr, RenderItem ritem) { + map.put(EntityPig.class, new RenderPig(mgr, new ModelPig())); + map.put(EntitySheep.class, new RenderSheep(mgr, new ModelSheep2())); + map.put(EntityCow.class, new RenderCow(mgr, new ModelCow())); + map.put(EntityMooshroom.class, new RenderMooshroom(mgr, new ModelCow())); + map.put(EntityWolf.class, new RenderWolf(mgr, new ModelWolf())); + map.put(EntityFox.class, new RenderFox(mgr, new ModelFox())); + map.put(EntityChicken.class, new RenderChicken(mgr, new ModelChicken())); + map.put(EntityOcelot.class, new RenderOcelot(mgr, new ModelOcelot())); + map.put(EntityRabbit.class, new RenderRabbit(mgr, new ModelRabbit())); + map.put(EntitySquid.class, new RenderSquid(mgr, new ModelSquid())); + map.put(EntityBat.class, new RenderBat(mgr)); + map.put(EntityDragon.class, new RenderDragon(mgr)); + map.put(EntityCrystal.class, new RenderCrystal(mgr)); + map.put(Entity.class, new RenderEntity(mgr)); +// map.put(EntityPainting.class, new RenderPainting(mgr)); +// map.put(EntityFrame.class, new RenderItemFrame(mgr, ritem)); + map.put(EntityLeashKnot.class, new RenderLeashKnot(mgr)); + map.put(EntityArrow.class, new RenderArrow(mgr)); + map.put(EntitySnowball.class, new RenderItemEntity(mgr, Items.snowball, ritem)); + map.put(EntityOrb.class, new RenderItemEntity(mgr, Items.charged_orb, ritem)); + map.put(EntityEgg.class, new RenderItemEntity(mgr, Items.egg, ritem)); + map.put(EntityPotion.class, new RenderPotion(mgr, ritem)); + map.put(EntityXpBottle.class, new RenderItemEntity(mgr, Items.experience_bottle, ritem)); + map.put(EntityFireworks.class, new RenderItemEntity(mgr, Items.fireworks, ritem)); + map.put(EntityFireball.class, new RenderFireball(mgr, 0.75F)); + map.put(EntityFireCharge.class, new RenderFireball(mgr, 0.5F)); + map.put(EntityBox.class, new RenderFlyingBox(mgr)); + map.put(EntityItem.class, new RenderEntityItem(mgr, ritem)); + map.put(EntityXp.class, new RenderXpOrb(mgr)); + map.put(EntityTnt.class, new RenderTntPrimed(mgr)); + map.put(EntityFalling.class, new RenderFallingBlock(mgr)); + map.put(EntityTntCart.class, new RenderTntMinecart(mgr)); + map.put(EntityCart.class, new RenderMinecart(mgr)); + map.put(EntityBoat.class, new RenderBoat(mgr)); + map.put(EntityHook.class, new RenderFish(mgr)); + map.put(EntityHorse.class, new RenderHorse(mgr, new ModelHorse())); + map.put(EntityDynamite.class, new RenderDynamite(mgr, Items.dynamite, ritem)); + map.put(EntityNuke.class, new RenderBlockEntity(mgr, Blocks.nuke.getState())); + map.put(EntityMouse.class, new RenderMouse(mgr, new ModelMouse())); + map.put(EntityDie.class, new RenderDie(mgr)); + map.put(EntityBullet.class, new RenderBullet(mgr)); + map.put(EntityLightning.class, new RenderLightning(mgr)); + models.put(ModelType.HUMANOID, new RenderHumanoid(mgr, 12, 12, "textures/entity/char.png")); + models.put(ModelType.ARACHNOID, new RenderArachnoid(mgr)); + models.put(ModelType.SLIME, new RenderSlime(mgr)); + models.put(ModelType.DWARF, new RenderHumanoid(mgr, 10, 10, "textures/entity/dwarf.png")); + models.put(ModelType.HALFLING, new RenderHumanoid(mgr, 8, 8, "textures/entity/goblin.png")); + models.put(ModelType.SPACE_MARINE, new RenderSpaceMarine(mgr)); + for(int z = 0; z < SpeciesRegistry.SPECIMEN.size(); z++) { + SpeciesInfo info = SpeciesRegistry.SPECIMEN.get(z); + map.put(info.clazz, models.get(info.renderer)); + } + } + + public static void registerAnimations(Map> anim) { + anim.put("fire1", TextureFlamesFX1.class); + anim.put("fire2", TextureFlamesFX2.class); + anim.put("flame1", TextureFlamesFXMono1.class); + anim.put("flame2", TextureFlamesFXMono2.class); + anim.put("lavaflow", TextureLavaFlowFX.class); + anim.put("lava", TextureLavaFX.class); + anim.put("waterflow", TextureWaterFlowFX.class); + anim.put("water", TextureWaterFX.class); + } +} diff --git a/client/src/main/java/client/network/ClientLoginHandler.java b/client/src/main/java/client/network/ClientLoginHandler.java new file mode 100755 index 0000000..2721d05 --- /dev/null +++ b/client/src/main/java/client/network/ClientLoginHandler.java @@ -0,0 +1,209 @@ +package client.network; + +import java.security.KeyPair; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.util.Base64; + +import client.Client; +import client.gui.GuiConfirm; +import client.gui.GuiConnect; +import client.gui.GuiConnect.ServerInfo; +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; +import common.network.IClientLoginHandler; +import common.network.NetConnection; +import common.network.PacketRegistry; +import common.packet.LPacketChallenge; +import common.packet.LPacketPassword; +import common.packet.LPacketPubkey; +import common.packet.LPacketResponse; +import common.packet.LPacketStartEncrypt; +import common.packet.RPacketChallenge; +import common.packet.RPacketDisconnect; +import common.packet.RPacketEnableCompression; +import common.packet.RPacketLoginSuccess; +import common.packet.RPacketRequestEncrypt; +import common.packet.RPacketResponse; +import common.packet.RPacketServerConfig; +import common.util.EncryptUtil; +import common.util.Util; + +public class ClientLoginHandler implements IClientLoginHandler { + private static enum LoginState { + HANDSHAKE, CONFIRMING, CHALLENGE, ENCRYPTED, PROVING, AUTHENTICATING, DONE; + } + + private static final SecureRandom TOKEN_RNG = new SecureRandom(); + + private final Client gm; + private final NetConnection connection; + private final ServerInfo server; + private final KeyPair tempKeys; + + private LoginState state = LoginState.HANDSHAKE; + private byte[] token; + + public ClientLoginHandler(NetConnection conn, Client gm, ServerInfo server) { + this.connection = conn; + this.gm = gm; + this.server = server; + this.tempKeys = EncryptUtil.createDHKeypair(); + } + + public void onDisconnect(String reason) + { + this.gm.disconnected(reason); + } + + public void handleDisconnect(RPacketDisconnect packet) + { + this.connection.closeChannel(packet.getReason()); + } + + public void handleEncrypt(RPacketRequestEncrypt packet) { + if(this.state != LoginState.HANDSHAKE) { + this.connection.closeChannel("Unerwartetes Verschlüsselungs-Paket"); + return; + } + this.connection.setConnectionState(PacketRegistry.LOGIN); + final PublicKey pubkey = packet.getKey(); + final PublicKey tempKey = packet.getTempKey(); + if(this.server.getServerKey() == null) { + this.state = LoginState.CONFIRMING; + this.gm.schedule(new Runnable() { + public void run() { + ClientLoginHandler.this.gm.displayGuiScreen(new GuiConfirm(new GuiConfirm.Callback() { + public void confirm(boolean confirmed) { + if(confirmed) { + ClientLoginHandler.this.server.setServerKey(pubkey); + GuiConnect.INSTANCE.editServer(ClientLoginHandler.this.server); + ClientLoginHandler.this.gm.displayConnecting(ClientLoginHandler.this.server); + ClientLoginHandler.this.startEncryption(tempKey); + } + else { + ClientLoginHandler.this.connection.closeChannel("Verbindung wurde abgebrochen"); + } + } + }, "Die Identität des Servers ist unbekannt", "Es wurde noch nie mit diesem Server verbunden.\nSoll die Verbindung wirklich fortgesetzt werden?\n\nDie Pubkey-ID des Servers lautet:\n" + EncryptUtil.KEY_ALGO_DISPLAY + " " + EncryptUtil.getXorSha512Hash(pubkey.getEncoded()) + "\n\nDer öffentliche Schlüssel des Servers lautet:\n" + Util.breakString(Base64.getEncoder().encodeToString(pubkey.getEncoded()), 64), "Verbindung herstellen", "Abbrechen und trennen")); + } + }); + return; + } + else if(!this.server.getServerKey().equals(pubkey)) { + this.connection.closeChannel("Die Identität des Servers hat sich geändert\n\nDer Server hat einen anderen öffentlichen Schlüssel als vorher bekannt war,\ndies kann bedeuten dass der Inhaber jetzt einen anderen Schlüssel verwendet\noder sich ein anderer Server als dieser ausgibt (\"Man-in-the-middle-attack\").\n\nDie Pubkey-ID des Servers lautet: " + EncryptUtil.KEY_ALGO_DISPLAY + " " + EncryptUtil.getXorSha512Hash(pubkey.getEncoded()) + "\n\nDer öffentliche Schlüssel des Servers lautet:\n" + Util.breakString(Base64.getEncoder().encodeToString(pubkey.getEncoded()), 64) + "\n\nDie vertrauenswürdige Pubkey-ID lautet: " + EncryptUtil.KEY_ALGO_DISPLAY + " " + EncryptUtil.getXorSha512Hash(this.server.getServerKey().getEncoded()) + + "\n\nFalls der Server trotzdem vertrauenswürdig wirkt, kann die Server-Identifizierung\nin den Einstellungen von '" + this.server.getName() + "' zurückgesetzt werden."); + return; + } + this.startEncryption(tempKey); + } + + private void startEncryption(PublicKey serverKey) { + this.state = LoginState.CHALLENGE; + this.connection.sendPacket(new LPacketStartEncrypt(this.tempKeys.getPublic()), new GenericFutureListener < Future > () { + public void operationComplete(Future u) throws Exception { + ClientLoginHandler.this.connection.startEncryption(EncryptUtil.makeKeyAgreement(ClientLoginHandler.this.tempKeys.getPrivate(), serverKey)); + ClientLoginHandler.this.token = new byte[32]; + TOKEN_RNG.nextBytes(ClientLoginHandler.this.token); + ClientLoginHandler.this.connection.sendPacket(new LPacketChallenge(ClientLoginHandler.this.token)); + } + }); + } + + public void handleResponse(RPacketResponse packet) { + if(this.state != LoginState.CHALLENGE) { + this.connection.closeChannel("Unerwartetes Beweis-Paket"); + return; + } + if(!packet.verifyToken(this.server.getServerKey(), this.token)) { + this.connection.closeChannel("Fehlerhaftes Beweis-Token"); + return; + } + this.state = LoginState.ENCRYPTED; + } + + public void handleConfig(final RPacketServerConfig packet) { + if(this.state == LoginState.HANDSHAKE) { + this.connection.setConnectionState(PacketRegistry.LOGIN); + if(this.server.requiresEncryption()) { + this.connection.closeChannel("Der Server unterstützt keine verschlüsselte Verbindung, dies ist\nin den Servereinstellungen von '" + + this.server.getName() + "' als erforderlich\neingestellt, stelle keine ungesicherte Verbindung her."); + return; + } + if(this.server.getServerKey() != null) { + this.state = LoginState.CONFIRMING; + this.gm.schedule(new Runnable() { + public void run() { + ClientLoginHandler.this.gm.displayGuiScreen(new GuiConfirm(new GuiConfirm.Callback() { + public void confirm(boolean confirmed) { + if(confirmed) { + ClientLoginHandler.this.server.setServerKey(null); + GuiConnect.INSTANCE.editServer(ClientLoginHandler.this.server); + ClientLoginHandler.this.gm.displayConnecting(ClientLoginHandler.this.server); + ClientLoginHandler.this.state = LoginState.HANDSHAKE; + ClientLoginHandler.this.handleConfig(packet); + } + else { + ClientLoginHandler.this.connection.closeChannel("Verbindung wurde abgebrochen"); + } + } + }, "Der Server hat die Verschlüsselung deaktiviert", "Es wurde bereits verschlüsselt mit diesem Server kommuniziert.\n\nSoll die Verbindung wirklich fortgesetzt werden?\n\nDie Pubkey-Authentifizierung wird nicht verfügbar sein\nund die Server-ID wird ignoriert und zurückgesetzt.", "Unverschlüsselt verbinden", "Abbrechen und trennen")); + } + }); + return; + } + } + else if(this.state != LoginState.ENCRYPTED) { + this.connection.closeChannel("Unerwartetes Konfigurations-Paket"); + return; + } + if(packet.hasAccessPassword() && this.server.getAccess().isEmpty()) { + this.connection.closeChannel("Der Server verlangt ein Zugangs-Passwort zur Authentifizierung"); + return; + } + boolean auth = packet.isAuthenticating(); + boolean passwordAuth = packet.canUsePassword(); + boolean pubkeyAuth = packet.canUsePubkey() && this.state == LoginState.ENCRYPTED; + if(auth && (!passwordAuth || this.server.getPassword().isEmpty()) && (!pubkeyAuth || this.server.getKeypair() == null)) { + this.connection.closeChannel("Der Server unterstützt keine der vorhandenen\nAuthentifizierungsmethoden\n\nUnterstützt vom Server: " + + (!passwordAuth && !pubkeyAuth ? "Keine" : ((passwordAuth ? "Passwort" : "") + (passwordAuth && pubkeyAuth ? " und " : "") + (pubkeyAuth ? "Pubkey" : ""))) + + "\n\nVorhanden in Konfiguration für '" + this.server.getName() + "': " + (this.server.getPassword().isEmpty() && this.server.getKeypair() == null ? "Keine" : + ((!this.server.getPassword().isEmpty() ? "Passwort" : "") + + (!this.server.getPassword().isEmpty() && this.server.getKeypair() != null ? " und " : "") + (this.server.getKeypair() != null ? "Pubkey" : "")))); + return; + } + if(auth && pubkeyAuth && this.server.getKeypair() != null) { + this.state = LoginState.PROVING; + this.connection.sendPacket(new LPacketPubkey(this.server.getUser(), this.server.getAccess(), this.server.getKeypair().getPublic())); + } + else { + this.state = LoginState.AUTHENTICATING; + this.connection.sendPacket(new LPacketPassword(this.server.getUser(), this.server.getAccess(), auth ? this.server.getPassword() : "")); + } + } + + public void handleChallenge(RPacketChallenge packet) { + if(this.state != LoginState.PROVING) { + this.connection.closeChannel("Unerwartetes Anforderungs-Paket"); + return; + } + this.state = LoginState.AUTHENTICATING; + this.connection.sendPacket(new LPacketResponse(this.server.getKeypair().getPrivate(), packet.getToken())); + } + + public void handleLoginSuccess(RPacketLoginSuccess packet) + { + if(this.state != LoginState.AUTHENTICATING) { + this.connection.closeChannel("Unerwartetes Bestätigungs-Paket"); + return; + } + this.state = LoginState.DONE; + this.connection.setConnectionState(PacketRegistry.PLAY); + this.connection.setNetHandler(new ClientPlayer(this.gm, this.connection)); + } + + public void handleEnableCompression(RPacketEnableCompression packet) + { + this.connection.setCompressionTreshold(packet.getValue()); + } +} diff --git a/java/src/game/network/ClientPlayer.java b/client/src/main/java/client/network/ClientPlayer.java similarity index 59% rename from java/src/game/network/ClientPlayer.java rename to client/src/main/java/client/network/ClientPlayer.java index 8bc4e24..5981cfc 100755 --- a/java/src/game/network/ClientPlayer.java +++ b/client/src/main/java/client/network/ClientPlayer.java @@ -1,165 +1,205 @@ -package game.network; +package client.network; -import java.util.Collection; import java.util.List; -import java.util.Map; import java.util.Map.Entry; -import java.util.Set; +import client.Client; +import client.gui.Gui; +import client.gui.GuiConsole; +import client.gui.GuiLoading; +import client.gui.character.GuiChar; +import client.gui.character.GuiCharacters; +import client.gui.container.GuiBrewing; +import client.gui.container.GuiChest; +import client.gui.container.GuiCrafting; +import client.gui.container.GuiDispenser; +import client.gui.container.GuiEnchant; +import client.gui.container.GuiFurnace; +import client.gui.container.GuiHopper; +import client.gui.container.GuiEntity; +import client.gui.container.GuiTile; +import client.gui.container.GuiMerchant; +import client.gui.container.GuiRepair; +import client.gui.ingame.GuiSign; +import client.gui.ingame.GuiForm; +import client.renderer.particle.EntityPickupFX; +import client.renderer.texture.EntityTexManager; +import client.util.PlayerController; +import client.world.ChunkClient; +import client.world.WorldClient; +import common.block.Block; +import common.block.tech.BlockWorkbench; +import common.dimension.Dimension; +import common.entity.DataWatcher; +import common.entity.Entity; +import common.entity.effect.EntityLightning; +import common.entity.item.EntityBoat; +import common.entity.item.EntityXp; +import common.entity.npc.EntityNPC; +import common.entity.npc.PlayerCharacter; +import common.entity.projectile.EntityProjectile; +import common.entity.types.EntityLiving; +import common.init.BlockRegistry; +import common.init.EntityRegistry; +import common.init.ItemRegistry; +import common.init.SoundEvent; +import common.inventory.AnimalChest; +import common.inventory.Container; +import common.inventory.InventoryBasic; +import common.inventory.InventoryPlayer; +import common.item.ItemStack; +import common.log.Log; +import common.model.ParticleType; +import common.network.IClientPlayer; +import common.network.NetConnection; +import common.network.NetHandler; +import common.network.Packet; +import common.packet.CPacketPlayerPosLook; +import common.packet.CPacketAction; +import common.packet.CPacketKeepAlive; +import common.packet.SPacketEntity; +import common.packet.SPacketEntityTeleport; +import common.packet.SPacketEntityHeadLook; +import common.packet.SPacketEntityStatus; +import common.packet.SPacketEntityAttach; +import common.packet.SPacketEntityMetadata; +import common.packet.SPacketEntityEffect; +import common.packet.SPacketRemoveEntityEffect; +import common.packet.SPacketExplosion; +import common.packet.SPacketEffect; +import common.packet.SPacketSoundEffect; +import common.packet.SPacketParticles; +import common.packet.SPacketChangeGameState; +import common.packet.SPacketSpawnGlobalEntity; +import common.packet.SPacketOpenWindow; +import common.packet.SPacketCloseWindow; +import common.packet.SPacketSetSlot; +import common.packet.SPacketWindowItems; +import common.packet.SPacketWindowProperty; +import common.packet.SPacketConfirmTransaction; +import common.packet.SPacketUpdateSign; +import common.packet.SPacketUpdateTileEntity; +import common.packet.SPacketSignEditorOpen; +import common.packet.SPacketPlayerListItem; +import common.packet.SPacketPlayerAbilities; +import common.packet.SPacketTabComplete; +import common.packet.SPacketUpdateEntityTags; +import common.packet.SPacketAnimation; +import common.packet.SPacketBiome; +import common.packet.SPacketBlockAction; +import common.packet.SPacketBlockBreakAnim; +import common.packet.SPacketBlockChange; +import common.packet.SPacketCamera; +import common.packet.SPacketCharacterList; +import common.packet.SPacketChunkData; +import common.packet.SPacketCollectItem; +import common.packet.SPacketDestroyEntities; +import common.packet.SPacketDimensionName; +import common.packet.SPacketDisconnect; +import common.packet.SPacketDisplayForm; +import common.packet.SPacketEntityEquipment; +import common.packet.SPacketEntityVelocity; +import common.packet.SPacketHeldItemChange; +import common.packet.SPacketJoinGame; +import common.packet.SPacketKeepAlive; +import common.packet.SPacketLoading; +import common.packet.SPacketMapChunkBulk; +import common.packet.SPacketMessage; +import common.packet.SPacketMultiBlockChange; +import common.packet.SPacketPlayerPosLook; +import common.packet.SPacketRespawn; +import common.packet.SPacketServerTick; +import common.packet.SPacketSetExperience; +import common.packet.SPacketSkin; +import common.packet.SPacketSpawnMob; +import common.packet.SPacketSpawnObject; +import common.packet.SPacketSpawnPlayer; +import common.packet.SPacketTimeUpdate; +import common.packet.SPacketTrades; +import common.packet.SPacketUpdateHealth; +import common.packet.SPacketWorld; +import common.potion.PotionEffect; +import common.rng.Random; +import common.sound.Sound; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityDevice; +import common.tileentity.TileEntitySign; +import common.village.MerchantRecipeList; +import common.world.Explosion; +import common.world.Weather; +import common.world.World; -import game.collect.Lists; -import game.collect.Maps; - -import game.Game; -import game.dimension.Dimension; -import game.entity.DataWatcher; -import game.entity.Entity; -import game.entity.animal.EntityHorse; -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.AttributeMap; -import game.entity.attributes.AttributeModifier; -import game.entity.effect.EntityLightning; -import game.entity.item.EntityBoat; -import game.entity.item.EntityXp; -import game.entity.npc.EntityNPC; -import game.entity.npc.PlayerCharacter; -import game.entity.projectile.EntityProjectile; -import game.entity.types.EntityLiving; -import game.gui.Gui; -import game.gui.GuiConsole; -import game.gui.GuiLoading; -import game.gui.character.GuiChar; -import game.gui.character.GuiCharacters; -import game.gui.container.GuiMachine; -import game.gui.container.GuiMerchant; -import game.init.EntityRegistry; -import game.init.ItemRegistry; -import game.init.SoundEvent; -import game.inventory.AnimalChest; -import game.inventory.Container; -import game.inventory.ContainerLocalMenu; -import game.inventory.InventoryBasic; -import game.inventory.InventoryPlayer; -import game.item.ItemStack; -import game.log.Log; -import game.packet.CPacketAction; -import game.packet.CPacketKeepAlive; -import game.packet.CPacketPlayer; -import game.packet.S14PacketEntity; -import game.packet.S18PacketEntityTeleport; -import game.packet.S19PacketEntityHeadLook; -import game.packet.S1APacketEntityStatus; -import game.packet.S1BPacketEntityAttach; -import game.packet.S1CPacketEntityMetadata; -import game.packet.S1DPacketEntityEffect; -import game.packet.S1EPacketRemoveEntityEffect; -import game.packet.S20PacketEntityProperties; -import game.packet.S27PacketExplosion; -import game.packet.S28PacketEffect; -import game.packet.S29PacketSoundEffect; -import game.packet.S2APacketParticles; -import game.packet.S2BPacketChangeGameState; -import game.packet.S2CPacketSpawnGlobalEntity; -import game.packet.S2DPacketOpenWindow; -import game.packet.S2EPacketCloseWindow; -import game.packet.S2FPacketSetSlot; -import game.packet.S30PacketWindowItems; -import game.packet.S31PacketWindowProperty; -import game.packet.S32PacketConfirmTransaction; -import game.packet.S33PacketUpdateSign; -import game.packet.S35PacketUpdateTileEntity; -import game.packet.S36PacketSignEditorOpen; -import game.packet.S38PacketPlayerListItem; -import game.packet.S39PacketPlayerAbilities; -import game.packet.S3APacketTabComplete; -import game.packet.S43PacketUpdateEntityNBT; -import game.packet.SPacketAnimation; -import game.packet.SPacketBiomes; -import game.packet.SPacketBlockAction; -import game.packet.SPacketBlockBreakAnim; -import game.packet.SPacketBlockChange; -import game.packet.SPacketCamera; -import game.packet.SPacketCharacterList; -import game.packet.SPacketChunkData; -import game.packet.SPacketCollectItem; -import game.packet.SPacketDestroyEntities; -import game.packet.SPacketDimensionName; -import game.packet.SPacketDisconnect; -import game.packet.SPacketEntityEquipment; -import game.packet.SPacketEntityVelocity; -import game.packet.SPacketHeldItemChange; -import game.packet.SPacketJoinGame; -import game.packet.SPacketKeepAlive; -import game.packet.SPacketLoading; -import game.packet.SPacketMapChunkBulk; -import game.packet.SPacketMessage; -import game.packet.SPacketMultiBlockChange; -import game.packet.SPacketPlayerPosLook; -import game.packet.SPacketRespawn; -import game.packet.SPacketServerTick; -import game.packet.SPacketSetExperience; -import game.packet.SPacketSkin; -import game.packet.SPacketSpawnMob; -import game.packet.SPacketSpawnObject; -import game.packet.SPacketSpawnPlayer; -import game.packet.SPacketTimeUpdate; -import game.packet.SPacketTrades; -import game.packet.SPacketUpdateHealth; -import game.packet.SPacketWorld; -import game.potion.PotionEffect; -import game.renderer.particle.EntityPickupFX; -import game.renderer.particle.ParticleType; -import game.renderer.texture.EntityTexManager; -import game.rng.Random; -import game.tileentity.LocalBlockIntercommunication; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityMachine; -import game.tileentity.TileEntitySign; -import game.village.MerchantRecipeList; -import game.world.Chunk; -import game.world.Explosion; -import game.world.Weather; -import game.world.WorldClient; - -public class ClientPlayer extends NetHandler +public class ClientPlayer implements IClientPlayer { - /** - * The NetworkManager instance used to communicate with the server (used only by handlePlayerPosLook to update - * positioning and handleJoinGame to inform the server of the client distribution/mods) - */ - private final NetConnection netManager; + protected final Client gm; + private final NetConnection connection; + private WorldClient world; + private boolean loaded; + private final Random rand = new Random(); - /** - * Reference to the Game instance, which many handler methods operate on - */ - private Game gameController; - - /** - * Reference to the current ClientWorld instance, which many handler methods operate on - */ - private WorldClient clientWorldController; - - /** - * True if the client has finished downloading terrain and may spawn. Set upon receipt of S08PacketPlayerPosLook, - * reset upon respawning - */ - private boolean doneLoadingTerrain; -// private boolean travelSound; - private final Map playerList = Maps.newTreeMap(); - private final List characterList = Lists.newArrayList(); -// private final List> players = Lists.newArrayList(); - private int selectedCharacter = -1; - - /** - * Just an ordinary random number generator, used to randomize audio pitch of item/orb pickup and randomize both - * particlespawn offset and velocity - */ - private final Random avRandomizer = new Random(); - - public ClientPlayer(Game gmIn, NetConnection p_i46300_3_) + public ClientPlayer(Client gm, NetConnection connection) { - this.gameController = gmIn; - this.netManager = p_i46300_3_; + this.gm = gm; + this.connection = connection; + } + + + public final boolean isJumping() { + return this.gm.jump; + } + + public final boolean isSprinting() { + return this.gm.sprint; + } + + public final boolean isSneaking() { + return this.gm.sneak; + } + + public final float getMoveForward() { + return this.gm.moveForward; + } + + public final float getMoveStrafe() { + return this.gm.moveStrafe; + } + + public final void setMoveForward(float value) { + this.gm.moveForward = value; + } + + public final void setMoveStrafe(float value) { + this.gm.moveStrafe = value; + } + + public final boolean isRenderViewEntity(Entity entity) { + return this.gm.getRenderViewEntity() == entity; + } + + public final void updatePlayerMoveState() { + this.gm.updatePlayerMoveState(); + } + + public final NetConnection getConnection() { + return this.connection; + } + + + public void playSound(Sound sound) { + this.gm.getSoundManager().playSound(sound); + } + + public void emitParticleAtEntity(Entity entityIn, ParticleType particleTypes) { + this.gm.effectRenderer.emitParticleAtEntity(entityIn, particleTypes); + } + + public void onDisconnect(String reason) + { + this.gm.disconnected(reason); + } + + public void addToSendQueue(Packet p_147297_1_) + { + this.connection.sendPacket(p_147297_1_); } /** @@ -167,7 +207,7 @@ public class ClientPlayer extends NetHandler */ public void cleanup() { - this.clientWorldController = null; + this.world = null; // for(String user : this.playerInfoMap.keySet()) { // DefaultPlayerSkin.setTexture(user, null); // } @@ -177,15 +217,15 @@ public class ClientPlayer extends NetHandler public void handleJoinGame(SPacketJoinGame packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController); - this.gameController.charEditor = packetIn.isInEditor(); - this.gameController.controller = new PlayerController(this.gameController, this); - this.clientWorldController = new WorldClient(this.gameController.debugWorld, packetIn.getDimension()); + NetHandler.checkThread(packetIn, this, this.gm); + this.gm.charEditor = packetIn.isInEditor(); + this.gm.controller = new PlayerController(this.gm, this); + this.world = new WorldClient(this.gm, packetIn.getDimension()); // this.gameController.gameSettings.difficulty = packetIn.getDifficulty(); - this.gameController.loadWorld(this.clientWorldController, packetIn.getEntityType()); + this.gm.loadWorld(this.world, packetIn.getEntityType()); // this.gameController.thePlayer.dimension = this.clientWorldController.dimension.getDimensionId(); - this.gameController.thePlayer.setId(packetIn.getEntityId()); - this.gameController.displayGuiScreen(this.gameController.charEditor ? GuiChar.INSTANCE : null); + this.gm.player.setId(packetIn.getEntityId()); + this.gm.displayGuiScreen(this.gm.charEditor ? GuiChar.INSTANCE : null); // this.currentServerMaxPlayers = packetIn.getMaxPlayers(); // this.gameController.controller.setCheat(packetIn.getCheat()); // this.gameController.updateViewDistance(); @@ -203,7 +243,7 @@ public class ClientPlayer extends NetHandler */ public void handleSpawnObject(SPacketSpawnObject packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); double d0 = (double)packetIn.getX() / 32.0D; double d1 = (double)packetIn.getY() / 32.0D; double d2 = (double)packetIn.getZ() / 32.0D; @@ -226,7 +266,7 @@ public class ClientPlayer extends NetHandler // packetIn.setData(0); // } // else { - entity = EntityRegistry.createEntityByID(packetIn.getType(), this.clientWorldController, d0, d1, d2, packetIn.getData()); + entity = EntityRegistry.createEntityByID(packetIn.getType(), this.world, d0, d1, d2, packetIn.getData()); // } if(entity != null && entity.dead) { entity = null; @@ -344,10 +384,10 @@ public class ClientPlayer extends NetHandler } entity.setId(packetIn.getEntityID()); - this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entity); + this.world.addEntityToWorld(packetIn.getEntityID(), entity); - if(entity instanceof EntityProjectile) { - ((EntityProjectile)entity).setAcceleration((double)packetIn.getSpeedX() / 8000.0D, (double)packetIn.getSpeedY() / 8000.0D, (double)packetIn.getSpeedZ() / 8000.0D); + if(entity instanceof EntityProjectile projectile) { + projectile.setAcceleration((double)packetIn.getSpeedX() / 8000.0D, (double)packetIn.getSpeedY() / 8000.0D, (double)packetIn.getSpeedZ() / 8000.0D); } else if (entity.hasSpawnVelocity()) // packetIn.getData() > 0) { @@ -385,9 +425,9 @@ public class ClientPlayer extends NetHandler /** * Handles globally visible entities. Used in vanilla for lightning bolts */ - public void handleSpawnGlobalEntity(S2CPacketSpawnGlobalEntity packetIn) + public void handleSpawnGlobalEntity(SPacketSpawnGlobalEntity packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); double d0 = (double)packetIn.getEncodedX() / 32.0D; double d1 = (double)packetIn.getEncodedY() / 32.0D; double d2 = (double)packetIn.getEncodedZ() / 32.0D; @@ -395,7 +435,7 @@ public class ClientPlayer extends NetHandler if (packetIn.getType() == 1) { - entity = new EntityLightning(this.clientWorldController, d0, d1, d2, packetIn.getData(), 0, false, null); + entity = new EntityLightning(this.world, d0, d1, d2, packetIn.getData(), 0, false, null); } if (entity != null) @@ -406,7 +446,7 @@ public class ClientPlayer extends NetHandler entity.rotYaw = 0.0F; entity.rotPitch = 0.0F; entity.setId(packetIn.getEntityId()); - this.clientWorldController.effects.add(entity); + this.world.effects.add(entity); } } @@ -425,8 +465,8 @@ public class ClientPlayer extends NetHandler */ public void handleEntityVelocity(SPacketEntityVelocity packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = this.world.getEntityByID(packetIn.getEntityID()); if (entity != null) { @@ -438,17 +478,17 @@ public class ClientPlayer extends NetHandler * Invoked when the server registers new proximate objects in your watchlist or when objects in your watchlist have * changed -> Registers any changes locally */ - public void handleEntityMetadata(S1CPacketEntityMetadata packetIn) + public void handleEntityMetadata(SPacketEntityMetadata packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = this.world.getEntityByID(packetIn.getEntityId()); if (entity != null && packetIn.func_149376_c() != null) { entity.getDataWatcher().updateWatchedObjectsFromList(packetIn.func_149376_c()); - if(entity == this.gameController.thePlayer && this.gameController.open instanceof GuiChar) - ((GuiChar)this.gameController.open).checkReopen(); + if(entity == this.gm.player && this.gm.open instanceof GuiChar gui) + gui.checkReopen(); } } @@ -457,14 +497,14 @@ public class ClientPlayer extends NetHandler */ public void handleSpawnPlayer(SPacketSpawnPlayer packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); double x = (double)packetIn.getX() / 32.0D; double y = (double)packetIn.getY() / 32.0D; double z = (double)packetIn.getZ() / 32.0D; float yaw = packetIn.getYaw(); float pitch = packetIn.getPitch(); - EntityNPC player = (EntityNPC)EntityRegistry.createEntityByID(packetIn.getEntityType(), this.gameController.theWorld); // new EntityNPC(this.gameController.theWorld); // , /* this.getPlayerInfo( */ packetIn.getUser()); // ).getUser()); - player.setOtherPlayer(this.gameController); + EntityNPC player = (EntityNPC)EntityRegistry.createEntityByID(packetIn.getEntityType(), this.gm.world); // new EntityNPC(this.gameController.theWorld); // , /* this.getPlayerInfo( */ packetIn.getUser()); // ).getUser()); + player.setOtherPlayer(); player.prevX = player.lastTickPosX = (double)(player.serverPosX = packetIn.getX()); player.prevY = player.lastTickPosY = (double)(player.serverPosY = packetIn.getY()); player.prevZ = player.lastTickPosZ = (double)(player.serverPosZ = packetIn.getZ()); @@ -481,7 +521,7 @@ public class ClientPlayer extends NetHandler } player.setPositionAndRotation(x, y, z, yaw, pitch); - this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), player); + this.world.addEntityToWorld(packetIn.getEntityID(), player); List list = packetIn.getData(); if (list != null) @@ -495,10 +535,10 @@ public class ClientPlayer extends NetHandler /** * Updates an entity's position and rotation as specified by the packet */ - public void handleEntityTeleport(S18PacketEntityTeleport packetIn) + public void handleEntityTeleport(SPacketEntityTeleport packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = this.world.getEntityByID(packetIn.getEntityId()); if (entity != null) { @@ -513,11 +553,11 @@ public class ClientPlayer extends NetHandler if (Math.abs(entity.posX - d0) < 0.03125D && Math.abs(entity.posY - d1) < 0.015625D && Math.abs(entity.posZ - d2) < 0.03125D) { - entity.setPositionAndRotation2(entity.posX, entity.posY, entity.posZ, f, f1, 3, true); + entity.setClientPosition(entity.posX, entity.posY, entity.posZ, f, f1, true); } else { - entity.setPositionAndRotation2(d0, d1, d2, f, f1, 3, true); + entity.setClientPosition(d0, d1, d2, f, f1, true); } entity.onGround = packetIn.getOnGround(); @@ -529,11 +569,11 @@ public class ClientPlayer extends NetHandler */ public void handleHeldItemChange(SPacketHeldItemChange packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); if (packetIn.getHeldItemHotbarIndex() >= 0 && packetIn.getHeldItemHotbarIndex() < InventoryPlayer.getHotbarSize()) { - this.gameController.thePlayer.inventory.currentItem = packetIn.getHeldItemHotbarIndex(); + this.gm.player.inventory.currentItem = packetIn.getHeldItemHotbarIndex(); } } @@ -542,10 +582,10 @@ public class ClientPlayer extends NetHandler * subclassing of the packet allows for the specification of a subset of this data (e.g. only rel. position, abs. * rotation or both). */ - public void handleEntityMovement(S14PacketEntity packetIn) + public void handleEntityMovement(SPacketEntity packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = packetIn.getEntity(this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = packetIn.getEntity(this.world); if (entity != null) { @@ -557,7 +597,7 @@ public class ClientPlayer extends NetHandler double d2 = (double)entity.serverPosZ / 32.0D; float f = packetIn.hasRotations() ? (float)(packetIn.getYaw() * 360) / 256.0F : entity.rotYaw; float f1 = packetIn.hasRotations() ? (float)(packetIn.getPitch() * 360) / 256.0F : entity.rotPitch; - entity.setPositionAndRotation2(d0, d1, d2, f, f1, 3, false); + entity.setClientPosition(d0, d1, d2, f, f1, false); entity.onGround = packetIn.getOnGround(); } } @@ -566,10 +606,10 @@ public class ClientPlayer extends NetHandler * Updates the direction in which the specified entity is looking, normally this head rotation is independent of the * rotation of the entity itself */ - public void handleEntityHeadLook(S19PacketEntityHeadLook packetIn) + public void handleEntityHeadLook(SPacketEntityHeadLook packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = packetIn.getEntity(this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = packetIn.getEntity(this.world); if (entity != null) { @@ -585,11 +625,11 @@ public class ClientPlayer extends NetHandler */ public void handleDestroyEntities(SPacketDestroyEntities packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); for (int i = 0; i < packetIn.getEntityIDs().length; ++i) { - this.clientWorldController.removeEntityFromWorld(packetIn.getEntityIDs()[i]); + this.world.removeEntityFromWorld(packetIn.getEntityIDs()[i]); EntityTexManager.setTexture(packetIn.getEntityIDs()[i], null, null); } } @@ -601,8 +641,8 @@ public class ClientPlayer extends NetHandler */ public void handlePlayerPosLook(SPacketPlayerPosLook packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - EntityNPC entityplayer = this.gameController.thePlayer; + NetHandler.checkThread(packetIn, this, this.gm, this.world); + EntityNPC entityplayer = this.gm.player; double d0 = packetIn.getX(); double d1 = packetIn.getY(); double d2 = packetIn.getZ(); @@ -647,14 +687,15 @@ public class ClientPlayer extends NetHandler } entityplayer.setPositionAndRotation(d0, d1, d2, f, f1); - this.netManager.sendPacket(new CPacketPlayer.C06PacketPlayerPosLook(entityplayer.posX, entityplayer.getEntityBoundingBox().minY, entityplayer.posZ, entityplayer.rotYaw, entityplayer.rotPitch, false)); + this.connection.sendPacket(new CPacketPlayerPosLook(entityplayer.posX, entityplayer.getEntityBoundingBox().minY, entityplayer.posZ, entityplayer.rotYaw, entityplayer.rotPitch, false)); - if (!this.doneLoadingTerrain) + if (!this.loaded) { - this.gameController.thePlayer.prevX = this.gameController.thePlayer.posX; - this.gameController.thePlayer.prevY = this.gameController.thePlayer.posY; - this.gameController.thePlayer.prevZ = this.gameController.thePlayer.posZ; - this.doneLoadingTerrain = true; + this.gm.player.prevX = this.gm.player.posX; + this.gm.player.prevY = this.gm.player.posY; + this.gm.player.prevZ = this.gm.player.posZ; + this.loaded = true; + this.world.markReload(); // this.gameController.displayGuiScreen(null); // if(this.travelSound) { // this.gameController.getSoundManager().playSound(new PositionedSound(SoundEvent.TELEPORT)); @@ -671,11 +712,11 @@ public class ClientPlayer extends NetHandler */ public void handleMultiBlockChange(SPacketMultiBlockChange packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); - for (SPacketMultiBlockChange.BlockUpdateData s22packetmultiblockchange$blockupdatedata : packetIn.getChangedBlocks()) + for (SPacketMultiBlockChange.BlockUpdateData update : packetIn.getChangedBlocks()) { - this.clientWorldController.invalidateRegionAndSetBlock(s22packetmultiblockchange$blockupdatedata.getPos(), s22packetmultiblockchange$blockupdatedata.getBlockState()); + this.world.invalidateRegionAndSetBlock(SPacketMultiBlockChange.getPos(packetIn.getChunkPos(), update.getRawPos()), update.getBlockState()); } } @@ -684,36 +725,36 @@ public class ClientPlayer extends NetHandler */ public void handleChunkData(SPacketChunkData packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); if (packetIn.hasBiomes()) { - if (packetIn.getExtractedSize() == 0) + if (packetIn.getExtractedExtend().length == 0) { - this.clientWorldController.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), false); + this.world.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), false); return; } - this.clientWorldController.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), true); + this.world.doPreChunk(packetIn.getChunkX(), packetIn.getChunkZ(), true); } // this.clientWorldController.invalidateBlockReceiveRegion(packetIn.getChunkX() << 4, 0, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, 512, (packetIn.getChunkZ() << 4) + 15); - Chunk chunk = this.clientWorldController.getChunk(packetIn.getChunkX(), packetIn.getChunkZ()); - chunk.setData(packetIn.getExtractedDataBytes(), packetIn.getExtractedSize(), packetIn.hasBiomes()); - this.clientWorldController.markBlockRangeForRenderUpdate(packetIn.getChunkX() << 4, 0, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, 512, (packetIn.getChunkZ() << 4) + 15); + ChunkClient chunk = this.world.getChunk(packetIn.getChunkX(), packetIn.getChunkZ()); + chunk.setData(packetIn.getExtractedDataBytes(), packetIn.getExtractedExtend(), packetIn.hasBiomes()); + this.world.markBlockRangeForRenderUpdate(packetIn.getChunkX() << 4, -World.MAX_SIZE_Y, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, World.MAX_SIZE_Y, (packetIn.getChunkZ() << 4) + 15); - if (!packetIn.hasBiomes() || this.clientWorldController.dimension.hasNoLight()) // TODO: check + if (!packetIn.hasBiomes() || this.world.dimension.hasNoLight()) // TODO: check { chunk.resetRelight(); } } - public void handleBiomes(SPacketBiomes packetIn) + public void handleBiomes(SPacketBiome packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Chunk chunk = this.clientWorldController.getChunk(packetIn.getChunkX(), packetIn.getChunkZ()); - chunk.setBiomes(packetIn.getBiomes()); - this.clientWorldController.markBlockRangeForRenderUpdate(packetIn.getChunkX() << 4, 0, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, 512, (packetIn.getChunkZ() << 4) + 15); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + ChunkClient chunk = this.world.getChunk(packetIn.getChunkX(), packetIn.getChunkZ()); + chunk.setBiome(packetIn.getPos(), packetIn.getBiome()); + this.world.markBlockRangeForRenderUpdate(packetIn.getChunkX() << 4, -World.MAX_SIZE_Y, packetIn.getChunkZ() << 4, (packetIn.getChunkX() << 4) + 15, World.MAX_SIZE_Y, (packetIn.getChunkZ() << 4) + 15); } /** @@ -721,8 +762,8 @@ public class ClientPlayer extends NetHandler */ public void handleBlockChange(SPacketBlockChange packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - this.clientWorldController.invalidateRegionAndSetBlock(packetIn.getBlockPosition(), packetIn.getBlockState()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + this.world.invalidateRegionAndSetBlock(packetIn.getBlockPosition(), packetIn.getBlockState()); } /** @@ -730,43 +771,33 @@ public class ClientPlayer extends NetHandler */ public void handleDisconnect(SPacketDisconnect packetIn) { - this.netManager.closeChannel("Getrennt"); - } - - public void onDisconnect(String reason) - { - this.gameController.disconnected(reason); - } - - public void addToSendQueue(Packet p_147297_1_) - { - this.netManager.sendPacket(p_147297_1_); + this.connection.closeChannel(packetIn.getMessage()); } public void handleCollectItem(SPacketCollectItem packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = this.clientWorldController.getEntityByID(packetIn.getCollectedItemEntityID()); - EntityLiving entitylivingbase = (EntityLiving)this.clientWorldController.getEntityByID(packetIn.getEntityID()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = this.world.getEntityByID(packetIn.getCollectedItemEntityID()); + EntityLiving entitylivingbase = (EntityLiving)this.world.getEntityByID(packetIn.getEntityID()); if (entitylivingbase == null) { - entitylivingbase = this.gameController.thePlayer; + entitylivingbase = this.gm.player; } if (entity != null) { if (entity instanceof EntityXp) { - this.clientWorldController.playSoundAtEntity(entity, SoundEvent.ORB, 0.2F); + this.world.playSoundAtEntity(entity, SoundEvent.ORB, 0.2F); } else { - this.clientWorldController.playSoundAtEntity(entity, SoundEvent.POP, 0.2F); + this.world.playSoundAtEntity(entity, SoundEvent.POP, 0.2F); } - this.gameController.effectRenderer.addEffect(new EntityPickupFX(this.clientWorldController, entity, entitylivingbase, 0.5F)); - this.clientWorldController.removeEntityFromWorld(packetIn.getCollectedItemEntityID()); + this.gm.effectRenderer.addEffect(new EntityPickupFX(this.world, entity, entitylivingbase, 0.5F)); + this.world.removeEntityFromWorld(packetIn.getCollectedItemEntityID()); } } @@ -775,44 +806,44 @@ public class ClientPlayer extends NetHandler */ public void handleMessage(SPacketMessage packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController); + NetHandler.checkThread(packetIn, this, this.gm); // if(this.gameController.chatVisibility == EnumChatVisibility.FULL || // (this.gameController.chatVisibility == EnumChatVisibility.SYSTEM && packetIn.isSystem())) // { switch(packetIn.getType()) { case CONSOLE: - this.gameController.logConsole(packetIn.getMessage()); + this.gm.logConsole(packetIn.getMessage()); break; case CHAT: - this.gameController.logChat(packetIn.getMessage()); + this.gm.logChat(packetIn.getMessage()); break; case FEED: - this.gameController.logFeed(packetIn.getMessage()); + this.gm.logFeed(packetIn.getMessage()); break; case HOTBAR: - this.gameController.logHotbar(packetIn.getMessage()); + this.gm.logHotbar(packetIn.getMessage()); break; } // } } public void handleLoading(SPacketLoading packet) { - NetHandler.checkThread(packet, this, this.gameController); + NetHandler.checkThread(packet, this, this.gm); if(packet.getMessage() == null) { if(packet.getTask() != null) - this.gameController.message = packet.getTask(); + this.gm.message = packet.getTask(); if(packet.getTotal() >= 0) - this.gameController.total = packet.getTotal(); + this.gm.total = packet.getTotal(); if(packet.getProgress() >= -1) - this.gameController.progress = packet.getProgress(); + this.gm.progress = packet.getProgress(); } else { - this.gameController.message = ""; - this.gameController.total = 0; - this.gameController.progress = -1; - this.gameController.displayGuiScreen(GuiLoading.makeServerTask(packet.getMessage())); + this.gm.message = ""; + this.gm.total = 0; + this.gm.progress = -1; + this.gm.displayGuiScreen(GuiLoading.makeServerTask(packet.getMessage())); } } @@ -837,8 +868,8 @@ public class ClientPlayer extends NetHandler */ public void handleAnimation(SPacketAnimation packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = this.world.getEntityByID(packetIn.getEntityID()); if (entity != null) { @@ -858,11 +889,11 @@ public class ClientPlayer extends NetHandler // } else if (packetIn.getAnimationType() == 4) { - this.gameController.effectRenderer.emitParticleAtEntity(entity, ParticleType.CRIT); + this.gm.effectRenderer.emitParticleAtEntity(entity, ParticleType.CRIT); } else if (packetIn.getAnimationType() == 5) { - this.gameController.effectRenderer.emitParticleAtEntity(entity, ParticleType.CRIT_MAGIC); + this.gm.effectRenderer.emitParticleAtEntity(entity, ParticleType.CRIT_MAGIC); } } } @@ -883,13 +914,13 @@ public class ClientPlayer extends NetHandler */ public void handleSpawnMob(SPacketSpawnMob packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); double d0 = (double)packetIn.getX() / 32.0D; double d1 = (double)packetIn.getY() / 32.0D; double d2 = (double)packetIn.getZ() / 32.0D; float f = (float)(packetIn.getYaw() * 360) / 256.0F; float f1 = (float)(packetIn.getPitch() * 360) / 256.0F; - EntityLiving entitylivingbase = (EntityLiving)EntityRegistry.createEntityByID(packetIn.getEntityType(), this.gameController.theWorld); + EntityLiving entitylivingbase = (EntityLiving)EntityRegistry.createEntityByID(packetIn.getEntityType(), this.gm.world); entitylivingbase.serverPosX = packetIn.getX(); entitylivingbase.serverPosY = packetIn.getY(); entitylivingbase.serverPosZ = packetIn.getZ(); @@ -911,7 +942,7 @@ public class ClientPlayer extends NetHandler entitylivingbase.motionX = (double)((float)packetIn.getVelocityX() / 8000.0F); entitylivingbase.motionY = (double)((float)packetIn.getVelocityY() / 8000.0F); entitylivingbase.motionZ = (double)((float)packetIn.getVelocityZ() / 8000.0F); - this.clientWorldController.addEntityToWorld(packetIn.getEntityID(), entitylivingbase); + this.world.addEntityToWorld(packetIn.getEntityID(), entitylivingbase); List list = packetIn.getMetadata(); if (list != null) @@ -922,16 +953,16 @@ public class ClientPlayer extends NetHandler public void handleTimeUpdate(SPacketTimeUpdate packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); // this.gameController.theWorld.getWorldInfo().setTime(packetIn.getTotalWorldTime()); - this.gameController.theWorld.setDayTime(packetIn.getWorldTime()); - this.gameController.setTicked(packetIn.getServerinfo()); + this.gm.world.setDayTime(packetIn.getWorldTime()); + this.gm.setTicked(packetIn.getServerinfo()); } public void handleServerTick(SPacketServerTick packet) { - NetHandler.checkThread(packet, this, this.gameController); - this.gameController.setLastTick(packet.getTime()); + NetHandler.checkThread(packet, this, this.gm); + this.gm.setLastTick(packet.getTime()); } // public void handleCompass(SPacketCompass packetIn) @@ -940,30 +971,30 @@ public class ClientPlayer extends NetHandler // this.gameController.thePlayer.setSpawnPoint(packetIn.getSpawnPos(), true); // } - public void handleEntityAttach(S1BPacketEntityAttach packetIn) + public void handleEntityAttach(SPacketEntityAttach packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - Entity entity1 = this.clientWorldController.getEntityByID(packetIn.getVehicleEntityId()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = this.world.getEntityByID(packetIn.getEntityId()); + Entity entity1 = this.world.getEntityByID(packetIn.getVehicleEntityId()); if (packetIn.getLeash() == 0) { // boolean flag = false; - if (packetIn.getEntityId() == this.gameController.thePlayer.getId()) + if (packetIn.getEntityId() == this.gm.player.getId()) { - entity = this.gameController.thePlayer; + entity = this.gm.player; - if (entity1 instanceof EntityBoat) + if (entity1 instanceof EntityBoat boat) { - ((EntityBoat)entity1).setIsBoatEmpty(false); + boat.setIsBoatEmpty(false); } // flag = entity.vehicle == null && entity1 != null; } - else if (entity1 instanceof EntityBoat) + else if (entity1 instanceof EntityBoat boat) { - ((EntityBoat)entity1).setIsBoatEmpty(true); + boat.setIsBoatEmpty(true); } if (entity == null) @@ -978,15 +1009,15 @@ public class ClientPlayer extends NetHandler // this.gameController.ingameGui.displayHotbar(TextColor.LIGHT_GRAY + String.format("Drücke %s zum Verlassen", this.gameController.keyBindSneak.getKeyDisplay())); // } } - else if (packetIn.getLeash() == 1 && entity instanceof EntityLiving) + else if (packetIn.getLeash() == 1 && entity instanceof EntityLiving living) { if (entity1 != null) { - ((EntityLiving)entity).setLeashedTo(entity1, false); + living.setLeashedTo(entity1, false); } else { - ((EntityLiving)entity).clearLeashed(false, false); + living.clearLeashed(false, false); } } } @@ -997,10 +1028,10 @@ public class ClientPlayer extends NetHandler * (spawn particles), Zombie (villager transformation), Animal (breeding mode particles), Horse (breeding/smoke * particles), Sheep (...), Tameable (...), Villager (particles for breeding mode, angry and happy), Wolf (...) */ - public void handleEntityStatus(S1APacketEntityStatus packetIn) + public void handleEntityStatus(SPacketEntityStatus packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = packetIn.getEntity(this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = packetIn.getEntity(this.world); if (entity != null) { @@ -1017,115 +1048,141 @@ public class ClientPlayer extends NetHandler public void handleUpdateHealth(SPacketUpdateHealth packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - this.gameController.thePlayer.setPlayerSPHealth(packetIn.getHealth()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + this.gm.player.setPlayerSPHealth(packetIn.getHealth()); // this.gameController.thePlayer.getFoodStats().setFoodLevel(packetIn.getFoodLevel()); // this.gameController.thePlayer.getFoodStats().setFoodSaturationLevel(packetIn.getSaturationLevel()); } public void handleSetExperience(SPacketSetExperience packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - this.gameController.thePlayer.setXPStats(packetIn.getProgress(), packetIn.getTotalExperience(), packetIn.getLevel()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + this.gm.player.setXPStats(packetIn.getProgress(), packetIn.getTotalExperience(), packetIn.getLevel()); } public void handleRespawn(SPacketRespawn packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - this.gameController.charEditor = packetIn.isInEditor(); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + this.gm.charEditor = packetIn.isInEditor(); Dimension dim = packetIn.getDimension(); - if (dim.getDimensionId() != this.clientWorldController.dimension.getDimensionId()) // this.gameController.thePlayer.dimension) + if (dim.getDimensionId() != this.world.dimension.getDimensionId()) // this.gameController.thePlayer.dimension) { - this.doneLoadingTerrain = false; + this.loaded = false; // if(dim.getDimensionId() < 0 && this.gameController.thePlayer.dimension >= 0) { // this.travelSound = "portal.travel"; // } // Scoreboard scoreboard = this.clientWorldController.getScoreboard(); - this.clientWorldController = new WorldClient(this.gameController.debugWorld, dim); + this.world = new WorldClient(this.gm, dim); // this.clientWorldController.setWorldScoreboard(scoreboard); - this.gameController.loadWorld(this.clientWorldController, packetIn.getEntityType()); + this.gm.loadWorld(this.world, packetIn.getEntityType()); // this.gameController.thePlayer.dimension = dim.getDimensionId(); } // else if(this.gameController.charEditor) { // this.gameController.displayGuiScreen(GuiSkin.INSTANCE); // } - this.gameController.setDimensionAndSpawnPlayer(dim.getDimensionId(), packetIn.getEntityType()); - this.gameController.displayGuiScreen(this.gameController.charEditor ? GuiChar.INSTANCE : null); + this.gm.setDimensionAndSpawnPlayer(dim.getDimensionId(), packetIn.getEntityType()); + this.gm.displayGuiScreen(this.gm.charEditor ? GuiChar.INSTANCE : null); // this.gameController.controller.setCheat(packetIn.getCheat()); } /** * Initiates a new explosion (sound, particles, drop spawn) for the affected blocks indicated by the packet. */ - public void handleExplosion(S27PacketExplosion packetIn) + public void handleExplosion(SPacketExplosion packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Explosion explosion = new Explosion(this.gameController.theWorld, (Entity)null, packetIn.getX(), packetIn.getY(), packetIn.getZ(), packetIn.getStrength(), packetIn.getAffectedBlockPositions()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Explosion explosion = new Explosion(this.gm.world, (Entity)null, packetIn.getX(), packetIn.getY(), packetIn.getZ(), packetIn.getStrength(), packetIn.getAffectedBlockPositions()); explosion.doExplosionB(true, packetIn.hasAltSound()); - this.gameController.thePlayer.motionX += (double)packetIn.func_149149_c(); - this.gameController.thePlayer.motionY += (double)packetIn.func_149144_d(); - this.gameController.thePlayer.motionZ += (double)packetIn.func_149147_e(); + this.gm.player.motionX += (double)packetIn.func_149149_c(); + this.gm.player.motionY += (double)packetIn.func_149144_d(); + this.gm.player.motionZ += (double)packetIn.func_149147_e(); } /** * Displays a GUI by ID. In order starting from id 0: Chest, Workbench, Furnace, Dispenser, Enchanting table, * Brewing stand, Villager merchant, Beacon, Anvil, Hopper, Dropper, Horse */ - public void handleOpenWindow(S2DPacketOpenWindow packetIn) + public void handleOpenWindow(SPacketOpenWindow packet) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - EntityNPC entityplayersp = this.gameController.thePlayer; + NetHandler.checkThread(packet, this, this.gm, this.world); + EntityNPC player = this.gm.player; + String id = packet.getGuiId(); + String title = packet.getWindowTitle(); + int slots = packet.getSlotCount(); + LocalContainer local = new LocalContainer(title, slots); - if ("container".equals(packetIn.getGuiId())) + if ("container".equals(id)) { - entityplayersp.displayGUIChest(new InventoryBasic(packetIn.getWindowTitle(), packetIn.getSlotCount())); - entityplayersp.openContainer.windowId = packetIn.getWindowId(); + this.gm.displayGuiScreen(new GuiChest(player.inventory, new InventoryBasic(title, slots))); } - else if ("trade".equals(packetIn.getGuiId())) + else if ("enchanting_table".equals(id)) { - entityplayersp.displayTradeGui(packetIn.getWindowTitle()); - entityplayersp.openContainer.windowId = packetIn.getWindowId(); + this.gm.displayGuiScreen(new GuiEnchant(player.inventory, player.worldObj, title)); } - else if ("EntityHorse".equals(packetIn.getGuiId())) + else if ("anvil".equals(id)) { - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - - if (entity instanceof EntityHorse) - { - entityplayersp.displayGUIHorse((EntityHorse)entity, new AnimalChest(packetIn.getWindowTitle(), true, packetIn.getSlotCount())); - entityplayersp.openContainer.windowId = packetIn.getWindowId(); - } + this.gm.displayGuiScreen(new GuiRepair(player.inventory, player.worldObj)); } - else if (!packetIn.hasSlots()) + else if ("chest".equals(id)) { - entityplayersp.displayGui(new LocalBlockIntercommunication(packetIn.getGuiId(), packetIn.getWindowTitle())); - entityplayersp.openContainer.windowId = packetIn.getWindowId(); + this.gm.displayGuiScreen(new GuiChest(player.inventory, local)); + } + else if ("hopper".equals(id)) + { + this.gm.displayGuiScreen(new GuiHopper(player.inventory, local)); + } + else if ("furnace".equals(id)) + { + this.gm.displayGuiScreen(new GuiFurnace(player.inventory, local)); + } + else if ("brewing_stand".equals(id)) + { + this.gm.displayGuiScreen(new GuiBrewing(player.inventory, local)); + } + else if ("dispenser".equals(id) || "dropper".equals(id)) + { + this.gm.displayGuiScreen(new GuiDispenser(player.inventory, local)); + } + else if ("trade".equals(id)) + { + this.gm.displayGuiScreen(new GuiMerchant(player.inventory, title, player.worldObj)); + } + else if ("entity".equals(id)) + { + Entity entity = this.world.getEntityByID(packet.getEntityId()); + if(entity == null) + return; + this.gm.displayGuiScreen(new GuiEntity(player.inventory, new AnimalChest(title, true, slots), entity)); + } + else if ("tile".equals(id)) + { + TileEntity tile = this.world.getTileEntity(packet.getTilePos()); + if(!(tile instanceof TileEntityDevice dev)) + return; + this.gm.displayGuiScreen(new GuiTile(this.gm.player.inventory, local, dev)); } else { - ContainerLocalMenu containerlocalmenu = new ContainerLocalMenu(packetIn.getGuiId(), packetIn.getWindowTitle(), packetIn.getSlotCount()); - if (packetIn.getGuiId().startsWith("machine_")) - { - TileEntity machine = this.clientWorldController.getTileEntity(packetIn.getTilePos()); - if(machine instanceof TileEntityMachine) - this.gameController.displayGuiScreen(new GuiMachine(this.gameController.thePlayer.inventory, containerlocalmenu, (TileEntityMachine)machine)); - } - else { - entityplayersp.displayGUIChest(containerlocalmenu); - } - entityplayersp.openContainer.windowId = packetIn.getWindowId(); + Block block = BlockRegistry.getRegisteredBlock(id); + if(block instanceof BlockWorkbench bench) { + this.gm.displayGuiScreen(new GuiCrafting(player.inventory, player.worldObj, bench)); + } + else { + this.gm.displayGuiScreen(new GuiChest(player.inventory, local)); + } } + player.openContainer.windowId = packet.getWindowId(); } - - /** + + /** * Handles pickin up an ItemStack or dropping one in your inventory or an open container */ - public void handleSetSlot(S2FPacketSetSlot packetIn) + public void handleSetSlot(SPacketSetSlot packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - EntityNPC entityplayer = this.gameController.thePlayer; + NetHandler.checkThread(packetIn, this, this.gm, this.world); + EntityNPC entityplayer = this.gm.player; if (packetIn.getWindowId() == -1) { @@ -1163,11 +1220,11 @@ public class ClientPlayer extends NetHandler * Verifies that the server and client are synchronized with respect to the inventory/container opened by the player * and confirms if it is the case. */ - public void handleConfirmTransaction(S32PacketConfirmTransaction packetIn) + public void handleConfirmTransaction(SPacketConfirmTransaction packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); Container container = null; - EntityNPC entityplayer = this.gameController.thePlayer; + EntityNPC entityplayer = this.gm.player; if (packetIn.getWindowId() == 0) { @@ -1187,10 +1244,10 @@ public class ClientPlayer extends NetHandler /** * Handles the placement of a specified ItemStack in a specified container/inventory slot */ - public void handleWindowItems(S30PacketWindowItems packetIn) + public void handleWindowItems(SPacketWindowItems packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - EntityNPC entityplayer = this.gameController.thePlayer; + NetHandler.checkThread(packetIn, this, this.gm, this.world); + EntityNPC entityplayer = this.gm.player; if (packetIn.func_148911_c() == 0) { @@ -1205,37 +1262,40 @@ public class ClientPlayer extends NetHandler /** * Creates a sign in the specified location if it didn't exist and opens the GUI to edit its text */ - public void handleSignEditorOpen(S36PacketSignEditorOpen packetIn) + public void handleSignEditorOpen(SPacketSignEditorOpen packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - TileEntity tileentity = this.clientWorldController.getTileEntity(packetIn.getSignPosition()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + TileEntity tileentity = this.world.getTileEntity(packetIn.getSignPosition()); if (!(tileentity instanceof TileEntitySign)) { tileentity = new TileEntitySign(); - tileentity.setWorldObj(this.clientWorldController); + tileentity.setWorldObj(this.world); tileentity.setPos(packetIn.getSignPosition()); } - this.gameController.thePlayer.openEditSign((TileEntitySign)tileentity); + this.gm.displayGuiScreen(new GuiSign(packetIn.getSignPosition(), ((TileEntitySign)tileentity).signText)); + } + + public void handleForm(SPacketDisplayForm packet) { + NetHandler.checkThread(packet, this, this.gm, this.world); + this.gm.displayGuiScreen(new GuiForm(packet.getId(), packet.getTitle(), packet.getData())); } /** * Updates a specified sign with the specified text lines */ - public void handleUpdateSign(S33PacketUpdateSign packetIn) + public void handleUpdateSign(SPacketUpdateSign packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); // boolean flag = false; - if (this.gameController.theWorld.isBlockLoaded(packetIn.getPos())) + if (this.gm.world.isBlockLoaded(packetIn.getPos())) { - TileEntity tileentity = this.gameController.theWorld.getTileEntity(packetIn.getPos()); + TileEntity tileentity = this.gm.world.getTileEntity(packetIn.getPos()); - if (tileentity instanceof TileEntitySign) + if (tileentity instanceof TileEntitySign tileentitysign) { - TileEntitySign tileentitysign = (TileEntitySign)tileentity; - // if (tileentitysign.getIsEditable()) // { System.arraycopy(packetIn.getLines(), 0, tileentitysign.signText, 0, 4); @@ -1255,21 +1315,21 @@ public class ClientPlayer extends NetHandler } /** - * Updates the NBTTagCompound metadata of instances of the following entitytypes: Mob spawners, command blocks, + * Updates the metadata of instances of the following entitytypes: Mob spawners, command blocks, * beacons, skulls, flowerpot */ - public void handleUpdateTileEntity(S35PacketUpdateTileEntity packetIn) + public void handleUpdateTileEntity(SPacketUpdateTileEntity packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); - if (this.gameController.theWorld.isBlockLoaded(packetIn.getPos())) + if (this.gm.world.isBlockLoaded(packetIn.getPos())) { - TileEntity tileentity = this.gameController.theWorld.getTileEntity(packetIn.getPos()); + TileEntity tileentity = this.gm.world.getTileEntity(packetIn.getPos()); // int i = packetIn.getTileEntityType(); if (tileentity != null && packetIn.isTileEntityType(tileentity)) // i == 1 && tileentity instanceof TileEntityMobSpawner || /* i == 2 && tileentity instanceof TileEntityCommandBlock || */ i == 3 && tileentity instanceof TileEntityBeacon || i == 4 && tileentity instanceof TileEntitySkull || /* i == 5 && tileentity instanceof TileEntityFlowerPot || */ i == 6 && tileentity instanceof TileEntityBanner || i == 7 && tileentity instanceof TileEntityMachine) { - tileentity.readFromNBT(packetIn.getNbtCompound()); + tileentity.readTags(packetIn.getTags()); } } } @@ -1277,10 +1337,10 @@ public class ClientPlayer extends NetHandler /** * Sets the progressbar of the opened window to the specified value */ - public void handleWindowProperty(S31PacketWindowProperty packetIn) + public void handleWindowProperty(SPacketWindowProperty packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - EntityNPC entityplayer = this.gameController.thePlayer; + NetHandler.checkThread(packetIn, this, this.gm, this.world); + EntityNPC entityplayer = this.gm.player; if (entityplayer.openContainer != null && entityplayer.openContainer.windowId == packetIn.getWindowId()) { @@ -1290,8 +1350,8 @@ public class ClientPlayer extends NetHandler public void handleEntityEquipment(SPacketEntityEquipment packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityID()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = this.world.getEntityByID(packetIn.getEntityID()); if (entity != null) { @@ -1302,11 +1362,11 @@ public class ClientPlayer extends NetHandler /** * Resets the ItemStack held in hand and closes the window that is opened */ - public void handleCloseWindow(S2EPacketCloseWindow packetIn) + public void handleCloseWindow(SPacketCloseWindow packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); // this.gameController.thePlayer.closeScreenAndDropStack(); - this.gameController.displayGuiScreen(null); + this.gm.displayGuiScreen(null); } /** @@ -1316,8 +1376,8 @@ public class ClientPlayer extends NetHandler */ public void handleBlockAction(SPacketBlockAction packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - this.gameController.theWorld.addBlockEvent(packetIn.getBlockPosition(), packetIn.getBlockType(), packetIn.getData1(), packetIn.getData2()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + this.gm.world.addBlockEvent(packetIn.getBlockPosition(), packetIn.getBlockType(), packetIn.getData1(), packetIn.getData2()); } /** @@ -1325,59 +1385,59 @@ public class ClientPlayer extends NetHandler */ public void handleBlockBreakAnim(SPacketBlockBreakAnim packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - this.gameController.theWorld.sendBlockBreakProgress(packetIn.getBreakerId(), packetIn.getPosition(), packetIn.getProgress()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + this.gm.world.sendBlockBreakProgress(packetIn.getBreakerId(), packetIn.getPosition(), packetIn.getProgress()); } public void handleMapChunkBulk(SPacketMapChunkBulk packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); for (int i = 0; i < packetIn.getChunkCount(); ++i) { int j = packetIn.getChunkX(i); int k = packetIn.getChunkZ(i); - this.clientWorldController.doPreChunk(j, k, true); + this.world.doPreChunk(j, k, true); // this.clientWorldController.invalidateBlockReceiveRegion(j << 4, 0, k << 4, (j << 4) + 15, 512, (k << 4) + 15); - Chunk chunk = this.clientWorldController.getChunk(j, k); - chunk.setData(packetIn.getChunkBytes(i), packetIn.getChunkSize(i), true); - this.clientWorldController.markBlockRangeForRenderUpdate(j << 4, 0, k << 4, (j << 4) + 15, 512, (k << 4) + 15); + ChunkClient chunk = this.world.getChunk(j, k); + chunk.setData(packetIn.getChunkBytes(i), packetIn.getChunkExtend(i), true); + this.world.markBlockRangeForRenderUpdate(j << 4, -World.MAX_SIZE_Y, k << 4, (j << 4) + 15, World.MAX_SIZE_Y, (k << 4) + 15); - if (this.clientWorldController.dimension.hasNoLight()) // TODO: check + if (this.world.dimension.hasNoLight()) // TODO: check { chunk.resetRelight(); } } } - public void handleChangeGameState(S2BPacketChangeGameState packetIn) + public void handleChangeGameState(SPacketChangeGameState packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); switch(packetIn.getAction()) { // case SET_CHEAT: // this.gameController.controller.setCheat(packetIn.getInt() == 1); // break; case SET_WEATHER: - this.clientWorldController.setWeather(Weather.getByID(packetIn.getInt())); + this.world.setWeather(Weather.getByID(packetIn.getInt())); break; case RAIN_STRENGTH: - this.clientWorldController.setRainStrength(packetIn.getFloat(true)); + this.world.setRainStrength(packetIn.getFloat(true)); break; case DARKNESS: - this.clientWorldController.setDarkness(packetIn.getFloat(true)); + this.world.setDarkness(packetIn.getFloat(true)); break; case FOG_STRENGTH: - this.clientWorldController.setFogStrength(packetIn.getFloat(true)); + this.world.setFogStrength(packetIn.getFloat(true)); break; case TEMPERATURE: - this.clientWorldController.setTemperature(packetIn.getFloat(false)); + this.world.setTemperature(packetIn.getFloat(false)); break; } } - public void handleEffect(S28PacketEffect packetIn) + public void handleEffect(SPacketEffect packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); // if (packetIn.isSoundServerwide()) // { @@ -1385,7 +1445,7 @@ public class ClientPlayer extends NetHandler // } // else // { - this.gameController.theWorld.playAuxSFX(packetIn.getSoundType(), packetIn.getSoundPos(), packetIn.getSoundData()); + this.gm.world.playAuxSFX(packetIn.getSoundType(), packetIn.getSoundPos(), packetIn.getSoundData()); // } } @@ -1440,16 +1500,16 @@ public class ClientPlayer extends NetHandler // } // } - public void handleEntityEffect(S1DPacketEntityEffect packetIn) + public void handleEntityEffect(SPacketEntityEffect packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = this.world.getEntityByID(packetIn.getEntityId()); - if (entity instanceof EntityLiving) + if (entity instanceof EntityLiving living) { PotionEffect potioneffect = new PotionEffect(packetIn.getEffectId(), packetIn.getDuration(), packetIn.getAmplifier(), false, packetIn.hasParticles()) .setRemaining(packetIn.getRemaining()); - ((EntityLiving)entity).addEffect(potioneffect); + living.addEffect(potioneffect); } } @@ -1468,12 +1528,12 @@ public class ClientPlayer extends NetHandler public void handleCamera(SPacketCamera packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = packetIn.getEntity(this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = packetIn.getEntity(this.world); if (entity != null) { - this.gameController.setRenderViewEntity(entity); + this.gm.setRenderViewEntity(entity); } } @@ -1517,27 +1577,27 @@ public class ClientPlayer extends NetHandler //// } // } - public void handleRemoveEntityEffect(S1EPacketRemoveEntityEffect packetIn) + public void handleRemoveEntityEffect(SPacketRemoveEntityEffect packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = this.world.getEntityByID(packetIn.getEntityId()); - if (entity instanceof EntityLiving) + if (entity instanceof EntityLiving living) { - ((EntityLiving)entity).removeEffectClient(packetIn.getEffectId()); + living.removeEffectClient(packetIn.getEffectId()); } } - public void handlePlayerListItem(S38PacketPlayerListItem packetIn) + public void handlePlayerListItem(SPacketPlayerListItem packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController); + NetHandler.checkThread(packetIn, this, this.gm); for(Entry data : packetIn.getEntries()) { if(data.getValue() < 0) - this.playerList.remove(data.getKey()); + this.gm.playerList.remove(data.getKey()); else - this.playerList.put(data.getKey(), data.getValue()); + this.gm.playerList.put(data.getKey(), data.getValue()); } // String[] list = new String[this.playerList.size()]; // int[] data = new int[this.playerList.size()]; @@ -1551,23 +1611,26 @@ public class ClientPlayer extends NetHandler public void handleCharacterList(SPacketCharacterList packet) { - NetHandler.checkThread(packet, this, this.gameController); + NetHandler.checkThread(packet, this, this.gm); for(Entry data : packet.getEntries()) { if(data.getValue() == null) - this.characterList.remove(data.getKey().intValue()); - else if(data.getKey() < this.characterList.size()) - this.characterList.set(data.getKey(), data.getValue()); + this.gm.characterList.remove(data.getKey().intValue()); + else if(data.getKey() < this.gm.characterList.size()) + this.gm.characterList.set(data.getKey(), data.getValue()); else - this.characterList.add(data.getKey(), data.getValue()); + this.gm.characterList.add(data.getKey(), data.getValue()); } - this.selectedCharacter = packet.getSelected(); - if(this.gameController.charEditor && this.selectedCharacter >= 0) { - this.gameController.charEditor = false; - this.gameController.displayGuiScreen(null); + this.gm.selectedCharacter = packet.getSelected(); + if(this.gm.charEditor && this.gm.selectedCharacter >= 0) { + this.gm.charEditor = false; + this.gm.displayGuiScreen(null); } - else if(this.gameController.open instanceof GuiCharacters) { - this.gameController.displayGuiScreen(this.gameController.open); + else if(this.gm.open instanceof GuiCharacters) { + this.gm.displayGuiScreen(this.gm.open); + } + else if(this.gm.open instanceof GuiChar guichar) { + guichar.setCharsAvailable(); } } @@ -1576,10 +1639,10 @@ public class ClientPlayer extends NetHandler this.addToSendQueue(new CPacketKeepAlive(packetIn.getValue())); } - public void handlePlayerAbilities(S39PacketPlayerAbilities packetIn) + public void handlePlayerAbilities(SPacketPlayerAbilities packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - EntityNPC entityplayer = this.gameController.thePlayer; + NetHandler.checkThread(packetIn, this, this.gm, this.world); + EntityNPC entityplayer = this.gm.player; entityplayer.flying = packetIn.isFlying(); entityplayer.noclip = packetIn.isNoclip(); // entityplayer.speed = packetIn.getSpeed(); @@ -1589,29 +1652,28 @@ public class ClientPlayer extends NetHandler /** * Displays the available command-completion options the server knows of */ - public void handleTabComplete(S3APacketTabComplete packetIn) + public void handleTabComplete(SPacketTabComplete packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); String[] astring = packetIn.func_149630_c(); // this.gameController.complete(astring); - if (this.gameController.open instanceof GuiConsole) + if (this.gm.open instanceof GuiConsole guichat) { - GuiConsole guichat = (GuiConsole)this.gameController.open; guichat.onAutocompleteResponse(astring); } } - public void handleSoundEffect(S29PacketSoundEffect packetIn) + public void handleSoundEffect(SPacketSoundEffect packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); if(packetIn.getSound() == null) { - this.gameController.getSoundManager().stopSounds(); + this.gm.getSoundManager().stopSounds(); return; } // else if(packetIn.getSoundName().startsWith("music#")) { // return; // } - this.gameController.theWorld.playSound(packetIn.getX(), packetIn.getY(), packetIn.getZ(), packetIn.getSound(), packetIn.getVolume()); + this.gm.world.playSound(packetIn.getX(), packetIn.getY(), packetIn.getZ(), packetIn.getSound(), packetIn.getVolume()); } // public void handleDisplay(S48PacketDisplay packetIn) @@ -1638,14 +1700,14 @@ public class ClientPlayer extends NetHandler //// } // } - public void handleEntityNBT(S43PacketUpdateEntityNBT packetIn) + public void handleEntityTags(SPacketUpdateEntityTags packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = packetIn.getEntity(this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + Entity entity = packetIn.getEntity(this.world); if (entity != null) { - entity.clientUpdateEntityNBT(packetIn.getTagCompound()); + entity.clientUpdateEntityTags(packetIn.getTagCompound()); } } @@ -1762,9 +1824,9 @@ public class ClientPlayer extends NetHandler * Spawns a specified number of particles at the specified location with a randomized displacement according to * specified bounds */ - public void handleParticles(S2APacketParticles packetIn) + public void handleParticles(SPacketParticles packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); if (packetIn.getParticleCount() == 0) { @@ -1775,83 +1837,42 @@ public class ClientPlayer extends NetHandler try { ParticleType particle = packetIn.getParticleType(); - this.clientWorldController.spawnEntityFX(particle, particle.getShouldIgnoreRange() | packetIn.isLongDistance(), packetIn.getXCoordinate(), packetIn.getYCoordinate(), packetIn.getZCoordinate(), d0, d2, d4, packetIn.getParticleArgs()); + this.world.spawnEntityFX(particle, particle.getShouldIgnoreRange() | packetIn.isLongDistance(), packetIn.getXCoordinate(), packetIn.getYCoordinate(), packetIn.getZCoordinate(), d0, d2, d4, packetIn.getParticleArgs()); } catch (Throwable var17) { - Log.JNI.warn("Konnte Partikel-Effekt " + packetIn.getParticleType() + " nicht erzeugen"); + Log.RENDER.warn("Konnte Partikel-Effekt " + packetIn.getParticleType() + " nicht erzeugen"); } } else { for (int i = 0; i < packetIn.getParticleCount(); ++i) { - double d1 = this.avRandomizer.gaussian() * (double)packetIn.getXOffset(); - double d3 = this.avRandomizer.gaussian() * (double)packetIn.getYOffset(); - double d5 = this.avRandomizer.gaussian() * (double)packetIn.getZOffset(); - double d6 = this.avRandomizer.gaussian() * (double)packetIn.getParticleSpeed(); - double d7 = this.avRandomizer.gaussian() * (double)packetIn.getParticleSpeed(); - double d8 = this.avRandomizer.gaussian() * (double)packetIn.getParticleSpeed(); + double d1 = this.rand.gaussian() * (double)packetIn.getXOffset(); + double d3 = this.rand.gaussian() * (double)packetIn.getYOffset(); + double d5 = this.rand.gaussian() * (double)packetIn.getZOffset(); + double d6 = this.rand.gaussian() * (double)packetIn.getParticleSpeed(); + double d7 = this.rand.gaussian() * (double)packetIn.getParticleSpeed(); + double d8 = this.rand.gaussian() * (double)packetIn.getParticleSpeed(); try { ParticleType particle = packetIn.getParticleType(); - this.clientWorldController.spawnEntityFX(particle, particle.getShouldIgnoreRange() | packetIn.isLongDistance(), packetIn.getXCoordinate() + d1, packetIn.getYCoordinate() + d3, packetIn.getZCoordinate() + d5, d6, d7, d8, packetIn.getParticleArgs()); + this.world.spawnEntityFX(particle, particle.getShouldIgnoreRange() | packetIn.isLongDistance(), packetIn.getXCoordinate() + d1, packetIn.getYCoordinate() + d3, packetIn.getZCoordinate() + d5, d6, d7, d8, packetIn.getParticleArgs()); } catch (Throwable var16) { - Log.JNI.warn("Konnte Partikel-Effekt " + packetIn.getParticleType() + " nicht erzeugen"); + Log.RENDER.warn("Konnte Partikel-Effekt " + packetIn.getParticleType() + " nicht erzeugen"); return; } } } } - /** - * Updates en entity's attributes and their respective modifiers, which are used for speed bonusses (player - * sprinting, animals fleeing, baby speed), weapon/tool attackDamage, hostiles followRange randomization, zombie - * maxHealth and knockback resistance as well as reinforcement spawning chance. - */ - public void handleEntityProperties(S20PacketEntityProperties packetIn) - { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - Entity entity = this.clientWorldController.getEntityByID(packetIn.getEntityId()); - - if (entity != null) - { - if (!(entity instanceof EntityLiving)) - { - throw new IllegalStateException("Server tried to update attributes of a non-living entity (actually: " + entity + ")"); - } - else - { - AttributeMap baseattributemap = ((EntityLiving)entity).getAttributeMap(); - - for (S20PacketEntityProperties.Snapshot s20packetentityproperties$snapshot : packetIn.func_149441_d()) - { - AttributeInstance iattributeinstance = baseattributemap.getAttributeInstanceByName(s20packetentityproperties$snapshot.func_151409_a()); - - if (iattributeinstance == null) - { - iattributeinstance = baseattributemap.registerAttribute(Attribute.getAttribute(s20packetentityproperties$snapshot.func_151409_a())); - } - - iattributeinstance.setBaseValue(s20packetentityproperties$snapshot.func_151410_b()); - iattributeinstance.removeAllModifiers(); - - for (AttributeModifier attributemodifier : s20packetentityproperties$snapshot.func_151408_c()) - { - iattributeinstance.applyModifier(attributemodifier); - } - } - } - } - } - public void handleSkin(SPacketSkin packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); - Entity entity = packetIn.getEntity(this.clientWorldController); + Entity entity = packetIn.getEntity(this.world); if(entity != null && entity.isPlayer()) // { EntityTexManager.setTexture(entity.getId(), packetIn.getTexture(), ((EntityNPC)entity).getModel()); // if(entity == this.gameController.thePlayer) @@ -1876,65 +1897,37 @@ public class ClientPlayer extends NetHandler // } public void handleTrades(SPacketTrades packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); + NetHandler.checkThread(packetIn, this, this.gm, this.world); try { int i = packetIn.getWindowId(); - Gui gui = this.gameController.open; + Gui gui = this.gm.open; - if (gui != null && gui instanceof GuiMerchant && i == this.gameController.thePlayer.openContainer.windowId) + if (gui != null && gui instanceof GuiMerchant merchant && i == this.gm.player.openContainer.windowId) { // NpcMerchant imerchant = ((GuiMerchant)guiscreen).getMerchant(); MerchantRecipeList merchantrecipelist = packetIn.getTrades(); - ((GuiMerchant)gui).setRecipes(merchantrecipelist); + merchant.setRecipes(merchantrecipelist); } } catch (Exception exception) { - Log.JNI.error((Throwable)exception, (String)"Konnte Handel nicht laden"); + Log.TICK.error((Throwable)exception, (String)"Konnte Handel nicht laden"); } } public void handleWorld(SPacketWorld packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - this.clientWorldController.setGravity(this.gameController.gravity = packetIn.getGravity()); - this.clientWorldController.setTimeFactor(this.gameController.timeFactor = packetIn.getTimeFactor()); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + this.world.setGravity(this.gm.gravity = packetIn.getGravity()); + this.world.setTimeFactor(this.gm.timeFactor = packetIn.getTimeFactor()); // this.clientWorldController.setDifficulty(this.gameController.difficulty = packetIn.getDifficulty()); - this.gameController.dayCycle = packetIn.hasDayCycle(); + this.gm.dayCycle = packetIn.hasDayCycle(); } public void handleDimName(SPacketDimensionName packetIn) { - NetHandler.checkThread(packetIn, this, this.gameController, this.clientWorldController); - this.clientWorldController.dimension.setFullName(packetIn.getFullName()); - this.clientWorldController.dimension.setCustomName(packetIn.getCustomName()); - } - - /** - * Returns this the NetworkManager instance registered with this NetworkHandlerPlayClient - */ - public NetConnection getNetworkManager() - { - return this.netManager; - } - - public Set> getPlayerList() - { - return this.playerList.entrySet(); - } - - public Collection getCharacterList() - { - return this.characterList; - } - - public int getSelectedCharacter() - { - return this.selectedCharacter; - } - - public Iterable getPlayerNames() - { - return this.playerList.keySet(); + NetHandler.checkThread(packetIn, this, this.gm, this.world); + this.world.dimension.setFullName(packetIn.getFullName()); + this.world.dimension.setCustomName(packetIn.getCustomName()); } } diff --git a/client/src/main/java/client/network/DummyConnection.java b/client/src/main/java/client/network/DummyConnection.java new file mode 100644 index 0000000..b9f6323 --- /dev/null +++ b/client/src/main/java/client/network/DummyConnection.java @@ -0,0 +1,67 @@ +package client.network; + +import javax.crypto.SecretKey; + +import common.net.channel.ChannelHandlerContext; +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; +import common.network.NetConnection; +import common.network.NetHandler; +import common.network.Packet; +import common.network.PacketRegistry; + +public class DummyConnection extends NetConnection { + public void channelActive(ChannelHandlerContext context) throws Exception { + } + + public void setConnectionState(PacketRegistry newState) { + } + + public void channelInactive(ChannelHandlerContext context) throws Exception { + } + + public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) throws Exception { + } + + protected void channelRead0(ChannelHandlerContext context, Packet packet) throws Exception { + } + + public void setNetHandler(NetHandler handler) { + } + + public void sendPacket(Packet packet) { + } + + public void sendPacket(Packet packet, GenericFutureListener> listener) { + } + + public void processReceivedPackets() { + } + + public String getCutAddress() { + return "local"; + } + + public void closeChannel(String message) { + } + + public boolean isChannelOpen() { + return true; + } + + public boolean hasNoChannel() { + return false; + } + + public void disableAutoRead() { + } + + public void setCompressionTreshold(int treshold) { + } + + public void checkDisconnected() { + } + + public void startEncryption(SecretKey key) { + } +} diff --git a/client/src/main/java/client/network/LocalContainer.java b/client/src/main/java/client/network/LocalContainer.java new file mode 100755 index 0000000..80653a1 --- /dev/null +++ b/client/src/main/java/client/network/LocalContainer.java @@ -0,0 +1,50 @@ +package client.network; + +import java.util.Map; + +import common.collect.Maps; +import common.entity.npc.EntityNPC; +import common.inventory.Container; +import common.inventory.InventoryBasic; +import common.inventory.InventoryPlayer; +import common.tileentity.ILockableContainer; +import common.tileentity.Passcode; + +public class LocalContainer extends InventoryBasic implements ILockableContainer { + private Map fields = Maps.newHashMap(); + + public LocalContainer(String title, int slotCount) { + super(title, slotCount); + } + + public int getField(int id) { + return this.fields.containsKey(Integer.valueOf(id)) ? ((Integer)this.fields.get(Integer.valueOf(id))).intValue() : 0; + } + + public void setField(int id, int value) { + this.fields.put(Integer.valueOf(id), Integer.valueOf(value)); + } + + public int getFieldCount() { + return this.fields.size(); + } + + public boolean isLocked() { + return false; + } + + public void setLockCode(Passcode code) { + } + + public Passcode getLockCode() { + return Passcode.EMPTY_CODE; + } + + public String getGuiID() { + return null; + } + + public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) { + throw new UnsupportedOperationException(); + } +} diff --git a/java/src/game/renderer/ActiveRenderInfo.java b/client/src/main/java/client/renderer/ActiveRenderInfo.java similarity index 94% rename from java/src/game/renderer/ActiveRenderInfo.java rename to client/src/main/java/client/renderer/ActiveRenderInfo.java index 3987341..a8e79b2 100755 --- a/java/src/game/renderer/ActiveRenderInfo.java +++ b/client/src/main/java/client/renderer/ActiveRenderInfo.java @@ -1,4 +1,4 @@ -package game.renderer; +package client.renderer; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -7,15 +7,15 @@ import java.nio.IntBuffer; import org.lwjgl.opengl.GL11; -import game.block.Block; -import game.block.BlockLiquid; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.Vec3; -import game.world.World; +import common.block.Block; +import common.block.liquid.BlockLiquid; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Vec3; +import common.world.State; +import common.world.World; public class ActiveRenderInfo { diff --git a/java/src/game/renderer/BlockRenderer.java b/client/src/main/java/client/renderer/BlockRenderer.java similarity index 95% rename from java/src/game/renderer/BlockRenderer.java rename to client/src/main/java/client/renderer/BlockRenderer.java index 0747812..f0f7871 100755 --- a/java/src/game/renderer/BlockRenderer.java +++ b/client/src/main/java/client/renderer/BlockRenderer.java @@ -1,4 +1,4 @@ -package game.renderer; +package client.renderer; import java.util.BitSet; import java.util.List; @@ -6,37 +6,36 @@ import java.util.Map; import org.lwjgl.opengl.GL11; -import game.collect.Maps; - -import game.Game; -import game.block.Block; -import game.block.BlockLiquid; -import game.init.BlockRegistry; -import game.init.FluidRegistry; -import game.item.ItemStack; -import game.material.Material; -import game.model.BakedModel; -import game.model.IBakedModel; -import game.model.ModelManager; -import game.renderer.blockmodel.BakedQuad; -import game.renderer.texture.TextureAtlasSprite; -import game.renderer.texture.TextureMap; -import game.renderer.tileentity.TileEntityItemStackRenderer; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.Vec3i; +import client.Client; +import client.renderer.blockmodel.BakedModel; +import client.renderer.blockmodel.BakedQuad; +import client.renderer.blockmodel.IBakedModel; +import client.renderer.blockmodel.ModelManager; +import client.renderer.texture.TextureAtlasSprite; +import client.renderer.texture.TextureMap; +import client.renderer.tileentity.TileEntityItemStackRenderer; +import common.block.Block; +import common.block.Material; +import common.block.liquid.BlockLiquid; +import common.collect.Maps; +import common.init.BlockRegistry; +import common.init.FluidRegistry; +import common.item.ItemStack; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.util.Vec3i; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.State; public class BlockRenderer { private ModelManager manager; - private final Game gm; + private final Client gm; private final Map fluids = Maps.newHashMap(); - public BlockRenderer(ModelManager manager, Game gm) + public BlockRenderer(ModelManager manager, Client gm) { this.manager = manager; this.gm = gm; @@ -190,7 +189,7 @@ public class BlockRenderer for (Facing enumfacing : Facing.values()) { - List list = modelIn.getFaceQuads(enumfacing); + List list = modelIn.getFace(enumfacing); if (!list.isEmpty()) { @@ -205,7 +204,7 @@ public class BlockRenderer } } - List list1 = modelIn.getGeneralQuads(); + List list1 = modelIn.getQuads(); if (list1.size() > 0) { @@ -349,10 +348,10 @@ public class BlockRenderer { for (Facing enumfacing : Facing.values()) { - this.renderModelBrightnessColorQuads(p_178262_2_, red, green, blue, bakedModel.getFaceQuads(enumfacing)); + this.renderModelBrightnessColorQuads(p_178262_2_, red, green, blue, bakedModel.getFace(enumfacing)); } - this.renderModelBrightnessColorQuads(p_178262_2_, red, green, blue, bakedModel.getGeneralQuads()); + this.renderModelBrightnessColorQuads(p_178262_2_, red, green, blue, bakedModel.getQuads()); } private void renderModelBrightness(IBakedModel model, State p_178266_2_, float brightness, boolean p_178266_4_) @@ -406,10 +405,10 @@ public class BlockRenderer private void initAtlasSprites() { - TextureMap texturemap = Game.getGame().getTextureMapBlocks(); + TextureMap texturemap = Client.CLIENT.getTextureMapBlocks(); for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { BlockLiquid block = FluidRegistry.getStaticBlock(z); - String name = BlockRegistry.REGISTRY.getNameForObject(block).toString(); + String name = BlockRegistry.getNameFromBlock(block).toString(); TextureAtlasSprite[] sprites = new TextureAtlasSprite[] {texturemap.getAtlasSprite("blocks/" + name + "_still"), texturemap.getAtlasSprite("blocks/" + name + "_flow")}; this.fluids.put(FluidRegistry.getFluidBlock(z), sprites); this.fluids.put(block, sprites); diff --git a/java/src/game/renderer/DefaultVertexFormats.java b/client/src/main/java/client/renderer/DefaultVertexFormats.java similarity index 99% rename from java/src/game/renderer/DefaultVertexFormats.java rename to client/src/main/java/client/renderer/DefaultVertexFormats.java index 51416dd..ab287a5 100755 --- a/java/src/game/renderer/DefaultVertexFormats.java +++ b/client/src/main/java/client/renderer/DefaultVertexFormats.java @@ -1,4 +1,4 @@ -package game.renderer; +package client.renderer; public class DefaultVertexFormats { diff --git a/java/src/game/renderer/Drawing.java b/client/src/main/java/client/renderer/Drawing.java similarity index 89% rename from java/src/game/renderer/Drawing.java rename to client/src/main/java/client/renderer/Drawing.java index 934f5af..1337d9b 100644 --- a/java/src/game/renderer/Drawing.java +++ b/client/src/main/java/client/renderer/Drawing.java @@ -1,13 +1,13 @@ -package game.renderer; +package client.renderer; import org.lwjgl.opengl.GL11; -import game.Game; -import game.color.TextColor; -import game.gui.Font; -import game.gui.FontChar; -import game.log.Log; -import game.util.Util; +import client.Client; +import client.gui.Font; +import client.gui.FontChar; +import common.color.TextColor; +import common.log.Log; +import common.util.Util; public abstract class Drawing { public static class Vec2i { @@ -497,6 +497,28 @@ public abstract class Drawing { drawGradient(x + 2, y + 2, w - 4, h - 4, top, bottom); } + public static void drawRect(int x, int y, int w, int h, int color, int topleft, int btmright) { + int corner = Util.mixColor(topleft, btmright); + drawRect(x, y, w - 1, 1, topleft); + drawRect(x, y + 1, 1, h - 1, topleft); + drawRect(x + w - 1, y + 1, 1, 1, corner); + drawRect(x, y + h - 1, 1, 1, corner); + drawRect(x + w - 1, y + 1, 1, h - 1, btmright); + drawRect(x + 1, y + h - 1, w - 2, 1, btmright); + drawRect(x + 1, y + 1, w - 2, h - 2, color); + } + + public static void drawGradient(int x, int y, int w, int h, int top, int bottom, int topleft, int btmright) { + int corner = Util.mixColor(topleft, btmright); + drawRect(x, y, w - 1, 1, topleft); + drawRect(x, y + 1, 1, h - 1, topleft); + drawRect(x + w - 1, y + 1, 1, 1, corner); + drawRect(x, y + h - 1, 1, 1, corner); + drawRect(x + w - 1, y + 1, 1, h - 1, btmright); + drawRect(x + 1, y + h - 1, w - 2, 1, btmright); + drawGradient(x + 1, y + 1, w - 2, h - 2, top, bottom); + } + public static int getWidth(String str) { return getSize(str).xpos; } @@ -507,8 +529,8 @@ public abstract class Drawing { public static void drawTextbox(String str, int x, int y, int back) { Vec2i size = getSize(str); - drawRect(x, y, size.xpos + 4, size.ypos, back); - drawText(str, x + 2, y, 0xffffffff); + drawRect(x, y, size.xpos + 4, size.ypos + 2, back); + drawText(str, x + 2, y + 1, 0xffffffff); } public static void drawTextboxRight(String str, int x, int y, int back) { @@ -543,29 +565,25 @@ public abstract class Drawing { drawText(str, x - size.xpos / 2, y - size.ypos, color); } - public static void drawScaled(Game gm, String texture) { - drawScaled(gm, texture, 0, 0, gm.fb_x, gm.fb_y); + public static void drawScaled(Client gm, String texture) { + drawScaled(gm, texture, 0, 0, gm.fb_x, gm.fb_y, 0xffffffff); } - public static void drawScaled(Game gm, String texture, double x, double y, double width, double height) { + public static void drawScaled(Client gm, String texture, int x, int y, int width, int height, int color) { GlState.enableTexture2D(); GlState.disableLighting(); GlState.disableFog(); RenderBuffer buf = Tessellator.getBuffer(); gm.getTextureManager().bindTexture(texture); - GlState.color(1.0F, 1.0F, 1.0F, 1.0F); + GlState.color(color); double scale = 32.0; - buf.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); - buf.pos(x, y + height, 0.0D).tex(0.0D, height / scale) - .color(64, 64, 64, 255).endVertex(); - buf.pos(x + width, y + height, 0.0D) - .tex(width / scale, height / scale) - .color(64, 64, 64, 255).endVertex(); - buf.pos(x + width, y, 0.0D).tex(width / scale, 0.0) - .color(64, 64, 64, 255).endVertex(); - buf.pos(x, y, 0.0D).tex(0.0D, 0.0) - .color(64, 64, 64, 255).endVertex(); + buf.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX); + buf.pos((double)x, (double)y + (double)height, 0.0D).tex(0.0D, (double)height / scale).endVertex(); + buf.pos((double)x + (double)width, (double)y + (double)height, 0.0D).tex((double)width / scale, (double)height / scale).endVertex(); + buf.pos((double)x + (double)width, (double)y, 0.0D).tex((double)width / scale, 0.0).endVertex(); + buf.pos((double)x, (double)y, 0.0D).tex(0.0D, 0.0).endVertex(); Tessellator.draw(); GlState.disableTexture2D(); + GlState.color(1.0F, 1.0F, 1.0F, 1.0F); } } diff --git a/java/src/game/renderer/EntityRenderer.java b/client/src/main/java/client/renderer/EntityRenderer.java similarity index 93% rename from java/src/game/renderer/EntityRenderer.java rename to client/src/main/java/client/renderer/EntityRenderer.java index 2f63441..71968c7 100755 --- a/java/src/game/renderer/EntityRenderer.java +++ b/client/src/main/java/client/renderer/EntityRenderer.java @@ -1,38 +1,39 @@ -package game.renderer; +package client.renderer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.util.List; +import java.util.function.Predicate; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import java.util.function.Predicate; - -import game.Game; -import game.biome.Biome; -import game.block.Block; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.init.SoundEvent; -import game.material.Material; -import game.potion.Potion; -import game.renderer.particle.EffectRenderer; -import game.renderer.particle.ParticleType; -import game.renderer.texture.DynamicTexture; -import game.renderer.texture.TextureMap; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.HitPosition; -import game.world.Vec3; -import game.world.World; -import game.world.WorldClient; +import client.Client; +import client.renderer.particle.EffectRenderer; +import client.renderer.texture.DynamicTexture; +import client.renderer.texture.TextureMap; +import client.world.WorldClient; +import common.biome.Biome; +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.Items; +import common.init.SoundEvent; +import common.model.BlockLayer; +import common.model.ParticleType; +import common.potion.Potion; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.HitPosition; +import common.util.Vec3; +import common.world.World; public class EntityRenderer { private static final String locationMoltenPng = "textures/world/molten.png"; @@ -44,7 +45,7 @@ public class EntityRenderer { private static final float FOG_DISTANCE = 0.4f; private static final float SQRT_2 = ExtMath.sqrtf(2.0F); - private Game gm; + private Client gm; private Random random = new Random(); private float farPlaneDistance; public final ItemRenderer itemRenderer; @@ -72,7 +73,7 @@ public class EntityRenderer { private double cameraPitch; private int frameCount; - public EntityRenderer(Game gmIn) + public EntityRenderer(Client gmIn) { this.frameCount = 0; this.gm = gmIn; @@ -129,10 +130,10 @@ public class EntityRenderer { if (this.gm.getRenderViewEntity() == null) { - this.gm.setRenderViewEntity(this.gm.thePlayer); + this.gm.setRenderViewEntity(this.gm.player); } - float light = this.gm.theWorld.getLightBrightness(new BlockPos(this.gm.getRenderViewEntity())); + float light = this.gm.world.getLightBrightness(new BlockPos(this.gm.getRenderViewEntity())); // Log.info(String.format("%.3f", light)); float dist = (float)this.gm.renderDistance / 32.0F; float shift = light * (1.0F - dist) + dist; @@ -186,10 +187,10 @@ public class EntityRenderer { if (entity != null) { - if (this.gm.theWorld != null) + if (this.gm.world != null) { this.gm.setPointedEntity(null); - double max = this.gm.thePlayer != null ? this.gm.thePlayer.getReachDistance() : 5.0; + double max = this.gm.player != null ? this.gm.player.getReachDistance() : 5.0; this.gm.pointed = entity.rayTrace(max, partialTicks); double dist = max; Vec3 eye = entity.getPositionEyes(partialTicks); @@ -219,7 +220,7 @@ public class EntityRenderer { this.pointedEntity = null; Vec3 hit = null; float exp = 1.0F; - List list = this.gm.theWorld.getEntitiesInAABBexcluding(entity, entity.getEntityBoundingBox().addCoord(look.xCoord * max, look.yCoord * max, look.zCoord * max).expand((double)exp, (double)exp, (double)exp), new Predicate() + List list = this.gm.world.getEntitiesInAABBexcluding(entity, entity.getEntityBoundingBox().addCoord(look.xCoord * max, look.yCoord * max, look.zCoord * max).expand((double)exp, (double)exp, (double)exp), new Predicate() { public boolean test(Entity p_apply_1_) { @@ -502,7 +503,7 @@ public class EntityRenderer { f3 = f3 * 0.1F; f4 = f4 * 0.1F; f5 = f5 * 0.1F; - HitPosition movingobjectposition = this.gm.theWorld.rayTraceBlocks(new Vec3(d0 + (double)f3, d1 + (double)f4, d2 + (double)f5), new Vec3(d0 - d4 + (double)f3 + (double)f5, d1 - d6 + (double)f4, d2 - d5 + (double)f5)); + HitPosition movingobjectposition = this.gm.world.rayTraceBlocks(new Vec3(d0 + (double)f3, d1 + (double)f4, d2 + (double)f5), new Vec3(d0 - d4 + (double)f3 + (double)f5, d1 - d6 + (double)f4, d2 - d5 + (double)f5)); if (movingobjectposition != null) { @@ -589,7 +590,7 @@ public class EntityRenderer { // SKC.glScaled(this.cameraZoom, this.cameraZoom, 1.0D); // } - Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * SQRT_2); + Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * SQRT_2); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); @@ -667,7 +668,7 @@ public class EntityRenderer { // SKC.glTranslatef((float)(-(xOffset * 2 - 1)) * f, 0.0F, 0.0F); // } - Project.gluPerspective(this.getFOVModifier(partialTicks, false), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * 2.0F); + Project.gluPerspective(this.getFOVModifier(partialTicks, false), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * 2.0F); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glLoadIdentity(); @@ -749,7 +750,7 @@ public class EntityRenderer { { if (this.lightmapUpdateNeeded) { - WorldClient world = this.gm.theWorld; + WorldClient world = this.gm.world; if (world != null) { @@ -792,9 +793,9 @@ public class EntityRenderer { // f10 = 0.25F + f7 * 0.75F; // } - if (this.gm.thePlayer.hasEffect(Potion.NIGHT_VISION)) + if (this.gm.player.hasEffect(Potion.NIGHT_VISION)) { - float vis = this.getNightVisionBrightness(this.gm.thePlayer, partialTicks); + float vis = this.getNightVisionBrightness(this.gm.player, partialTicks); float mult = 1.0F / red; if (mult > 1.0F / green) @@ -926,7 +927,7 @@ public class EntityRenderer { if (this.gm.getRenderViewEntity() == null) { - this.gm.setRenderViewEntity(this.gm.thePlayer); + this.gm.setRenderViewEntity(this.gm.player); } this.getMouseOver(partialTicks); @@ -958,7 +959,7 @@ public class EntityRenderer { this.updateFogColor(partialTicks); GL11.glClear(16640); this.setupCameraTransform(partialTicks); - ActiveRenderInfo.updateRenderInfo(this.gm.thePlayer, this.gm.thirdPersonView == 2); + ActiveRenderInfo.updateRenderInfo(this.gm.player, this.gm.thirdPersonView == 2); Entity entity = this.gm.getRenderViewEntity(); double d0 = entity.lastTickPosX + (entity.posX - entity.lastTickPosX) * (double)partialTicks; double d1 = entity.lastTickPosY + (entity.posY - entity.lastTickPosY) * (double)partialTicks; @@ -969,26 +970,26 @@ public class EntityRenderer { this.setupFog(-1, partialTicks); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); - Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * 2.0F); + Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * 2.0F); GL11.glMatrixMode(GL11.GL_MODELVIEW); renderglobal.renderSky(partialTicks); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); - Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * SQRT_2); + Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * SQRT_2); GL11.glMatrixMode(GL11.GL_MODELVIEW); } this.setupFog(0, partialTicks); GlState.shadeModel(GL11.GL_SMOOTH); - if (entity.posY + (double)entity.getEyeHeight() < (double)this.gm.theWorld.dimension.getCloudHeight()) + if (entity.posY + (double)entity.getEyeHeight() < (double)this.gm.world.dimension.getCloudHeight()) { this.renderCloudsCheck(renderglobal, partialTicks); } this.setupFog(0, partialTicks); this.gm.getTextureManager().bindTexture(TextureMap.locationBlocksTexture); ItemRenderer.disableStandardItemLighting(); - renderglobal.setupTerrain(entity, (double)partialTicks, this.frameCount++, this.gm.thePlayer.noclip); + renderglobal.setupTerrain(entity, (double)partialTicks, this.frameCount++, this.gm.player.noclip); this.gm.renderGlobal.updateChunks(finishTimeNano); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); @@ -1073,7 +1074,7 @@ public class EntityRenderer { GlState.disableBlend(); GlState.disableFog(); - if (entity.posY + (double)entity.getEyeHeight() >= (double)this.gm.theWorld.dimension.getCloudHeight()) + if (entity.posY + (double)entity.getEyeHeight() >= (double)this.gm.world.dimension.getCloudHeight()) { this.renderCloudsCheck(renderglobal, partialTicks); } @@ -1091,25 +1092,25 @@ public class EntityRenderer { { GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); - Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * 4.0F); + Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * 4.0F); GL11.glMatrixMode(GL11.GL_MODELVIEW); GL11.glPushMatrix(); this.setupFog(0, partialTicks); // renderGlobalIn.renderClouds(partialTicks); - if(this.gm.theWorld.dimension.getType().clouds) + if(this.gm.world.dimension.getType().clouds) renderGlobalIn.renderClouds(partialTicks); GlState.disableFog(); GL11.glPopMatrix(); GL11.glMatrixMode(GL11.GL_PROJECTION); GL11.glLoadIdentity(); - Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_x / (float)this.gm.fb_y, 0.05F, this.farPlaneDistance * SQRT_2); + Project.gluPerspective(this.getFOVModifier(partialTicks, true), (float)this.gm.fb_raw_x / (float)this.gm.fb_raw_y, 0.05F, this.farPlaneDistance * SQRT_2); GL11.glMatrixMode(GL11.GL_MODELVIEW); } } private void addRainParticles() { - float f = this.gm.theWorld.getRainStrength(); + float f = this.gm.world.getRainStrength(); // if (this.gm.downfallSetting != 0) // { @@ -1120,7 +1121,7 @@ public class EntityRenderer { { this.random.setSeed((long)this.rendererUpdateCount * 312987231L); Entity entity = this.gm.getRenderViewEntity(); - World world = this.gm.theWorld; + World world = this.gm.world; BlockPos blockpos = new BlockPos(entity); int i = 10; double d0 = 0.0D; @@ -1154,7 +1155,7 @@ public class EntityRenderer { double d3 = this.random.doublev(); double d4 = this.random.doublev(); - if (temp >= 194.0f || block.getMaterial() == Material.lava) + if (temp >= 194.0f || block.getMaterial() == Material.LAVA) { if(temp >= 194.0f) { ++n; @@ -1166,9 +1167,9 @@ public class EntityRenderer { } } if(temp < 194.0f || this.random.chance(5)) - this.gm.theWorld.spawnParticle(temp >= 194.0f && this.random.chance(10) ? ParticleType.LAVA : ParticleType.SMOKE_NORMAL, (double)blockpos1.getX() + d3, (double)((float)blockpos1.getY() + 0.1F) - block.getBlockBoundsMinY(), (double)blockpos1.getZ() + d4, 0.0D, 0.0D, 0.0D); + this.gm.world.spawnParticle(temp >= 194.0f && this.random.chance(10) ? ParticleType.LAVA : ParticleType.SMOKE_NORMAL, (double)blockpos1.getX() + d3, (double)((float)blockpos1.getY() + 0.1F) - block.getBlockBoundsMinY(), (double)blockpos1.getZ() + d4, 0.0D, 0.0D, 0.0D); } - else if (block.getMaterial() != Material.air) + else if (block != Blocks.air) { block.setBlockBoundsBasedOnState(world, blockpos2); ++j; @@ -1180,7 +1181,7 @@ public class EntityRenderer { d2 = (double)blockpos2.getZ() + d4; } - this.gm.theWorld.spawnParticle(temp <= 5.0f ? ParticleType.HAIL_CORN : ParticleType.WATER_DROP, (double)blockpos2.getX() + d3, (double)((float)blockpos2.getY() + 0.1F) + block.getBlockBoundsMaxY(), (double)blockpos2.getZ() + d4, 0.0D, 0.0D, 0.0D); + this.gm.world.spawnParticle(temp <= 5.0f ? ParticleType.HAIL_CORN : ParticleType.WATER_DROP, (double)blockpos2.getX() + d3, (double)((float)blockpos2.getY() + 0.1F) + block.getBlockBoundsMaxY(), (double)blockpos2.getZ() + d4, 0.0D, 0.0D, 0.0D); } } } @@ -1191,11 +1192,11 @@ public class EntityRenderer { if (d1 > (double)(blockpos.getY() + 1) && world.getPrecipitationHeight(blockpos).getY() > ExtMath.floorf((float)blockpos.getY())) { - this.gm.theWorld.playSound(d0, d1, d2, n >= j ? this.pickMoltenSound() : SoundEvent.RAIN, n >= j ? 0.2f : 0.1F); + this.gm.world.playSound(d0, d1, d2, n >= j ? this.pickMoltenSound() : SoundEvent.RAIN, n >= j ? 0.2f : 0.1F); } else { - this.gm.theWorld.playSound(d0, d1, d2, n >= j ? this.pickMoltenSound() : SoundEvent.RAIN, n >= j ? 0.4f : 0.2F); + this.gm.world.playSound(d0, d1, d2, n >= j ? this.pickMoltenSound() : SoundEvent.RAIN, n >= j ? 0.4f : 0.2F); } } } @@ -1210,13 +1211,13 @@ public class EntityRenderer { */ protected void renderRainSnow(float partialTicks) { - float f = this.gm.theWorld.getRainStrength(); + float f = this.gm.world.getRainStrength(); if (f > 0.0F) // && this.gm.downfallSetting < 2) { this.enableLightmap(); Entity entity = this.gm.getRenderViewEntity(); - World world = this.gm.theWorld; + World world = this.gm.world; int i = ExtMath.floord(entity.posX); int j = ExtMath.floord(entity.posY); int k = ExtMath.floord(entity.posZ); @@ -1314,14 +1315,14 @@ public class EntityRenderer { } else if (/* world.getBiomeGenerator().getTemperatureAtHeight( */ f2 /* , j2) */ > 0.0F) { - if (mode != 0) + if (mode != (f2 <= 5.0f ? 3 : 0)) { if (mode >= 0) { Tessellator.draw(); } - mode = 0; + mode = f2 <= 5.0f ? 3 : 0; this.gm.getTextureManager().bindTexture(f2 <= 5.0f ? locationHailPng : locationRainPng); worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.PARTICLE_POSITION_TEX_COLOR_LMAP); } @@ -1411,7 +1412,7 @@ public class EntityRenderer { */ private void updateFogColor(float partial) { - WorldClient world = this.gm.theWorld; + WorldClient world = this.gm.world; Entity entity = this.gm.getRenderViewEntity(); float dist = 0.25F + 0.75F * (float)this.gm.renderDistance / 32.0F; dist = 1.0F - (float)Math.pow((double)dist, 0.25D); @@ -1473,7 +1474,7 @@ public class EntityRenderer { this.fogColorBlue *= mul; } - Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(this.gm.theWorld, entity, partial); + Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(this.gm.world, entity, partial); // if (this.cloudFog) // { @@ -1586,7 +1587,7 @@ public class EntityRenderer { private void setupFog(int start, float partial) { Entity entity = this.gm.getRenderViewEntity(); - float fog = this.gm.theWorld.getFogStrength(); + float fog = this.gm.world.getFogStrength(); float distance = Math.min(0.995f, Math.max(0.005f, FOG_DISTANCE - (0.3f * fog))); float density = 1.0f - Math.min(1.0f, FOG_DENSITY * (1.0f - fog * 0.1f)); // boolean flag = false; @@ -1599,7 +1600,7 @@ public class EntityRenderer { GL11.glFogfv(GL11.GL_FOG_COLOR, (FloatBuffer)this.setFogColorBuffer(this.fogColorRed, this.fogColorGreen, this.fogColorBlue, 1.0F)); GL11.glNormal3f(0.0F, -1.0F, 0.0F); GlState.color(1.0F, 1.0F, 1.0F, 1.0F); - Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(this.gm.theWorld, entity, partial); + Block block = ActiveRenderInfo.getBlockAtEntityViewpoint(this.gm.world, entity, partial); if(distance >= 1.0f) { ; @@ -1676,7 +1677,7 @@ public class EntityRenderer { // SKC.glFogi(NVFogDistance.GL_FOG_DISTANCE_MODE_NV, NVFogDistance.GL_EYE_RADIAL_NV); // } - if (this.gm.theWorld.dimension.hasDenseFog()) + if (this.gm.world.dimension.hasDenseFog()) { GlState.setFogStart(far * ((distance / 0.75f) * 0.05F)); GlState.setFogEnd(Math.min(far, 192.0F) * Math.max(density * (distance / 0.75f), (distance / 0.75f) * 0.05F + 0.01f)); diff --git a/java/src/game/renderer/Frustum.java b/client/src/main/java/client/renderer/Frustum.java similarity index 98% rename from java/src/game/renderer/Frustum.java rename to client/src/main/java/client/renderer/Frustum.java index d4769f1..581321b 100755 --- a/java/src/game/renderer/Frustum.java +++ b/client/src/main/java/client/renderer/Frustum.java @@ -1,4 +1,4 @@ -package game.renderer; +package client.renderer; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -6,8 +6,8 @@ import java.nio.FloatBuffer; import org.lwjgl.opengl.GL11; -import game.util.ExtMath; -import game.world.BoundingBox; +import common.util.BoundingBox; +import common.util.ExtMath; public class Frustum { private static class ClippingHelper { diff --git a/java/src/game/renderer/GlState.java b/client/src/main/java/client/renderer/GlState.java similarity index 99% rename from java/src/game/renderer/GlState.java rename to client/src/main/java/client/renderer/GlState.java index 569b0eb..d9eea4c 100755 --- a/java/src/game/renderer/GlState.java +++ b/client/src/main/java/client/renderer/GlState.java @@ -1,4 +1,4 @@ -package game.renderer; +package client.renderer; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; diff --git a/java/src/game/renderer/ItemModelMesher.java b/client/src/main/java/client/renderer/ItemModelMesher.java similarity index 83% rename from java/src/game/renderer/ItemModelMesher.java rename to client/src/main/java/client/renderer/ItemModelMesher.java index 80958f6..619016b 100755 --- a/java/src/game/renderer/ItemModelMesher.java +++ b/client/src/main/java/client/renderer/ItemModelMesher.java @@ -1,17 +1,17 @@ -package game.renderer; +package client.renderer; import java.util.List; import java.util.Map; -import game.collect.Lists; -import game.collect.Maps; - -import game.init.ItemRegistry; -import game.item.Item; -import game.item.ItemStack; -import game.model.IBakedModel; -import game.model.ModelManager; -import game.renderer.texture.TextureAtlasSprite; +import client.renderer.blockmodel.IBakedModel; +import client.renderer.blockmodel.ModelManager; +import client.renderer.texture.TextureAtlasSprite; +import common.collect.Lists; +import common.collect.Maps; +import common.init.ItemRegistry; +import common.item.Item; +import common.item.ItemStack; +import common.model.ItemMeshDefinition; public class ItemModelMesher { @@ -37,7 +37,7 @@ public class ItemModelMesher public TextureAtlasSprite getParticleIcon(Item item, int meta) { - return this.getItemModel(new ItemStack(item, 1, meta)).getParticleTexture(); + return this.getItemModel(new ItemStack(item, 1, meta)).getBaseTexture(); } public IBakedModel getItemModel(ItemStack stack) @@ -83,13 +83,13 @@ public class ItemModelMesher // public void registerItem(Item itm, int subType, String identifier) // { // this.register(itm, subType, new ResourceLocation(identifier, "inventory")); -//// String id = ItemRegistry.REGISTRY.getNameForObject(itm).toString(); +//// String id = ItemRegistry.getNameFromItem(itm).toString(); //// if(id.equals(identifier)) { ////// throw new IllegalArgumentException("Duplikat: " + identifier); -//// Log.DATA.info("MATCHING: " + ItemRegistry.REGISTRY.getNameForObject(itm) + ":" + subType); +//// Log.DATA.info("MATCHING: " + ItemRegistry.getNameFromItem(itm) + ":" + subType); //// } //// else { -//// Log.DATA.info("MISMATCH: " + ItemRegistry.REGISTRY.getNameForObject(itm) + ":" + subType + ": " + identifier); +//// Log.DATA.info("MISMATCH: " + ItemRegistry.getNameFromItem(itm) + ":" + subType + ": " + identifier); //// } // } @@ -124,7 +124,7 @@ public class ItemModelMesher for(ItemStack stack : stacks) { this.simpleShapesCache.put(this.getIndex(item, stack.getMetadata()), this.modelManager.getModel("item/" + - ItemRegistry.REGISTRY.getNameForObject(item).toString() + "#" + stack.getMetadata() + '#' + "inventory")); + ItemRegistry.getNameFromItem(item).toString() + "#" + stack.getMetadata() + '#' + "inventory")); } stacks.clear(); } diff --git a/java/src/game/renderer/ItemRenderer.java b/client/src/main/java/client/renderer/ItemRenderer.java similarity index 93% rename from java/src/game/renderer/ItemRenderer.java rename to client/src/main/java/client/renderer/ItemRenderer.java index 6fdbf98..0c310a6 100755 --- a/java/src/game/renderer/ItemRenderer.java +++ b/client/src/main/java/client/renderer/ItemRenderer.java @@ -1,4 +1,4 @@ -package game.renderer; +package client.renderer; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -7,23 +7,25 @@ import java.nio.FloatBuffer; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import game.Game; -import game.block.Block; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.item.Item; -import game.item.ItemAction; -import game.item.ItemStack; -import game.renderer.blockmodel.Transforms; -import game.renderer.entity.RenderItem; -import game.renderer.entity.RenderManager; -import game.renderer.entity.RenderNpc; -import game.renderer.texture.TextureAtlasSprite; -import game.renderer.texture.TextureMap; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.Vec3; +import client.Client; +import client.renderer.entity.RenderItem; +import client.renderer.entity.RenderManager; +import client.renderer.entity.RenderNpc; +import client.renderer.texture.EntityTexManager; +import client.renderer.texture.TextureAtlasSprite; +import client.renderer.texture.TextureMap; +import common.block.Block; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.item.Item; +import common.item.ItemAction; +import common.item.ItemStack; +import common.model.BlockLayer; +import common.model.Transforms; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Vec3; +import common.world.State; public class ItemRenderer @@ -33,7 +35,7 @@ public class ItemRenderer private static final Vec3 LIGHT1_POS = (new Vec3(-0.20000000298023224D, 1.0D, 0.699999988079071D)).normalize(); /** A reference to the Game object. */ - private final Game gm; + private final Client gm; private ItemStack itemToRender; /** @@ -96,7 +98,7 @@ public class ItemRenderer GlState.disableColorMaterial(); } - public ItemRenderer(Game gmIn) + public ItemRenderer(Client gmIn) { this.gm = gmIn; this.renderManager = gmIn.getRenderManager(); @@ -161,7 +163,7 @@ public class ItemRenderer */ private void setLightMapFromPlayer(EntityNPC clientPlayer) { - int i = this.gm.theWorld.getCombinedLight(new BlockPos(clientPlayer.posX, clientPlayer.posY + (double)clientPlayer.getEyeHeight(), clientPlayer.posZ), 0); + int i = this.gm.world.getCombinedLight(new BlockPos(clientPlayer.posX, clientPlayer.posY + (double)clientPlayer.getEyeHeight(), clientPlayer.posZ), 0); float f = (float)(i & 65535); float f1 = (float)(i >> 16); GL13.glMultiTexCoord2f(GL13.GL_TEXTURE1, f, f1); @@ -290,16 +292,16 @@ public class ItemRenderer float f4 = ExtMath.sin(ExtMath.sqrtf(swingProgress) * (float)Math.PI); GL11.glRotatef(f4 * 70.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef(f3 * -20.0F, 0.0F, 0.0F, 1.0F); - this.gm.getTextureManager().bindTexture(clientPlayer.getLocationSkin()); + this.gm.getTextureManager().bindTexture(EntityTexManager.getSkin(clientPlayer)); GL11.glTranslatef(-1.0F, 3.6F, 3.5F); GL11.glRotatef(120.0F, 0.0F, 0.0F, 1.0F); GL11.glRotatef(200.0F, 1.0F, 0.0F, 0.0F); GL11.glRotatef(-135.0F, 0.0F, 1.0F, 0.0F); GL11.glScalef(1.0F, 1.0F, 1.0F); GL11.glTranslatef(5.6F, 0.0F, 0.0F); - RenderNpc render = this.renderManager.getRenderObject(this.gm.thePlayer.getModel()); + RenderNpc render = this.renderManager.getRenderObject(this.gm.player.getModel()); GlState.disableCull(); - render.renderPlayerArm(this.gm.thePlayer); + render.renderPlayerArm(this.gm.player); GlState.enableCull(); } @@ -405,7 +407,7 @@ public class ItemRenderer public void renderItemInFirstPerson(float partialTicks) { float f = 1.0F - (this.prevEquippedProgress + (this.equippedProgress - this.prevEquippedProgress) * partialTicks); - EntityNPC clientplayer = this.gm.thePlayer; + EntityNPC clientplayer = this.gm.player; float f1 = clientplayer.getSwingProgress(partialTicks); float f2 = clientplayer.prevPitch + (clientplayer.rotPitch - clientplayer.prevPitch) * partialTicks; float f3 = clientplayer.prevYaw + (clientplayer.rotYaw - clientplayer.prevYaw) * partialTicks; @@ -473,10 +475,10 @@ public class ItemRenderer { GlState.disableAlpha(); - if (this.gm.thePlayer.isEntityInsideOpaqueBlock()) + if (this.gm.player.isEntityInsideOpaqueBlock()) { - State iblockstate = this.gm.theWorld.getState(new BlockPos(this.gm.thePlayer)); - EntityNPC entityplayer = this.gm.thePlayer; + State iblockstate = this.gm.world.getState(new BlockPos(this.gm.player)); + EntityNPC entityplayer = this.gm.player; for (int i = 0; i < 8; ++i) { @@ -484,7 +486,7 @@ public class ItemRenderer double d1 = entityplayer.posY + (double)(((float)((i >> 1) % 2) - 0.5F) * 0.1F); double d2 = entityplayer.posZ + (double)(((float)((i >> 2) % 2) - 0.5F) * entityplayer.width * 0.8F); BlockPos blockpos = new BlockPos(d0, d1 + (double)entityplayer.getEyeHeight(), d2); - State iblockstate1 = this.gm.theWorld.getState(blockpos); + State iblockstate1 = this.gm.world.getState(blockpos); if (iblockstate1.getBlock().isVisuallyOpaque()) { @@ -498,7 +500,7 @@ public class ItemRenderer } } - if(this.gm.thePlayer.isBurning()) { + if(this.gm.player.isBurning()) { this.renderFireInFirstPerson(partialTicks); } @@ -588,7 +590,7 @@ public class ItemRenderer public void updateEquippedItem() { this.prevEquippedProgress = this.equippedProgress; - EntityNPC entityplayer = this.gm.thePlayer; + EntityNPC entityplayer = this.gm.player; ItemStack itemstack = entityplayer.inventory.getCurrentItem(); boolean flag = false; diff --git a/java/src/game/renderer/Project.java b/client/src/main/java/client/renderer/Project.java similarity index 99% rename from java/src/game/renderer/Project.java rename to client/src/main/java/client/renderer/Project.java index e6d3dd4..ce0b8a8 100644 --- a/java/src/game/renderer/Project.java +++ b/client/src/main/java/client/renderer/Project.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package game.renderer; +package client.renderer; import java.nio.ByteBuffer; import java.nio.ByteOrder; diff --git a/java/src/game/renderer/RegionRenderCache.java b/client/src/main/java/client/renderer/RegionRenderCache.java similarity index 58% rename from java/src/game/renderer/RegionRenderCache.java rename to client/src/main/java/client/renderer/RegionRenderCache.java index cfd4050..d2cba9e 100755 --- a/java/src/game/renderer/RegionRenderCache.java +++ b/client/src/main/java/client/renderer/RegionRenderCache.java @@ -1,49 +1,63 @@ -package game.renderer; +package client.renderer; import java.util.Arrays; -import game.biome.Biome; -import game.init.Blocks; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.Chunk; -import game.world.ChunkCache; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.LightType; -import game.world.State; -import game.world.Vec3i; -import game.world.World; +import client.world.ChunkClient; +import client.world.WorldClient; +import common.biome.Biome; +import common.init.Blocks; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.Facing; +import common.util.Vec3i; +import common.world.IWorldAccess; +import common.world.LightType; +import common.world.State; +import common.world.World; -public class RegionRenderCache extends ChunkCache implements IWorldAccess +public class RegionRenderCache implements IWorldAccess { private static final State DEFAULT_STATE = Blocks.air.getState(); - - private final World worldObj; + + private final int xPos; + private final int zPos; + private final ChunkClient[][] chunks; + private final World world; private final BlockPos position; private final boolean empty; private int[] combinedLights; private State[] blockStates; - public RegionRenderCache(World worldIn, BlockPos posFromIn, BlockPos posToIn, int subIn) + public RegionRenderCache(WorldClient world, BlockPos from, BlockPos to, int sub) { - super(worldIn, posFromIn, posToIn, subIn); - this.worldObj = worldIn; - boolean empty = true; - for (int i1 = posFromIn.getX() >> 4; i1 <= posToIn.getX() >> 4; ++i1) + this.world = world; + this.xPos = from.getX() - sub >> 4; + this.zPos = from.getZ() - sub >> 4; + int x2 = to.getX() + sub >> 4; + int z2 = to.getZ() + sub >> 4; + this.chunks = new ChunkClient[x2 - this.xPos + 1][z2 - this.zPos + 1]; + for (int x = this.xPos; x <= x2; ++x) { - for (int j1 = posFromIn.getZ() >> 4; j1 <= posToIn.getZ() >> 4; ++j1) + for (int z = this.zPos; z <= z2; ++z) { - Chunk chunk = this.chunkArray[i1 - this.chunkX][j1 - this.chunkZ]; + this.chunks[x - this.xPos][z - this.zPos] = world.getChunk(x, z); + } + } + boolean empty = true; + for (int x = from.getX() >> 4; x <= to.getX() >> 4; ++x) + { + for (int z = from.getZ() >> 4; z <= to.getZ() >> 4; ++z) + { + ChunkClient chunk = this.chunks[x - this.xPos][z - this.zPos]; - if (chunk != null && !chunk.isEmpty(posFromIn.getY(), posToIn.getY())) + if (chunk != null && !chunk.isEmpty(from.getY(), to.getY())) { empty = false; } } } this.empty = empty; - this.position = posFromIn.subtract(new Vec3i(subIn, subIn, subIn)); + this.position = from.subtract(new Vec3i(sub, sub, sub)); int i = 16000; this.combinedLights = new int[16000]; Arrays.fill((int[])this.combinedLights, (int) - 1); @@ -52,9 +66,9 @@ public class RegionRenderCache extends ChunkCache implements IWorldAccess public TileEntity getTileEntity(BlockPos pos) { - int i = (pos.getX() >> 4) - this.chunkX; - int j = (pos.getZ() >> 4) - this.chunkZ; - return this.chunkArray[i][j].getTileEntity(pos, TileEntity.EnumCreateEntityType.QUEUED); + int i = (pos.getX() >> 4) - this.xPos; + int j = (pos.getZ() >> 4) - this.zPos; + return this.chunks[i][j].getTileEntity(pos, TileEntity.EnumCreateEntityType.QUEUED); } public int getCombinedLight(BlockPos pos, int lightValue) @@ -87,11 +101,11 @@ public class RegionRenderCache extends ChunkCache implements IWorldAccess private State getBlockStateRaw(BlockPos pos) { - if (pos.getY() >= 0 && pos.getY() < 512) + if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) { - int i = (pos.getX() >> 4) - this.chunkX; - int j = (pos.getZ() >> 4) - this.chunkZ; - return this.chunkArray[i][j].getState(pos); + int i = (pos.getX() >> 4) - this.xPos; + int j = (pos.getZ() >> 4) - this.zPos; + return this.chunks[i][j].getState(pos); } else { @@ -127,16 +141,16 @@ public class RegionRenderCache extends ChunkCache implements IWorldAccess public Biome getBiomeGenForCoords(BlockPos pos) { - return this.worldObj.getBiomeGenForCoords(pos); + return this.world.getBiomeGenForCoords(pos); } private int getLightForExt(LightType p_175629_1_, BlockPos pos) { - if (p_175629_1_ == LightType.SKY && this.worldObj.dimension.hasNoLight()) + if (p_175629_1_ == LightType.SKY && this.world.dimension.hasNoLight()) { return 0; } - else if (pos.getY() >= 0 && pos.getY() < 512) + else if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) { if (this.getState(pos).getBlock().getSumBrightness()) { @@ -161,9 +175,9 @@ public class RegionRenderCache extends ChunkCache implements IWorldAccess } else { - int i = (pos.getX() >> 4) - this.chunkX; - int j = (pos.getZ() >> 4) - this.chunkZ; - return this.chunkArray[i][j].getLight(p_175629_1_, pos); + int i = (pos.getX() >> 4) - this.xPos; + int j = (pos.getZ() >> 4) - this.zPos; + return this.chunks[i][j].getLight(p_175629_1_, pos); } } else @@ -178,16 +192,16 @@ public class RegionRenderCache extends ChunkCache implements IWorldAccess // */ // public boolean isAirBlock(BlockPos pos) // { -// return this.getBlockState(pos).getBlock().getMaterial() == Material.air; +// return this.getBlockState(pos).getBlock() == Blocks.air; // } public int getLightFor(LightType p_175628_1_, BlockPos pos) { - if (pos.getY() >= 0 && pos.getY() < 512) + if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) { - int i = (pos.getX() >> 4) - this.chunkX; - int j = (pos.getZ() >> 4) - this.chunkZ; - return this.chunkArray[i][j].getLight(p_175628_1_, pos); + int i = (pos.getX() >> 4) - this.xPos; + int j = (pos.getZ() >> 4) - this.zPos; + return this.chunks[i][j].getLight(p_175628_1_, pos); } else { diff --git a/java/src/game/renderer/RegionRenderCacheBuilder.java b/client/src/main/java/client/renderer/RegionRenderCacheBuilder.java similarity index 92% rename from java/src/game/renderer/RegionRenderCacheBuilder.java rename to client/src/main/java/client/renderer/RegionRenderCacheBuilder.java index e2b175a..7318dc3 100755 --- a/java/src/game/renderer/RegionRenderCacheBuilder.java +++ b/client/src/main/java/client/renderer/RegionRenderCacheBuilder.java @@ -1,4 +1,6 @@ -package game.renderer; +package client.renderer; + +import common.model.BlockLayer; public class RegionRenderCacheBuilder { diff --git a/java/src/game/renderer/RenderBuffer.java b/client/src/main/java/client/renderer/RenderBuffer.java similarity index 97% rename from java/src/game/renderer/RenderBuffer.java rename to client/src/main/java/client/renderer/RenderBuffer.java index a0c4cb5..ceaa45a 100755 --- a/java/src/game/renderer/RenderBuffer.java +++ b/client/src/main/java/client/renderer/RenderBuffer.java @@ -1,4 +1,4 @@ -package game.renderer; +package client.renderer; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -9,8 +9,8 @@ import java.util.Arrays; import java.util.BitSet; import java.util.Comparator; -import game.log.Log; -import game.util.ExtMath; +import common.log.Log; +import common.util.ExtMath; public class RenderBuffer { @@ -46,7 +46,7 @@ public class RenderBuffer int i = this.byteBuffer.capacity(); int j = i % 2097152; int k = j + (((this.rawIntBuffer.position() + p_181670_1_) * 4 - j) / 2097152 + 1) * 2097152; - Log.JNI.warn("Musste Puffer vergrößern: Alte Größe " + i + " Bytes, neue Größe " + k + " Bytes."); + Log.RENDER.warn("Musste Puffer vergrößern: Alte Größe " + i + " Bytes, neue Größe " + k + " Bytes."); int l = this.rawIntBuffer.position(); ByteBuffer bytebuffer = ByteBuffer.allocateDirect(k).order(ByteOrder.nativeOrder()); this.byteBuffer.position(0); @@ -196,7 +196,7 @@ public class RenderBuffer { int i = this.vertexCount * this.vertexFormat.getNextOffset() + this.vertexFormat.getOffset(this.vertexFormatIndex); - switch (this.vertexFormatElement.getType()) + switch (this.vertexFormatElement.type()) { case FLOAT: this.byteBuffer.putFloat(i, (float)u); @@ -229,7 +229,7 @@ public class RenderBuffer { int i = this.vertexCount * this.vertexFormat.getNextOffset() + this.vertexFormat.getOffset(this.vertexFormatIndex); - switch (this.vertexFormatElement.getType()) + switch (this.vertexFormatElement.type()) { case FLOAT: this.byteBuffer.putFloat(i, (float)p_181671_1_); @@ -381,7 +381,7 @@ public class RenderBuffer { int i = this.vertexCount * this.vertexFormat.getNextOffset() + this.vertexFormat.getOffset(this.vertexFormatIndex); - switch (this.vertexFormatElement.getType()) + switch (this.vertexFormatElement.type()) { case FLOAT: this.byteBuffer.putFloat(i, (float)red / 255.0F); @@ -447,7 +447,7 @@ public class RenderBuffer { int i = this.vertexCount * this.vertexFormat.getNextOffset() + this.vertexFormat.getOffset(this.vertexFormatIndex); - switch (this.vertexFormatElement.getType()) + switch (this.vertexFormatElement.type()) { case FLOAT: this.byteBuffer.putFloat(i, (float)(x + this.xOffset)); @@ -500,7 +500,7 @@ public class RenderBuffer this.vertexFormatIndex %= this.vertexFormat.getElementCount(); this.vertexFormatElement = this.vertexFormat.getElement(this.vertexFormatIndex); - if (this.vertexFormatElement.getUsage() == VertexFormatElement.EnumUsage.PADDING) + if (this.vertexFormatElement.usage() == VertexFormatElement.EnumUsage.PADDING) { this.nextVertexFormatIndex(); } @@ -510,7 +510,7 @@ public class RenderBuffer { int i = this.vertexCount * this.vertexFormat.getNextOffset() + this.vertexFormat.getOffset(this.vertexFormatIndex); - switch (this.vertexFormatElement.getType()) + switch (this.vertexFormatElement.type()) { case FLOAT: this.byteBuffer.putFloat(i, p_181663_1_); diff --git a/java/src/game/renderer/RenderGlobal.java b/client/src/main/java/client/renderer/RenderGlobal.java similarity index 94% rename from java/src/game/renderer/RenderGlobal.java rename to client/src/main/java/client/renderer/RenderGlobal.java index c91daa9..e5e257c 100755 --- a/java/src/game/renderer/RenderGlobal.java +++ b/client/src/main/java/client/renderer/RenderGlobal.java @@ -1,4 +1,4 @@ -package game.renderer; +package client.renderer; import java.util.ArrayList; import java.util.Collection; @@ -15,43 +15,44 @@ import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; import org.lwjgl.opengl.GL15; -import game.collect.Lists; -import game.collect.Maps; -import game.collect.Sets; - -import game.Game; -import game.audio.Sound; -import game.block.Block; -import game.block.BlockChest; -import game.block.BlockSign; -import game.block.BlockSkull; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityBox; -import game.entity.types.EntityLiving; -import game.material.Material; -import game.renderer.chunk.ChunkRenderDispatcher; -import game.renderer.chunk.CompiledChunk; -import game.renderer.chunk.RenderChunk; -import game.renderer.chunk.VisGraph; -import game.renderer.entity.RenderManager; -import game.renderer.texture.TextureAtlasSprite; -import game.renderer.texture.TextureManager; -import game.renderer.texture.TextureMap; -import game.renderer.tileentity.TileEntityRendererDispatcher; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityChest; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Chunk; -import game.world.ClassInheritanceMultiMap; -import game.world.Facing; -import game.world.HitPosition; -import game.world.State; -import game.world.Vec3; -import game.world.WorldClient; +import client.Client; +import client.renderer.chunk.ChunkRenderDispatcher; +import client.renderer.chunk.CompiledChunk; +import client.renderer.chunk.RenderChunk; +import client.renderer.chunk.VisGraph; +import client.renderer.entity.RenderManager; +import client.renderer.texture.TextureAtlasSprite; +import client.renderer.texture.TextureManager; +import client.renderer.texture.TextureMap; +import client.renderer.tileentity.TileEntityRendererDispatcher; +import client.world.ChunkClient; +import client.world.WorldClient; +import common.block.Block; +import common.block.tech.BlockChest; +import common.block.tile.BlockSign; +import common.collect.Lists; +import common.collect.Maps; +import common.collect.Sets; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityBox; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.model.BlockLayer; +import common.rng.Random; +import common.sound.Sound; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityChest; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.InheritanceMultiMap; +import common.util.ExtMath; +import common.util.Facing; +import common.util.HitPosition; +import common.util.Vec3; +import common.util.Vector3f; +import common.world.State; +import common.world.World; public class RenderGlobal { @@ -112,7 +113,7 @@ public class RenderGlobal private static final String SUN_TEX = "textures/world/sun.png"; private static final float[] SUN_COLOR = new float[4]; - private final Game gm; + private final Client gm; private final TextureManager renderEngine; private final RenderManager renderManager; private WorldClient theWorld; @@ -156,7 +157,7 @@ public class RenderGlobal private double prevRenderSortZ; private boolean displayListEntitiesDirty = true; - public RenderGlobal(Game gmIn) + public RenderGlobal(Client gmIn) { this.gm = gmIn; this.renderManager = gmIn.getRenderManager(); @@ -462,7 +463,7 @@ public class RenderGlobal if (entity != null) { - this.viewFrustum.updateChunkPositions(entity.posX, entity.posZ); + this.viewFrustum.updateChunkPositions(entity.posX, entity.posY, entity.posZ); } } @@ -559,7 +560,7 @@ public class RenderGlobal GlState.enableAlpha(); } - if (this.gm.renderOutlines && this.gm.thePlayer != null) + if (this.gm.renderOutlines && this.gm.player != null) { GlState.depthFunc(GL11.GL_ALWAYS); GlState.disableFog(); @@ -574,7 +575,7 @@ public class RenderGlobal { Entity entity3 = list.get(j); if ((entity3 != this.gm.getRenderViewEntity() || this.gm.thirdPersonView != 0) && - entity3 instanceof EntityLiving && entity3.isInRangeToRender3d(d0, d1, d2) && (entity3.noFrustumCheck || Frustum.isInFrustum(entity3.getEntityBoundingBox()) || entity3.passenger == this.gm.thePlayer)) + entity3 instanceof EntityLiving && entity3.isInRangeToRender3d(d0, d1, d2) && (entity3.noFrustumCheck || Frustum.isInFrustum(entity3.getEntityBoundingBox()) || entity3.passenger == this.gm.player)) { // this.renderManager.renderEntity(entity3, partialTicks); int c = ((EntityLiving)entity3).getColor(); @@ -602,8 +603,8 @@ public class RenderGlobal for (RenderGlobal.ContainerLocalRenderInformation renderglobal$containerlocalrenderinformation : this.renderInfos) { - Chunk chunk = this.theWorld.getChunk(renderglobal$containerlocalrenderinformation.renderChunk.getPosition()); - ClassInheritanceMultiMap classinheritancemultimap = chunk.getEntities()[renderglobal$containerlocalrenderinformation.renderChunk.getPosition().getY() / 16]; + ChunkClient chunk = this.theWorld.getChunk(renderglobal$containerlocalrenderinformation.renderChunk.getPosition()); + InheritanceMultiMap classinheritancemultimap = chunk.getEntities()[ExtMath.clampi(renderglobal$containerlocalrenderinformation.renderChunk.getPosition().getY() / 16, 0, 31)]; if (!classinheritancemultimap.isEmpty()) { @@ -622,7 +623,7 @@ public class RenderGlobal } entity2 = (Entity)iterator.next(); - flag2 = this.renderManager.shouldRender(entity2, d0, d1, d2) || entity2.passenger == this.gm.thePlayer; + flag2 = this.renderManager.shouldRender(entity2, d0, d1, d2) || entity2.passenger == this.gm.player; if (!flag2) { @@ -631,7 +632,7 @@ public class RenderGlobal // boolean flag3 = this.gm.getRenderViewEntity() instanceof EntityLivingBase ? ((EntityLivingBase)this.gm.getRenderViewEntity()).isPlayerSleeping() : false; - if (entity2.posY < 0.0D || entity2.posY >= 512.0D || this.theWorld.isBlockLoaded(new BlockPos(entity2))) + if (entity2.posY < (double)(-World.MAX_SIZE_Y) || entity2.posY >= (double)World.MAX_SIZE_Y || this.theWorld.isBlockLoaded(new BlockPos(entity2))) { if((entity2 != this.gm.getRenderViewEntity() || this.gm.thirdPersonView != 0 /* || flag3 */)) { ++this.countEntitiesRendered; @@ -700,7 +701,7 @@ public class RenderGlobal Block block = this.theWorld.getState(blockpos).getBlock(); - if (tileentity1 != null && (block instanceof BlockChest || /* block instanceof BlockWarpChest || */ block instanceof BlockSign || block instanceof BlockSkull)) + if (tileentity1 != null && (block instanceof BlockChest || block instanceof BlockSign)) { TileEntityRendererDispatcher.instance.renderTileEntity(tileentity1, partialTicks, destroyblockprogress.getPartialBlockDamage()); } @@ -750,6 +751,7 @@ public class RenderGlobal double d0 = viewEntity.posX - this.frustumUpdatePosX; double d1 = viewEntity.posY - this.frustumUpdatePosY; double d2 = viewEntity.posZ - this.frustumUpdatePosZ; + int prev = this.frustumUpdatePosChunkY; if (this.frustumUpdatePosChunkX != viewEntity.chunkCoordX || this.frustumUpdatePosChunkY != viewEntity.chunkCoordY || this.frustumUpdatePosChunkZ != viewEntity.chunkCoordZ || d0 * d0 + d1 * d1 + d2 * d2 > 16.0D) { @@ -759,7 +761,7 @@ public class RenderGlobal this.frustumUpdatePosChunkX = viewEntity.chunkCoordX; this.frustumUpdatePosChunkY = viewEntity.chunkCoordY; this.frustumUpdatePosChunkZ = viewEntity.chunkCoordZ; - this.viewFrustum.updateChunkPositions(viewEntity.posX, viewEntity.posZ); + this.viewFrustum.updateChunkPositions(viewEntity.posX, viewEntity.posY, viewEntity.posZ); } double d3 = viewEntity.lastTickPosX + (viewEntity.posX - viewEntity.lastTickPosX) * partialTicks; double d4 = viewEntity.lastTickPosY + (viewEntity.posY - viewEntity.lastTickPosY) * partialTicks; @@ -819,18 +821,21 @@ public class RenderGlobal else { // int i = blockpos1.getY() > 0 ? 248 : 8; - int i = blockpos1.getY() > 0 ? 504 : 8; +// int i = blockpos1.getY() > 0 ? 504 : 8; for (int j = -this.renderDistanceChunks; j <= this.renderDistanceChunks; ++j) { for (int k = -this.renderDistanceChunks; k <= this.renderDistanceChunks; ++k) { - RenderChunk renderchunk1 = this.viewFrustum.getRenderChunk(new BlockPos((j << 4) + 8, i, (k << 4) + 8)); - - if (renderchunk1 != null && Frustum.isInFrustum(renderchunk1.boundingBox)) + for (int i = -this.renderDistanceChunks; i <= this.renderDistanceChunks; ++i) { - renderchunk1.setFrameIndex(frameCount); - queue.add(new RenderGlobal.ContainerLocalRenderInformation(renderchunk1, (Facing)null, 0)); + RenderChunk renderchunk1 = this.viewFrustum.getRenderChunk(new BlockPos((j << 4) + 8, (i << 4) + 8, (k << 4) + 8)); + + if (renderchunk1 != null && Frustum.isInFrustum(renderchunk1.boundingBox)) + { + renderchunk1.setFrameIndex(frameCount); + queue.add(new RenderGlobal.ContainerLocalRenderInformation(renderchunk1, (Facing)null, 0)); + } } } } @@ -899,6 +904,24 @@ public class RenderGlobal } this.chunksToUpdate.addAll(set); + + if(prev != Integer.MIN_VALUE && viewEntity.chunkCoordY != prev) { + for (int j = -this.renderDistanceChunks; j <= this.renderDistanceChunks; ++j) + { + for (int k = -this.renderDistanceChunks; k <= this.renderDistanceChunks; ++k) + { + for (int i = -this.renderDistanceChunks; i <= this.renderDistanceChunks; ++i) + { + RenderChunk renderchunk1 = this.viewFrustum.getRenderChunk(new BlockPos((j << 4) + 8, (i << 4) + 8, (k << 4) + 8)); + + if (renderchunk1 != null) + { + renderchunk1.setNeedsUpdate(true); + } + } + } + } + } } private boolean isPositionInRenderChunk(BlockPos pos, RenderChunk renderChunkIn) @@ -911,7 +934,7 @@ public class RenderGlobal { VisGraph visgraph = new VisGraph(); BlockPos blockpos = new BlockPos(pos.getX() >> 4 << 4, pos.getY() >> 4 << 4, pos.getZ() >> 4 << 4); - Chunk chunk = this.theWorld.getChunk(blockpos); + ChunkClient chunk = this.theWorld.getChunk(blockpos); for (BlockPos.MutableBlockPos blockpos$mutableblockpos : BlockPos.getAllInBoxMutable(blockpos, blockpos.add(15, 15, 15))) { @@ -930,7 +953,7 @@ public class RenderGlobal private RenderChunk getRenderChunkOffset(BlockPos playerPos, RenderChunk renderChunkBase, Facing facing) { BlockPos blockpos = renderChunkBase.getBlockPosOffset16(facing); - return ExtMath.absi(playerPos.getX() - blockpos.getX()) > this.renderDistanceChunks * 16 ? null : (blockpos.getY() >= 0 && blockpos.getY() < 512 ? (ExtMath.absi(playerPos.getZ() - blockpos.getZ()) > this.renderDistanceChunks * 16 ? null : this.viewFrustum.getRenderChunk(blockpos)) : null); + return ExtMath.absi(playerPos.getX() - blockpos.getX()) > this.renderDistanceChunks * 16 ? null : (ExtMath.absi(playerPos.getY() - blockpos.getY()) <= this.renderDistanceChunks * 16 ? (ExtMath.absi(playerPos.getZ() - blockpos.getZ()) > this.renderDistanceChunks * 16 ? null : this.viewFrustum.getRenderChunk(blockpos)) : null); } protected Vector3f getViewVector(Entity entityIn, double partialTicks) @@ -938,7 +961,7 @@ public class RenderGlobal float f = (float)((double)entityIn.prevPitch + (double)(entityIn.rotPitch - entityIn.prevPitch) * partialTicks); float f1 = (float)((double)entityIn.prevYaw + (double)(entityIn.rotYaw - entityIn.prevYaw) * partialTicks); - if (Game.getGame().thirdPersonView == 2) + if (Client.CLIENT.thirdPersonView == 2) { f += 180.0F; } @@ -1018,8 +1041,8 @@ public class RenderGlobal // { for (VertexFormatElement vertexformatelement : DefaultVertexFormats.BLOCK.getElements()) { - VertexFormatElement.EnumUsage vertexformatelement$enumusage = vertexformatelement.getUsage(); - int i = vertexformatelement.getIndex(); + VertexFormatElement.EnumUsage vertexformatelement$enumusage = vertexformatelement.usage(); + int i = vertexformatelement.index(); switch (vertexformatelement$enumusage) { @@ -1124,11 +1147,11 @@ public class RenderGlobal public void renderSky(float partialTicks) { - if (this.gm.theWorld.dimension.getSkyBoxTexture() != null) + if (this.gm.world.dimension.getSkyBoxTexture() != null) { - this.renderSkyBox(this.gm.theWorld.dimension.getSkyBoxTexture()); + this.renderSkyBox(this.gm.world.dimension.getSkyBoxTexture()); } - else if (this.gm.theWorld.dimension.getType().sky) + else if (this.gm.world.dimension.getType().sky) { GlState.disableTexture2D(); Vec3 vec3 = this.theWorld.getSkyColor(this.gm.getRenderViewEntity(), partialTicks); @@ -1222,7 +1245,7 @@ public class RenderGlobal GlState.color(1.0F, 1.0F, 1.0F, f16); GL11.glRotatef(-90.0F, 0.0F, 1.0F, 0.0F); GL11.glRotatef(this.theWorld.getCelestialAngle(partialTicks) * 360.0F, 1.0F, 0.0F, 0.0F); - if(this.gm.theWorld.dimension.getType().sun) { + if(this.gm.world.dimension.getType().sun) { float size = 30.0F; this.renderEngine.bindTexture(SUN_TEX); worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX); @@ -1232,7 +1255,7 @@ public class RenderGlobal worldrenderer.pos((double)(-size), 100.0D, (double)size).tex(0.0D, 1.0D).endVertex(); Tessellator.draw(); } - if(this.gm.theWorld.dimension.getType().moon) { + if(this.gm.world.dimension.getType().moon) { float size = 20.0F; this.renderEngine.bindTexture(MOON_TEX); int i = this.theWorld.getMoonPhase(); @@ -1331,7 +1354,7 @@ public class RenderGlobal int j = ExtMath.floord(d2 / 2048.0D); d1 = d1 - (double)(i * 2048); d2 = d2 - (double)(j * 2048); - this.renderEngine.bindTexture(this.gm.theWorld.dimension.getCloudTexture()); + this.renderEngine.bindTexture(this.gm.world.dimension.getCloudTexture()); GlState.enableBlend(); GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); Vec3 vec3 = this.theWorld.getCloudColour(this.gm.getRenderViewEntity(), partialTicks); @@ -1546,7 +1569,7 @@ public class RenderGlobal double d5 = (double)blockpos.getZ() - d2; Block block = this.theWorld.getState(blockpos).getBlock(); - if (!(block instanceof BlockChest) && /* !(block instanceof BlockWarpChest) && */ !(block instanceof BlockSign) && !(block instanceof BlockSkull)) + if (!(block instanceof BlockChest) && !(block instanceof BlockSign)) { if (d3 * d3 + d4 * d4 + d5 * d5 > 1024.0D) { @@ -1556,7 +1579,7 @@ public class RenderGlobal { State iblockstate = this.theWorld.getState(blockpos); - if (iblockstate.getBlock().getMaterial() != Material.air) + if (iblockstate.getBlock() != Blocks.air) { int i = destroyblockprogress.getPartialBlockDamage(); TextureAtlasSprite textureatlassprite = this.destroyBlockIcons[i]; @@ -1592,7 +1615,7 @@ public class RenderGlobal BlockPos blockpos = movingObjectPositionIn.block; Block block = this.theWorld.getState(blockpos).getBlock(); - if (block.getMaterial() != Material.air) // && this.theWorld.getWorldBorder().contains(blockpos)) + if (block != Blocks.air) // && this.theWorld.getWorldBorder().contains(blockpos)) { block.setBlockBoundsBasedOnState(this.theWorld, blockpos); double d0 = player.lastTickPosX + (player.posX - player.lastTickPosX) * (double)partialTicks; diff --git a/java/src/game/renderer/Tessellator.java b/client/src/main/java/client/renderer/Tessellator.java similarity index 83% rename from java/src/game/renderer/Tessellator.java rename to client/src/main/java/client/renderer/Tessellator.java index bc6412e..c7d69b9 100755 --- a/java/src/game/renderer/Tessellator.java +++ b/client/src/main/java/client/renderer/Tessellator.java @@ -1,4 +1,4 @@ -package game.renderer; +package client.renderer; import java.nio.ByteBuffer; import java.util.List; @@ -28,27 +28,27 @@ public abstract class Tessellator for (int j = 0; j < list.size(); ++j) { VertexFormatElement vertexformatelement = (VertexFormatElement)list.get(j); - VertexFormatElement.EnumUsage vertexformatelement$enumusage = vertexformatelement.getUsage(); - int k = vertexformatelement.getType().getGlConstant(); - int l = vertexformatelement.getIndex(); + VertexFormatElement.EnumUsage vertexformatelement$enumusage = vertexformatelement.usage(); + int k = vertexformatelement.type().getGlConstant(); + int l = vertexformatelement.index(); bytebuffer.position(vertexformat.getOffset(j)); switch (vertexformatelement$enumusage) { case POSITION: - GL11.glVertexPointer(vertexformatelement.getElementCount(), k, i, bytebuffer); + GL11.glVertexPointer(vertexformatelement.count(), k, i, bytebuffer); GL11.glEnableClientState(GL11.GL_VERTEX_ARRAY); break; case UV: GL13.glClientActiveTexture(GL13.GL_TEXTURE0 + l); - GL11.glTexCoordPointer(vertexformatelement.getElementCount(), k, i, bytebuffer); + GL11.glTexCoordPointer(vertexformatelement.count(), k, i, bytebuffer); GL11.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY); GL13.glClientActiveTexture(GL13.GL_TEXTURE0); break; case COLOR: - GL11.glColorPointer(vertexformatelement.getElementCount(), k, i, bytebuffer); + GL11.glColorPointer(vertexformatelement.count(), k, i, bytebuffer); GL11.glEnableClientState(GL11.GL_COLOR_ARRAY); break; @@ -64,8 +64,8 @@ public abstract class Tessellator for (int j1 = list.size(); i1 < j1; ++i1) { VertexFormatElement vertexformatelement1 = (VertexFormatElement)list.get(i1); - VertexFormatElement.EnumUsage vertexformatelement$enumusage1 = vertexformatelement1.getUsage(); - int k1 = vertexformatelement1.getIndex(); + VertexFormatElement.EnumUsage vertexformatelement$enumusage1 = vertexformatelement1.usage(); + int k1 = vertexformatelement1.index(); switch (vertexformatelement$enumusage1) { diff --git a/java/src/game/renderer/VertexBuffer.java b/client/src/main/java/client/renderer/VertexBuffer.java similarity index 97% rename from java/src/game/renderer/VertexBuffer.java rename to client/src/main/java/client/renderer/VertexBuffer.java index ab21f17..ee8a33e 100755 --- a/java/src/game/renderer/VertexBuffer.java +++ b/client/src/main/java/client/renderer/VertexBuffer.java @@ -1,4 +1,4 @@ -package game.renderer; +package client.renderer; import java.nio.ByteBuffer; diff --git a/java/src/game/renderer/VertexFormat.java b/client/src/main/java/client/renderer/VertexFormat.java similarity index 89% rename from java/src/game/renderer/VertexFormat.java rename to client/src/main/java/client/renderer/VertexFormat.java index 42be6f3..0ab4281 100755 --- a/java/src/game/renderer/VertexFormat.java +++ b/client/src/main/java/client/renderer/VertexFormat.java @@ -1,10 +1,9 @@ -package game.renderer; +package client.renderer; import java.util.List; -import game.collect.Lists; - -import game.log.Log; +import common.collect.Lists; +import common.log.Log; public class VertexFormat { @@ -52,9 +51,9 @@ public class VertexFormat public VertexFormat addElement(VertexFormatElement element) { - if (element.isPositionElement() && this.hasPosition()) + if (element.isPosition() && this.hasPosition()) { - Log.JNI.warn("VertexFormat-Fehler: Versuche eine Position vom Typ VertexFormatElement hinzuzufügen, während eine bereits existiert, ignoriere."); + Log.RENDER.warn("VertexFormat-Fehler: Versuche eine Position vom Typ VertexFormatElement hinzuzufügen, während eine bereits existiert, ignoriere."); return this; } else @@ -62,7 +61,7 @@ public class VertexFormat this.elements.add(element); this.offsets.add(Integer.valueOf(this.nextOffset)); - switch (element.getUsage()) + switch (element.usage()) { case NORMAL: this.normalElementOffset = this.nextOffset; @@ -73,10 +72,10 @@ public class VertexFormat break; case UV: - this.uvOffsetsById.add(element.getIndex(), Integer.valueOf(this.nextOffset)); + this.uvOffsetsById.add(element.index(), Integer.valueOf(this.nextOffset)); } - this.nextOffset += element.getSize(); + this.nextOffset += element.size(); return this; } } @@ -136,7 +135,7 @@ public class VertexFormat { VertexFormatElement vertexformatelement = (VertexFormatElement)this.elements.get(i); - if (vertexformatelement.isPositionElement()) + if (vertexformatelement.isPosition()) { return true; } diff --git a/client/src/main/java/client/renderer/VertexFormatElement.java b/client/src/main/java/client/renderer/VertexFormatElement.java new file mode 100755 index 0000000..9062f91 --- /dev/null +++ b/client/src/main/java/client/renderer/VertexFormatElement.java @@ -0,0 +1,84 @@ +package client.renderer; + +import org.lwjgl.opengl.GL11; + +public record VertexFormatElement(int index, VertexFormatElement.EnumType type, VertexFormatElement.EnumUsage usage, int count) { + public String toString() { + return this.count + "," + this.usage.getName() + "," + this.type.getName(); + } + + public int size() { + return this.type.getSize() * this.count; + } + + public boolean isPosition() { + return this.usage == VertexFormatElement.EnumUsage.POSITION; + } + + public boolean equals(Object other) { + if(this == other) + return true; + if(!(other instanceof VertexFormatElement)) + return false; + VertexFormatElement elem = (VertexFormatElement)other; + return this.count == elem.count && this.index == elem.index && this.type == elem.type && this.usage == elem.usage; + } + + public int hashCode() { + int i = this.type.hashCode(); + i = 31 * i + this.usage.hashCode(); + i = 31 * i + this.index; + i = 31 * i + this.count; + return i; + } + + public static enum EnumType { + FLOAT(4, "Float", GL11.GL_FLOAT), + UBYTE(1, "Unsigned Byte", GL11.GL_UNSIGNED_BYTE), + BYTE(1, "Byte", GL11.GL_BYTE), + USHORT(2, "Unsigned Short", GL11.GL_UNSIGNED_SHORT), + SHORT(2, "Short", GL11.GL_SHORT), + UINT(4, "Unsigned Int", GL11.GL_UNSIGNED_INT), + INT(4, "Int", GL11.GL_INT); + + private final int size; + private final String name; + private final int glConstant; + + private EnumType(int size, String name, int glConstant) { + this.size = size; + this.name = name; + this.glConstant = glConstant; + } + + public int getSize() { + return this.size; + } + + public String getName() { + return this.name; + } + + public int getGlConstant() { + return this.glConstant; + } + } + + public static enum EnumUsage { + POSITION("Position"), + NORMAL("Normal"), + COLOR("Vertex Color"), + UV("UV"), + PADDING("Padding"); + + private final String name; + + private EnumUsage(String name) { + this.name = name; + } + + public String getName() { + return this.name; + } + } +} diff --git a/java/src/game/renderer/ViewFrustum.java b/client/src/main/java/client/renderer/ViewFrustum.java similarity index 83% rename from java/src/game/renderer/ViewFrustum.java rename to client/src/main/java/client/renderer/ViewFrustum.java index c0d460a..ede3e1c 100755 --- a/java/src/game/renderer/ViewFrustum.java +++ b/client/src/main/java/client/renderer/ViewFrustum.java @@ -1,14 +1,14 @@ -package game.renderer; +package client.renderer; -import game.renderer.chunk.RenderChunk; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.World; +import client.renderer.chunk.RenderChunk; +import client.world.WorldClient; +import common.util.BlockPos; +import common.util.ExtMath; public class ViewFrustum { protected final RenderGlobal renderGlobal; - protected final World world; + protected final WorldClient world; protected int countChunksY; protected int countChunksX; protected int countChunksZ; @@ -18,7 +18,7 @@ public class ViewFrustum return i < 0 ? -((-i - 1) / 16) - 1 : i / 16; } - public ViewFrustum(World worldIn, int renderDistanceChunks, RenderGlobal p_i46246_3_) + public ViewFrustum(WorldClient worldIn, int renderDistanceChunks, RenderGlobal p_i46246_3_) { this.renderGlobal = p_i46246_3_; this.world = worldIn; @@ -58,13 +58,14 @@ public class ViewFrustum { int i = renderDistanceChunks * 2 + 1; this.countChunksX = i; - this.countChunksY = 32; + this.countChunksY = i; this.countChunksZ = i; } - public void updateChunkPositions(double viewEntityX, double viewEntityZ) + public void updateChunkPositions(double viewEntityX, double viewEntityY, double viewEntityZ) { int i = ExtMath.floord(viewEntityX) - 8; + int n = ExtMath.floord(viewEntityY) - 8; int j = ExtMath.floord(viewEntityZ) - 8; int k = this.countChunksX * 16; @@ -78,7 +79,7 @@ public class ViewFrustum for (int l1 = 0; l1 < this.countChunksY; ++l1) { - int i2 = l1 * 16; + int i2 = this.func_178157_a(n, k, l1); RenderChunk renderchunk = this.renderChunks[(j1 * this.countChunksY + l1) * this.countChunksX + l]; BlockPos blockpos = new BlockPos(i1, i2, k1); @@ -154,28 +155,28 @@ public class ViewFrustum int y = bucketInt(pos.getY()); int z = bucketInt(pos.getZ()); - if (y >= 0 && y < this.countChunksY) + x = x % this.countChunksX; + + if (x < 0) { - x = x % this.countChunksX; - - if (x < 0) - { - x += this.countChunksX; - } - - z = z % this.countChunksZ; - - if (z < 0) - { - z += this.countChunksZ; - } - - int p = (z * this.countChunksY + y) * this.countChunksX + x; - return this.renderChunks[p]; + x += this.countChunksX; } - else + + y = y % this.countChunksY; + + if (y < 0) { - return null; + y += this.countChunksY; } + + z = z % this.countChunksZ; + + if (z < 0) + { + z += this.countChunksZ; + } + + int p = (z * this.countChunksY + y) * this.countChunksX + x; + return this.renderChunks[p]; } } diff --git a/client/src/main/java/client/renderer/blockmodel/BakedModel.java b/client/src/main/java/client/renderer/blockmodel/BakedModel.java new file mode 100755 index 0000000..c0ccd78 --- /dev/null +++ b/client/src/main/java/client/renderer/blockmodel/BakedModel.java @@ -0,0 +1,87 @@ +package client.renderer.blockmodel; + +import java.util.ArrayList; +import java.util.List; + +import client.renderer.texture.TextureAtlasSprite; +import common.collect.Lists; +import common.model.Transforms; +import common.util.Facing; + +public record BakedModel(List getQuads, List> getFace, boolean isGui3d, TextureAtlasSprite getBaseTexture, Transforms getTransforms) implements IBakedModel { + public List getFace(Facing face) { + return this.getFace.get(face.ordinal()); + } + + public boolean isBuiltin() { + return false; + } + + public static class Builder { + private final List quads; + private final List> faces; + private TextureAtlasSprite texture; + private boolean gui3d; + private Transforms transforms; + + public Builder(ModelBlock model) { + this(model.isGui3d(), model.getTransform()); + } + + public Builder(IBakedModel model, TextureAtlasSprite texture) { + this(model.isGui3d(), model.getTransforms()); + this.texture = model.getBaseTexture(); + + for(Facing face : Facing.values()) { + this.addFaceBreakingFours(model, texture, face); + } + + this.addGeneralBreakingFours(model, texture); + } + + private void addFaceBreakingFours(IBakedModel model, TextureAtlasSprite texture, Facing facing) { + for(BakedQuad quad : model.getFace(facing)) { + this.addFaceQuad(facing, new BreakingFour(quad, texture)); + } + } + + private void addGeneralBreakingFours(IBakedModel model, TextureAtlasSprite texture) { + for(BakedQuad quad : model.getQuads()) { + this.addGeneralQuad(new BreakingFour(quad, texture)); + } + } + + private Builder(boolean gui3d, Transforms transforms) { + this.quads = Lists.newArrayList(); + this.faces = new ArrayList>(6); + + for(Facing face : Facing.values()) { + this.faces.add(Lists.newArrayList()); + } + + this.gui3d = gui3d; + this.transforms = transforms; + } + + public BakedModel.Builder addFaceQuad(Facing face, BakedQuad quad) { + this.faces.get(face.ordinal()).add(quad); + return this; + } + + public BakedModel.Builder addGeneralQuad(BakedQuad quad) { + this.quads.add(quad); + return this; + } + + public BakedModel.Builder setTexture(TextureAtlasSprite texture) { + this.texture = texture; + return this; + } + + public BakedModel makeBakedModel() { + if(this.texture == null) + throw new RuntimeException("Fehlende Basistextur"); + return new BakedModel(this.quads, this.faces, this.gui3d, this.texture, this.transforms); + } + } +} diff --git a/java/src/game/renderer/blockmodel/BakedQuad.java b/client/src/main/java/client/renderer/blockmodel/BakedQuad.java similarity index 87% rename from java/src/game/renderer/blockmodel/BakedQuad.java rename to client/src/main/java/client/renderer/blockmodel/BakedQuad.java index 8fe6886..e50b3d0 100755 --- a/java/src/game/renderer/blockmodel/BakedQuad.java +++ b/client/src/main/java/client/renderer/blockmodel/BakedQuad.java @@ -1,6 +1,6 @@ -package game.renderer.blockmodel; +package client.renderer.blockmodel; -import game.world.Facing; +import common.util.Facing; public class BakedQuad { protected final int[] data; diff --git a/java/src/game/renderer/blockmodel/BlockFaceUV.java b/client/src/main/java/client/renderer/blockmodel/BlockFaceUV.java similarity index 94% rename from java/src/game/renderer/blockmodel/BlockFaceUV.java rename to client/src/main/java/client/renderer/blockmodel/BlockFaceUV.java index 4eef325..6dfb737 100755 --- a/java/src/game/renderer/blockmodel/BlockFaceUV.java +++ b/client/src/main/java/client/renderer/blockmodel/BlockFaceUV.java @@ -1,4 +1,4 @@ -package game.renderer.blockmodel; +package client.renderer.blockmodel; public class BlockFaceUV { public float[] uvs; diff --git a/java/src/game/renderer/blockmodel/BlockPart.java b/client/src/main/java/client/renderer/blockmodel/BlockPart.java similarity index 91% rename from java/src/game/renderer/blockmodel/BlockPart.java rename to client/src/main/java/client/renderer/blockmodel/BlockPart.java index 92fa935..830f491 100755 --- a/java/src/game/renderer/blockmodel/BlockPart.java +++ b/client/src/main/java/client/renderer/blockmodel/BlockPart.java @@ -1,9 +1,9 @@ -package game.renderer.blockmodel; +package client.renderer.blockmodel; import java.util.Map; -import game.renderer.Vector3f; -import game.world.Facing; +import common.util.Facing; +import common.util.Vector3f; public class BlockPart { @@ -22,7 +22,7 @@ public class BlockPart this.shade = shadeIn; } - protected float[] getFaceUvs(Facing face) + public float[] getFaceUvs(Facing face) { float[] afloat; diff --git a/java/src/game/renderer/blockmodel/BlockPartFace.java b/client/src/main/java/client/renderer/blockmodel/BlockPartFace.java similarity index 76% rename from java/src/game/renderer/blockmodel/BlockPartFace.java rename to client/src/main/java/client/renderer/blockmodel/BlockPartFace.java index 67dbc8d..03791d7 100755 --- a/java/src/game/renderer/blockmodel/BlockPartFace.java +++ b/client/src/main/java/client/renderer/blockmodel/BlockPartFace.java @@ -1,7 +1,7 @@ -package game.renderer.blockmodel; +package client.renderer.blockmodel; -import game.renderer.texture.TextureMap; -import game.world.Facing; +import client.renderer.texture.TextureMap; +import common.util.Facing; public class BlockPartFace { public Facing cull; diff --git a/java/src/game/renderer/blockmodel/BlockPartRotation.java b/client/src/main/java/client/renderer/blockmodel/BlockPartRotation.java similarity index 81% rename from java/src/game/renderer/blockmodel/BlockPartRotation.java rename to client/src/main/java/client/renderer/blockmodel/BlockPartRotation.java index ccf026e..7bde7ed 100755 --- a/java/src/game/renderer/blockmodel/BlockPartRotation.java +++ b/client/src/main/java/client/renderer/blockmodel/BlockPartRotation.java @@ -1,7 +1,7 @@ -package game.renderer.blockmodel; +package client.renderer.blockmodel; -import game.renderer.Vector3f; -import game.world.Facing; +import common.util.Facing; +import common.util.Vector3f; public class BlockPartRotation { public final Vector3f origin; diff --git a/java/src/game/renderer/blockmodel/BreakingFour.java b/client/src/main/java/client/renderer/blockmodel/BreakingFour.java similarity index 95% rename from java/src/game/renderer/blockmodel/BreakingFour.java rename to client/src/main/java/client/renderer/blockmodel/BreakingFour.java index 976d9e2..ec2cbc9 100755 --- a/java/src/game/renderer/blockmodel/BreakingFour.java +++ b/client/src/main/java/client/renderer/blockmodel/BreakingFour.java @@ -1,8 +1,8 @@ -package game.renderer.blockmodel; +package client.renderer.blockmodel; import java.util.Arrays; -import game.renderer.texture.TextureAtlasSprite; +import client.renderer.texture.TextureAtlasSprite; public class BreakingFour extends BakedQuad { diff --git a/client/src/main/java/client/renderer/blockmodel/BuiltInModel.java b/client/src/main/java/client/renderer/blockmodel/BuiltInModel.java new file mode 100755 index 0000000..fd40a16 --- /dev/null +++ b/client/src/main/java/client/renderer/blockmodel/BuiltInModel.java @@ -0,0 +1,29 @@ +package client.renderer.blockmodel; + +import java.util.List; + +import client.renderer.texture.TextureAtlasSprite; +import common.model.Transforms; +import common.util.Facing; + +public record BuiltInModel(Transforms getTransforms) implements IBakedModel { + public List getFace(Facing face) { + return null; + } + + public List getQuads() { + return null; + } + + public boolean isGui3d() { + return true; + } + + public boolean isBuiltin() { + return true; + } + + public TextureAtlasSprite getBaseTexture() { + return null; + } +} diff --git a/java/src/game/renderer/blockmodel/FaceBakery.java b/client/src/main/java/client/renderer/blockmodel/FaceBakery.java similarity index 98% rename from java/src/game/renderer/blockmodel/FaceBakery.java rename to client/src/main/java/client/renderer/blockmodel/FaceBakery.java index 878669e..cb73b49 100755 --- a/java/src/game/renderer/blockmodel/FaceBakery.java +++ b/client/src/main/java/client/renderer/blockmodel/FaceBakery.java @@ -1,13 +1,13 @@ -package game.renderer.blockmodel; +package client.renderer.blockmodel; -import game.model.ModelRotation; -import game.renderer.Matrix4f; -import game.renderer.Vector3f; -import game.renderer.Vector4f; -import game.renderer.texture.TextureAtlasSprite; -import game.util.ExtMath; -import game.world.Facing; -import game.world.Vec3i; +import client.renderer.texture.TextureAtlasSprite; +import common.model.ModelRotation; +import common.util.ExtMath; +import common.util.Facing; +import common.util.Matrix4f; +import common.util.Vec3i; +import common.util.Vector3f; +import common.util.Vector4f; public class FaceBakery { diff --git a/client/src/main/java/client/renderer/blockmodel/IBakedModel.java b/client/src/main/java/client/renderer/blockmodel/IBakedModel.java new file mode 100755 index 0000000..d1de616 --- /dev/null +++ b/client/src/main/java/client/renderer/blockmodel/IBakedModel.java @@ -0,0 +1,22 @@ +package client.renderer.blockmodel; + +import java.util.List; + +import client.renderer.texture.TextureAtlasSprite; +import common.model.Transforms; +import common.util.Facing; + +public interface IBakedModel +{ + List getFace(Facing facing); + + List getQuads(); + + boolean isGui3d(); + + boolean isBuiltin(); + + TextureAtlasSprite getBaseTexture(); + + Transforms getTransforms(); +} diff --git a/java/src/game/model/ModelBakery.java b/client/src/main/java/client/renderer/blockmodel/ModelBakery.java similarity index 88% rename from java/src/game/model/ModelBakery.java rename to client/src/main/java/client/renderer/blockmodel/ModelBakery.java index 4c80d7a..3bd370d 100755 --- a/java/src/game/model/ModelBakery.java +++ b/client/src/main/java/client/renderer/blockmodel/ModelBakery.java @@ -1,4 +1,4 @@ -package game.model; +package client.renderer.blockmodel; import java.util.Collections; import java.util.Comparator; @@ -7,27 +7,22 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import game.collect.Lists; -import game.collect.Maps; -import game.collect.Sets; - -import game.init.BlockRegistry; -import game.init.FluidRegistry; -import game.init.IRegistry; -import game.init.ItemRegistry; -import game.init.RegistrySimple; -import game.item.Item; -import game.item.ItemStack; -import game.renderer.blockmodel.BlockPart; -import game.renderer.blockmodel.BlockPartFace; -import game.renderer.blockmodel.FaceBakery; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.ModelGenerator; -import game.renderer.texture.IIconCreator; -import game.renderer.texture.TextureAtlasSprite; -import game.renderer.texture.TextureMap; -import game.world.Facing; -import game.world.State; +import client.renderer.texture.IIconCreator; +import client.renderer.texture.TextureAtlasSprite; +import client.renderer.texture.TextureMap; +import common.collect.Lists; +import common.collect.Maps; +import common.collect.Sets; +import common.init.BlockRegistry; +import common.init.FluidRegistry; +import common.init.ItemRegistry; +import common.item.Item; +import common.item.ItemStack; +import common.model.ModelRotation; +import common.util.Facing; +import common.util.IRegistry; +import common.util.RegistrySimple; +import common.world.State; public abstract class ModelBakery { @@ -42,12 +37,12 @@ public abstract class ModelBakery "items/empty_armor_slot_helmet", "items/empty_armor_slot_chestplate", "items/empty_armor_slot_leggings", "items/empty_armor_slot_boots"); protected static final String MISSING = "builtin/missing" + '#' + "missing"; - public static final ModelBlock MODEL_GENERATED = new ModelBlock(null).add().d(""); - public static final ModelBlock MODEL_ENTITY = new ModelBlock(null).add().d(""); + public static final ModelBlock MODEL_GENERATED = (ModelBlock)new ModelBlock(null).add().d(""); + public static final ModelBlock MODEL_ENTITY = (ModelBlock)new ModelBlock(null).add().d(""); static { for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { - String name = BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)).toString(); + String name = BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)).toString(); LOCATIONS_BUILTIN_TEXTURES.add("blocks/" + name + "_flow"); LOCATIONS_BUILTIN_TEXTURES.add("blocks/" + name + "_still"); } @@ -65,11 +60,11 @@ public abstract class ModelBakery // Map> variantNames = Maps.>newIdentityHashMap(); // variants.clear(); // Map map = blockModelShapes.getMap(); - models.put(MISSING, new ModelBlock(null).add().all()); + models.put(MISSING, (ModelBlock)new ModelBlock(null).add().all()); variants.add(MISSING); for(Entry entry : map.entrySet()) { - ModelBlock model = entry.getKey().getBlock().getModel(BlockRegistry.REGISTRY.getNameForObject(entry.getKey().getBlock()) - .toString(), entry.getKey()); + ModelBlock model = (ModelBlock)entry.getKey().getBlock().getModel(ModelBlock.PROVIDER, BlockRegistry.getNameFromBlock(entry.getKey().getBlock()) + .toString(), entry.getKey()); // ResourceLocation blk = new ResourceLocation(entry.getValue().getName()); models.put(entry.getValue(), model); variants.add(entry.getValue()); @@ -149,8 +144,8 @@ public abstract class ModelBakery // { item.getRenderItems(item, stacks); for(ItemStack stack : stacks) { - String resourcelocation = "item/" + ItemRegistry.REGISTRY.getNameForObject(item).toString() + "#" + stack.getMetadata() + '#' + "inventory"; - models.put(resourcelocation, item.getModel(ItemRegistry.REGISTRY.getNameForObject(item).toString(), stack.getMetadata())); + String resourcelocation = "item/" + ItemRegistry.getNameFromItem(item).toString() + "#" + stack.getMetadata() + '#' + "inventory"; + models.put(resourcelocation, (ModelBlock)item.getModel(ModelBlock.PROVIDER, ItemRegistry.getNameFromItem(item).toString(), stack.getMetadata())); itemLocations.add(resourcelocation); } stacks.clear(); diff --git a/client/src/main/java/client/renderer/blockmodel/ModelBlock.java b/client/src/main/java/client/renderer/blockmodel/ModelBlock.java new file mode 100755 index 0000000..351704d --- /dev/null +++ b/client/src/main/java/client/renderer/blockmodel/ModelBlock.java @@ -0,0 +1,192 @@ +package client.renderer.blockmodel; + +import java.util.List; + +import client.renderer.texture.TextureMap; +import common.collect.Lists; +import common.collect.Maps; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.Transforms; +import common.util.Facing; +import common.util.Vector3f; + +public class ModelBlock extends Model { + static final ModelProvider PROVIDER = new ModelProvider() { + public Model getModel(String primary) { + return new ModelBlock(primary); + } + + public Model getModel(Transforms transform, String... layers) { + return new ModelBlock(transform, layers); + } + + public Model getModel(Model parent, Transforms transform) { + return new ModelBlock((ModelBlock)parent, transform); + } + + public Model getEntityModel() { + return ModelBakery.MODEL_ENTITY; + } + }; + + private final List elements; + private final boolean gui3d; + private final String primary; + private final String[] layers; + private final ModelBlock parent; + + private ModelRotation rotation; + private boolean uvLock; + private Transforms transform; + + private BlockPart lastPart; + private BlockPartFace[] last; + + public static void setAsProvider() { + ModelProvider.setProvider(PROVIDER); + } + + public ModelBlock uvLock() { + this.uvLock = true; + return this; + } + + public ModelBlock rotate(ModelRotation rot) { + this.rotation = rot; + return this; + } + + public ModelBlock add(float x1, float y1, float z1, float x2, float y2, float z2) { + this.elements.add(this.lastPart = new BlockPart(new Vector3f(x1, y1, z1), new Vector3f(x2, y2, z2), + Maps.newEnumMap(Facing.class), null, true)); + return this; + } + + public ModelBlock noShade() { + this.lastPart.shade = false; + return this; + } + + public ModelBlock rotate(float x, float y, float z, Facing.Axis axisIn, float angleIn, boolean rescaleIn) { + this.lastPart.partRotation = new BlockPartRotation(x, y, z, axisIn, angleIn, rescaleIn); + return this; + } + + public ModelBlock face(String texture, Facing ... faces) { + texture = !texture.equals(TextureMap.LOCATION_MISSING_TEXTURE) && texture.indexOf('/') == -1 ? "blocks/" + texture : texture; + this.last = new BlockPartFace[faces.length]; + for(int z = 0; z < faces.length; z++) { + this.lastPart.mapFaces.put(faces[z], this.last[z] = + new BlockPartFace(faces[z], -1, texture, new BlockFaceUV(this.lastPart.getFaceUvs(faces[z]), 0))); + } + return this; + } + + public ModelBlock cull(Facing cull) { + for(BlockPartFace last : this.last) { + last.cull = cull; + } + return this; + } + + public ModelBlock tint() { + for(BlockPartFace last : this.last) { + last.tint = 0; + } + return this; + } + + public ModelBlock rot(int rot) { + for(BlockPartFace last : this.last) { + last.uv = new BlockFaceUV(last.uv.uvs, rot); + } + return this; + } + + public ModelBlock uv(float x1, float y1, float x2, float y2) { + for(BlockPartFace last : this.last) { + last.uv = new BlockFaceUV(new float[] {x1, y1, x2, y2}, last.uv.rotation); + } + return this; + } + + public String getPrimary() { + return this.primary; + } + + + public ModelBlock(String primary) { + this(null, Lists.newArrayList(), primary != null && primary.indexOf('/') == -1 ? "blocks/" + primary : primary, true, true, Transforms.DEFAULT, null); + } + + public ModelBlock(Transforms transform, String ... layers) { + this(ModelBakery.MODEL_GENERATED, ModelBakery.MODEL_GENERATED.elements, + layers[0].indexOf('/') == -1 ? "items/" + layers[0] : layers[0], false, false, transform, layers); + } + + public ModelBlock(ModelBlock parent, Transforms transform) { + this(parent, Lists.newArrayList(), parent.getPrimary(), false, true, transform, null); + } + + public ModelBlock(String primary, Transforms transform, String ... layers) { + this(ModelBakery.MODEL_GENERATED, ModelBakery.MODEL_GENERATED.elements, + primary.indexOf('/') == -1 ? "items/" + primary : primary, false, false, transform, layers); + } + + public ModelBlock(String primary, List elements, Transforms transform, String ... layers) { + this(null, elements, primary, false, false, transform, layers); + } + + private ModelBlock(ModelBlock parent, List elements, String primary, boolean occlude, boolean gui3d, + Transforms transform, String[] layers) { + for(int z = 0; layers != null && z < layers.length; z++) { + layers[z] = layers[z].indexOf('/') == -1 ? "items/" + layers[z] : layers[z]; + } + this.elements = parent == null ? elements : parent.getElements(); + this.gui3d = gui3d; + this.primary = primary == null ? TextureMap.LOCATION_MISSING_TEXTURE : primary; + this.parent = parent; + this.transform = transform; + this.uvLock = false; + this.rotation = ModelRotation.X0_Y0; + this.layers = layers; + } + + public List getElements() { + return this.elements; + } + + public boolean isGui3d() { + return this.gui3d; + } + + public String[] getTextures() { + return this.layers; + } + + public int getNumTextures() { + return this.layers == null ? 0 : this.layers.length; + } + + public String getTexture(int layer) { + return this.layers == null || this.layers[layer] == null ? TextureMap.LOCATION_MISSING_TEXTURE : this.layers[layer]; + } + + public ModelBlock getParent() { + return this.parent; + } + + public Transforms getTransform() { + return this.transform; + } + + public ModelRotation getRotation() { + return this.rotation; + } + + public boolean isUvLocked() { + return this.uvLock; + } +} diff --git a/java/src/game/renderer/blockmodel/ModelGenerator.java b/client/src/main/java/client/renderer/blockmodel/ModelGenerator.java similarity index 93% rename from java/src/game/renderer/blockmodel/ModelGenerator.java rename to client/src/main/java/client/renderer/blockmodel/ModelGenerator.java index 818db2a..b487010 100755 --- a/java/src/game/renderer/blockmodel/ModelGenerator.java +++ b/client/src/main/java/client/renderer/blockmodel/ModelGenerator.java @@ -1,19 +1,18 @@ -package game.renderer.blockmodel; +package client.renderer.blockmodel; import java.io.FileNotFoundException; import java.util.List; import java.util.Map; -import game.collect.Lists; -import game.collect.Maps; - -import game.log.Log; -import game.renderer.Vector3f; -import game.renderer.model.ModelBox; -import game.renderer.texture.TextureAtlasSprite; -import game.renderer.texture.TextureMap; -import game.renderer.texture.TextureUtil; -import game.world.Facing; +import client.renderer.model.ModelBox; +import client.renderer.texture.TextureAtlasSprite; +import client.renderer.texture.TextureMap; +import client.renderer.texture.TextureUtil; +import common.collect.Lists; +import common.collect.Maps; +import common.log.Log; +import common.util.Facing; +import common.util.Vector3f; public abstract class ModelGenerator { // public static final List LAYERS = Lists.newArrayList("layer0", "layer1", "layer2", "layer3", "layer4"); @@ -27,13 +26,13 @@ public abstract class ModelGenerator { } catch(Throwable e) { if(e instanceof FileNotFoundException) - Log.JNI.warn("Textur ist nicht zum Zusammenstellen vorhanden: " + textureLocation); + Log.IO.warn("Textur ist nicht zum Zusammenstellen vorhanden: " + textureLocation); else - Log.JNI.error(e, "Konnte Textur '" + textureLocation + "' nicht zum Zusammenstellen laden"); + Log.IO.error(e, "Konnte Textur '" + textureLocation + "' nicht zum Zusammenstellen laden"); return Lists.newArrayList(); } if(img.length < tw * th) { - Log.JNI.warn("Konnte Textur '" + textureLocation.toString() + "' nicht zum Zusammenstellen laden weil sie zu klein ist " + + Log.IO.warn("Konnte Textur '" + textureLocation.toString() + "' nicht zum Zusammenstellen laden weil sie zu klein ist " + "(benötige " + (tw*th) + " [" + tw + "x" + th + "], habe " + img.length + ")"); return Lists.newArrayList(); } diff --git a/java/src/game/model/ModelManager.java b/client/src/main/java/client/renderer/blockmodel/ModelManager.java similarity index 82% rename from java/src/game/model/ModelManager.java rename to client/src/main/java/client/renderer/blockmodel/ModelManager.java index 41e86b5..55a9399 100755 --- a/java/src/game/model/ModelManager.java +++ b/client/src/main/java/client/renderer/blockmodel/ModelManager.java @@ -1,25 +1,21 @@ -package game.model; +package client.renderer.blockmodel; import java.util.Collections; import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import game.collect.Maps; - -import game.block.Block; -import game.block.BlockLiquid; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.FluidRegistry; -import game.init.IRegistry; -import game.properties.IProperty; -import game.renderer.blockmodel.MultiStateMap; -import game.renderer.blockmodel.SingleStateMap; -import game.renderer.blockmodel.StateMap; -import game.renderer.texture.TextureAtlasSprite; -import game.renderer.texture.TextureMap; -import game.world.State; +import client.renderer.texture.TextureAtlasSprite; +import client.renderer.texture.TextureMap; +import common.block.Block; +import common.block.liquid.BlockLiquid; +import common.collect.Maps; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.FluidRegistry; +import common.properties.IProperty; +import common.util.IRegistry; +import common.world.State; public class ModelManager { @@ -37,7 +33,7 @@ public class ModelManager for(Block block : BlockRegistry.REGISTRY) { if(block.getRenderType() != 3) { this.builtin.add(block); - // Log.info("Builtin: " + BlockRegistry.REGISTRY.getNameForObject(block)); + // Log.info("Builtin: " + BlockRegistry.getNameFromBlock(block)); } else { IProperty[] ignored = block.getIgnoredProperties(); @@ -104,11 +100,6 @@ public class ModelManager return this.texMap.getAtlasSprite("blocks/water_still"); } - if (block == Blocks.skull) - { - return this.texMap.getAtlasSprite("blocks/soul_sand"); - } - // if (block == Blocks.barrier) // { // return this.modelManager.getTextureMap().getAtlasSprite("items/barrier"); @@ -118,7 +109,7 @@ public class ModelManager { String texture = this.liquidMap.get(block); if(texture == null) - this.liquidMap.put(block, texture = "blocks/" + BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(FluidRegistry.getFluidMeta((BlockLiquid)block))) + "_still"); + this.liquidMap.put(block, texture = "blocks/" + BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(FluidRegistry.getFluidMeta((BlockLiquid)block))) + "_still"); return this.texMap.getAtlasSprite(texture); } } @@ -128,7 +119,7 @@ public class ModelManager ibakedmodel = this.defaultModel; } - return ibakedmodel.getParticleTexture(); + return ibakedmodel.getBaseTexture(); } public IBakedModel getModelForState(State state) diff --git a/java/src/game/renderer/blockmodel/MultiStateMap.java b/client/src/main/java/client/renderer/blockmodel/MultiStateMap.java similarity index 88% rename from java/src/game/renderer/blockmodel/MultiStateMap.java rename to client/src/main/java/client/renderer/blockmodel/MultiStateMap.java index 17996e3..496e619 100755 --- a/java/src/game/renderer/blockmodel/MultiStateMap.java +++ b/client/src/main/java/client/renderer/blockmodel/MultiStateMap.java @@ -1,15 +1,14 @@ -package game.renderer.blockmodel; +package client.renderer.blockmodel; import java.util.Collections; import java.util.List; import java.util.Map; -import game.collect.Lists; -import game.collect.Maps; - -import game.init.BlockRegistry; -import game.properties.IProperty; -import game.world.State; +import common.collect.Lists; +import common.collect.Maps; +import common.init.BlockRegistry; +import common.properties.IProperty; +import common.world.State; public class MultiStateMap extends StateMap { @@ -31,7 +30,7 @@ public class MultiStateMap extends StateMap if (this.name == null) { - s = BlockRegistry.REGISTRY.getNameForObject(state.getBlock()); + s = BlockRegistry.getNameFromBlock(state.getBlock()); } else { diff --git a/client/src/main/java/client/renderer/blockmodel/SingleStateMap.java b/client/src/main/java/client/renderer/blockmodel/SingleStateMap.java new file mode 100755 index 0000000..73100e9 --- /dev/null +++ b/client/src/main/java/client/renderer/blockmodel/SingleStateMap.java @@ -0,0 +1,13 @@ +package client.renderer.blockmodel; + +import common.init.BlockRegistry; +import common.world.State; + + +public class SingleStateMap extends StateMap +{ + protected String getResourceLocation(State state) + { + return BlockRegistry.getNameFromBlock(state.getBlock()).toString() + '#' + this.getPropertyString(state.getProperties()); + } +} diff --git a/java/src/game/renderer/blockmodel/StateMap.java b/client/src/main/java/client/renderer/blockmodel/StateMap.java similarity index 89% rename from java/src/game/renderer/blockmodel/StateMap.java rename to client/src/main/java/client/renderer/blockmodel/StateMap.java index caf1a7a..d85f8a1 100755 --- a/java/src/game/renderer/blockmodel/StateMap.java +++ b/client/src/main/java/client/renderer/blockmodel/StateMap.java @@ -1,13 +1,12 @@ -package game.renderer.blockmodel; +package client.renderer.blockmodel; import java.util.Map; import java.util.Map.Entry; -import game.collect.Maps; - -import game.block.Block; -import game.properties.IProperty; -import game.world.State; +import common.block.Block; +import common.collect.Maps; +import common.properties.IProperty; +import common.world.State; public abstract class StateMap { diff --git a/java/src/game/renderer/chunk/ChunkCompileTaskGenerator.java b/client/src/main/java/client/renderer/chunk/ChunkCompileTaskGenerator.java similarity index 96% rename from java/src/game/renderer/chunk/ChunkCompileTaskGenerator.java rename to client/src/main/java/client/renderer/chunk/ChunkCompileTaskGenerator.java index f1014f3..d8244ea 100755 --- a/java/src/game/renderer/chunk/ChunkCompileTaskGenerator.java +++ b/client/src/main/java/client/renderer/chunk/ChunkCompileTaskGenerator.java @@ -1,11 +1,10 @@ -package game.renderer.chunk; +package client.renderer.chunk; import java.util.List; import java.util.concurrent.locks.ReentrantLock; -import game.collect.Lists; - -import game.renderer.RegionRenderCacheBuilder; +import client.renderer.RegionRenderCacheBuilder; +import common.collect.Lists; public class ChunkCompileTaskGenerator { diff --git a/java/src/game/renderer/chunk/ChunkRenderDispatcher.java b/client/src/main/java/client/renderer/chunk/ChunkRenderDispatcher.java similarity index 94% rename from java/src/game/renderer/chunk/ChunkRenderDispatcher.java rename to client/src/main/java/client/renderer/chunk/ChunkRenderDispatcher.java index ff897c0..735cadb 100755 --- a/java/src/game/renderer/chunk/ChunkRenderDispatcher.java +++ b/client/src/main/java/client/renderer/chunk/ChunkRenderDispatcher.java @@ -1,4 +1,4 @@ -package game.renderer.chunk; +package client.renderer.chunk; import java.util.ArrayDeque; import java.util.List; @@ -7,17 +7,16 @@ import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ThreadFactory; -import game.collect.Lists; -import game.future.Futures; -import game.future.ListenableFuture; -import game.future.ListenableFutureTask; -import game.future.ThreadFactoryBuilder; - -import game.Game; -import game.renderer.BlockLayer; -import game.renderer.RegionRenderCacheBuilder; -import game.renderer.RenderBuffer; -import game.renderer.VertexBuffer; +import client.Client; +import client.renderer.RegionRenderCacheBuilder; +import client.renderer.RenderBuffer; +import client.renderer.VertexBuffer; +import common.collect.Lists; +import common.future.Futures; +import common.future.ListenableFuture; +import common.future.ListenableFutureTask; +import common.future.ThreadFactoryBuilder; +import common.model.BlockLayer; public class ChunkRenderDispatcher { @@ -228,7 +227,7 @@ public class ChunkRenderDispatcher public ListenableFuture uploadChunk(final BlockLayer player, final RenderBuffer p_178503_2_, final RenderChunk chunkRenderer, final CompiledChunk compiledChunkIn) { - if (Game.getGame().isMainThread()) + if (Client.CLIENT.isMainThread()) { p_178503_2_.reset(); chunkRenderer.getVertexBufferByLayer(player.ordinal()).bufferData(p_178503_2_.getByteBuffer()); diff --git a/java/src/game/renderer/chunk/ChunkRenderWorker.java b/client/src/main/java/client/renderer/chunk/ChunkRenderWorker.java similarity index 87% rename from java/src/game/renderer/chunk/ChunkRenderWorker.java rename to client/src/main/java/client/renderer/chunk/ChunkRenderWorker.java index fecc36a..0fe9a2b 100755 --- a/java/src/game/renderer/chunk/ChunkRenderWorker.java +++ b/client/src/main/java/client/renderer/chunk/ChunkRenderWorker.java @@ -1,19 +1,18 @@ -package game.renderer.chunk; +package client.renderer.chunk; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CancellationException; -import game.collect.Lists; -import game.future.FutureCallback; -import game.future.Futures; -import game.future.ListenableFuture; - -import game.Game; -import game.entity.Entity; -import game.log.Log; -import game.renderer.BlockLayer; -import game.renderer.RegionRenderCacheBuilder; +import client.Client; +import client.renderer.RegionRenderCacheBuilder; +import common.collect.Lists; +import common.entity.Entity; +import common.future.FutureCallback; +import common.future.Futures; +import common.future.ListenableFuture; +import common.log.Log; +import common.model.BlockLayer; public class ChunkRenderWorker implements Runnable { @@ -63,7 +62,7 @@ public class ChunkRenderWorker implements Runnable { if (!generator.isFinished()) { - Log.JNI.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn PENDING erwartet war; ignoriere Aufgabe"); + Log.RENDER.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn PENDING erwartet war; ignoriere Aufgabe"); } return; @@ -76,7 +75,7 @@ public class ChunkRenderWorker implements Runnable generator.getLock().unlock(); } - Entity lvt_2_1_ = Game.getGame().getRenderViewEntity(); + Entity lvt_2_1_ = Client.CLIENT.getRenderViewEntity(); if (lvt_2_1_ == null) { @@ -107,7 +106,7 @@ public class ChunkRenderWorker implements Runnable { if (!generator.isFinished()) { - Log.JNI.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn COMPILING erwartet war; breche Aufgabe ab"); + Log.RENDER.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn COMPILING erwartet war; breche Aufgabe ab"); } this.freeRenderBuilder(generator); @@ -165,7 +164,7 @@ public class ChunkRenderWorker implements Runnable if (!generator.isFinished()) { - Log.JNI.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn UPLOADING erwartet war; breche Aufgabe ab"); + Log.RENDER.warn("Chunk-Rendering-Aufgabe war " + generator.getStatus() + " wenn UPLOADING erwartet war; breche Aufgabe ab"); } } finally @@ -183,7 +182,7 @@ public class ChunkRenderWorker implements Runnable if (!(p_onFailure_1_ instanceof CancellationException) && !(p_onFailure_1_ instanceof InterruptedException)) { - Log.JNI.error(p_onFailure_1_, "Fehler beim Rendern des Chunks"); + Log.RENDER.error(p_onFailure_1_, "Fehler beim Rendern des Chunks"); } } }); diff --git a/java/src/game/renderer/chunk/CompiledChunk.java b/client/src/main/java/client/renderer/chunk/CompiledChunk.java similarity index 91% rename from java/src/game/renderer/chunk/CompiledChunk.java rename to client/src/main/java/client/renderer/chunk/CompiledChunk.java index 947eec7..7155915 100755 --- a/java/src/game/renderer/chunk/CompiledChunk.java +++ b/client/src/main/java/client/renderer/chunk/CompiledChunk.java @@ -1,13 +1,12 @@ -package game.renderer.chunk; +package client.renderer.chunk; import java.util.List; -import game.collect.Lists; - -import game.renderer.BlockLayer; -import game.renderer.RenderBuffer; -import game.tileentity.TileEntity; -import game.world.Facing; +import client.renderer.RenderBuffer; +import common.collect.Lists; +import common.model.BlockLayer; +import common.tileentity.TileEntity; +import common.util.Facing; public class CompiledChunk { diff --git a/java/src/game/renderer/chunk/RenderChunk.java b/client/src/main/java/client/renderer/chunk/RenderChunk.java similarity index 92% rename from java/src/game/renderer/chunk/RenderChunk.java rename to client/src/main/java/client/renderer/chunk/RenderChunk.java index be4673f..06de2e2 100755 --- a/java/src/game/renderer/chunk/RenderChunk.java +++ b/client/src/main/java/client/renderer/chunk/RenderChunk.java @@ -1,4 +1,4 @@ -package game.renderer.chunk; +package client.renderer.chunk; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -10,30 +10,29 @@ import java.util.concurrent.locks.ReentrantLock; import org.lwjgl.opengl.GL11; -import game.collect.Maps; -import game.collect.Sets; - -import game.Game; -import game.block.Block; -import game.renderer.BlockLayer; -import game.renderer.BlockRenderer; -import game.renderer.DefaultVertexFormats; -import game.renderer.RegionRenderCache; -import game.renderer.RenderBuffer; -import game.renderer.RenderGlobal; -import game.renderer.VertexBuffer; -import game.renderer.tileentity.TileEntityRendererDispatcher; -import game.renderer.tileentity.TileEntitySpecialRenderer; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.State; -import game.world.World; +import client.Client; +import client.renderer.BlockRenderer; +import client.renderer.DefaultVertexFormats; +import client.renderer.RegionRenderCache; +import client.renderer.RenderBuffer; +import client.renderer.RenderGlobal; +import client.renderer.VertexBuffer; +import client.renderer.tileentity.TileEntityRendererDispatcher; +import client.renderer.tileentity.TileEntitySpecialRenderer; +import client.world.WorldClient; +import common.block.Block; +import common.collect.Maps; +import common.collect.Sets; +import common.model.BlockLayer; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.State; public class RenderChunk { - private World world; + private WorldClient world; private final RenderGlobal renderGlobal; public static int renderChunksUpdated; private BlockPos position; @@ -50,7 +49,7 @@ public class RenderChunk private boolean needsUpdate = true; private EnumMap mapEnumFacing = Maps.newEnumMap(Facing.class); - public RenderChunk(World worldIn, RenderGlobal renderGlobalIn, BlockPos blockPosIn, int indexIn) + public RenderChunk(WorldClient worldIn, RenderGlobal renderGlobalIn, BlockPos blockPosIn, int indexIn) { this.world = worldIn; this.renderGlobal = renderGlobalIn; @@ -142,7 +141,7 @@ public class RenderChunk { ++renderChunksUpdated; boolean[] aboolean = new boolean[BlockLayer.values().length]; - BlockRenderer blockrendererdispatcher = Game.getGame().getBlockRendererDispatcher(); + BlockRenderer blockrendererdispatcher = Client.CLIENT.getBlockRendererDispatcher(); for (BlockPos.MutableBlockPos blockpos$mutableblockpos : BlockPos.getAllInBoxMutable(blockpos, blockpos1)) { diff --git a/java/src/game/renderer/chunk/SetVisibility.java b/client/src/main/java/client/renderer/chunk/SetVisibility.java similarity index 97% rename from java/src/game/renderer/chunk/SetVisibility.java rename to client/src/main/java/client/renderer/chunk/SetVisibility.java index f927525..3dfdebc 100755 --- a/java/src/game/renderer/chunk/SetVisibility.java +++ b/client/src/main/java/client/renderer/chunk/SetVisibility.java @@ -1,9 +1,9 @@ -package game.renderer.chunk; +package client.renderer.chunk; import java.util.BitSet; import java.util.Set; -import game.world.Facing; +import common.util.Facing; public class SetVisibility { diff --git a/java/src/game/renderer/chunk/VisGraph.java b/client/src/main/java/client/renderer/chunk/VisGraph.java similarity index 98% rename from java/src/game/renderer/chunk/VisGraph.java rename to client/src/main/java/client/renderer/chunk/VisGraph.java index 4bc1de7..ebca265 100755 --- a/java/src/game/renderer/chunk/VisGraph.java +++ b/client/src/main/java/client/renderer/chunk/VisGraph.java @@ -1,4 +1,4 @@ -package game.renderer.chunk; +package client.renderer.chunk; import java.util.BitSet; import java.util.EnumSet; @@ -6,8 +6,8 @@ import java.util.LinkedList; import java.util.Queue; import java.util.Set; -import game.world.BlockPos; -import game.world.Facing; +import common.util.BlockPos; +import common.util.Facing; public class VisGraph { diff --git a/java/src/game/renderer/entity/Render.java b/client/src/main/java/client/renderer/entity/Render.java similarity index 96% rename from java/src/game/renderer/entity/Render.java rename to client/src/main/java/client/renderer/entity/Render.java index 2d523f0..4f29cae 100755 --- a/java/src/game/renderer/entity/Render.java +++ b/client/src/main/java/client/renderer/entity/Render.java @@ -1,21 +1,21 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.Game; -import game.block.Block; -import game.entity.Entity; -import game.renderer.DefaultVertexFormats; -import game.renderer.Drawing; -import game.renderer.Frustum; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.renderer.texture.TextureAtlasSprite; -import game.renderer.texture.TextureMap; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.World; +import client.Client; +import client.renderer.DefaultVertexFormats; +import client.renderer.Drawing; +import client.renderer.Frustum; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.renderer.texture.TextureAtlasSprite; +import client.renderer.texture.TextureMap; +import common.block.Block; +import common.entity.Entity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.world.World; public abstract class Render { @@ -98,7 +98,7 @@ public abstract class Render private void renderEntityOnFire(Entity entity, double x, double y, double z, float partialTicks) { GlState.disableLighting(); - TextureMap texturemap = Game.getGame().getTextureMapBlocks(); + TextureMap texturemap = Client.CLIENT.getTextureMapBlocks(); TextureAtlasSprite textureatlassprite = texturemap.getAtlasSprite("blocks/fire_layer_0"); TextureAtlasSprite textureatlassprite1 = texturemap.getAtlasSprite("blocks/fire_layer_1"); GL11.glPushMatrix(); diff --git a/java/src/game/renderer/entity/RenderArachnoid.java b/client/src/main/java/client/renderer/entity/RenderArachnoid.java similarity index 93% rename from java/src/game/renderer/entity/RenderArachnoid.java rename to client/src/main/java/client/renderer/entity/RenderArachnoid.java index 8a59b4b..1a35652 100755 --- a/java/src/game/renderer/entity/RenderArachnoid.java +++ b/client/src/main/java/client/renderer/entity/RenderArachnoid.java @@ -1,10 +1,10 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.npc.EntityNPC; -import game.renderer.layers.LayerArachnoidArmor; -import game.renderer.model.ModelArachnoid; +import client.renderer.layers.LayerArachnoidArmor; +import client.renderer.model.ModelArachnoid; +import common.entity.npc.EntityNPC; public class RenderArachnoid extends RenderHumanoid diff --git a/java/src/game/renderer/entity/RenderArrow.java b/client/src/main/java/client/renderer/entity/RenderArrow.java similarity index 93% rename from java/src/game/renderer/entity/RenderArrow.java rename to client/src/main/java/client/renderer/entity/RenderArrow.java index 4b6ad8b..59b26ab 100755 --- a/java/src/game/renderer/entity/RenderArrow.java +++ b/client/src/main/java/client/renderer/entity/RenderArrow.java @@ -1,13 +1,13 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.projectile.EntityArrow; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.util.ExtMath; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import common.entity.projectile.EntityArrow; +import common.util.ExtMath; public class RenderArrow extends Render diff --git a/java/src/game/renderer/entity/RenderBat.java b/client/src/main/java/client/renderer/entity/RenderBat.java similarity index 89% rename from java/src/game/renderer/entity/RenderBat.java rename to client/src/main/java/client/renderer/entity/RenderBat.java index 6435569..0aa6c4a 100755 --- a/java/src/game/renderer/entity/RenderBat.java +++ b/client/src/main/java/client/renderer/entity/RenderBat.java @@ -1,10 +1,10 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.animal.EntityBat; -import game.renderer.model.ModelBat; -import game.util.ExtMath; +import client.renderer.model.ModelBat; +import common.entity.animal.EntityBat; +import common.util.ExtMath; public class RenderBat extends RenderLiving diff --git a/java/src/game/renderer/entity/RenderBlockEntity.java b/client/src/main/java/client/renderer/entity/RenderBlockEntity.java similarity index 89% rename from java/src/game/renderer/entity/RenderBlockEntity.java rename to client/src/main/java/client/renderer/entity/RenderBlockEntity.java index 93308da..8d40d11 100755 --- a/java/src/game/renderer/entity/RenderBlockEntity.java +++ b/client/src/main/java/client/renderer/entity/RenderBlockEntity.java @@ -1,12 +1,12 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.Game; -import game.entity.Entity; -import game.renderer.BlockRenderer; -import game.renderer.texture.TextureMap; -import game.world.State; +import client.Client; +import client.renderer.BlockRenderer; +import client.renderer.texture.TextureMap; +import common.entity.Entity; +import common.world.State; public class RenderBlockEntity extends Render @@ -28,7 +28,7 @@ public class RenderBlockEntity extends Render // if(entity.isInvisible()) { // return; // } - BlockRenderer blockrendererdispatcher = Game.getGame().getBlockRendererDispatcher(); + BlockRenderer blockrendererdispatcher = Client.CLIENT.getBlockRendererDispatcher(); GL11.glPushMatrix(); GL11.glTranslatef((float)x, (float)y + 0.5F, (float)z); diff --git a/java/src/game/renderer/entity/RenderBoat.java b/client/src/main/java/client/renderer/entity/RenderBoat.java similarity index 90% rename from java/src/game/renderer/entity/RenderBoat.java rename to client/src/main/java/client/renderer/entity/RenderBoat.java index 515da63..a9fafca 100755 --- a/java/src/game/renderer/entity/RenderBoat.java +++ b/client/src/main/java/client/renderer/entity/RenderBoat.java @@ -1,11 +1,11 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.item.EntityBoat; -import game.renderer.model.ModelBase; -import game.renderer.model.ModelBoat; -import game.util.ExtMath; +import client.renderer.model.ModelBase; +import client.renderer.model.ModelBoat; +import common.entity.item.EntityBoat; +import common.util.ExtMath; public class RenderBoat extends Render diff --git a/java/src/game/renderer/entity/RenderBullet.java b/client/src/main/java/client/renderer/entity/RenderBullet.java similarity index 93% rename from java/src/game/renderer/entity/RenderBullet.java rename to client/src/main/java/client/renderer/entity/RenderBullet.java index c94042a..c143312 100755 --- a/java/src/game/renderer/entity/RenderBullet.java +++ b/client/src/main/java/client/renderer/entity/RenderBullet.java @@ -1,12 +1,12 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.projectile.EntityBullet; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import common.entity.projectile.EntityBullet; public class RenderBullet extends Render diff --git a/java/src/game/renderer/entity/RenderChicken.java b/client/src/main/java/client/renderer/entity/RenderChicken.java similarity index 67% rename from java/src/game/renderer/entity/RenderChicken.java rename to client/src/main/java/client/renderer/entity/RenderChicken.java index 6757c92..d9f885c 100755 --- a/java/src/game/renderer/entity/RenderChicken.java +++ b/client/src/main/java/client/renderer/entity/RenderChicken.java @@ -1,8 +1,8 @@ -package game.renderer.entity; +package client.renderer.entity; -import game.entity.animal.EntityChicken; -import game.renderer.model.ModelBase; -import game.util.ExtMath; +import client.renderer.model.ModelBase; +import common.entity.animal.EntityChicken; +import common.util.ExtMath; public class RenderChicken extends RenderLiving @@ -27,8 +27,8 @@ public class RenderChicken extends RenderLiving */ protected float handleRotationFloat(EntityChicken livingBase, float partialTicks) { - float f = livingBase.field_70888_h + (livingBase.wingRotation - livingBase.field_70888_h) * partialTicks; - float f1 = livingBase.field_70884_g + (livingBase.destPos - livingBase.field_70884_g) * partialTicks; + float f = livingBase.lastWingRotation + (livingBase.wingRotation - livingBase.lastWingRotation) * partialTicks; + float f1 = livingBase.lastDestPos + (livingBase.destPos - livingBase.lastDestPos) * partialTicks; return (ExtMath.sin(f) + 1.0F) * f1; } } diff --git a/java/src/game/renderer/entity/RenderCow.java b/client/src/main/java/client/renderer/entity/RenderCow.java similarity index 81% rename from java/src/game/renderer/entity/RenderCow.java rename to client/src/main/java/client/renderer/entity/RenderCow.java index 9fd024e..b6280ab 100755 --- a/java/src/game/renderer/entity/RenderCow.java +++ b/client/src/main/java/client/renderer/entity/RenderCow.java @@ -1,7 +1,7 @@ -package game.renderer.entity; +package client.renderer.entity; -import game.entity.animal.EntityCow; -import game.renderer.model.ModelBase; +import client.renderer.model.ModelBase; +import common.entity.animal.EntityCow; public class RenderCow extends RenderLiving diff --git a/java/src/game/renderer/entity/RenderCrystal.java b/client/src/main/java/client/renderer/entity/RenderCrystal.java similarity index 87% rename from java/src/game/renderer/entity/RenderCrystal.java rename to client/src/main/java/client/renderer/entity/RenderCrystal.java index c5bea5d..d5642b1 100755 --- a/java/src/game/renderer/entity/RenderCrystal.java +++ b/client/src/main/java/client/renderer/entity/RenderCrystal.java @@ -1,11 +1,11 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.item.EntityCrystal; -import game.renderer.model.ModelBase; -import game.renderer.model.ModelCrystal; -import game.util.ExtMath; +import client.renderer.model.ModelBase; +import client.renderer.model.ModelCrystal; +import common.entity.item.EntityCrystal; +import common.util.ExtMath; public class RenderCrystal extends Render diff --git a/java/src/game/renderer/entity/RenderDie.java b/client/src/main/java/client/renderer/entity/RenderDie.java similarity index 81% rename from java/src/game/renderer/entity/RenderDie.java rename to client/src/main/java/client/renderer/entity/RenderDie.java index 2971d80..38be9de 100755 --- a/java/src/game/renderer/entity/RenderDie.java +++ b/client/src/main/java/client/renderer/entity/RenderDie.java @@ -1,12 +1,12 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.Game; -import game.entity.projectile.EntityDie; -import game.renderer.blockmodel.Transforms.Camera; -import game.renderer.model.ModelDie; -import game.renderer.texture.TextureMap; +import client.Client; +import client.renderer.model.ModelDie; +import client.renderer.texture.TextureMap; +import common.entity.projectile.EntityDie; +import common.model.Transforms.Camera; public class RenderDie extends Render { @@ -33,7 +33,7 @@ public class RenderDie extends Render GL11.glRotatef((float)((entity.ticksExisted % 10) * (360 / 10)), 0.3f, 0.4f, 0.1f); // GlState.translate(-0.05F, -0.05F, 0.05F); GL11.glScalef(0.5f, 0.5f, 0.5f); - Game.getGame().getRenderItem().renderItem(entity.getStack(), Camera.GROUND); + Client.CLIENT.getRenderItem().renderItem(entity.getStack(), Camera.GROUND); // blockrendererdispatcher.renderBlockBrightness(Blocks.planks.getDefaultState(), entity.getBrightness(partialTicks)); GL11.glPopMatrix(); super.doRender(entity, x, y, z, partialTicks); diff --git a/java/src/game/renderer/entity/RenderDragon.java b/client/src/main/java/client/renderer/entity/RenderDragon.java similarity index 94% rename from java/src/game/renderer/entity/RenderDragon.java rename to client/src/main/java/client/renderer/entity/RenderDragon.java index 53453fe..e76f636 100755 --- a/java/src/game/renderer/entity/RenderDragon.java +++ b/client/src/main/java/client/renderer/entity/RenderDragon.java @@ -1,12 +1,12 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.animal.EntityDragon; -import game.renderer.GlState; -import game.renderer.layers.LayerEnderDragonEyes; -import game.renderer.model.ModelDragon; -import game.util.ExtMath; +import client.renderer.GlState; +import client.renderer.layers.LayerEnderDragonEyes; +import client.renderer.model.ModelDragon; +import common.entity.animal.EntityDragon; +import common.util.ExtMath; public class RenderDragon extends RenderLiving diff --git a/java/src/game/renderer/entity/RenderDynamite.java b/client/src/main/java/client/renderer/entity/RenderDynamite.java similarity index 72% rename from java/src/game/renderer/entity/RenderDynamite.java rename to client/src/main/java/client/renderer/entity/RenderDynamite.java index a7bdebf..376e2ae 100755 --- a/java/src/game/renderer/entity/RenderDynamite.java +++ b/client/src/main/java/client/renderer/entity/RenderDynamite.java @@ -1,8 +1,8 @@ -package game.renderer.entity; +package client.renderer.entity; -import game.entity.projectile.EntityDynamite; -import game.item.Item; -import game.item.ItemStack; +import common.entity.projectile.EntityDynamite; +import common.item.Item; +import common.item.ItemStack; public class RenderDynamite extends RenderItemEntity { public RenderDynamite(RenderManager renderManagerIn, Item itemIn, RenderItem renderItemIn) { diff --git a/java/src/game/renderer/entity/RenderEntity.java b/client/src/main/java/client/renderer/entity/RenderEntity.java similarity index 93% rename from java/src/game/renderer/entity/RenderEntity.java rename to client/src/main/java/client/renderer/entity/RenderEntity.java index 5d8e2cc..40f7baa 100755 --- a/java/src/game/renderer/entity/RenderEntity.java +++ b/client/src/main/java/client/renderer/entity/RenderEntity.java @@ -1,8 +1,8 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.Entity; +import common.entity.Entity; public class RenderEntity extends Render diff --git a/java/src/game/renderer/entity/RenderEntityItem.java b/client/src/main/java/client/renderer/entity/RenderEntityItem.java similarity index 81% rename from java/src/game/renderer/entity/RenderEntityItem.java rename to client/src/main/java/client/renderer/entity/RenderEntityItem.java index 6cb9bf3..4ba2eff 100755 --- a/java/src/game/renderer/entity/RenderEntityItem.java +++ b/client/src/main/java/client/renderer/entity/RenderEntityItem.java @@ -1,16 +1,16 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.item.EntityItem; -import game.item.Item; -import game.item.ItemStack; -import game.model.IBakedModel; -import game.renderer.GlState; -import game.renderer.blockmodel.Transforms; -import game.renderer.texture.TextureMap; -import game.rng.Random; -import game.util.ExtMath; +import client.renderer.GlState; +import client.renderer.blockmodel.IBakedModel; +import client.renderer.texture.TextureMap; +import common.entity.item.EntityItem; +import common.item.Item; +import common.item.ItemStack; +import common.model.Transforms; +import common.rng.Random; +import common.util.ExtMath; public class RenderEntityItem extends Render { @@ -40,7 +40,7 @@ public class RenderEntityItem extends Render int i = this.func_177078_a(itemstack); float f = 0.25F; float f1 = ExtMath.sin(((float)itemIn.getAge() + p_177077_8_) / 10.0F + itemIn.hoverStart) * 0.1F + 0.1F; - float f2 = p_177077_9_.getItemCameraTransforms().get(Transforms.Camera.GROUND).scale.y; + float f2 = p_177077_9_.getTransforms().get(Transforms.Camera.GROUND).scale(); GL11.glTranslatef((float)p_177077_2_, (float)p_177077_4_ + f1 + 0.25F * f2, (float)p_177077_6_); if (flag || this.renderManager.gm != null) @@ -66,19 +66,19 @@ public class RenderEntityItem extends Render { int i = 1; - if (stack.stackSize > 48) + if (stack.size > 48) { i = 5; } - else if (stack.stackSize > 32) + else if (stack.size > 32) { i = 4; } - else if (stack.stackSize > 16) + else if (stack.size > 16) { i = 3; } - else if (stack.stackSize > 1) + else if (stack.size > 1) { i = 2; } @@ -126,20 +126,18 @@ public class RenderEntityItem extends Render } GL11.glScalef(0.5F, 0.5F, 0.5F); - ibakedmodel.getItemCameraTransforms().apply(Transforms.Camera.GROUND); + RenderItem.apply(ibakedmodel.getTransforms(), Transforms.Camera.GROUND); this.itemRenderer.renderItem(itemstack, ibakedmodel); GL11.glPopMatrix(); } else { GL11.glPushMatrix(); - ibakedmodel.getItemCameraTransforms().apply(Transforms.Camera.GROUND); + RenderItem.apply(ibakedmodel.getTransforms(), Transforms.Camera.GROUND); this.itemRenderer.renderItem(itemstack, ibakedmodel); GL11.glPopMatrix(); - float f3 = ibakedmodel.getItemCameraTransforms().ground.scale.x; - float f4 = ibakedmodel.getItemCameraTransforms().ground.scale.y; - float f5 = ibakedmodel.getItemCameraTransforms().ground.scale.z; - GL11.glTranslatef(0.0F * f3, 0.0F * f4, 0.046875F * f5); + float f3 = ibakedmodel.getTransforms().ground.scale(); + GL11.glTranslatef(0.0F, 0.0F, 0.046875F * f3); } } diff --git a/java/src/game/renderer/entity/RenderFallingBlock.java b/client/src/main/java/client/renderer/entity/RenderFallingBlock.java similarity index 80% rename from java/src/game/renderer/entity/RenderFallingBlock.java rename to client/src/main/java/client/renderer/entity/RenderFallingBlock.java index 25a240f..c004df8 100755 --- a/java/src/game/renderer/entity/RenderFallingBlock.java +++ b/client/src/main/java/client/renderer/entity/RenderFallingBlock.java @@ -1,20 +1,20 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.Game; -import game.block.Block; -import game.entity.item.EntityFalling; -import game.model.IBakedModel; -import game.renderer.BlockRenderer; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.renderer.texture.TextureMap; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import client.Client; +import client.renderer.BlockRenderer; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.renderer.blockmodel.IBakedModel; +import client.renderer.texture.TextureMap; +import common.block.Block; +import common.entity.item.EntityFalling; +import common.util.BlockPos; +import common.world.State; +import common.world.World; public class RenderFallingBlock extends Render { @@ -51,7 +51,7 @@ public class RenderFallingBlock extends Render int j = blockpos.getY(); int k = blockpos.getZ(); worldrenderer.setTranslation((double)((float)(-i) - 0.5F), (double)(-j), (double)((float)(-k) - 0.5F)); - BlockRenderer blockrendererdispatcher = Game.getGame().getBlockRendererDispatcher(); + BlockRenderer blockrendererdispatcher = Client.CLIENT.getBlockRendererDispatcher(); IBakedModel ibakedmodel = blockrendererdispatcher.getModelFromBlockState(iblockstate, world, (BlockPos)null); blockrendererdispatcher.renderModel(world, ibakedmodel, iblockstate, blockpos, worldrenderer, false); worldrenderer.setTranslation(0.0D, 0.0D, 0.0D); diff --git a/java/src/game/renderer/entity/RenderFireball.java b/client/src/main/java/client/renderer/entity/RenderFireball.java similarity index 81% rename from java/src/game/renderer/entity/RenderFireball.java rename to client/src/main/java/client/renderer/entity/RenderFireball.java index d4f8768..0e68614 100755 --- a/java/src/game/renderer/entity/RenderFireball.java +++ b/client/src/main/java/client/renderer/entity/RenderFireball.java @@ -1,16 +1,16 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.Game; -import game.entity.projectile.EntityProjectile; -import game.init.Items; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.renderer.texture.TextureAtlasSprite; -import game.renderer.texture.TextureMap; +import client.Client; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.renderer.texture.TextureAtlasSprite; +import client.renderer.texture.TextureMap; +import common.entity.projectile.EntityProjectile; +import common.init.Items; public class RenderFireball extends Render @@ -33,7 +33,7 @@ public class RenderFireball extends Render GL11.glTranslatef((float)x, (float)y, (float)z); GlState.enableRescaleNormal(); GL11.glScalef(this.scale, this.scale, this.scale); - TextureAtlasSprite textureatlassprite = Game.getGame().getRenderItem().getItemModelMesher().getParticleIcon(Items.fire_charge); + TextureAtlasSprite textureatlassprite = Client.CLIENT.getRenderItem().getItemModelMesher().getParticleIcon(Items.fire_charge); // Tessellator tessellator = Tessellator.getInstance(); RenderBuffer worldrenderer = Tessellator.getBuffer(); float f = textureatlassprite.getMinU(); diff --git a/java/src/game/renderer/entity/RenderFish.java b/client/src/main/java/client/renderer/entity/RenderFish.java similarity index 92% rename from java/src/game/renderer/entity/RenderFish.java rename to client/src/main/java/client/renderer/entity/RenderFish.java index f5ce13a..6782994 100755 --- a/java/src/game/renderer/entity/RenderFish.java +++ b/client/src/main/java/client/renderer/entity/RenderFish.java @@ -1,16 +1,16 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.Game; -import game.entity.projectile.EntityHook; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.renderer.particle.EffectRenderer; -import game.util.ExtMath; -import game.world.Vec3; +import client.Client; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.renderer.particle.EffectRenderer; +import common.entity.projectile.EntityHook; +import common.util.ExtMath; +import common.util.Vec3; public class RenderFish extends Render { @@ -65,7 +65,7 @@ public class RenderFish extends Render double d2 = entity.angler.prevZ + (entity.angler.posZ - entity.angler.prevZ) * (double)partialTicks + vec3.zCoord; double d3 = (double)entity.angler.getEyeHeight(); - if (this.renderManager.gm != null && this.renderManager.gm.thirdPersonView > 0 || entity.angler != Game.getGame().thePlayer) + if (this.renderManager.gm != null && this.renderManager.gm.thirdPersonView > 0 || entity.angler != Client.CLIENT.player) { float f9 = (entity.angler.prevYawOffset + (entity.angler.yawOffset - entity.angler.prevYawOffset) * partialTicks) * (float)Math.PI / 180.0F; double d4 = (double)ExtMath.sin(f9); diff --git a/java/src/game/renderer/entity/RenderFlyingBox.java b/client/src/main/java/client/renderer/entity/RenderFlyingBox.java similarity index 92% rename from java/src/game/renderer/entity/RenderFlyingBox.java rename to client/src/main/java/client/renderer/entity/RenderFlyingBox.java index 7bca700..a8518c5 100755 --- a/java/src/game/renderer/entity/RenderFlyingBox.java +++ b/client/src/main/java/client/renderer/entity/RenderFlyingBox.java @@ -1,10 +1,10 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.projectile.EntityBox; -import game.renderer.GlState; -import game.renderer.model.ModelHead; +import client.renderer.GlState; +import client.renderer.model.ModelHead; +import common.entity.projectile.EntityBox; public class RenderFlyingBox extends Render diff --git a/client/src/main/java/client/renderer/entity/RenderFox.java b/client/src/main/java/client/renderer/entity/RenderFox.java new file mode 100644 index 0000000..d3bc73b --- /dev/null +++ b/client/src/main/java/client/renderer/entity/RenderFox.java @@ -0,0 +1,16 @@ +package client.renderer.entity; + +import client.renderer.model.ModelBase; +import common.entity.animal.EntityFox; + +public class RenderFox extends RenderLiving { + private static final String FOX_TEXTURE = "textures/entity/fox.png"; + + public RenderFox(RenderManager renderManagerIn, ModelBase modelBaseIn) { + super(renderManagerIn, modelBaseIn); + } + + protected String getEntityTexture(EntityFox entity) { + return FOX_TEXTURE; + } +} diff --git a/java/src/game/renderer/entity/RenderHorse.java b/client/src/main/java/client/renderer/entity/RenderHorse.java similarity index 88% rename from java/src/game/renderer/entity/RenderHorse.java rename to client/src/main/java/client/renderer/entity/RenderHorse.java index 8763953..36656eb 100755 --- a/java/src/game/renderer/entity/RenderHorse.java +++ b/client/src/main/java/client/renderer/entity/RenderHorse.java @@ -1,15 +1,14 @@ -package game.renderer.entity; +package client.renderer.entity; import java.util.Set; import org.lwjgl.opengl.GL11; -import game.collect.Sets; - -import game.Game; -import game.entity.animal.EntityHorse; -import game.renderer.model.ModelHorse; -import game.renderer.texture.LayeredTexture; +import client.Client; +import client.renderer.model.ModelHorse; +import client.renderer.texture.LayeredTexture; +import common.collect.Sets; +import common.entity.animal.EntityHorse; public class RenderHorse extends RenderLiving { @@ -91,7 +90,7 @@ public class RenderHorse extends RenderLiving { if (!loaded.contains(s)) { - Game.getGame().getTextureManager().loadTexture(s, new LayeredTexture(horse.getVariantTexturePaths())); + Client.CLIENT.getTextureManager().loadTexture(s, new LayeredTexture(horse.getVariantTexturePaths())); loaded.add(s); } diff --git a/java/src/game/renderer/entity/RenderHumanoid.java b/client/src/main/java/client/renderer/entity/RenderHumanoid.java similarity index 93% rename from java/src/game/renderer/entity/RenderHumanoid.java rename to client/src/main/java/client/renderer/entity/RenderHumanoid.java index e36c7d9..42660a5 100755 --- a/java/src/game/renderer/entity/RenderHumanoid.java +++ b/client/src/main/java/client/renderer/entity/RenderHumanoid.java @@ -1,20 +1,21 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.npc.EntityNPC; -import game.item.ItemAction; -import game.item.ItemStack; -import game.renderer.GlState; -import game.renderer.layers.LayerArmor; -import game.renderer.layers.LayerArrow; -import game.renderer.layers.LayerCape; -import game.renderer.layers.LayerCharge; -import game.renderer.layers.LayerExtra; -import game.renderer.layers.LayerHeldItem; -import game.renderer.layers.LayerPowerRods; -import game.renderer.model.ModelBiped; -import game.renderer.model.ModelHumanoid; +import client.renderer.GlState; +import client.renderer.layers.LayerArmor; +import client.renderer.layers.LayerArrow; +import client.renderer.layers.LayerCape; +import client.renderer.layers.LayerCharge; +import client.renderer.layers.LayerExtra; +import client.renderer.layers.LayerHeldItem; +import client.renderer.layers.LayerPowerRods; +import client.renderer.model.ModelBiped; +import client.renderer.model.ModelHumanoid; +import client.renderer.texture.EntityTexManager; +import common.entity.npc.EntityNPC; +import common.item.ItemAction; +import common.item.ItemStack; public class RenderHumanoid extends RenderNpc @@ -68,12 +69,12 @@ public class RenderHumanoid extends RenderNpc public void doRender(EntityNPC entity, double x, double y, double z, float partialTicks) { - if (entity != this.renderManager.gm.thePlayer || this.renderManager.livingPlayer == entity) + if (entity != this.renderManager.gm.player || this.renderManager.livingPlayer == entity) { // if(entity.isBoss()) // BossStatus.setBossStatus(entity); double d0 = y; - if(/* this.canSneak() && */ entity.isSneakingVisually() && entity != this.renderManager.gm.thePlayer) + if(/* this.canSneak() && */ entity.isSneakingVisually() && entity != this.renderManager.gm.player) d0 = y - 0.125D; this.setModelVisibilities(entity); super.doRender(entity, x, d0, z, partialTicks); @@ -82,7 +83,7 @@ public class RenderHumanoid extends RenderNpc protected void renderLayers(EntityNPC entity, float swing, float amount, float partial, float time, float dYaw, float dPitch, float scale) { super.renderLayers(entity, swing, amount, partial, time, dYaw, dPitch, scale); - LayerExtra extra = entity.getExtrasLayer(); + LayerExtra extra = EntityTexManager.getLayer(entity); if(extra != null) { extra.setModel(this.getMainModel()); // boolean bright = this.setBrightness(entity, partial, extra.shouldCombineTextures()); diff --git a/java/src/game/renderer/entity/RenderItem.java b/client/src/main/java/client/renderer/entity/RenderItem.java similarity index 86% rename from java/src/game/renderer/entity/RenderItem.java rename to client/src/main/java/client/renderer/entity/RenderItem.java index 418e2f8..a2a790f 100755 --- a/java/src/game/renderer/entity/RenderItem.java +++ b/client/src/main/java/client/renderer/entity/RenderItem.java @@ -1,29 +1,29 @@ -package game.renderer.entity; +package client.renderer.entity; import java.util.List; import org.lwjgl.opengl.GL11; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.item.Item; -import game.item.ItemStack; -import game.model.IBakedModel; -import game.model.ModelManager; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.ItemModelMesher; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.renderer.blockmodel.BakedQuad; -import game.renderer.blockmodel.Transform; -import game.renderer.blockmodel.Transforms; -import game.renderer.texture.TextureManager; -import game.renderer.texture.TextureMap; -import game.renderer.tileentity.TileEntityItemStackRenderer; -import game.world.Facing; -import game.world.Vec3i; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.ItemModelMesher; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.renderer.blockmodel.BakedQuad; +import client.renderer.blockmodel.IBakedModel; +import client.renderer.blockmodel.ModelManager; +import client.renderer.texture.TextureManager; +import client.renderer.texture.TextureMap; +import client.renderer.tileentity.TileEntityItemStackRenderer; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.item.Item; +import common.item.ItemStack; +import common.model.Transform; +import common.model.Transforms; +import common.util.Facing; +import common.util.Vec3i; public class RenderItem { @@ -77,10 +77,10 @@ public class RenderItem for (Facing enumfacing : Facing.values()) { - this.renderQuads(worldrenderer, model.getFaceQuads(enumfacing), color, stack); + this.renderQuads(worldrenderer, model.getFace(enumfacing), color, stack); } - this.renderQuads(worldrenderer, model.getGeneralQuads(), color, stack); + this.renderQuads(worldrenderer, model.getQuads(), color, stack); Tessellator.draw(); } @@ -91,7 +91,7 @@ public class RenderItem GL11.glPushMatrix(); GL11.glScalef(0.5F, 0.5F, 0.5F); - if (model.isBuiltInRenderer()) + if (model.isBuiltin()) { GL11.glRotatef(180.0F, 0.0F, 1.0F, 0.0F); GL11.glTranslatef(-0.5F, -0.5F, -0.5F); @@ -270,13 +270,8 @@ public class RenderItem GlState.enableBlend(); GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ONE, GL11.GL_ZERO); GL11.glPushMatrix(); - Transforms itemcameratransforms = model.getItemCameraTransforms(); - itemcameratransforms.apply(cameraTransformType); - - if (this.isThereOneNegativeScale(itemcameratransforms.get(cameraTransformType))) - { - GlState.cullFace(GL11.GL_FRONT); - } + Transforms itemcameratransforms = model.getTransforms(); + RenderItem.apply(itemcameratransforms, cameraTransformType); this.renderItem(stack, model); GlState.cullFace(GL11.GL_BACK); @@ -287,16 +282,6 @@ public class RenderItem // this.textureManager.getTexture(TextureMap.locationBlocksTexture).restoreLastMipmap(); } - /** - * Return true if only one scale is negative - * - * @param itemTranformVec The ItemTransformVec3f instance - */ - private boolean isThereOneNegativeScale(Transform itemTranformVec) - { - return itemTranformVec.scale.x < 0.0F ^ itemTranformVec.scale.y < 0.0F ^ itemTranformVec.scale.z < 0.0F; - } - private void renderItemIntoGUI(ItemStack stack, int x, int y) { IBakedModel ibakedmodel = this.itemModelMesher.getItemModel(stack); @@ -310,7 +295,7 @@ public class RenderItem GlState.blendFunc(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA); GlState.color(1.0F, 1.0F, 1.0F, 1.0F); this.setupGuiTransform(x, y, ibakedmodel.isGui3d()); - ibakedmodel.getItemCameraTransforms().apply(Transforms.Camera.GUI); + RenderItem.apply(ibakedmodel.getTransforms(), Transforms.Camera.GUI); this.renderItem(stack, ibakedmodel); GlState.disableAlpha(); GlState.disableRescaleNormal(); @@ -358,4 +343,15 @@ public class RenderItem { this.itemModelMesher.rebuildCache(); } + + public static void apply(Transforms trans, Transforms.Camera type) { + Transform vec = trans.get(type); + if(vec != Transform.IDENTITY) { + GL11.glTranslatef(vec.translationX(), vec.translationY(), vec.translationZ()); + GL11.glRotatef(vec.rotationY(), 0.0F, 1.0F, 0.0F); + GL11.glRotatef(vec.rotationX(), 1.0F, 0.0F, 0.0F); + GL11.glRotatef(vec.rotationZ(), 0.0F, 0.0F, 1.0F); + GL11.glScalef(vec.scale(), vec.scale(), vec.scale()); + } + } } diff --git a/java/src/game/renderer/entity/RenderItemEntity.java b/client/src/main/java/client/renderer/entity/RenderItemEntity.java similarity index 85% rename from java/src/game/renderer/entity/RenderItemEntity.java rename to client/src/main/java/client/renderer/entity/RenderItemEntity.java index 1776f47..41da344 100755 --- a/java/src/game/renderer/entity/RenderItemEntity.java +++ b/client/src/main/java/client/renderer/entity/RenderItemEntity.java @@ -1,13 +1,13 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.item.Item; -import game.item.ItemStack; -import game.renderer.GlState; -import game.renderer.blockmodel.Transforms; -import game.renderer.texture.TextureMap; +import client.renderer.GlState; +import client.renderer.texture.TextureMap; +import common.entity.Entity; +import common.item.Item; +import common.item.ItemStack; +import common.model.Transforms; public class RenderItemEntity extends Render diff --git a/java/src/game/renderer/entity/RenderLeashKnot.java b/client/src/main/java/client/renderer/entity/RenderLeashKnot.java similarity index 89% rename from java/src/game/renderer/entity/RenderLeashKnot.java rename to client/src/main/java/client/renderer/entity/RenderLeashKnot.java index ee7afa0..9a03683 100755 --- a/java/src/game/renderer/entity/RenderLeashKnot.java +++ b/client/src/main/java/client/renderer/entity/RenderLeashKnot.java @@ -1,10 +1,10 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.item.EntityLeashKnot; -import game.renderer.GlState; -import game.renderer.model.ModelLeashKnot; +import client.renderer.GlState; +import client.renderer.model.ModelLeashKnot; +import common.entity.item.EntityLeashKnot; public class RenderLeashKnot extends Render diff --git a/java/src/game/renderer/entity/RenderLightning.java b/client/src/main/java/client/renderer/entity/RenderLightning.java similarity index 94% rename from java/src/game/renderer/entity/RenderLightning.java rename to client/src/main/java/client/renderer/entity/RenderLightning.java index d520f5a..3cf3319 100755 --- a/java/src/game/renderer/entity/RenderLightning.java +++ b/client/src/main/java/client/renderer/entity/RenderLightning.java @@ -1,13 +1,13 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.effect.EntityLightning; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.rng.Random; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import common.entity.effect.EntityLightning; +import common.rng.Random; public class RenderLightning extends Render diff --git a/java/src/game/renderer/entity/RenderLiving.java b/client/src/main/java/client/renderer/entity/RenderLiving.java similarity index 94% rename from java/src/game/renderer/entity/RenderLiving.java rename to client/src/main/java/client/renderer/entity/RenderLiving.java index afb8281..4e308dd 100755 --- a/java/src/game/renderer/entity/RenderLiving.java +++ b/client/src/main/java/client/renderer/entity/RenderLiving.java @@ -1,17 +1,17 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import game.entity.Entity; -import game.entity.item.EntityLeashKnot; -import game.entity.types.EntityLiving; -import game.renderer.DefaultVertexFormats; -import game.renderer.Frustum; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.renderer.model.ModelBase; +import client.renderer.DefaultVertexFormats; +import client.renderer.Frustum; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.renderer.model.ModelBase; +import common.entity.Entity; +import common.entity.item.EntityLeashKnot; +import common.entity.types.EntityLiving; public abstract class RenderLiving extends RendererLivingEntity { public RenderLiving(RenderManager manager, ModelBase model) { diff --git a/java/src/game/renderer/entity/RenderManager.java b/client/src/main/java/client/renderer/entity/RenderManager.java similarity index 94% rename from java/src/game/renderer/entity/RenderManager.java rename to client/src/main/java/client/renderer/entity/RenderManager.java index 26cf651..6a373ce 100755 --- a/java/src/game/renderer/entity/RenderManager.java +++ b/client/src/main/java/client/renderer/entity/RenderManager.java @@ -1,26 +1,25 @@ -package game.renderer.entity; +package client.renderer.entity; import java.util.Map; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import game.collect.Maps; - -import game.Game; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.init.EntityRegistry; -import game.init.SpeciesRegistry.ModelType; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.RenderGlobal; -import game.renderer.Tessellator; -import game.renderer.texture.TextureManager; -import game.world.BoundingBox; -import game.world.Vec3; -import game.world.World; +import client.Client; +import client.init.RenderRegistry; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.RenderGlobal; +import client.renderer.Tessellator; +import client.renderer.texture.TextureManager; +import common.collect.Maps; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.init.SpeciesRegistry.ModelType; +import common.util.BoundingBox; +import common.util.Vec3; +import common.world.World; public class RenderManager { @@ -56,7 +55,7 @@ public class RenderManager public Entity pointedEntity; public float playerViewY; public float playerViewX; - public Game gm; + public Client gm; public double viewerPosX; public double viewerPosY; public double viewerPosZ; @@ -69,7 +68,7 @@ public class RenderManager public RenderManager(TextureManager renderEngineIn, RenderItem itemRendererIn) { this.renderEngine = renderEngineIn; - EntityRegistry.registerRenderers(this.entityRenderMap, this.models, this, itemRendererIn); + RenderRegistry.registerRenderers(this.entityRenderMap, this.models, this, itemRendererIn); for(RenderNpc render : this.models.values()) { render.initSegments(); } @@ -146,7 +145,7 @@ public class RenderManager return this.models.get(model); } - public void cacheActiveRenderInfo(World worldIn, Entity livingPlayerIn, Entity pointedEntityIn, Game optionsIn, float partialTicks) + public void cacheActiveRenderInfo(World worldIn, Entity livingPlayerIn, Entity pointedEntityIn, Client optionsIn, float partialTicks) { this.worldObj = worldIn; this.gm = optionsIn; diff --git a/java/src/game/renderer/entity/RenderMinecart.java b/client/src/main/java/client/renderer/entity/RenderMinecart.java similarity index 90% rename from java/src/game/renderer/entity/RenderMinecart.java rename to client/src/main/java/client/renderer/entity/RenderMinecart.java index 88a70fa..6844f89 100755 --- a/java/src/game/renderer/entity/RenderMinecart.java +++ b/client/src/main/java/client/renderer/entity/RenderMinecart.java @@ -1,16 +1,16 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.Game; -import game.entity.item.EntityCart; -import game.renderer.GlState; -import game.renderer.model.ModelBase; -import game.renderer.model.ModelMinecart; -import game.renderer.texture.TextureMap; -import game.util.ExtMath; -import game.world.State; -import game.world.Vec3; +import client.Client; +import client.renderer.GlState; +import client.renderer.model.ModelBase; +import client.renderer.model.ModelMinecart; +import client.renderer.texture.TextureMap; +import common.entity.item.EntityCart; +import common.util.ExtMath; +import common.util.Vec3; +import common.world.State; public class RenderMinecart extends Render { @@ -123,7 +123,7 @@ public class RenderMinecart extends Render protected void func_180560_a(T minecart, float partialTicks, State state) { GL11.glPushMatrix(); - Game.getGame().getBlockRendererDispatcher().renderBlockBrightness(state, minecart.getBrightness(partialTicks)); + Client.CLIENT.getBlockRendererDispatcher().renderBlockBrightness(state, minecart.getBrightness(partialTicks)); GL11.glPopMatrix(); } } diff --git a/java/src/game/renderer/entity/RenderMooshroom.java b/client/src/main/java/client/renderer/entity/RenderMooshroom.java similarity index 77% rename from java/src/game/renderer/entity/RenderMooshroom.java rename to client/src/main/java/client/renderer/entity/RenderMooshroom.java index 75701b3..28793f3 100755 --- a/java/src/game/renderer/entity/RenderMooshroom.java +++ b/client/src/main/java/client/renderer/entity/RenderMooshroom.java @@ -1,8 +1,8 @@ -package game.renderer.entity; +package client.renderer.entity; -import game.entity.animal.EntityMooshroom; -import game.renderer.layers.LayerMooshroomMushroom; -import game.renderer.model.ModelBase; +import client.renderer.layers.LayerMooshroomMushroom; +import client.renderer.model.ModelBase; +import common.entity.animal.EntityMooshroom; public class RenderMooshroom extends RenderLiving diff --git a/java/src/game/renderer/entity/RenderMouse.java b/client/src/main/java/client/renderer/entity/RenderMouse.java similarity index 77% rename from java/src/game/renderer/entity/RenderMouse.java rename to client/src/main/java/client/renderer/entity/RenderMouse.java index 5b07a11..5c266dd 100755 --- a/java/src/game/renderer/entity/RenderMouse.java +++ b/client/src/main/java/client/renderer/entity/RenderMouse.java @@ -1,7 +1,7 @@ -package game.renderer.entity; +package client.renderer.entity; -import game.entity.animal.EntityMouse; -import game.renderer.model.ModelBase; +import client.renderer.model.ModelBase; +import common.entity.animal.EntityMouse; public class RenderMouse extends RenderLiving diff --git a/java/src/game/renderer/entity/RenderNpc.java b/client/src/main/java/client/renderer/entity/RenderNpc.java similarity index 94% rename from java/src/game/renderer/entity/RenderNpc.java rename to client/src/main/java/client/renderer/entity/RenderNpc.java index 72c4b64..7462455 100755 --- a/java/src/game/renderer/entity/RenderNpc.java +++ b/client/src/main/java/client/renderer/entity/RenderNpc.java @@ -1,10 +1,11 @@ -package game.renderer.entity; +package client.renderer.entity; import java.util.ArrayList; -import game.entity.npc.EntityNPC; -import game.renderer.model.ModelBase; -import game.renderer.texture.EntityTexManager; +import client.renderer.model.ModelBase; +import client.renderer.texture.EntityTexManager; +import common.entity.npc.EntityNPC; +import common.network.IPlayer; public abstract class RenderNpc extends RenderLiving @@ -64,7 +65,7 @@ public abstract class RenderNpc extends RenderLiving TexList alpha = new TexList(); this.getSegments(opaque, alpha); this.compressedSize = alpha.getSize() * 4 + opaque.getSize() * 3; - if(this.compressedSize > EntityTexManager.MAX_SKIN_SIZE) + if(this.compressedSize > IPlayer.MAX_SKIN_SIZE) throw new IllegalArgumentException("Renderer " + this.getClass() + ": Textur zu Groß (" + this.compressedSize + " Bytes)"); this.opaqueSegments = opaque.compile(); this.alphaSegments = alpha.compile(); @@ -91,7 +92,7 @@ public abstract class RenderNpc extends RenderLiving protected String getEntityTexture(EntityNPC entity) { - return entity.getLocationSkin(); + return EntityTexManager.getSkin(entity); } public void renderPlayerArm(EntityNPC entity) diff --git a/java/src/game/renderer/entity/RenderOcelot.java b/client/src/main/java/client/renderer/entity/RenderOcelot.java similarity index 93% rename from java/src/game/renderer/entity/RenderOcelot.java rename to client/src/main/java/client/renderer/entity/RenderOcelot.java index 5b9ce7c..09edb56 100755 --- a/java/src/game/renderer/entity/RenderOcelot.java +++ b/client/src/main/java/client/renderer/entity/RenderOcelot.java @@ -1,9 +1,9 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.animal.EntityOcelot; -import game.renderer.model.ModelBase; +import client.renderer.model.ModelBase; +import common.entity.animal.EntityOcelot; public class RenderOcelot extends RenderLiving diff --git a/java/src/game/renderer/entity/RenderPig.java b/client/src/main/java/client/renderer/entity/RenderPig.java similarity index 78% rename from java/src/game/renderer/entity/RenderPig.java rename to client/src/main/java/client/renderer/entity/RenderPig.java index 73d73a6..be614ee 100755 --- a/java/src/game/renderer/entity/RenderPig.java +++ b/client/src/main/java/client/renderer/entity/RenderPig.java @@ -1,8 +1,8 @@ -package game.renderer.entity; +package client.renderer.entity; -import game.entity.animal.EntityPig; -import game.renderer.layers.LayerSaddle; -import game.renderer.model.ModelBase; +import client.renderer.layers.LayerSaddle; +import client.renderer.model.ModelBase; +import common.entity.animal.EntityPig; public class RenderPig extends RenderLiving diff --git a/java/src/game/renderer/entity/RenderPotion.java b/client/src/main/java/client/renderer/entity/RenderPotion.java similarity index 73% rename from java/src/game/renderer/entity/RenderPotion.java rename to client/src/main/java/client/renderer/entity/RenderPotion.java index 06de9c3..4256783 100755 --- a/java/src/game/renderer/entity/RenderPotion.java +++ b/client/src/main/java/client/renderer/entity/RenderPotion.java @@ -1,8 +1,8 @@ -package game.renderer.entity; +package client.renderer.entity; -import game.entity.projectile.EntityPotion; -import game.init.Items; -import game.item.ItemStack; +import common.entity.projectile.EntityPotion; +import common.init.Items; +import common.item.ItemStack; public class RenderPotion extends RenderItemEntity { diff --git a/java/src/game/renderer/entity/RenderRabbit.java b/client/src/main/java/client/renderer/entity/RenderRabbit.java similarity index 88% rename from java/src/game/renderer/entity/RenderRabbit.java rename to client/src/main/java/client/renderer/entity/RenderRabbit.java index 3796049..7527e5a 100755 --- a/java/src/game/renderer/entity/RenderRabbit.java +++ b/client/src/main/java/client/renderer/entity/RenderRabbit.java @@ -1,8 +1,8 @@ -package game.renderer.entity; +package client.renderer.entity; -import game.color.TextColor; -import game.entity.animal.EntityRabbit; -import game.renderer.model.ModelBase; +import client.renderer.model.ModelBase; +import common.color.TextColor; +import common.entity.animal.EntityRabbit; public class RenderRabbit extends RenderLiving { diff --git a/java/src/game/renderer/entity/RenderSheep.java b/client/src/main/java/client/renderer/entity/RenderSheep.java similarity index 78% rename from java/src/game/renderer/entity/RenderSheep.java rename to client/src/main/java/client/renderer/entity/RenderSheep.java index e6289a0..c9277db 100755 --- a/java/src/game/renderer/entity/RenderSheep.java +++ b/client/src/main/java/client/renderer/entity/RenderSheep.java @@ -1,8 +1,8 @@ -package game.renderer.entity; +package client.renderer.entity; -import game.entity.animal.EntitySheep; -import game.renderer.layers.LayerSheepWool; -import game.renderer.model.ModelBase; +import client.renderer.layers.LayerSheepWool; +import client.renderer.model.ModelBase; +import common.entity.animal.EntitySheep; public class RenderSheep extends RenderLiving diff --git a/java/src/game/renderer/entity/RenderSlime.java b/client/src/main/java/client/renderer/entity/RenderSlime.java similarity index 94% rename from java/src/game/renderer/entity/RenderSlime.java rename to client/src/main/java/client/renderer/entity/RenderSlime.java index 4cfc046..e76df43 100755 --- a/java/src/game/renderer/entity/RenderSlime.java +++ b/client/src/main/java/client/renderer/entity/RenderSlime.java @@ -1,11 +1,11 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.npc.EntityNPC; -import game.entity.npc.EntitySlime; -import game.renderer.layers.LayerSlimeGel; -import game.renderer.model.ModelSlime; +import client.renderer.layers.LayerSlimeGel; +import client.renderer.model.ModelSlime; +import common.entity.npc.EntityNPC; +import common.entity.npc.EntitySlime; public class RenderSlime extends RenderNpc diff --git a/java/src/game/renderer/entity/RenderSpaceMarine.java b/client/src/main/java/client/renderer/entity/RenderSpaceMarine.java similarity index 92% rename from java/src/game/renderer/entity/RenderSpaceMarine.java rename to client/src/main/java/client/renderer/entity/RenderSpaceMarine.java index 083ccd8..864b24c 100755 --- a/java/src/game/renderer/entity/RenderSpaceMarine.java +++ b/client/src/main/java/client/renderer/entity/RenderSpaceMarine.java @@ -1,13 +1,13 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.npc.EntityNPC; -import game.item.ItemAction; -import game.item.ItemStack; -import game.renderer.layers.LayerArrow; -import game.renderer.layers.LayerHeldItem; -import game.renderer.model.ModelSpaceMarine; +import client.renderer.layers.LayerArrow; +import client.renderer.layers.LayerHeldItem; +import client.renderer.model.ModelSpaceMarine; +import common.entity.npc.EntityNPC; +import common.item.ItemAction; +import common.item.ItemStack; public class RenderSpaceMarine extends RenderNpc diff --git a/java/src/game/renderer/entity/RenderSquid.java b/client/src/main/java/client/renderer/entity/RenderSquid.java similarity index 92% rename from java/src/game/renderer/entity/RenderSquid.java rename to client/src/main/java/client/renderer/entity/RenderSquid.java index d122968..15f3c96 100755 --- a/java/src/game/renderer/entity/RenderSquid.java +++ b/client/src/main/java/client/renderer/entity/RenderSquid.java @@ -1,9 +1,9 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.entity.animal.EntitySquid; -import game.renderer.model.ModelBase; +import client.renderer.model.ModelBase; +import common.entity.animal.EntitySquid; public class RenderSquid extends RenderLiving diff --git a/java/src/game/renderer/entity/RenderTntMinecart.java b/client/src/main/java/client/renderer/entity/RenderTntMinecart.java similarity index 80% rename from java/src/game/renderer/entity/RenderTntMinecart.java rename to client/src/main/java/client/renderer/entity/RenderTntMinecart.java index f8ac46c..9e48e44 100755 --- a/java/src/game/renderer/entity/RenderTntMinecart.java +++ b/client/src/main/java/client/renderer/entity/RenderTntMinecart.java @@ -1,14 +1,14 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.Game; -import game.entity.item.EntityTntCart; -import game.init.Blocks; -import game.renderer.BlockRenderer; -import game.renderer.GlState; -import game.util.ExtMath; -import game.world.State; +import client.Client; +import client.renderer.BlockRenderer; +import client.renderer.GlState; +import common.entity.item.EntityTntCart; +import common.init.Blocks; +import common.util.ExtMath; +import common.world.State; public class RenderTntMinecart extends RenderMinecart { @@ -35,7 +35,7 @@ public class RenderTntMinecart extends RenderMinecart if (i > -1 && i / 5 % 2 == 0) { - BlockRenderer blockrendererdispatcher = Game.getGame().getBlockRendererDispatcher(); + BlockRenderer blockrendererdispatcher = Client.CLIENT.getBlockRendererDispatcher(); GlState.disableTexture2D(); GlState.disableLighting(); GlState.enableBlend(); diff --git a/java/src/game/renderer/entity/RenderTntPrimed.java b/client/src/main/java/client/renderer/entity/RenderTntPrimed.java similarity index 85% rename from java/src/game/renderer/entity/RenderTntPrimed.java rename to client/src/main/java/client/renderer/entity/RenderTntPrimed.java index 9ecee6e..616fd3b 100755 --- a/java/src/game/renderer/entity/RenderTntPrimed.java +++ b/client/src/main/java/client/renderer/entity/RenderTntPrimed.java @@ -1,15 +1,15 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; -import game.Game; -import game.block.BlockTNT; -import game.entity.item.EntityTnt; -import game.init.Blocks; -import game.renderer.BlockRenderer; -import game.renderer.GlState; -import game.renderer.texture.TextureMap; -import game.util.ExtMath; +import client.Client; +import client.renderer.BlockRenderer; +import client.renderer.GlState; +import client.renderer.texture.TextureMap; +import common.block.tech.BlockTNT; +import common.entity.item.EntityTnt; +import common.init.Blocks; +import common.util.ExtMath; public class RenderTntPrimed extends Render @@ -25,7 +25,7 @@ public class RenderTntPrimed extends Render */ public void doRender(EntityTnt entity, double x, double y, double z, float partialTicks) { - BlockRenderer blockrendererdispatcher = Game.getGame().getBlockRendererDispatcher(); + BlockRenderer blockrendererdispatcher = Client.CLIENT.getBlockRendererDispatcher(); GL11.glPushMatrix(); GL11.glTranslatef((float)x, (float)y + 0.5F, (float)z); diff --git a/java/src/game/renderer/entity/RenderWolf.java b/client/src/main/java/client/renderer/entity/RenderWolf.java similarity index 88% rename from java/src/game/renderer/entity/RenderWolf.java rename to client/src/main/java/client/renderer/entity/RenderWolf.java index f9cae80..3fb1bf1 100755 --- a/java/src/game/renderer/entity/RenderWolf.java +++ b/client/src/main/java/client/renderer/entity/RenderWolf.java @@ -1,9 +1,9 @@ -package game.renderer.entity; +package client.renderer.entity; -import game.entity.animal.EntityWolf; -import game.renderer.GlState; -import game.renderer.layers.LayerWolfCollar; -import game.renderer.model.ModelBase; +import client.renderer.GlState; +import client.renderer.layers.LayerWolfCollar; +import client.renderer.model.ModelBase; +import common.entity.animal.EntityWolf; public class RenderWolf extends RenderLiving diff --git a/java/src/game/renderer/entity/RenderXpOrb.java b/client/src/main/java/client/renderer/entity/RenderXpOrb.java similarity index 93% rename from java/src/game/renderer/entity/RenderXpOrb.java rename to client/src/main/java/client/renderer/entity/RenderXpOrb.java index 43252b2..815456d 100755 --- a/java/src/game/renderer/entity/RenderXpOrb.java +++ b/client/src/main/java/client/renderer/entity/RenderXpOrb.java @@ -1,14 +1,14 @@ -package game.renderer.entity; +package client.renderer.entity; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import game.entity.item.EntityXp; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.util.ExtMath; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import common.entity.item.EntityXp; +import common.util.ExtMath; public class RenderXpOrb extends Render diff --git a/java/src/game/renderer/entity/RendererLivingEntity.java b/client/src/main/java/client/renderer/entity/RendererLivingEntity.java similarity index 96% rename from java/src/game/renderer/entity/RendererLivingEntity.java rename to client/src/main/java/client/renderer/entity/RendererLivingEntity.java index 3034ba3..26c5539 100755 --- a/java/src/game/renderer/entity/RendererLivingEntity.java +++ b/client/src/main/java/client/renderer/entity/RendererLivingEntity.java @@ -1,4 +1,4 @@ -package game.renderer.entity; +package client.renderer.entity; import java.nio.ByteBuffer; import java.nio.ByteOrder; @@ -8,23 +8,22 @@ import java.util.List; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import game.collect.Lists; - -import game.color.TextColor; -import game.entity.Entity; -import game.entity.item.EntityCrystal; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.log.Log; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.ItemRenderer; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.renderer.layers.LayerRenderer; -import game.renderer.model.ModelBase; -import game.renderer.texture.DynamicTexture; -import game.util.ExtMath; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.ItemRenderer; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.renderer.layers.LayerRenderer; +import client.renderer.model.ModelBase; +import client.renderer.texture.DynamicTexture; +import common.collect.Lists; +import common.color.TextColor; +import common.entity.Entity; +import common.entity.item.EntityCrystal; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.log.Log; +import common.util.ExtMath; public abstract class RendererLivingEntity extends Render { @@ -183,7 +182,7 @@ public abstract class RendererLivingEntity extends Rende } catch (Exception exception) { - Log.JNI.error((Throwable)exception, (String)"Konnte Objekt nicht rendern"); + Log.RENDER.error((Throwable)exception, (String)"Konnte Objekt nicht rendern"); } GlState.setActiveTexture(GL13.GL_TEXTURE1); diff --git a/java/src/game/renderer/layers/LayerArachnoidArmor.java b/client/src/main/java/client/renderer/layers/LayerArachnoidArmor.java similarity index 80% rename from java/src/game/renderer/layers/LayerArachnoidArmor.java rename to client/src/main/java/client/renderer/layers/LayerArachnoidArmor.java index 9673886..52e8ef5 100755 --- a/java/src/game/renderer/layers/LayerArachnoidArmor.java +++ b/client/src/main/java/client/renderer/layers/LayerArachnoidArmor.java @@ -1,7 +1,7 @@ -package game.renderer.layers; +package client.renderer.layers; -import game.renderer.entity.RendererLivingEntity; -import game.renderer.model.ModelBiped; +import client.renderer.entity.RendererLivingEntity; +import client.renderer.model.ModelBiped; public class LayerArachnoidArmor extends LayerArmor { diff --git a/java/src/game/renderer/layers/LayerArmor.java b/client/src/main/java/client/renderer/layers/LayerArmor.java similarity index 96% rename from java/src/game/renderer/layers/LayerArmor.java rename to client/src/main/java/client/renderer/layers/LayerArmor.java index 7780453..35f1280 100755 --- a/java/src/game/renderer/layers/LayerArmor.java +++ b/client/src/main/java/client/renderer/layers/LayerArmor.java @@ -1,14 +1,14 @@ -package game.renderer.layers; +package client.renderer.layers; import org.lwjgl.opengl.GL11; -import game.entity.types.EntityLiving; -import game.item.ItemArmor; -import game.item.ItemStack; -import game.renderer.GlState; -import game.renderer.entity.RendererLivingEntity; -import game.renderer.model.ModelArmor; -import game.renderer.model.ModelBiped; +import client.renderer.GlState; +import client.renderer.entity.RendererLivingEntity; +import client.renderer.model.ModelArmor; +import client.renderer.model.ModelBiped; +import common.entity.types.EntityLiving; +import common.item.ItemArmor; +import common.item.ItemStack; public class LayerArmor implements LayerRenderer { diff --git a/java/src/game/renderer/layers/LayerArrow.java b/client/src/main/java/client/renderer/layers/LayerArrow.java similarity index 87% rename from java/src/game/renderer/layers/LayerArrow.java rename to client/src/main/java/client/renderer/layers/LayerArrow.java index 8ef39b7..6fa6589 100755 --- a/java/src/game/renderer/layers/LayerArrow.java +++ b/client/src/main/java/client/renderer/layers/LayerArrow.java @@ -1,16 +1,16 @@ -package game.renderer.layers; +package client.renderer.layers; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.entity.projectile.EntityArrow; -import game.entity.types.EntityLiving; -import game.renderer.ItemRenderer; -import game.renderer.entity.RendererLivingEntity; -import game.renderer.model.ModelBox; -import game.renderer.model.ModelRenderer; -import game.rng.Random; -import game.util.ExtMath; +import client.renderer.ItemRenderer; +import client.renderer.entity.RendererLivingEntity; +import client.renderer.model.ModelBox; +import client.renderer.model.ModelRenderer; +import common.entity.Entity; +import common.entity.projectile.EntityArrow; +import common.entity.types.EntityLiving; +import common.rng.Random; +import common.util.ExtMath; public class LayerArrow implements LayerRenderer { diff --git a/java/src/game/renderer/layers/LayerCape.java b/client/src/main/java/client/renderer/layers/LayerCape.java similarity index 89% rename from java/src/game/renderer/layers/LayerCape.java rename to client/src/main/java/client/renderer/layers/LayerCape.java index 986284d..495e678 100755 --- a/java/src/game/renderer/layers/LayerCape.java +++ b/client/src/main/java/client/renderer/layers/LayerCape.java @@ -1,12 +1,13 @@ -package game.renderer.layers; +package client.renderer.layers; import org.lwjgl.opengl.GL11; -import game.entity.npc.EntityNPC; -import game.renderer.GlState; -import game.renderer.entity.RenderHumanoid; -import game.renderer.model.ModelRenderer; -import game.util.ExtMath; +import client.renderer.GlState; +import client.renderer.entity.RenderHumanoid; +import client.renderer.model.ModelRenderer; +import client.renderer.texture.EntityTexManager; +import common.entity.npc.EntityNPC; +import common.util.ExtMath; public class LayerCape implements LayerRenderer { @@ -28,9 +29,9 @@ public class LayerCape implements LayerRenderer { if(/* !entitylivingbaseIn.isInvisible() && */ // entitylivingbaseIn.isWearing(ModelPart.CAPE) // && - entitylivingbaseIn.getLocationCape() != null) { + EntityTexManager.getCape(entitylivingbaseIn) != null) { GlState.color(1.0F, 1.0F, 1.0F, 1.0F); - this.renderer.bindTexture(entitylivingbaseIn.getLocationCape()); + this.renderer.bindTexture(EntityTexManager.getCape(entitylivingbaseIn)); GL11.glPushMatrix(); GL11.glTranslatef(0.0F, 0.0F, 0.125F); if(entitylivingbaseIn.isPlayer()) { diff --git a/java/src/game/renderer/layers/LayerCharge.java b/client/src/main/java/client/renderer/layers/LayerCharge.java similarity index 91% rename from java/src/game/renderer/layers/LayerCharge.java rename to client/src/main/java/client/renderer/layers/LayerCharge.java index 80dcb6b..2bc6578 100755 --- a/java/src/game/renderer/layers/LayerCharge.java +++ b/client/src/main/java/client/renderer/layers/LayerCharge.java @@ -1,11 +1,11 @@ -package game.renderer.layers; +package client.renderer.layers; import org.lwjgl.opengl.GL11; -import game.entity.npc.EntityNPC; -import game.renderer.GlState; -import game.renderer.entity.RenderHumanoid; -import game.renderer.model.ModelCharge; +import client.renderer.GlState; +import client.renderer.entity.RenderHumanoid; +import client.renderer.model.ModelCharge; +import common.entity.npc.EntityNPC; public class LayerCharge implements LayerRenderer diff --git a/java/src/game/renderer/layers/LayerEnderDragonEyes.java b/client/src/main/java/client/renderer/layers/LayerEnderDragonEyes.java similarity index 90% rename from java/src/game/renderer/layers/LayerEnderDragonEyes.java rename to client/src/main/java/client/renderer/layers/LayerEnderDragonEyes.java index 2b3a528..7fb6b27 100755 --- a/java/src/game/renderer/layers/LayerEnderDragonEyes.java +++ b/client/src/main/java/client/renderer/layers/LayerEnderDragonEyes.java @@ -1,11 +1,11 @@ -package game.renderer.layers; +package client.renderer.layers; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL13; -import game.entity.animal.EntityDragon; -import game.renderer.GlState; -import game.renderer.entity.RenderDragon; +import client.renderer.GlState; +import client.renderer.entity.RenderDragon; +import common.entity.animal.EntityDragon; public class LayerEnderDragonEyes implements LayerRenderer diff --git a/java/src/game/renderer/layers/LayerEntityBreak.java b/client/src/main/java/client/renderer/layers/LayerEntityBreak.java similarity index 91% rename from java/src/game/renderer/layers/LayerEntityBreak.java rename to client/src/main/java/client/renderer/layers/LayerEntityBreak.java index 03aa1e1..a705c6d 100755 --- a/java/src/game/renderer/layers/LayerEntityBreak.java +++ b/client/src/main/java/client/renderer/layers/LayerEntityBreak.java @@ -1,14 +1,14 @@ -package game.renderer.layers; +package client.renderer.layers; import org.lwjgl.opengl.GL11; -import game.entity.animal.EntityDragon; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.ItemRenderer; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.rng.Random; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.ItemRenderer; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import common.entity.animal.EntityDragon; +import common.rng.Random; public class LayerEntityBreak implements LayerRenderer { diff --git a/java/src/game/renderer/layers/LayerExtra.java b/client/src/main/java/client/renderer/layers/LayerExtra.java similarity index 93% rename from java/src/game/renderer/layers/LayerExtra.java rename to client/src/main/java/client/renderer/layers/LayerExtra.java index ff91870..ebfe2bb 100755 --- a/java/src/game/renderer/layers/LayerExtra.java +++ b/client/src/main/java/client/renderer/layers/LayerExtra.java @@ -1,19 +1,19 @@ -package game.renderer.layers; +package client.renderer.layers; import java.util.List; import org.lwjgl.opengl.GL11; -import game.collect.Lists; - -import game.Game; -import game.entity.npc.EntityNPC; -import game.init.SpeciesRegistry.ModelType; -import game.renderer.GlState; -import game.renderer.blockmodel.ModelGenerator; -import game.renderer.model.ModelBox; -import game.renderer.model.ModelHumanoid; -import game.renderer.model.ModelRenderer; +import client.Client; +import client.renderer.GlState; +import client.renderer.blockmodel.ModelGenerator; +import client.renderer.model.ModelBox; +import client.renderer.model.ModelHumanoid; +import client.renderer.model.ModelRenderer; +import client.renderer.texture.EntityTexManager; +import common.collect.Lists; +import common.entity.npc.EntityNPC; +import common.init.SpeciesRegistry.ModelType; public class LayerExtra implements LayerRenderer { @@ -62,7 +62,7 @@ public class LayerExtra implements LayerRenderer // if (!entity.isInvisible()) // { GlState.color(1.0F, 1.0F, 1.0F, 1.0F); - Game.getGame().getTextureManager().bindTexture(extended.getLocationSkin()); + Client.CLIENT.getTextureManager().bindTexture(EntityTexManager.getSkin(extended)); GL11.glPushMatrix(); if (entity.isSneakingVisually()) diff --git a/java/src/game/renderer/layers/LayerHeldItem.java b/client/src/main/java/client/renderer/layers/LayerHeldItem.java similarity index 85% rename from java/src/game/renderer/layers/LayerHeldItem.java rename to client/src/main/java/client/renderer/layers/LayerHeldItem.java index 3282fe6..00927e6 100755 --- a/java/src/game/renderer/layers/LayerHeldItem.java +++ b/client/src/main/java/client/renderer/layers/LayerHeldItem.java @@ -1,17 +1,17 @@ -package game.renderer.layers; +package client.renderer.layers; import org.lwjgl.opengl.GL11; -import game.Game; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.item.Item; -import game.item.ItemBlock; -import game.item.ItemStack; -import game.renderer.blockmodel.Transforms; -import game.renderer.entity.RendererLivingEntity; -import game.renderer.model.ModelBiped; +import client.Client; +import client.renderer.entity.RendererLivingEntity; +import client.renderer.model.ModelBiped; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.item.Item; +import common.item.ItemBlock; +import common.item.ItemStack; +import common.model.Transforms; public class LayerHeldItem implements LayerRenderer { @@ -53,7 +53,7 @@ public class LayerHeldItem implements LayerRenderer } Item item = itemstack.getItem(); - Game gm = Game.getGame(); + Client gm = Client.CLIENT; if (item instanceof ItemBlock && item.getBlock().getRenderType() == 2) { diff --git a/java/src/game/renderer/layers/LayerMooshroomMushroom.java b/client/src/main/java/client/renderer/layers/LayerMooshroomMushroom.java similarity index 83% rename from java/src/game/renderer/layers/LayerMooshroomMushroom.java rename to client/src/main/java/client/renderer/layers/LayerMooshroomMushroom.java index e6e421e..424b294 100755 --- a/java/src/game/renderer/layers/LayerMooshroomMushroom.java +++ b/client/src/main/java/client/renderer/layers/LayerMooshroomMushroom.java @@ -1,15 +1,15 @@ -package game.renderer.layers; +package client.renderer.layers; import org.lwjgl.opengl.GL11; -import game.Game; -import game.entity.animal.EntityMooshroom; -import game.init.Blocks; -import game.renderer.BlockRenderer; -import game.renderer.GlState; -import game.renderer.entity.RenderMooshroom; -import game.renderer.model.ModelQuadruped; -import game.renderer.texture.TextureMap; +import client.Client; +import client.renderer.BlockRenderer; +import client.renderer.GlState; +import client.renderer.entity.RenderMooshroom; +import client.renderer.model.ModelQuadruped; +import client.renderer.texture.TextureMap; +import common.entity.animal.EntityMooshroom; +import common.init.Blocks; public class LayerMooshroomMushroom implements LayerRenderer { @@ -24,7 +24,7 @@ public class LayerMooshroomMushroom implements LayerRenderer { if (!entitylivingbaseIn.isChild()) // && !entitylivingbaseIn.isInvisible()) { - BlockRenderer blockrendererdispatcher = Game.getGame().getBlockRendererDispatcher(); + BlockRenderer blockrendererdispatcher = Client.CLIENT.getBlockRendererDispatcher(); this.mooshroomRenderer.bindTexture(TextureMap.locationBlocksTexture); GlState.enableCull(); GlState.cullFace(GL11.GL_FRONT); diff --git a/java/src/game/renderer/layers/LayerPowerRods.java b/client/src/main/java/client/renderer/layers/LayerPowerRods.java similarity index 91% rename from java/src/game/renderer/layers/LayerPowerRods.java rename to client/src/main/java/client/renderer/layers/LayerPowerRods.java index 6e641df..54b45a4 100755 --- a/java/src/game/renderer/layers/LayerPowerRods.java +++ b/client/src/main/java/client/renderer/layers/LayerPowerRods.java @@ -1,10 +1,10 @@ -package game.renderer.layers; +package client.renderer.layers; -import game.entity.npc.EntityNPC; -import game.renderer.GlState; -import game.renderer.entity.RenderHumanoid; -import game.renderer.model.ModelRenderer; -import game.util.ExtMath; +import client.renderer.GlState; +import client.renderer.entity.RenderHumanoid; +import client.renderer.model.ModelRenderer; +import common.entity.npc.EntityNPC; +import common.util.ExtMath; public class LayerPowerRods implements LayerRenderer { diff --git a/java/src/game/renderer/layers/LayerRenderer.java b/client/src/main/java/client/renderer/layers/LayerRenderer.java similarity index 78% rename from java/src/game/renderer/layers/LayerRenderer.java rename to client/src/main/java/client/renderer/layers/LayerRenderer.java index 2ae4c8e..dd5905e 100755 --- a/java/src/game/renderer/layers/LayerRenderer.java +++ b/client/src/main/java/client/renderer/layers/LayerRenderer.java @@ -1,6 +1,6 @@ -package game.renderer.layers; +package client.renderer.layers; -import game.entity.types.EntityLiving; +import common.entity.types.EntityLiving; public interface LayerRenderer { diff --git a/java/src/game/renderer/layers/LayerSaddle.java b/client/src/main/java/client/renderer/layers/LayerSaddle.java similarity index 86% rename from java/src/game/renderer/layers/LayerSaddle.java rename to client/src/main/java/client/renderer/layers/LayerSaddle.java index 20893ac..ce30c6b 100755 --- a/java/src/game/renderer/layers/LayerSaddle.java +++ b/client/src/main/java/client/renderer/layers/LayerSaddle.java @@ -1,8 +1,8 @@ -package game.renderer.layers; +package client.renderer.layers; -import game.entity.animal.EntityPig; -import game.renderer.entity.RenderPig; -import game.renderer.model.ModelPig; +import client.renderer.entity.RenderPig; +import client.renderer.model.ModelPig; +import common.entity.animal.EntityPig; public class LayerSaddle implements LayerRenderer diff --git a/java/src/game/renderer/layers/LayerSheepWool.java b/client/src/main/java/client/renderer/layers/LayerSheepWool.java similarity index 91% rename from java/src/game/renderer/layers/LayerSheepWool.java rename to client/src/main/java/client/renderer/layers/LayerSheepWool.java index 1dd3f87..dd1022c 100755 --- a/java/src/game/renderer/layers/LayerSheepWool.java +++ b/client/src/main/java/client/renderer/layers/LayerSheepWool.java @@ -1,9 +1,9 @@ -package game.renderer.layers; +package client.renderer.layers; -import game.entity.animal.EntitySheep; -import game.renderer.GlState; -import game.renderer.entity.RenderSheep; -import game.renderer.model.ModelSheep1; +import client.renderer.GlState; +import client.renderer.entity.RenderSheep; +import client.renderer.model.ModelSheep1; +import common.entity.animal.EntitySheep; public class LayerSheepWool implements LayerRenderer diff --git a/java/src/game/renderer/layers/LayerSlimeGel.java b/client/src/main/java/client/renderer/layers/LayerSlimeGel.java similarity index 83% rename from java/src/game/renderer/layers/LayerSlimeGel.java rename to client/src/main/java/client/renderer/layers/LayerSlimeGel.java index aceaaf3..7cf892a 100755 --- a/java/src/game/renderer/layers/LayerSlimeGel.java +++ b/client/src/main/java/client/renderer/layers/LayerSlimeGel.java @@ -1,12 +1,12 @@ -package game.renderer.layers; +package client.renderer.layers; import org.lwjgl.opengl.GL11; -import game.entity.npc.EntityNPC; -import game.renderer.GlState; -import game.renderer.entity.RenderSlime; -import game.renderer.model.ModelBase; -import game.renderer.model.ModelSlime; +import client.renderer.GlState; +import client.renderer.entity.RenderSlime; +import client.renderer.model.ModelBase; +import client.renderer.model.ModelSlime; +import common.entity.npc.EntityNPC; public class LayerSlimeGel implements LayerRenderer { diff --git a/java/src/game/renderer/layers/LayerWolfCollar.java b/client/src/main/java/client/renderer/layers/LayerWolfCollar.java similarity index 83% rename from java/src/game/renderer/layers/LayerWolfCollar.java rename to client/src/main/java/client/renderer/layers/LayerWolfCollar.java index 2777896..7d07d87 100755 --- a/java/src/game/renderer/layers/LayerWolfCollar.java +++ b/client/src/main/java/client/renderer/layers/LayerWolfCollar.java @@ -1,10 +1,10 @@ -package game.renderer.layers; +package client.renderer.layers; -import game.color.DyeColor; -import game.entity.animal.EntitySheep; -import game.entity.animal.EntityWolf; -import game.renderer.GlState; -import game.renderer.entity.RenderWolf; +import client.renderer.GlState; +import client.renderer.entity.RenderWolf; +import common.color.DyeColor; +import common.entity.animal.EntitySheep; +import common.entity.animal.EntityWolf; public class LayerWolfCollar implements LayerRenderer diff --git a/java/src/game/renderer/model/ModelArachnoid.java b/client/src/main/java/client/renderer/model/ModelArachnoid.java similarity index 98% rename from java/src/game/renderer/model/ModelArachnoid.java rename to client/src/main/java/client/renderer/model/ModelArachnoid.java index 27b8c24..e828555 100755 --- a/java/src/game/renderer/model/ModelArachnoid.java +++ b/client/src/main/java/client/renderer/model/ModelArachnoid.java @@ -1,9 +1,9 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.util.ExtMath; +import common.entity.Entity; +import common.util.ExtMath; public class ModelArachnoid extends ModelHumanoid { diff --git a/java/src/game/renderer/model/ModelArmor.java b/client/src/main/java/client/renderer/model/ModelArmor.java similarity index 98% rename from java/src/game/renderer/model/ModelArmor.java rename to client/src/main/java/client/renderer/model/ModelArmor.java index edc71cc..69c970a 100755 --- a/java/src/game/renderer/model/ModelArmor.java +++ b/client/src/main/java/client/renderer/model/ModelArmor.java @@ -1,4 +1,4 @@ -package game.renderer.model; +package client.renderer.model; public class ModelArmor extends ModelBiped { public ModelArmor(float size, int arms, int legs) diff --git a/java/src/game/renderer/model/ModelBanner.java b/client/src/main/java/client/renderer/model/ModelBanner.java similarity index 96% rename from java/src/game/renderer/model/ModelBanner.java rename to client/src/main/java/client/renderer/model/ModelBanner.java index 7e9bc2b..bd7157e 100755 --- a/java/src/game/renderer/model/ModelBanner.java +++ b/client/src/main/java/client/renderer/model/ModelBanner.java @@ -1,4 +1,4 @@ -package game.renderer.model; +package client.renderer.model; public class ModelBanner extends ModelBase { diff --git a/java/src/game/renderer/model/ModelBase.java b/client/src/main/java/client/renderer/model/ModelBase.java similarity index 93% rename from java/src/game/renderer/model/ModelBase.java rename to client/src/main/java/client/renderer/model/ModelBase.java index 0793e10..f8f65af 100755 --- a/java/src/game/renderer/model/ModelBase.java +++ b/client/src/main/java/client/renderer/model/ModelBase.java @@ -1,14 +1,13 @@ -package game.renderer.model; +package client.renderer.model; import java.util.List; import java.util.Map; -import game.collect.Lists; -import game.collect.Maps; - -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.rng.Random; +import common.collect.Lists; +import common.collect.Maps; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.rng.Random; public abstract class ModelBase { diff --git a/java/src/game/renderer/model/ModelBat.java b/client/src/main/java/client/renderer/model/ModelBat.java similarity index 97% rename from java/src/game/renderer/model/ModelBat.java rename to client/src/main/java/client/renderer/model/ModelBat.java index 69a398c..80a5c31 100755 --- a/java/src/game/renderer/model/ModelBat.java +++ b/client/src/main/java/client/renderer/model/ModelBat.java @@ -1,8 +1,8 @@ -package game.renderer.model; +package client.renderer.model; -import game.entity.Entity; -import game.entity.animal.EntityBat; -import game.util.ExtMath; +import common.entity.Entity; +import common.entity.animal.EntityBat; +import common.util.ExtMath; public class ModelBat extends ModelBase { diff --git a/java/src/game/renderer/model/ModelBiped.java b/client/src/main/java/client/renderer/model/ModelBiped.java similarity index 98% rename from java/src/game/renderer/model/ModelBiped.java rename to client/src/main/java/client/renderer/model/ModelBiped.java index ca9876d..32801ca 100755 --- a/java/src/game/renderer/model/ModelBiped.java +++ b/client/src/main/java/client/renderer/model/ModelBiped.java @@ -1,10 +1,10 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.util.ExtMath; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.util.ExtMath; public abstract class ModelBiped extends ModelBase { diff --git a/java/src/game/renderer/model/ModelBoat.java b/client/src/main/java/client/renderer/model/ModelBoat.java similarity index 97% rename from java/src/game/renderer/model/ModelBoat.java rename to client/src/main/java/client/renderer/model/ModelBoat.java index 7d5ff91..34a15e4 100755 --- a/java/src/game/renderer/model/ModelBoat.java +++ b/client/src/main/java/client/renderer/model/ModelBoat.java @@ -1,6 +1,6 @@ -package game.renderer.model; +package client.renderer.model; -import game.entity.Entity; +import common.entity.Entity; public class ModelBoat extends ModelBase { diff --git a/java/src/game/renderer/model/ModelBox.java b/client/src/main/java/client/renderer/model/ModelBox.java similarity index 98% rename from java/src/game/renderer/model/ModelBox.java rename to client/src/main/java/client/renderer/model/ModelBox.java index 22d2846..354eaea 100755 --- a/java/src/game/renderer/model/ModelBox.java +++ b/client/src/main/java/client/renderer/model/ModelBox.java @@ -1,8 +1,8 @@ -package game.renderer.model; +package client.renderer.model; -import game.renderer.RenderBuffer; -import game.world.Facing; -import game.world.Vec3; +import client.renderer.RenderBuffer; +import common.util.Facing; +import common.util.Vec3; public class ModelBox { private static Vec3[] getPoints(float x1, float y1, float z1, float x2, float y2, float z2, int dir) { diff --git a/java/src/game/renderer/model/ModelCharge.java b/client/src/main/java/client/renderer/model/ModelCharge.java similarity index 90% rename from java/src/game/renderer/model/ModelCharge.java rename to client/src/main/java/client/renderer/model/ModelCharge.java index 77c507c..3f5def9 100755 --- a/java/src/game/renderer/model/ModelCharge.java +++ b/client/src/main/java/client/renderer/model/ModelCharge.java @@ -1,6 +1,6 @@ -package game.renderer.model; +package client.renderer.model; -import game.entity.Entity; +import common.entity.Entity; public class ModelCharge extends ModelBase { diff --git a/java/src/game/renderer/model/ModelChest.java b/client/src/main/java/client/renderer/model/ModelChest.java similarity index 97% rename from java/src/game/renderer/model/ModelChest.java rename to client/src/main/java/client/renderer/model/ModelChest.java index b3aafa0..bfb5ffe 100755 --- a/java/src/game/renderer/model/ModelChest.java +++ b/client/src/main/java/client/renderer/model/ModelChest.java @@ -1,4 +1,4 @@ -package game.renderer.model; +package client.renderer.model; public class ModelChest extends ModelBase { diff --git a/java/src/game/renderer/model/ModelChicken.java b/client/src/main/java/client/renderer/model/ModelChicken.java similarity index 98% rename from java/src/game/renderer/model/ModelChicken.java rename to client/src/main/java/client/renderer/model/ModelChicken.java index 7fce604..57e7a9f 100755 --- a/java/src/game/renderer/model/ModelChicken.java +++ b/client/src/main/java/client/renderer/model/ModelChicken.java @@ -1,9 +1,9 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.util.ExtMath; +import common.entity.Entity; +import common.util.ExtMath; public class ModelChicken extends ModelBase { diff --git a/java/src/game/renderer/model/ModelCow.java b/client/src/main/java/client/renderer/model/ModelCow.java similarity index 97% rename from java/src/game/renderer/model/ModelCow.java rename to client/src/main/java/client/renderer/model/ModelCow.java index ac19109..3c1f360 100755 --- a/java/src/game/renderer/model/ModelCow.java +++ b/client/src/main/java/client/renderer/model/ModelCow.java @@ -1,4 +1,4 @@ -package game.renderer.model; +package client.renderer.model; public class ModelCow extends ModelQuadruped { diff --git a/java/src/game/renderer/model/ModelCrystal.java b/client/src/main/java/client/renderer/model/ModelCrystal.java similarity index 96% rename from java/src/game/renderer/model/ModelCrystal.java rename to client/src/main/java/client/renderer/model/ModelCrystal.java index 6688da6..9074211 100755 --- a/java/src/game/renderer/model/ModelCrystal.java +++ b/client/src/main/java/client/renderer/model/ModelCrystal.java @@ -1,8 +1,8 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; +import common.entity.Entity; public class ModelCrystal extends ModelBase { diff --git a/java/src/game/renderer/model/ModelDie.java b/client/src/main/java/client/renderer/model/ModelDie.java similarity index 93% rename from java/src/game/renderer/model/ModelDie.java rename to client/src/main/java/client/renderer/model/ModelDie.java index d8f3d03..0f99092 100755 --- a/java/src/game/renderer/model/ModelDie.java +++ b/client/src/main/java/client/renderer/model/ModelDie.java @@ -1,8 +1,8 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; +import common.entity.Entity; public class ModelDie extends ModelBase { diff --git a/java/src/game/renderer/model/ModelDragon.java b/client/src/main/java/client/renderer/model/ModelDragon.java similarity index 98% rename from java/src/game/renderer/model/ModelDragon.java rename to client/src/main/java/client/renderer/model/ModelDragon.java index 45fb3b0..a4d0f76 100755 --- a/java/src/game/renderer/model/ModelDragon.java +++ b/client/src/main/java/client/renderer/model/ModelDragon.java @@ -1,11 +1,11 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.entity.animal.EntityDragon; -import game.entity.types.EntityLiving; -import game.renderer.GlState; +import client.renderer.GlState; +import common.entity.Entity; +import common.entity.animal.EntityDragon; +import common.entity.types.EntityLiving; public class ModelDragon extends ModelBase { diff --git a/client/src/main/java/client/renderer/model/ModelFox.java b/client/src/main/java/client/renderer/model/ModelFox.java new file mode 100644 index 0000000..cedf720 --- /dev/null +++ b/client/src/main/java/client/renderer/model/ModelFox.java @@ -0,0 +1,97 @@ +package client.renderer.model; + +import org.lwjgl.opengl.GL11; + +import common.entity.Entity; +import common.util.ExtMath; + +public class ModelFox extends ModelBase +{ + private final ModelRenderer head; + private final ModelRenderer body; + private final ModelRenderer wolfLeg1; + private final ModelRenderer wolfLeg2; + private final ModelRenderer wolfLeg3; + private final ModelRenderer wolfLeg4; + private final ModelRenderer tail; + + public ModelFox() + { + float f = 0.0F; + this.head = new ModelRenderer(this, 0, 0); + this.head.addBox(-3.0F, -3.0F, -2.0F, 6, 6, 4, f); + this.head.setRotationPoint(-1.0F, 15.5F, -7.0F); + this.body = new ModelRenderer(this, 24, 0); + this.body.addBox(-3.5F, -2.0F, -2.0F, 5, 13, 5, f); + this.body.setRotationPoint(0.0F, 16.0F, -4.0F); + this.wolfLeg1 = new ModelRenderer(this, 0, 18); + this.wolfLeg1.addBox(-1.0F, 0.0F, -1.0F, 2, 6, 2, f); + this.wolfLeg1.setRotationPoint(-2.49F, 18.0F, 5.0F); + this.wolfLeg2 = new ModelRenderer(this, 0, 18); + this.wolfLeg2.addBox(-1.0F, 0.0F, -1.0F, 2, 6, 2, f); + this.wolfLeg2.setRotationPoint(0.49F, 18.0F, 5.0F); + this.wolfLeg3 = new ModelRenderer(this, 0, 18); + this.wolfLeg3.addBox(-1.0F, 0.0F, -1.0F, 2, 6, 2, f); + this.wolfLeg3.setRotationPoint(-2.49F, 18.0F, -4.0F); + this.wolfLeg4 = new ModelRenderer(this, 0, 18); + this.wolfLeg4.addBox(-1.0F, 0.0F, -1.0F, 2, 6, 2, f); + this.wolfLeg4.setRotationPoint(0.49F, 18.0F, -4.0F); + this.tail = new ModelRenderer(this, 9, 18); + this.tail.addBox(-1.5F, 0.0F, -1.0F, 3, 10, 3, f); + this.tail.setRotationPoint(-1.0F, 15.0F, 6.0F); + this.head.setTextureOffset(16, 14).addBox(-3.15F, -4.35F, 0.0F, 2, 2, 1, f); + this.head.setTextureOffset(16, 14).addBox(1.15F, -4.35F, 0.0F, 2, 2, 1, f); + this.head.setTextureOffset(0, 10).addBox(-1.5F, 0.0F, -5.0F, 3, 2, 4, f); + this.head.setTextureOffset(16, 11).addBox(-3.15F, -5.35F, 0.0F, 1, 1, 1, f); + this.head.setTextureOffset(16, 11).addBox(2.15F, -5.35F, 0.0F, 1, 1, 1, f); + } + + public void render(Entity entityIn, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float scale) + { + super.render(entityIn, p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, scale); + this.setRotationAngles(p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, scale, entityIn); + + if (this.isChild) + { + float f = 2.0F; + GL11.glPushMatrix(); + GL11.glTranslatef(0.0F, 3.5F * scale, 2.0F * scale); + this.head.renderWithRotation(scale); + GL11.glPopMatrix(); + GL11.glPushMatrix(); + GL11.glScalef(1.0F / f, 1.0F / f, 1.0F / f); + GL11.glTranslatef(0.0F, 24.0F * scale, 0.0F); + this.body.render(scale); + this.wolfLeg1.render(scale); + this.wolfLeg2.render(scale); + this.wolfLeg3.render(scale); + this.wolfLeg4.render(scale); + this.tail.renderWithRotation(scale); + GL11.glPopMatrix(); + } + else + { + this.head.renderWithRotation(scale); + this.body.render(scale); + this.wolfLeg1.render(scale); + this.wolfLeg2.render(scale); + this.wolfLeg3.render(scale); + this.wolfLeg4.render(scale); + this.tail.renderWithRotation(scale); + } + } + + public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn) + { + super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn); + this.tail.rotateAngleY = ExtMath.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount; + this.body.rotateAngleX = ((float)Math.PI / 2F); + this.wolfLeg1.rotateAngleX = ExtMath.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount; + this.wolfLeg2.rotateAngleX = ExtMath.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount; + this.wolfLeg3.rotateAngleX = ExtMath.cos(limbSwing * 0.6662F + (float)Math.PI) * 1.4F * limbSwingAmount; + this.wolfLeg4.rotateAngleX = ExtMath.cos(limbSwing * 0.6662F) * 1.4F * limbSwingAmount; + this.head.rotateAngleX = headPitch / (180F / (float)Math.PI); + this.head.rotateAngleY = netHeadYaw / (180F / (float)Math.PI); + this.tail.rotateAngleX = (float)Math.PI / 2.5F; + } +} diff --git a/java/src/game/renderer/model/ModelHead.java b/client/src/main/java/client/renderer/model/ModelHead.java similarity index 96% rename from java/src/game/renderer/model/ModelHead.java rename to client/src/main/java/client/renderer/model/ModelHead.java index 3a48d0f..7f0c6f5 100755 --- a/java/src/game/renderer/model/ModelHead.java +++ b/client/src/main/java/client/renderer/model/ModelHead.java @@ -1,6 +1,6 @@ -package game.renderer.model; +package client.renderer.model; -import game.entity.Entity; +import common.entity.Entity; public class ModelHead extends ModelBase { diff --git a/java/src/game/renderer/model/ModelHorse.java b/client/src/main/java/client/renderer/model/ModelHorse.java similarity index 99% rename from java/src/game/renderer/model/ModelHorse.java rename to client/src/main/java/client/renderer/model/ModelHorse.java index af28039..9dc1003 100755 --- a/java/src/game/renderer/model/ModelHorse.java +++ b/client/src/main/java/client/renderer/model/ModelHorse.java @@ -1,11 +1,11 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.entity.animal.EntityHorse; -import game.entity.types.EntityLiving; -import game.util.ExtMath; +import common.entity.Entity; +import common.entity.animal.EntityHorse; +import common.entity.types.EntityLiving; +import common.util.ExtMath; public class ModelHorse extends ModelBase { diff --git a/java/src/game/renderer/model/ModelHumanoid.java b/client/src/main/java/client/renderer/model/ModelHumanoid.java similarity index 99% rename from java/src/game/renderer/model/ModelHumanoid.java rename to client/src/main/java/client/renderer/model/ModelHumanoid.java index d7333d0..df8f4fb 100755 --- a/java/src/game/renderer/model/ModelHumanoid.java +++ b/client/src/main/java/client/renderer/model/ModelHumanoid.java @@ -1,9 +1,9 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.util.ExtMath; +import common.entity.Entity; +import common.util.ExtMath; public class ModelHumanoid extends ModelBiped { diff --git a/java/src/game/renderer/model/ModelLargeChest.java b/client/src/main/java/client/renderer/model/ModelLargeChest.java similarity index 96% rename from java/src/game/renderer/model/ModelLargeChest.java rename to client/src/main/java/client/renderer/model/ModelLargeChest.java index a037d0c..0c585ac 100755 --- a/java/src/game/renderer/model/ModelLargeChest.java +++ b/client/src/main/java/client/renderer/model/ModelLargeChest.java @@ -1,4 +1,4 @@ -package game.renderer.model; +package client.renderer.model; public class ModelLargeChest extends ModelChest { diff --git a/java/src/game/renderer/model/ModelLeashKnot.java b/client/src/main/java/client/renderer/model/ModelLeashKnot.java similarity index 96% rename from java/src/game/renderer/model/ModelLeashKnot.java rename to client/src/main/java/client/renderer/model/ModelLeashKnot.java index 583988e..c2a413c 100755 --- a/java/src/game/renderer/model/ModelLeashKnot.java +++ b/client/src/main/java/client/renderer/model/ModelLeashKnot.java @@ -1,6 +1,6 @@ -package game.renderer.model; +package client.renderer.model; -import game.entity.Entity; +import common.entity.Entity; public class ModelLeashKnot extends ModelBase { diff --git a/java/src/game/renderer/model/ModelMinecart.java b/client/src/main/java/client/renderer/model/ModelMinecart.java similarity index 97% rename from java/src/game/renderer/model/ModelMinecart.java rename to client/src/main/java/client/renderer/model/ModelMinecart.java index 13aced3..cba48c6 100755 --- a/java/src/game/renderer/model/ModelMinecart.java +++ b/client/src/main/java/client/renderer/model/ModelMinecart.java @@ -1,6 +1,6 @@ -package game.renderer.model; +package client.renderer.model; -import game.entity.Entity; +import common.entity.Entity; public class ModelMinecart extends ModelBase { diff --git a/java/src/game/renderer/model/ModelMouse.java b/client/src/main/java/client/renderer/model/ModelMouse.java similarity index 98% rename from java/src/game/renderer/model/ModelMouse.java rename to client/src/main/java/client/renderer/model/ModelMouse.java index 0693896..5cc4e06 100755 --- a/java/src/game/renderer/model/ModelMouse.java +++ b/client/src/main/java/client/renderer/model/ModelMouse.java @@ -1,10 +1,10 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.util.ExtMath; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.util.ExtMath; public class ModelMouse extends ModelBase { diff --git a/java/src/game/renderer/model/ModelOcelot.java b/client/src/main/java/client/renderer/model/ModelOcelot.java similarity index 98% rename from java/src/game/renderer/model/ModelOcelot.java rename to client/src/main/java/client/renderer/model/ModelOcelot.java index 3f289c1..e7765ca 100755 --- a/java/src/game/renderer/model/ModelOcelot.java +++ b/client/src/main/java/client/renderer/model/ModelOcelot.java @@ -1,11 +1,11 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.entity.animal.EntityOcelot; -import game.entity.types.EntityLiving; -import game.util.ExtMath; +import common.entity.Entity; +import common.entity.animal.EntityOcelot; +import common.entity.types.EntityLiving; +import common.util.ExtMath; public class ModelOcelot extends ModelBase { diff --git a/java/src/game/renderer/model/ModelPig.java b/client/src/main/java/client/renderer/model/ModelPig.java similarity index 90% rename from java/src/game/renderer/model/ModelPig.java rename to client/src/main/java/client/renderer/model/ModelPig.java index 476512b..7bf7a8e 100755 --- a/java/src/game/renderer/model/ModelPig.java +++ b/client/src/main/java/client/renderer/model/ModelPig.java @@ -1,4 +1,4 @@ -package game.renderer.model; +package client.renderer.model; public class ModelPig extends ModelQuadruped { diff --git a/java/src/game/renderer/model/ModelQuadruped.java b/client/src/main/java/client/renderer/model/ModelQuadruped.java similarity index 97% rename from java/src/game/renderer/model/ModelQuadruped.java rename to client/src/main/java/client/renderer/model/ModelQuadruped.java index c287c1e..c608f36 100755 --- a/java/src/game/renderer/model/ModelQuadruped.java +++ b/client/src/main/java/client/renderer/model/ModelQuadruped.java @@ -1,9 +1,9 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.util.ExtMath; +import common.entity.Entity; +import common.util.ExtMath; public class ModelQuadruped extends ModelBase { diff --git a/java/src/game/renderer/model/ModelRabbit.java b/client/src/main/java/client/renderer/model/ModelRabbit.java similarity index 97% rename from java/src/game/renderer/model/ModelRabbit.java rename to client/src/main/java/client/renderer/model/ModelRabbit.java index f4efe68..71e7fff 100755 --- a/java/src/game/renderer/model/ModelRabbit.java +++ b/client/src/main/java/client/renderer/model/ModelRabbit.java @@ -1,11 +1,11 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.entity.animal.EntityRabbit; -import game.entity.types.EntityLiving; -import game.util.ExtMath; +import common.entity.Entity; +import common.entity.animal.EntityRabbit; +import common.entity.types.EntityLiving; +import common.util.ExtMath; public class ModelRabbit extends ModelBase { private final ModelRenderer rabbitLeftFoot; diff --git a/java/src/game/renderer/model/ModelRenderer.java b/client/src/main/java/client/renderer/model/ModelRenderer.java similarity index 99% rename from java/src/game/renderer/model/ModelRenderer.java rename to client/src/main/java/client/renderer/model/ModelRenderer.java index 0c0123b..330ff92 100755 --- a/java/src/game/renderer/model/ModelRenderer.java +++ b/client/src/main/java/client/renderer/model/ModelRenderer.java @@ -1,13 +1,12 @@ -package game.renderer.model; +package client.renderer.model; import java.util.List; import org.lwjgl.opengl.GL11; -import game.collect.Lists; - -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import common.collect.Lists; public class ModelRenderer { diff --git a/java/src/game/renderer/model/ModelSheep1.java b/client/src/main/java/client/renderer/model/ModelSheep1.java similarity index 94% rename from java/src/game/renderer/model/ModelSheep1.java rename to client/src/main/java/client/renderer/model/ModelSheep1.java index b6b2075..e25a89c 100755 --- a/java/src/game/renderer/model/ModelSheep1.java +++ b/client/src/main/java/client/renderer/model/ModelSheep1.java @@ -1,8 +1,8 @@ -package game.renderer.model; +package client.renderer.model; -import game.entity.Entity; -import game.entity.animal.EntitySheep; -import game.entity.types.EntityLiving; +import common.entity.Entity; +import common.entity.animal.EntitySheep; +import common.entity.types.EntityLiving; public class ModelSheep1 extends ModelQuadruped { diff --git a/java/src/game/renderer/model/ModelSheep2.java b/client/src/main/java/client/renderer/model/ModelSheep2.java similarity index 92% rename from java/src/game/renderer/model/ModelSheep2.java rename to client/src/main/java/client/renderer/model/ModelSheep2.java index 4db5e7a..510f948 100755 --- a/java/src/game/renderer/model/ModelSheep2.java +++ b/client/src/main/java/client/renderer/model/ModelSheep2.java @@ -1,8 +1,8 @@ -package game.renderer.model; +package client.renderer.model; -import game.entity.Entity; -import game.entity.animal.EntitySheep; -import game.entity.types.EntityLiving; +import common.entity.Entity; +import common.entity.animal.EntitySheep; +import common.entity.types.EntityLiving; public class ModelSheep2 extends ModelQuadruped { diff --git a/java/src/game/renderer/model/ModelSign.java b/client/src/main/java/client/renderer/model/ModelSign.java similarity index 95% rename from java/src/game/renderer/model/ModelSign.java rename to client/src/main/java/client/renderer/model/ModelSign.java index 85fc809..3685860 100755 --- a/java/src/game/renderer/model/ModelSign.java +++ b/client/src/main/java/client/renderer/model/ModelSign.java @@ -1,4 +1,4 @@ -package game.renderer.model; +package client.renderer.model; public class ModelSign extends ModelBase { diff --git a/java/src/game/renderer/model/ModelSlime.java b/client/src/main/java/client/renderer/model/ModelSlime.java similarity index 96% rename from java/src/game/renderer/model/ModelSlime.java rename to client/src/main/java/client/renderer/model/ModelSlime.java index 51165cc..2363426 100755 --- a/java/src/game/renderer/model/ModelSlime.java +++ b/client/src/main/java/client/renderer/model/ModelSlime.java @@ -1,6 +1,6 @@ -package game.renderer.model; +package client.renderer.model; -import game.entity.Entity; +import common.entity.Entity; public class ModelSlime extends ModelBase { diff --git a/java/src/game/renderer/model/ModelSpaceMarine.java b/client/src/main/java/client/renderer/model/ModelSpaceMarine.java similarity index 99% rename from java/src/game/renderer/model/ModelSpaceMarine.java rename to client/src/main/java/client/renderer/model/ModelSpaceMarine.java index 1464753..7fb4c55 100755 --- a/java/src/game/renderer/model/ModelSpaceMarine.java +++ b/client/src/main/java/client/renderer/model/ModelSpaceMarine.java @@ -1,4 +1,4 @@ -package game.renderer.model; +package client.renderer.model; public class ModelSpaceMarine extends ModelBiped { public ModelSpaceMarine() diff --git a/java/src/game/renderer/model/ModelSquid.java b/client/src/main/java/client/renderer/model/ModelSquid.java similarity index 97% rename from java/src/game/renderer/model/ModelSquid.java rename to client/src/main/java/client/renderer/model/ModelSquid.java index ccc0841..5db6680 100755 --- a/java/src/game/renderer/model/ModelSquid.java +++ b/client/src/main/java/client/renderer/model/ModelSquid.java @@ -1,6 +1,6 @@ -package game.renderer.model; +package client.renderer.model; -import game.entity.Entity; +import common.entity.Entity; public class ModelSquid extends ModelBase { diff --git a/java/src/game/renderer/model/ModelWolf.java b/client/src/main/java/client/renderer/model/ModelWolf.java similarity index 89% rename from java/src/game/renderer/model/ModelWolf.java rename to client/src/main/java/client/renderer/model/ModelWolf.java index adde16b..35d8eb2 100755 --- a/java/src/game/renderer/model/ModelWolf.java +++ b/client/src/main/java/client/renderer/model/ModelWolf.java @@ -1,11 +1,11 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.entity.Entity; -import game.entity.animal.EntityWolf; -import game.entity.types.EntityLiving; -import game.util.ExtMath; +import common.entity.Entity; +import common.entity.animal.EntityWolf; +import common.entity.types.EntityLiving; +import common.util.ExtMath; public class ModelWolf extends ModelBase { @@ -110,11 +110,11 @@ public class ModelWolf extends ModelBase * Used for easily adding entity-dependent animations. The second and third float params here are the same second * and third as in the setRotationAngles method. */ - public void setLivingAnimations(EntityLiving entitylivingbaseIn, float p_78086_2_, float p_78086_3_, float partialTickTime) + public void setLivingAnimations(EntityLiving living, float p_78086_2_, float p_78086_3_, float partialTickTime) { - EntityWolf entitywolf = (EntityWolf)entitylivingbaseIn; + EntityWolf wolf = (EntityWolf)living; - if (entitywolf.isAngry()) + if (wolf.isAngry()) { this.wolfTail.rotateAngleY = 0.0F; } @@ -123,7 +123,7 @@ public class ModelWolf extends ModelBase this.wolfTail.rotateAngleY = ExtMath.cos(p_78086_2_ * 0.6662F) * 1.4F * p_78086_3_; } - if (entitywolf.isSitting()) + if (wolf.isSitting()) { this.wolfMane.setRotationPoint(-1.0F, 16.0F, -3.0F); this.wolfMane.rotateAngleX = ((float)Math.PI * 2F / 5F); @@ -157,10 +157,10 @@ public class ModelWolf extends ModelBase this.wolfLeg4.rotateAngleX = ExtMath.cos(p_78086_2_ * 0.6662F) * 1.4F * p_78086_3_; } - this.wolfHeadMain.rotateAngleZ = entitywolf.getInterestedAngle(partialTickTime) + entitywolf.getShakeAngle(partialTickTime, 0.0F); - this.wolfMane.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.08F); - this.wolfBody.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.16F); - this.wolfTail.rotateAngleZ = entitywolf.getShakeAngle(partialTickTime, -0.2F); + this.wolfHeadMain.rotateAngleZ = wolf.getInterestedAngle(partialTickTime) + wolf.getShakeAngle(partialTickTime, 0.0F); + this.wolfMane.rotateAngleZ = wolf.getShakeAngle(partialTickTime, -0.08F); + this.wolfBody.rotateAngleZ = wolf.getShakeAngle(partialTickTime, -0.16F); + this.wolfTail.rotateAngleZ = wolf.getShakeAngle(partialTickTime, -0.2F); } /** diff --git a/java/src/game/renderer/model/PositionTextureVertex.java b/client/src/main/java/client/renderer/model/PositionTextureVertex.java similarity index 83% rename from java/src/game/renderer/model/PositionTextureVertex.java rename to client/src/main/java/client/renderer/model/PositionTextureVertex.java index df29489..4cde066 100755 --- a/java/src/game/renderer/model/PositionTextureVertex.java +++ b/client/src/main/java/client/renderer/model/PositionTextureVertex.java @@ -1,6 +1,6 @@ -package game.renderer.model; +package client.renderer.model; -import game.world.Vec3; +import common.util.Vec3; public class PositionTextureVertex { diff --git a/java/src/game/renderer/model/TextureOffset.java b/client/src/main/java/client/renderer/model/TextureOffset.java similarity index 92% rename from java/src/game/renderer/model/TextureOffset.java rename to client/src/main/java/client/renderer/model/TextureOffset.java index 8668dfa..535d70b 100755 --- a/java/src/game/renderer/model/TextureOffset.java +++ b/client/src/main/java/client/renderer/model/TextureOffset.java @@ -1,4 +1,4 @@ -package game.renderer.model; +package client.renderer.model; public class TextureOffset { diff --git a/java/src/game/renderer/model/TexturedQuad.java b/client/src/main/java/client/renderer/model/TexturedQuad.java similarity index 83% rename from java/src/game/renderer/model/TexturedQuad.java rename to client/src/main/java/client/renderer/model/TexturedQuad.java index d72d146..12da9c3 100755 --- a/java/src/game/renderer/model/TexturedQuad.java +++ b/client/src/main/java/client/renderer/model/TexturedQuad.java @@ -1,11 +1,11 @@ -package game.renderer.model; +package client.renderer.model; import org.lwjgl.opengl.GL11; -import game.renderer.DefaultVertexFormats; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.world.Vec3; +import client.renderer.DefaultVertexFormats; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import common.util.Vec3; public class TexturedQuad { @@ -19,10 +19,10 @@ public class TexturedQuad // this.vertices[1] = u1v1.toTextureVertex(u1 / tw + ax, v1 / th + ay); // this.vertices[2] = u1v2.toTextureVertex(u1 / tw + ax, v2 / th - ay); // this.vertices[3] = u2v2.toTextureVertex(u2 / tw - ax, v2 / th - ay); - this.vertices[0] = u2v1.toTextureVertex(u2 / tw, v1 / th); - this.vertices[1] = u1v1.toTextureVertex(u1 / tw, v1 / th); - this.vertices[2] = u1v2.toTextureVertex(u1 / tw, v2 / th); - this.vertices[3] = u2v2.toTextureVertex(u2 / tw, v2 / th); + this.vertices[0] = new PositionTextureVertex(u2v1, u2 / tw, v1 / th); + this.vertices[1] = new PositionTextureVertex(u1v1, u1 / tw, v1 / th); + this.vertices[2] = new PositionTextureVertex(u1v2, u1 / tw, v2 / th); + this.vertices[3] = new PositionTextureVertex(u2v2, u2 / tw, v2 / th); } public TexturedQuad(Vec3[] verts, int[] uvs, float tw, float th) diff --git a/java/src/game/renderer/particle/EffectRenderer.java b/client/src/main/java/client/renderer/particle/EffectRenderer.java similarity index 95% rename from java/src/game/renderer/particle/EffectRenderer.java rename to client/src/main/java/client/renderer/particle/EffectRenderer.java index 0431ab0..49d88cb 100755 --- a/java/src/game/renderer/particle/EffectRenderer.java +++ b/client/src/main/java/client/renderer/particle/EffectRenderer.java @@ -1,29 +1,29 @@ -package game.renderer.particle; +package client.renderer.particle; import java.util.List; import java.util.Map; import org.lwjgl.opengl.GL11; -import game.collect.Lists; -import game.collect.Maps; - -import game.block.Block; -import game.entity.Entity; -import game.material.Material; -import game.renderer.ActiveRenderInfo; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.renderer.texture.TextureManager; -import game.renderer.texture.TextureMap; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import client.renderer.ActiveRenderInfo; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.renderer.texture.TextureManager; +import client.renderer.texture.TextureMap; +import common.block.Block; +import common.collect.Lists; +import common.collect.Maps; +import common.entity.Entity; +import common.init.Blocks; +import common.model.ParticleType; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.world.State; +import common.world.World; public class EffectRenderer { @@ -319,7 +319,7 @@ public class EffectRenderer public void addBlockDestroyEffects(BlockPos pos, State state) { - if (state.getBlock().getMaterial() != Material.air) + if (state.getBlock() != Blocks.air) { state = state.getBlock().getActualState(state, this.worldObj, pos); int i = 4; diff --git a/java/src/game/renderer/particle/EntityAuraFX.java b/client/src/main/java/client/renderer/particle/EntityAuraFX.java similarity index 98% rename from java/src/game/renderer/particle/EntityAuraFX.java rename to client/src/main/java/client/renderer/particle/EntityAuraFX.java index 183a805..1240fb8 100755 --- a/java/src/game/renderer/particle/EntityAuraFX.java +++ b/client/src/main/java/client/renderer/particle/EntityAuraFX.java @@ -1,6 +1,6 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.world.World; +import common.world.World; public class EntityAuraFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityBlockDustFX.java b/client/src/main/java/client/renderer/particle/EntityBlockDustFX.java similarity index 88% rename from java/src/game/renderer/particle/EntityBlockDustFX.java rename to client/src/main/java/client/renderer/particle/EntityBlockDustFX.java index 963aee9..cc6f805 100755 --- a/java/src/game/renderer/particle/EntityBlockDustFX.java +++ b/client/src/main/java/client/renderer/particle/EntityBlockDustFX.java @@ -1,8 +1,8 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.init.BlockRegistry; -import game.world.State; -import game.world.World; +import common.init.BlockRegistry; +import common.world.State; +import common.world.World; public class EntityBlockDustFX extends EntityDiggingFX { diff --git a/java/src/game/renderer/particle/EntityBreakingFX.java b/client/src/main/java/client/renderer/particle/EntityBreakingFX.java similarity index 93% rename from java/src/game/renderer/particle/EntityBreakingFX.java rename to client/src/main/java/client/renderer/particle/EntityBreakingFX.java index c27924a..fb19236 100755 --- a/java/src/game/renderer/particle/EntityBreakingFX.java +++ b/client/src/main/java/client/renderer/particle/EntityBreakingFX.java @@ -1,12 +1,12 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.Game; -import game.entity.Entity; -import game.init.ItemRegistry; -import game.init.Items; -import game.item.Item; -import game.renderer.RenderBuffer; -import game.world.World; +import client.Client; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.init.ItemRegistry; +import common.init.Items; +import common.item.Item; +import common.world.World; public class EntityBreakingFX extends EntityFX { @@ -29,7 +29,7 @@ public class EntityBreakingFX extends EntityFX protected EntityBreakingFX(World worldIn, double posXIn, double posYIn, double posZIn, Item p_i1196_8_, int p_i1196_9_) { super(worldIn, posXIn, posYIn, posZIn, 0.0D, 0.0D, 0.0D); - this.setParticleIcon(Game.getGame().getRenderItem().getItemModelMesher().getParticleIcon(p_i1196_8_, p_i1196_9_)); + this.setParticleIcon(Client.CLIENT.getRenderItem().getItemModelMesher().getParticleIcon(p_i1196_8_, p_i1196_9_)); this.particleRed = this.particleGreen = this.particleBlue = 1.0F; this.particleGravity = 1.0F; // Blocks.snow.particleGravity; this.particleScale /= 2.0F; diff --git a/java/src/game/renderer/particle/EntityBubbleFX.java b/client/src/main/java/client/renderer/particle/EntityBubbleFX.java similarity index 92% rename from java/src/game/renderer/particle/EntityBubbleFX.java rename to client/src/main/java/client/renderer/particle/EntityBubbleFX.java index 2ace7d8..909b2b5 100755 --- a/java/src/game/renderer/particle/EntityBubbleFX.java +++ b/client/src/main/java/client/renderer/particle/EntityBubbleFX.java @@ -1,8 +1,8 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.material.Material; -import game.world.BlockPos; -import game.world.World; +import common.block.Material; +import common.util.BlockPos; +import common.world.World; public class EntityBubbleFX extends EntityFX { @@ -35,7 +35,7 @@ public class EntityBubbleFX extends EntityFX this.motionY *= 0.8500000238418579D; this.motionZ *= 0.8500000238418579D; - if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() != Material.water) + if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() != Material.WATER) { this.setDead(); } diff --git a/java/src/game/renderer/particle/EntityCloudFX.java b/client/src/main/java/client/renderer/particle/EntityCloudFX.java similarity index 94% rename from java/src/game/renderer/particle/EntityCloudFX.java rename to client/src/main/java/client/renderer/particle/EntityCloudFX.java index f76aed3..4b46bf9 100755 --- a/java/src/game/renderer/particle/EntityCloudFX.java +++ b/client/src/main/java/client/renderer/particle/EntityCloudFX.java @@ -1,10 +1,10 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.renderer.RenderBuffer; -import game.util.ExtMath; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.util.ExtMath; +import common.world.World; public class EntityCloudFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityCrit2FX.java b/client/src/main/java/client/renderer/particle/EntityCrit2FX.java similarity index 96% rename from java/src/game/renderer/particle/EntityCrit2FX.java rename to client/src/main/java/client/renderer/particle/EntityCrit2FX.java index 644fb2c..e021842 100755 --- a/java/src/game/renderer/particle/EntityCrit2FX.java +++ b/client/src/main/java/client/renderer/particle/EntityCrit2FX.java @@ -1,9 +1,9 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.util.ExtMath; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.util.ExtMath; +import common.world.World; public class EntityCrit2FX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityCritFX.java b/client/src/main/java/client/renderer/particle/EntityCritFX.java similarity index 92% rename from java/src/game/renderer/particle/EntityCritFX.java rename to client/src/main/java/client/renderer/particle/EntityCritFX.java index 4c039a8..2e224cc 100755 --- a/java/src/game/renderer/particle/EntityCritFX.java +++ b/client/src/main/java/client/renderer/particle/EntityCritFX.java @@ -1,6 +1,6 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.world.World; +import common.world.World; public class EntityCritFX extends EntitySmokeFX { diff --git a/java/src/game/renderer/particle/EntityDiggingFX.java b/client/src/main/java/client/renderer/particle/EntityDiggingFX.java similarity index 92% rename from java/src/game/renderer/particle/EntityDiggingFX.java rename to client/src/main/java/client/renderer/particle/EntityDiggingFX.java index 291692e..9a6e753 100755 --- a/java/src/game/renderer/particle/EntityDiggingFX.java +++ b/client/src/main/java/client/renderer/particle/EntityDiggingFX.java @@ -1,14 +1,14 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.Game; -import game.block.Block; -import game.entity.Entity; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.renderer.RenderBuffer; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import client.Client; +import client.renderer.RenderBuffer; +import common.block.Block; +import common.entity.Entity; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.util.BlockPos; +import common.world.State; +import common.world.World; public class EntityDiggingFX extends EntityFX { @@ -19,7 +19,7 @@ public class EntityDiggingFX extends EntityFX { super(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); this.sourceState = state; - this.setParticleIcon(Game.getGame().getBlockRendererDispatcher().getModelManager().getTexture(state)); + this.setParticleIcon(Client.CLIENT.getBlockRendererDispatcher().getModelManager().getTexture(state)); this.particleGravity = 1.0F; // state.getBlock().particleGravity; this.particleRed = this.particleGreen = this.particleBlue = 0.6F; this.particleScale /= 2.0F; diff --git a/java/src/game/renderer/particle/EntityDownfallFX.java b/client/src/main/java/client/renderer/particle/EntityDownfallFX.java similarity index 92% rename from java/src/game/renderer/particle/EntityDownfallFX.java rename to client/src/main/java/client/renderer/particle/EntityDownfallFX.java index 9a66aaa..d8d69eb 100755 --- a/java/src/game/renderer/particle/EntityDownfallFX.java +++ b/client/src/main/java/client/renderer/particle/EntityDownfallFX.java @@ -1,12 +1,12 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.block.Block; -import game.block.BlockLiquid; -import game.material.Material; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.block.liquid.BlockLiquid; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.State; +import common.world.World; public class EntityDownfallFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityDropParticleFX.java b/client/src/main/java/client/renderer/particle/EntityDropParticleFX.java similarity index 87% rename from java/src/game/renderer/particle/EntityDropParticleFX.java rename to client/src/main/java/client/renderer/particle/EntityDropParticleFX.java index 3c49a61..bce2874 100755 --- a/java/src/game/renderer/particle/EntityDropParticleFX.java +++ b/client/src/main/java/client/renderer/particle/EntityDropParticleFX.java @@ -1,11 +1,12 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.block.BlockLiquid; -import game.material.Material; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.Material; +import common.block.liquid.BlockLiquid; +import common.model.ParticleType; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.State; +import common.world.World; public class EntityDropParticleFX extends EntityFX { @@ -20,7 +21,7 @@ public class EntityDropParticleFX extends EntityFX super(worldIn, xCoordIn, yCoordIn, zCoordIn, 0.0D, 0.0D, 0.0D); this.motionX = this.motionY = this.motionZ = 0.0D; - if (p_i1203_8_ == Material.water) + if (p_i1203_8_ == Material.WATER) { this.particleRed = 0.0F; this.particleGreen = 0.0F; @@ -44,7 +45,7 @@ public class EntityDropParticleFX extends EntityFX public int getBrightnessForRender(float partialTicks) { - return this.materialType == Material.water ? super.getBrightnessForRender(partialTicks) : 257; + return this.materialType == Material.WATER ? super.getBrightnessForRender(partialTicks) : 257; } /** @@ -52,7 +53,7 @@ public class EntityDropParticleFX extends EntityFX */ public float getBrightness(float partialTicks) { - return this.materialType == Material.water ? super.getBrightness(partialTicks) : 1.0F; + return this.materialType == Material.WATER ? super.getBrightness(partialTicks) : 1.0F; } /** @@ -64,7 +65,7 @@ public class EntityDropParticleFX extends EntityFX this.prevY = this.posY; this.prevZ = this.posZ; - if (this.materialType == Material.water) + if (this.materialType == Material.WATER) { this.particleRed = 0.2F; this.particleGreen = 0.3F; @@ -103,7 +104,7 @@ public class EntityDropParticleFX extends EntityFX if (this.onGround) { - if (this.materialType == Material.water) + if (this.materialType == Material.WATER) { this.setDead(); this.worldObj.spawnParticle(ParticleType.WATER_SPLASH, this.posX, this.posY, this.posZ, 0.0D, 0.0D, 0.0D); @@ -143,7 +144,7 @@ public class EntityDropParticleFX extends EntityFX { public EntityFX getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { - return new EntityDropParticleFX(worldIn, xCoordIn, yCoordIn, zCoordIn, Material.lava); + return new EntityDropParticleFX(worldIn, xCoordIn, yCoordIn, zCoordIn, Material.LAVA); } } @@ -151,7 +152,7 @@ public class EntityDropParticleFX extends EntityFX { public EntityFX getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { - return new EntityDropParticleFX(worldIn, xCoordIn, yCoordIn, zCoordIn, Material.water); + return new EntityDropParticleFX(worldIn, xCoordIn, yCoordIn, zCoordIn, Material.WATER); } } } diff --git a/java/src/game/renderer/particle/EntityEnchantmentTableParticleFX.java b/client/src/main/java/client/renderer/particle/EntityEnchantmentTableParticleFX.java similarity index 98% rename from java/src/game/renderer/particle/EntityEnchantmentTableParticleFX.java rename to client/src/main/java/client/renderer/particle/EntityEnchantmentTableParticleFX.java index 7fd3b52..b337bc0 100755 --- a/java/src/game/renderer/particle/EntityEnchantmentTableParticleFX.java +++ b/client/src/main/java/client/renderer/particle/EntityEnchantmentTableParticleFX.java @@ -1,6 +1,6 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.world.World; +import common.world.World; public class EntityEnchantmentTableParticleFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityExplodeFX.java b/client/src/main/java/client/renderer/particle/EntityExplodeFX.java similarity index 97% rename from java/src/game/renderer/particle/EntityExplodeFX.java rename to client/src/main/java/client/renderer/particle/EntityExplodeFX.java index dbac18e..fcf1d11 100755 --- a/java/src/game/renderer/particle/EntityExplodeFX.java +++ b/client/src/main/java/client/renderer/particle/EntityExplodeFX.java @@ -1,6 +1,6 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.world.World; +import common.world.World; public class EntityExplodeFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityFX.java b/client/src/main/java/client/renderer/particle/EntityFX.java similarity index 94% rename from java/src/game/renderer/particle/EntityFX.java rename to client/src/main/java/client/renderer/particle/EntityFX.java index 963a872..6f177ff 100755 --- a/java/src/game/renderer/particle/EntityFX.java +++ b/client/src/main/java/client/renderer/particle/EntityFX.java @@ -1,13 +1,13 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.Game; -import game.entity.Entity; -import game.entity.EntityType; -import game.nbt.NBTTagCompound; -import game.renderer.RenderBuffer; -import game.renderer.texture.TextureAtlasSprite; -import game.util.ExtMath; -import game.world.World; +import client.Client; +import client.renderer.RenderBuffer; +import client.renderer.texture.TextureAtlasSprite; +import common.entity.Entity; +import common.entity.EntityType; +import common.tags.TagObject; +import common.util.ExtMath; +import common.world.World; public class EntityFX extends Entity { @@ -101,11 +101,11 @@ public class EntityFX extends Entity { if (this.particleAlpha == 1.0F && alpha < 1.0F) { - Game.getGame().effectRenderer.moveToAlphaLayer(this); + Client.CLIENT.effectRenderer.moveToAlphaLayer(this); } else if (this.particleAlpha < 1.0F && alpha == 1.0F) { - Game.getGame().effectRenderer.moveToNoAlphaLayer(this); + Client.CLIENT.effectRenderer.moveToNoAlphaLayer(this); } this.particleAlpha = alpha; @@ -208,16 +208,16 @@ public class EntityFX extends Entity } /** - * (abstract) Protected helper method to write subclass entity data to NBT. + * (abstract) Protected helper method to write subclass entity data. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tag) { } /** - * (abstract) Protected helper method to read subclass entity data from NBT. + * (abstract) Protected helper method to read subclass entity data. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tag) { } diff --git a/java/src/game/renderer/particle/EntityFirework.java b/client/src/main/java/client/renderer/particle/EntityFirework.java similarity index 91% rename from java/src/game/renderer/particle/EntityFirework.java rename to client/src/main/java/client/renderer/particle/EntityFirework.java index 24f483b..476388f 100755 --- a/java/src/game/renderer/particle/EntityFirework.java +++ b/client/src/main/java/client/renderer/particle/EntityFirework.java @@ -1,16 +1,16 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.Game; -import game.entity.Entity; -import game.init.SoundEvent; -import game.item.ItemDye; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.renderer.RenderBuffer; -import game.util.ExtMath; -import game.world.BoundingBox; -import game.world.World; -import game.world.WorldClient; +import client.Client; +import client.renderer.RenderBuffer; +import client.world.WorldClient; +import common.entity.Entity; +import common.init.SoundEvent; +import common.item.ItemDye; +import common.tags.TagObject; +import java.util.List; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.world.World; public class EntityFirework { @@ -18,7 +18,7 @@ public class EntityFirework { public EntityFX getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { - EntityFirework.SparkFX entityfirework$sparkfx = new EntityFirework.SparkFX(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn, Game.getGame().effectRenderer); + EntityFirework.SparkFX entityfirework$sparkfx = new EntityFirework.SparkFX(worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn, Client.CLIENT.effectRenderer); entityfirework$sparkfx.setAlphaF(0.99F); return entityfirework$sparkfx; } @@ -192,10 +192,10 @@ public class EntityFirework { private int fireworkAge; private final EffectRenderer theEffectRenderer; - private NBTTagList fireworkExplosions; + private List fireworkExplosions; boolean twinkle; - public StarterFX(World p_i46464_1_, double p_i46464_2_, double p_i46464_4_, double p_i46464_6_, double p_i46464_8_, double p_i46464_10_, double p_i46464_12_, EffectRenderer p_i46464_14_, NBTTagCompound p_i46464_15_) + public StarterFX(World p_i46464_1_, double p_i46464_2_, double p_i46464_4_, double p_i46464_6_, double p_i46464_8_, double p_i46464_10_, double p_i46464_12_, EffectRenderer p_i46464_14_, TagObject p_i46464_15_) { super(p_i46464_1_, p_i46464_2_, p_i46464_4_, p_i46464_6_, 0.0D, 0.0D, 0.0D); this.motionX = p_i46464_8_; @@ -206,21 +206,21 @@ public class EntityFirework if (p_i46464_15_ != null) { - this.fireworkExplosions = p_i46464_15_.getTagList("Explosions", 10); + this.fireworkExplosions = p_i46464_15_.getList("Explosions"); - if (this.fireworkExplosions.tagCount() == 0) + if (this.fireworkExplosions.size() == 0) { this.fireworkExplosions = null; } else { - this.particleMaxAge = this.fireworkExplosions.tagCount() * 2 - 1; + this.particleMaxAge = this.fireworkExplosions.size() * 2 - 1; - for (int i = 0; i < this.fireworkExplosions.tagCount(); ++i) + for (int i = 0; i < this.fireworkExplosions.size(); ++i) { - NBTTagCompound nbttagcompound = this.fireworkExplosions.getCompoundTagAt(i); + TagObject tag = this.fireworkExplosions.get(i); - if (nbttagcompound.getBoolean("Flicker")) + if (tag.getBool("Flicker")) { this.twinkle = true; this.particleMaxAge += 15; @@ -242,17 +242,17 @@ public class EntityFirework boolean flag = this.isFarAway(); boolean flag1 = false; - if (this.fireworkExplosions.tagCount() >= 3) + if (this.fireworkExplosions.size() >= 3) { flag1 = true; } else { - for (int i = 0; i < this.fireworkExplosions.tagCount(); ++i) + for (int i = 0; i < this.fireworkExplosions.size(); ++i) { - NBTTagCompound nbttagcompound = this.fireworkExplosions.getCompoundTagAt(i); + TagObject tag = this.fireworkExplosions.get(i); - if (nbttagcompound.getByte("Type") == 1) + if (tag.getByte("Type") == 1) { flag1 = true; break; @@ -265,15 +265,15 @@ public class EntityFirework ((WorldClient)this.worldObj).playSound(this.posX, this.posY, this.posZ, s1, 20.0F); } - if (this.fireworkAge % 2 == 0 && this.fireworkExplosions != null && this.fireworkAge / 2 < this.fireworkExplosions.tagCount()) + if (this.fireworkAge % 2 == 0 && this.fireworkExplosions != null && this.fireworkAge / 2 < this.fireworkExplosions.size()) { int k = this.fireworkAge / 2; - NBTTagCompound nbttagcompound1 = this.fireworkExplosions.getCompoundTagAt(k); - int l = nbttagcompound1.getByte("Type"); - boolean flag4 = nbttagcompound1.getBoolean("Trail"); - boolean flag2 = nbttagcompound1.getBoolean("Flicker"); - int[] aint = nbttagcompound1.getIntArray("Colors"); - int[] aint1 = nbttagcompound1.getIntArray("FadeColors"); + TagObject tag = this.fireworkExplosions.get(k); + int l = tag.getByte("Type"); + boolean flag4 = tag.getBool("Trail"); + boolean flag2 = tag.getBool("Flicker"); + int[] aint = tag.getIntArray("Colors"); + int[] aint1 = tag.getIntArray("FadeColors"); if (aint.length == 0) { @@ -333,7 +333,7 @@ public class EntityFirework private boolean isFarAway() { - Game gm = Game.getGame(); + Client gm = Client.CLIENT; return gm == null || gm.getRenderViewEntity() == null || gm.getRenderViewEntity().getDistanceSq(this.posX, this.posY, this.posZ) >= 256.0D; } diff --git a/java/src/game/renderer/particle/EntityFishWakeFX.java b/client/src/main/java/client/renderer/particle/EntityFishWakeFX.java similarity index 97% rename from java/src/game/renderer/particle/EntityFishWakeFX.java rename to client/src/main/java/client/renderer/particle/EntityFishWakeFX.java index 93ea151..c120d5e 100755 --- a/java/src/game/renderer/particle/EntityFishWakeFX.java +++ b/client/src/main/java/client/renderer/particle/EntityFishWakeFX.java @@ -1,6 +1,6 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.world.World; +import common.world.World; public class EntityFishWakeFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityFlameFX.java b/client/src/main/java/client/renderer/particle/EntityFlameFX.java similarity index 95% rename from java/src/game/renderer/particle/EntityFlameFX.java rename to client/src/main/java/client/renderer/particle/EntityFlameFX.java index 0f72184..462370d 100755 --- a/java/src/game/renderer/particle/EntityFlameFX.java +++ b/client/src/main/java/client/renderer/particle/EntityFlameFX.java @@ -1,9 +1,9 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.util.ExtMath; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.util.ExtMath; +import common.world.World; public class EntityFlameFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityFootStepFX.java b/client/src/main/java/client/renderer/particle/EntityFootStepFX.java similarity index 86% rename from java/src/game/renderer/particle/EntityFootStepFX.java rename to client/src/main/java/client/renderer/particle/EntityFootStepFX.java index 887fdf7..2bad9a1 100755 --- a/java/src/game/renderer/particle/EntityFootStepFX.java +++ b/client/src/main/java/client/renderer/particle/EntityFootStepFX.java @@ -1,16 +1,16 @@ -package game.renderer.particle; +package client.renderer.particle; import org.lwjgl.opengl.GL11; -import game.Game; -import game.entity.Entity; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.renderer.texture.TextureManager; -import game.world.BlockPos; -import game.world.World; +import client.Client; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.renderer.texture.TextureManager; +import common.entity.Entity; +import common.util.BlockPos; +import common.world.World; public class EntityFootStepFX extends EntityFX { @@ -88,7 +88,7 @@ public class EntityFootStepFX extends EntityFX { public EntityFX getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { - return new EntityFootStepFX(Game.getGame().getTextureManager(), worldIn, xCoordIn, yCoordIn, zCoordIn); + return new EntityFootStepFX(Client.CLIENT.getTextureManager(), worldIn, xCoordIn, yCoordIn, zCoordIn); } } } diff --git a/java/src/game/renderer/particle/EntityHeartFX.java b/client/src/main/java/client/renderer/particle/EntityHeartFX.java similarity index 95% rename from java/src/game/renderer/particle/EntityHeartFX.java rename to client/src/main/java/client/renderer/particle/EntityHeartFX.java index c9d14be..f048950 100755 --- a/java/src/game/renderer/particle/EntityHeartFX.java +++ b/client/src/main/java/client/renderer/particle/EntityHeartFX.java @@ -1,9 +1,9 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.util.ExtMath; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.util.ExtMath; +import common.world.World; public class EntityHeartFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityHugeExplodeFX.java b/client/src/main/java/client/renderer/particle/EntityHugeExplodeFX.java similarity index 91% rename from java/src/game/renderer/particle/EntityHugeExplodeFX.java rename to client/src/main/java/client/renderer/particle/EntityHugeExplodeFX.java index 2956853..7f287b9 100755 --- a/java/src/game/renderer/particle/EntityHugeExplodeFX.java +++ b/client/src/main/java/client/renderer/particle/EntityHugeExplodeFX.java @@ -1,8 +1,9 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.model.ParticleType; +import common.world.World; public class EntityHugeExplodeFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityLargeExplodeFX.java b/client/src/main/java/client/renderer/particle/EntityLargeExplodeFX.java similarity index 89% rename from java/src/game/renderer/particle/EntityLargeExplodeFX.java rename to client/src/main/java/client/renderer/particle/EntityLargeExplodeFX.java index 21020a8..9dfe387 100755 --- a/java/src/game/renderer/particle/EntityLargeExplodeFX.java +++ b/client/src/main/java/client/renderer/particle/EntityLargeExplodeFX.java @@ -1,17 +1,17 @@ -package game.renderer.particle; +package client.renderer.particle; import org.lwjgl.opengl.GL11; -import game.Game; -import game.entity.Entity; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.ItemRenderer; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.renderer.VertexFormat; -import game.renderer.texture.TextureManager; -import game.world.World; +import client.Client; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.ItemRenderer; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.renderer.VertexFormat; +import client.renderer.texture.TextureManager; +import common.entity.Entity; +import common.world.World; public class EntityLargeExplodeFX extends EntityFX { @@ -95,7 +95,7 @@ public class EntityLargeExplodeFX extends EntityFX { public EntityFX getEntityFX(int particleID, World worldIn, double xCoordIn, double yCoordIn, double zCoordIn, double xSpeedIn, double ySpeedIn, double zSpeedIn, int... p_178902_15_) { - return new EntityLargeExplodeFX(Game.getGame().getTextureManager(), worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); + return new EntityLargeExplodeFX(Client.CLIENT.getTextureManager(), worldIn, xCoordIn, yCoordIn, zCoordIn, xSpeedIn, ySpeedIn, zSpeedIn); } } } diff --git a/java/src/game/renderer/particle/EntityLavaFX.java b/client/src/main/java/client/renderer/particle/EntityLavaFX.java similarity index 94% rename from java/src/game/renderer/particle/EntityLavaFX.java rename to client/src/main/java/client/renderer/particle/EntityLavaFX.java index b187423..bd823f0 100755 --- a/java/src/game/renderer/particle/EntityLavaFX.java +++ b/client/src/main/java/client/renderer/particle/EntityLavaFX.java @@ -1,9 +1,10 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.util.ExtMath; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.model.ParticleType; +import common.util.ExtMath; +import common.world.World; public class EntityLavaFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityNoteFX.java b/client/src/main/java/client/renderer/particle/EntityNoteFX.java similarity index 95% rename from java/src/game/renderer/particle/EntityNoteFX.java rename to client/src/main/java/client/renderer/particle/EntityNoteFX.java index 0517d0c..2bfa850 100755 --- a/java/src/game/renderer/particle/EntityNoteFX.java +++ b/client/src/main/java/client/renderer/particle/EntityNoteFX.java @@ -1,9 +1,9 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.util.ExtMath; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.util.ExtMath; +import common.world.World; public class EntityNoteFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityParticleEmitter.java b/client/src/main/java/client/renderer/particle/EntityParticleEmitter.java similarity index 91% rename from java/src/game/renderer/particle/EntityParticleEmitter.java rename to client/src/main/java/client/renderer/particle/EntityParticleEmitter.java index 3f7e957..42f18a8 100755 --- a/java/src/game/renderer/particle/EntityParticleEmitter.java +++ b/client/src/main/java/client/renderer/particle/EntityParticleEmitter.java @@ -1,9 +1,10 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.world.World; -import game.world.WorldClient; +import client.renderer.RenderBuffer; +import client.world.WorldClient; +import common.entity.Entity; +import common.model.ParticleType; +import common.world.World; public class EntityParticleEmitter extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityPickupFX.java b/client/src/main/java/client/renderer/particle/EntityPickupFX.java similarity index 89% rename from java/src/game/renderer/particle/EntityPickupFX.java rename to client/src/main/java/client/renderer/particle/EntityPickupFX.java index 05f5153..67a4bd8 100755 --- a/java/src/game/renderer/particle/EntityPickupFX.java +++ b/client/src/main/java/client/renderer/particle/EntityPickupFX.java @@ -1,13 +1,13 @@ -package game.renderer.particle; +package client.renderer.particle; import org.lwjgl.opengl.GL13; -import game.Game; -import game.entity.Entity; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.entity.RenderManager; -import game.world.World; +import client.Client; +import client.renderer.GlState; +import client.renderer.RenderBuffer; +import client.renderer.entity.RenderManager; +import common.entity.Entity; +import common.world.World; public class EntityPickupFX extends EntityFX { @@ -16,7 +16,7 @@ public class EntityPickupFX extends EntityFX private int age; private int maxAge; private float field_174841_aA; - private RenderManager field_174842_aB = Game.getGame().getRenderManager(); + private RenderManager field_174842_aB = Client.CLIENT.getRenderManager(); public EntityPickupFX(World worldIn, Entity p_i1233_2_, Entity p_i1233_3_, float p_i1233_4_) { diff --git a/java/src/game/renderer/particle/EntityPortalFX.java b/client/src/main/java/client/renderer/particle/EntityPortalFX.java similarity index 96% rename from java/src/game/renderer/particle/EntityPortalFX.java rename to client/src/main/java/client/renderer/particle/EntityPortalFX.java index 5b07ac2..3c5dd59 100755 --- a/java/src/game/renderer/particle/EntityPortalFX.java +++ b/client/src/main/java/client/renderer/particle/EntityPortalFX.java @@ -1,8 +1,8 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.world.World; public class EntityPortalFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntityReddustFX.java b/client/src/main/java/client/renderer/particle/EntityReddustFX.java similarity index 95% rename from java/src/game/renderer/particle/EntityReddustFX.java rename to client/src/main/java/client/renderer/particle/EntityReddustFX.java index 8a0e278..f89e164 100755 --- a/java/src/game/renderer/particle/EntityReddustFX.java +++ b/client/src/main/java/client/renderer/particle/EntityReddustFX.java @@ -1,9 +1,9 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.util.ExtMath; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.util.ExtMath; +import common.world.World; public class EntityReddustFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntitySmokeFX.java b/client/src/main/java/client/renderer/particle/EntitySmokeFX.java similarity index 95% rename from java/src/game/renderer/particle/EntitySmokeFX.java rename to client/src/main/java/client/renderer/particle/EntitySmokeFX.java index ed2acaf..5566bf2 100755 --- a/java/src/game/renderer/particle/EntitySmokeFX.java +++ b/client/src/main/java/client/renderer/particle/EntitySmokeFX.java @@ -1,9 +1,9 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.util.ExtMath; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.util.ExtMath; +import common.world.World; public class EntitySmokeFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntitySnowShovelFX.java b/client/src/main/java/client/renderer/particle/EntitySnowShovelFX.java similarity index 95% rename from java/src/game/renderer/particle/EntitySnowShovelFX.java rename to client/src/main/java/client/renderer/particle/EntitySnowShovelFX.java index 31acfdf..ff9e9fa 100755 --- a/java/src/game/renderer/particle/EntitySnowShovelFX.java +++ b/client/src/main/java/client/renderer/particle/EntitySnowShovelFX.java @@ -1,9 +1,9 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.util.ExtMath; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.util.ExtMath; +import common.world.World; public class EntitySnowShovelFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntitySpellParticleFX.java b/client/src/main/java/client/renderer/particle/EntitySpellParticleFX.java similarity index 96% rename from java/src/game/renderer/particle/EntitySpellParticleFX.java rename to client/src/main/java/client/renderer/particle/EntitySpellParticleFX.java index 55b7a9a..4aaa047 100755 --- a/java/src/game/renderer/particle/EntitySpellParticleFX.java +++ b/client/src/main/java/client/renderer/particle/EntitySpellParticleFX.java @@ -1,10 +1,10 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.entity.Entity; -import game.renderer.RenderBuffer; -import game.rng.Random; -import game.util.ExtMath; -import game.world.World; +import client.renderer.RenderBuffer; +import common.entity.Entity; +import common.rng.Random; +import common.util.ExtMath; +import common.world.World; public class EntitySpellParticleFX extends EntityFX { diff --git a/java/src/game/renderer/particle/EntitySplashFX.java b/client/src/main/java/client/renderer/particle/EntitySplashFX.java similarity index 93% rename from java/src/game/renderer/particle/EntitySplashFX.java rename to client/src/main/java/client/renderer/particle/EntitySplashFX.java index 7a18588..8c1f93a 100755 --- a/java/src/game/renderer/particle/EntitySplashFX.java +++ b/client/src/main/java/client/renderer/particle/EntitySplashFX.java @@ -1,6 +1,6 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.world.World; +import common.world.World; public class EntitySplashFX extends EntityDownfallFX { diff --git a/java/src/game/renderer/particle/EntitySuspendFX.java b/client/src/main/java/client/renderer/particle/EntitySuspendFX.java similarity index 91% rename from java/src/game/renderer/particle/EntitySuspendFX.java rename to client/src/main/java/client/renderer/particle/EntitySuspendFX.java index ae02469..2e9893f 100755 --- a/java/src/game/renderer/particle/EntitySuspendFX.java +++ b/client/src/main/java/client/renderer/particle/EntitySuspendFX.java @@ -1,8 +1,8 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.material.Material; -import game.world.BlockPos; -import game.world.World; +import common.block.Material; +import common.util.BlockPos; +import common.world.World; public class EntitySuspendFX extends EntityFX { @@ -31,7 +31,7 @@ public class EntitySuspendFX extends EntityFX this.prevZ = this.posZ; this.moveEntity(this.motionX, this.motionY, this.motionZ); - if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() != Material.water) + if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() != Material.WATER) { this.setDead(); } diff --git a/java/src/game/renderer/particle/IParticleFactory.java b/client/src/main/java/client/renderer/particle/IParticleFactory.java similarity index 78% rename from java/src/game/renderer/particle/IParticleFactory.java rename to client/src/main/java/client/renderer/particle/IParticleFactory.java index dfef805..f018fda 100755 --- a/java/src/game/renderer/particle/IParticleFactory.java +++ b/client/src/main/java/client/renderer/particle/IParticleFactory.java @@ -1,6 +1,6 @@ -package game.renderer.particle; +package client.renderer.particle; -import game.world.World; +import common.world.World; public interface IParticleFactory { diff --git a/client/src/main/java/client/renderer/texture/ColormapLoader.java b/client/src/main/java/client/renderer/texture/ColormapLoader.java new file mode 100644 index 0000000..96ff88c --- /dev/null +++ b/client/src/main/java/client/renderer/texture/ColormapLoader.java @@ -0,0 +1,27 @@ +package client.renderer.texture; + +import java.awt.image.BufferedImage; + +import client.util.FileUtils; +import common.color.Colorizer; + +public abstract class ColormapLoader { + private static final String GRASS_TEX = "textures/world/grass.png"; + private static final String FOLIAGE_TEX = "textures/world/foliage.png"; + + public static void reload() { + BufferedImage img; + try { + img = TextureUtil.readImage(FileUtils.getResource(GRASS_TEX)); + img.getRGB(0, 0, 256, 256, Colorizer.getGrassMap(), 0, 256); + } + catch(Exception e) { + } + try { + img = TextureUtil.readImage(FileUtils.getResource(FOLIAGE_TEX)); + img.getRGB(0, 0, 256, 256, Colorizer.getFoliageMap(), 0, 256); + } + catch(Exception e) { + } + } +} diff --git a/java/src/game/renderer/texture/DynamicTexture.java b/client/src/main/java/client/renderer/texture/DynamicTexture.java similarity index 95% rename from java/src/game/renderer/texture/DynamicTexture.java rename to client/src/main/java/client/renderer/texture/DynamicTexture.java index 8067614..1d82fcd 100755 --- a/java/src/game/renderer/texture/DynamicTexture.java +++ b/client/src/main/java/client/renderer/texture/DynamicTexture.java @@ -1,9 +1,9 @@ -package game.renderer.texture; +package client.renderer.texture; import java.awt.image.BufferedImage; import java.io.IOException; -import game.renderer.GlState; +import client.renderer.GlState; public class DynamicTexture extends Texture { diff --git a/java/src/game/renderer/texture/EntityTexManager.java b/client/src/main/java/client/renderer/texture/EntityTexManager.java similarity index 73% rename from java/src/game/renderer/texture/EntityTexManager.java rename to client/src/main/java/client/renderer/texture/EntityTexManager.java index bc52a92..8160703 100755 --- a/java/src/game/renderer/texture/EntityTexManager.java +++ b/client/src/main/java/client/renderer/texture/EntityTexManager.java @@ -1,4 +1,4 @@ -package game.renderer.texture; +package client.renderer.texture; import java.awt.Color; import java.awt.Graphics2D; @@ -10,26 +10,23 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Set; -import game.collect.Lists; -import game.collect.Maps; -import game.collect.Sets; - -import game.Game; -import game.entity.npc.EntityNPC; -import game.init.SpeciesRegistry; -import game.init.SpeciesRegistry.ModelType; -import game.log.Log; -import game.renderer.entity.RenderNpc; -import game.renderer.layers.LayerExtra; -import game.util.FileUtils; +import client.Client; +import client.renderer.entity.RenderNpc; +import client.renderer.layers.LayerExtra; +import client.util.FileUtils; +import common.collect.Lists; +import common.collect.Maps; +import common.collect.Sets; +import common.entity.npc.EntityNPC; +import common.init.SpeciesRegistry; +import common.init.SpeciesRegistry.ModelType; +import common.log.Log; public abstract class EntityTexManager { public static String altTexture = null; public static int altLayer = -1; public static String altNpcLayer = null; - - public static final int MAX_SKIN_SIZE = 65536; private static final Set USER_TEXTURES = Sets.newHashSet(); private static final Map USER_LAYERS = Maps.newHashMap(); @@ -38,7 +35,7 @@ public abstract class EntityTexManager private static final Map DEF_LAYERS = Maps.newEnumMap(ModelType.class); public static void loadNpcTextures() { - TextureManager manager = Game.getGame().getTextureManager(); + TextureManager manager = Client.CLIENT.getTextureManager(); for(Entry entry : SpeciesRegistry.SKINS.entrySet()) { String skin = entry.getKey(); // skin = skin.startsWith("~") ? skin.substring(1) : skin; @@ -49,17 +46,17 @@ public abstract class EntityTexManager } catch(IOException e) { if(e instanceof FileNotFoundException) - Log.JNI.warn("Textur ist nicht vorhanden: " + loc); + Log.IO.warn("Textur ist nicht vorhanden: " + loc); else - Log.JNI.error(e, "Konnte Textur nicht laden: " + loc); + Log.IO.error(e, "Konnte Textur nicht laden: " + loc); try { image = TextureUtil.readImage(FileUtils.getResource(getDefault(entry.getValue()))); } catch(IOException e2) { if(e2 instanceof FileNotFoundException) - Log.JNI.warn("Textur ist nicht vorhanden: " + loc); + Log.IO.warn("Textur ist nicht vorhanden: " + loc); else - Log.JNI.error(e2, "Konnte Textur nicht laden: " + loc); + Log.IO.error(e2, "Konnte Textur nicht laden: " + loc); image = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setColor(Color.BLACK); @@ -101,9 +98,9 @@ public abstract class EntityTexManager } catch(IOException e) { if(e instanceof FileNotFoundException) - Log.JNI.warn("Textur ist nicht vorhanden: " + loc); + Log.IO.warn("Textur ist nicht vorhanden: " + loc); else - Log.JNI.error(e, "Konnte Textur nicht laden: " + loc); + Log.IO.error(e, "Konnte Textur nicht laden: " + loc); image = new BufferedImage(64, 32, BufferedImage.TYPE_INT_ARGB); Graphics2D g = image.createGraphics(); g.setColor(Color.BLACK); @@ -133,7 +130,7 @@ public abstract class EntityTexManager public static String getDefault(ModelType model) { String def = DEF_TEXTURES.get(model); if(def == null) - DEF_TEXTURES.put(model, def = Game.getGame().getRenderManager().getRenderObject(model).getDefaultTexture()); + DEF_TEXTURES.put(model, def = Client.CLIENT.getRenderManager().getRenderObject(model).getDefaultTexture()); return def; } @@ -152,21 +149,21 @@ public abstract class EntityTexManager public static LayerExtra getLayer(int id, String skin, ModelType model) { if(id == -1) - return Game.getGame().getTextureManager().getTexture(getNpcSkinLocation(skin)) != null ? NPC_LAYERS.get(skin.toLowerCase()) : DEF_LAYERS.get(model); - return altNpcLayer != null ? Game.getGame().getTextureManager().getTexture(getNpcSkinLocation(altNpcLayer)) != null ? - NPC_LAYERS.get(altNpcLayer.toLowerCase()) : DEF_LAYERS.get(model) : (altLayer != -1 ? USER_LAYERS.get(altLayer) : (USER_TEXTURES.contains(id) ? USER_LAYERS.get(id) : (skin != null && Game.getGame().getTextureManager().getTexture(getNpcSkinLocation(skin)) != null ? NPC_LAYERS.get(skin.toLowerCase()) : DEF_LAYERS.get(model)))); + return Client.CLIENT.getTextureManager().getTexture(getNpcSkinLocation(skin)) != null ? NPC_LAYERS.get(skin.toLowerCase()) : DEF_LAYERS.get(model); + return altNpcLayer != null ? Client.CLIENT.getTextureManager().getTexture(getNpcSkinLocation(altNpcLayer)) != null ? + NPC_LAYERS.get(altNpcLayer.toLowerCase()) : DEF_LAYERS.get(model) : (altLayer != -1 ? USER_LAYERS.get(altLayer) : (USER_TEXTURES.contains(id) ? USER_LAYERS.get(id) : (skin != null && Client.CLIENT.getTextureManager().getTexture(getNpcSkinLocation(skin)) != null ? NPC_LAYERS.get(skin.toLowerCase()) : DEF_LAYERS.get(model)))); } public static String getSkin(int id, String skin, ModelType model) { String loc = id != -1 ? (altTexture != null ? altTexture : getSkinLocation(id)) : getNpcSkinLocation(skin); - if(id != -1 && skin != null && Game.getGame().getTextureManager().getTexture(loc) == null) + if(id != -1 && skin != null && Client.CLIENT.getTextureManager().getTexture(loc) == null) loc = getNpcSkinLocation(skin); - return Game.getGame().getTextureManager().getTexture(loc) != null ? loc : getDefault(model); + return Client.CLIENT.getTextureManager().getTexture(loc) != null ? loc : getDefault(model); } public static boolean hasCustomSkin(int id) { - return Game.getGame().getTextureManager().getTexture(getSkinLocation(id)) != null; + return Client.CLIENT.getTextureManager().getTexture(getSkinLocation(id)) != null; } public static String getCape(String name) @@ -174,7 +171,7 @@ public abstract class EntityTexManager if(name == null || name.isEmpty()) return null; String loc = getCapeLocation(name); - return Game.getGame().getTextureManager().getTexture(loc) != null ? loc : null; + return Client.CLIENT.getTextureManager().getTexture(loc) != null ? loc : null; } public static void clearTextures() { @@ -188,7 +185,7 @@ public abstract class EntityTexManager if(comp == null && !USER_TEXTURES.contains(id)) return; // user = user.toLowerCase(); - TextureManager manager = Game.getGame().getTextureManager(); + TextureManager manager = Client.CLIENT.getTextureManager(); String loc = getSkinLocation(id); DynamicTexture dyntex = (DynamicTexture)manager.getTexture(loc); if(comp == null) { @@ -222,16 +219,28 @@ public abstract class EntityTexManager } public static void compToImage(byte[] comp, int[] img, ModelType model) { - RenderNpc render = Game.getGame().getRenderManager().getRenderObject(model); + RenderNpc render = Client.CLIENT.getRenderManager().getRenderObject(model); if(comp.length < render.getCompressedSize()) comp = new byte[render.getCompressedSize()]; render.compToImage(comp, img, model.texWidth); } public static byte[] imageToComp(int[] img, ModelType model) { - RenderNpc render = Game.getGame().getRenderManager().getRenderObject(model); + RenderNpc render = Client.CLIENT.getRenderManager().getRenderObject(model); byte[] comp = new byte[render.getCompressedSize()]; render.imageToComp(comp, img, model.texWidth); return comp; } + + public static String getSkin(EntityNPC entity) { + return getSkin(entity.isPlayer() ? entity.getId() : -1, entity.getChar(), entity.getSpecies().renderer); + } + + public static LayerExtra getLayer(EntityNPC entity) { + return getLayer(entity.isPlayer() ? entity.getId() : -1, entity.getChar(), entity.getSpecies().renderer); + } + + public static String getCape(EntityNPC entity) { + return !entity.getCape().isEmpty() ? EntityTexManager.getCape(entity.getCape()) : null; + } } diff --git a/java/src/game/renderer/texture/IIconCreator.java b/client/src/main/java/client/renderer/texture/IIconCreator.java similarity index 72% rename from java/src/game/renderer/texture/IIconCreator.java rename to client/src/main/java/client/renderer/texture/IIconCreator.java index 3b6c142..ed1f0aa 100755 --- a/java/src/game/renderer/texture/IIconCreator.java +++ b/client/src/main/java/client/renderer/texture/IIconCreator.java @@ -1,4 +1,4 @@ -package game.renderer.texture; +package client.renderer.texture; public interface IIconCreator { diff --git a/java/src/game/renderer/texture/LayeredColorMaskTexture.java b/client/src/main/java/client/renderer/texture/LayeredColorMaskTexture.java similarity index 94% rename from java/src/game/renderer/texture/LayeredColorMaskTexture.java rename to client/src/main/java/client/renderer/texture/LayeredColorMaskTexture.java index 14aff6b..dfb3312 100755 --- a/java/src/game/renderer/texture/LayeredColorMaskTexture.java +++ b/client/src/main/java/client/renderer/texture/LayeredColorMaskTexture.java @@ -1,4 +1,4 @@ -package game.renderer.texture; +package client.renderer.texture; import java.awt.Graphics; import java.awt.image.BufferedImage; @@ -7,9 +7,9 @@ import java.io.IOException; import java.io.InputStream; import java.util.List; -import game.color.DyeColor; -import game.log.Log; -import game.util.FileUtils; +import client.util.FileUtils; +import common.color.DyeColor; +import common.log.Log; public class LayeredColorMaskTexture extends Texture { @@ -92,7 +92,7 @@ public class LayeredColorMaskTexture extends Texture } catch (IOException ioexception) { - Log.JNI.error((Throwable)ioexception, (String)"Konnte Bild mit mehreren Schichten nicht laden"); + Log.IO.error((Throwable)ioexception, (String)"Konnte Bild mit mehreren Schichten nicht laden"); return; } diff --git a/java/src/game/renderer/texture/LayeredTexture.java b/client/src/main/java/client/renderer/texture/LayeredTexture.java similarity index 85% rename from java/src/game/renderer/texture/LayeredTexture.java rename to client/src/main/java/client/renderer/texture/LayeredTexture.java index cda67c9..26c5a96 100755 --- a/java/src/game/renderer/texture/LayeredTexture.java +++ b/client/src/main/java/client/renderer/texture/LayeredTexture.java @@ -1,4 +1,4 @@ -package game.renderer.texture; +package client.renderer.texture; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; @@ -6,10 +6,9 @@ import java.io.IOException; import java.io.InputStream; import java.util.List; -import game.collect.Lists; - -import game.log.Log; -import game.util.FileUtils; +import client.util.FileUtils; +import common.collect.Lists; +import common.log.Log; public class LayeredTexture extends Texture { @@ -45,7 +44,7 @@ public class LayeredTexture extends Texture } catch (IOException ioexception) { - Log.JNI.error((Throwable)ioexception, (String)"Konnte Bild mit mehreren Schichten nicht laden"); + Log.IO.error((Throwable)ioexception, (String)"Konnte Bild mit mehreren Schichten nicht laden"); return; } diff --git a/java/src/game/renderer/texture/SimpleTexture.java b/client/src/main/java/client/renderer/texture/SimpleTexture.java similarity index 92% rename from java/src/game/renderer/texture/SimpleTexture.java rename to client/src/main/java/client/renderer/texture/SimpleTexture.java index 0af92ec..c4aa0ed 100755 --- a/java/src/game/renderer/texture/SimpleTexture.java +++ b/client/src/main/java/client/renderer/texture/SimpleTexture.java @@ -1,10 +1,10 @@ -package game.renderer.texture; +package client.renderer.texture; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; -import game.util.FileUtils; +import client.util.FileUtils; public class SimpleTexture extends Texture { private final String location; diff --git a/java/src/game/renderer/texture/Stitcher.java b/client/src/main/java/client/renderer/texture/Stitcher.java similarity index 99% rename from java/src/game/renderer/texture/Stitcher.java rename to client/src/main/java/client/renderer/texture/Stitcher.java index e2b827d..f9cff3b 100755 --- a/java/src/game/renderer/texture/Stitcher.java +++ b/client/src/main/java/client/renderer/texture/Stitcher.java @@ -1,12 +1,12 @@ -package game.renderer.texture; +package client.renderer.texture; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; -import game.collect.Lists; -import game.collect.Sets; +import common.collect.Lists; +import common.collect.Sets; public class Stitcher { diff --git a/java/src/game/renderer/texture/Texture.java b/client/src/main/java/client/renderer/texture/Texture.java similarity index 90% rename from java/src/game/renderer/texture/Texture.java rename to client/src/main/java/client/renderer/texture/Texture.java index b98cdfd..4c0ab84 100755 --- a/java/src/game/renderer/texture/Texture.java +++ b/client/src/main/java/client/renderer/texture/Texture.java @@ -1,10 +1,10 @@ -package game.renderer.texture; +package client.renderer.texture; import java.io.IOException; import org.lwjgl.opengl.GL11; -import game.renderer.GlState; +import client.renderer.GlState; public abstract class Texture { diff --git a/java/src/game/renderer/texture/TextureAtlasSprite.java b/client/src/main/java/client/renderer/texture/TextureAtlasSprite.java similarity index 99% rename from java/src/game/renderer/texture/TextureAtlasSprite.java rename to client/src/main/java/client/renderer/texture/TextureAtlasSprite.java index d7ac2d9..4226a06 100755 --- a/java/src/game/renderer/texture/TextureAtlasSprite.java +++ b/client/src/main/java/client/renderer/texture/TextureAtlasSprite.java @@ -1,10 +1,10 @@ -package game.renderer.texture; +package client.renderer.texture; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.List; -import game.collect.Lists; +import common.collect.Lists; public class TextureAtlasSprite { diff --git a/java/src/game/renderer/texture/TextureManager.java b/client/src/main/java/client/renderer/texture/TextureManager.java similarity index 83% rename from java/src/game/renderer/texture/TextureManager.java rename to client/src/main/java/client/renderer/texture/TextureManager.java index 313f5cc..66f45fb 100755 --- a/java/src/game/renderer/texture/TextureManager.java +++ b/client/src/main/java/client/renderer/texture/TextureManager.java @@ -1,14 +1,13 @@ -package game.renderer.texture; +package client.renderer.texture; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Map; import java.util.Map.Entry; -import game.collect.Maps; - -import game.log.Log; -import game.renderer.GlState; +import client.renderer.GlState; +import common.collect.Maps; +import common.log.Log; public class TextureManager { private final Map textures = Maps.newHashMap(); @@ -29,9 +28,9 @@ public class TextureManager { } catch(IOException e) { if(e instanceof FileNotFoundException) - Log.JNI.warn("Textur ist nicht vorhanden: " + res); + Log.IO.warn("Textur ist nicht vorhanden: " + res); else - Log.JNI.error(e, "Konnte Textur nicht laden: " + res); + Log.IO.error(e, "Konnte Textur nicht laden: " + res); tex = TextureUtil.MISSING; this.textures.put(res, tex); flag = false; diff --git a/java/src/game/renderer/texture/TextureMap.java b/client/src/main/java/client/renderer/texture/TextureMap.java similarity index 84% rename from java/src/game/renderer/texture/TextureMap.java rename to client/src/main/java/client/renderer/texture/TextureMap.java index d0a89b6..9c52b1e 100755 --- a/java/src/game/renderer/texture/TextureMap.java +++ b/client/src/main/java/client/renderer/texture/TextureMap.java @@ -1,4 +1,4 @@ -package game.renderer.texture; +package client.renderer.texture; import java.awt.image.BufferedImage; import java.io.FileNotFoundException; @@ -7,15 +7,15 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; -import game.collect.Lists; -import game.collect.Maps; - -import game.block.Block; -import game.init.BlockRegistry; -import game.init.FluidRegistry; -import game.log.Log; -import game.renderer.GlState; -import game.util.FileUtils; +import client.init.RenderRegistry; +import client.renderer.GlState; +import client.util.FileUtils; +import common.block.Block; +import common.collect.Lists; +import common.collect.Maps; +import common.init.BlockRegistry; +import common.init.FluidRegistry; +import common.log.Log; public class TextureMap extends Texture { @@ -39,22 +39,30 @@ public class TextureMap extends Texture this.missingImage = new TextureAtlasSprite(LOCATION_MISSING_TEXTURE); // RenderRegistry.registerAnimations(this); Map map = Maps.newHashMap(); + Map> anim = Maps.newHashMap(); + RenderRegistry.registerAnimations(anim); for(Block block : BlockRegistry.REGISTRY) { block.getAnimatedTextures(map); } for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { - map.put("blocks/" + BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)) + "_still", + map.put("blocks/" + BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)) + "_still", FluidRegistry.getStaticAnim(z)); - map.put("blocks/" + BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)) + "_flow", + map.put("blocks/" + BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)) + "_flow", FluidRegistry.getFluidAnim(z)); } for(Entry entry : map.entrySet()) { - if(entry.getValue() instanceof Integer) + if(entry.getValue() instanceof Integer) { this.animTextures.put(entry.getKey(), (Integer)entry.getValue()); - else - this.tickedTextures.put(entry.getKey(), (Class)entry.getValue()); + } + else { + Class clazz = anim.get((String)entry.getValue()); + if(clazz == null) + throw new RuntimeException("Animation '" + (String)entry.getValue() + "' existiert nicht"); + this.tickedTextures.put(entry.getKey(), clazz); + } } map.clear(); + anim.clear(); } private void initMissingImage() @@ -107,17 +115,17 @@ public class TextureMap extends Texture } catch (RuntimeException runtimeexception) { - Log.JNI.error((Throwable)runtimeexception, (String)("Konnte Metadaten von " + name + " nicht laden")); + Log.IO.error((Throwable)runtimeexception, (String)("Konnte Metadaten von " + name + " nicht laden")); continue; } catch (FileNotFoundException f) { - Log.JNI.warn("Textur ist nicht vorhanden: " + name); + Log.IO.warn("Textur ist nicht vorhanden: " + name); continue; } catch (IOException ioexception1) { - Log.JNI.error((Throwable)ioexception1, (String)("Benutze Ersatztextur, konnte " + name + " nicht laden")); + Log.IO.error((Throwable)ioexception1, (String)("Benutze Ersatztextur, konnte " + name + " nicht laden")); continue; } @@ -159,7 +167,7 @@ public class TextureMap extends Texture throw stitcherexception; } - Log.JNI.info("Textur-Atlas in Größe " + stitcher.getCurrentWidth() + "x" + stitcher.getCurrentHeight() + " erstellt"); + Log.RENDER.info("Textur-Atlas in Größe " + stitcher.getCurrentWidth() + "x" + stitcher.getCurrentHeight() + " erstellt"); TextureUtil.allocateTexture(this.getGlTextureId(), stitcher.getCurrentWidth(), stitcher.getCurrentHeight()); Map map = Maps.newHashMap(this.mapRegisteredSprites); diff --git a/java/src/game/renderer/texture/TextureTicked.java b/client/src/main/java/client/renderer/texture/TextureTicked.java similarity index 79% rename from java/src/game/renderer/texture/TextureTicked.java rename to client/src/main/java/client/renderer/texture/TextureTicked.java index 5520aed..b2f0fa6 100755 --- a/java/src/game/renderer/texture/TextureTicked.java +++ b/client/src/main/java/client/renderer/texture/TextureTicked.java @@ -1,4 +1,4 @@ -package game.renderer.texture; +package client.renderer.texture; public abstract class TextureTicked { public abstract void renderStep(int[] data); diff --git a/java/src/game/renderer/texture/TextureUtil.java b/client/src/main/java/client/renderer/texture/TextureUtil.java similarity index 97% rename from java/src/game/renderer/texture/TextureUtil.java rename to client/src/main/java/client/renderer/texture/TextureUtil.java index 2baadf3..5fb705e 100755 --- a/java/src/game/renderer/texture/TextureUtil.java +++ b/client/src/main/java/client/renderer/texture/TextureUtil.java @@ -1,4 +1,4 @@ -package game.renderer.texture; +package client.renderer.texture; import static org.lwjgl.system.MemoryUtil.NULL; @@ -14,8 +14,8 @@ import javax.imageio.ImageIO; import org.lwjgl.opengl.GL11; import org.lwjgl.opengl.GL12; -import game.renderer.GlState; -import game.util.FileUtils; +import client.renderer.GlState; +import client.util.FileUtils; public class TextureUtil { diff --git a/java/src/game/renderer/ticked/TextureFlamesFX1.java b/client/src/main/java/client/renderer/ticked/TextureFlamesFX1.java similarity index 80% rename from java/src/game/renderer/ticked/TextureFlamesFX1.java rename to client/src/main/java/client/renderer/ticked/TextureFlamesFX1.java index adac8b8..470957b 100755 --- a/java/src/game/renderer/ticked/TextureFlamesFX1.java +++ b/client/src/main/java/client/renderer/ticked/TextureFlamesFX1.java @@ -1,15 +1,21 @@ -package game.renderer.ticked; +package client.renderer.ticked; -import game.renderer.texture.TextureTicked; +import client.renderer.texture.TextureTicked; public class TextureFlamesFX1 extends TextureTicked -{ +{ + private final boolean mono; - public TextureFlamesFX1() + public TextureFlamesFX1(boolean mono) { field_1133_g = new float[320]; - field_1132_h = new float[320]; + field_1132_h = new float[320]; + this.mono = mono; + } + + public TextureFlamesFX1() { + this(false); } public void renderStep(int textureData[]) @@ -76,8 +82,14 @@ public class TextureFlamesFX1 extends TextureTicked // j1 = l2; // l1 = i3; // j2 = j3; -// } - textureData[k] = (c << 24) | (j1 << 16) | (l1 << 8) | j2; +// } + if(this.mono) { + j2 = (j1 + l1 + j2) / 3; + textureData[k] = (c << 24) | (j2 << 16) | (j2 << 8) | j2; + } + else { + textureData[k] = (c << 24) | (j1 << 16) | (l1 << 8) | j2; + } } } diff --git a/java/src/game/renderer/ticked/TextureFlamesFX2.java b/client/src/main/java/client/renderer/ticked/TextureFlamesFX2.java similarity index 62% rename from java/src/game/renderer/ticked/TextureFlamesFX2.java rename to client/src/main/java/client/renderer/ticked/TextureFlamesFX2.java index 2328e07..89ede38 100755 --- a/java/src/game/renderer/ticked/TextureFlamesFX2.java +++ b/client/src/main/java/client/renderer/ticked/TextureFlamesFX2.java @@ -1,11 +1,17 @@ -package game.renderer.ticked; +package client.renderer.ticked; public class TextureFlamesFX2 extends TextureFlamesFX1 { - public TextureFlamesFX2() + public TextureFlamesFX2(boolean mono) { + super(mono); int[] tex = new int[256]; for(int z = 0; z < 160; z++) { this.renderStep(tex); } } + + public TextureFlamesFX2() + { + this(false); + } } diff --git a/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono1.java b/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono1.java new file mode 100644 index 0000000..df13b2a --- /dev/null +++ b/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono1.java @@ -0,0 +1,7 @@ +package client.renderer.ticked; + +public class TextureFlamesFXMono1 extends TextureFlamesFX1 { + public TextureFlamesFXMono1() { + super(true); + } +} diff --git a/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono2.java b/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono2.java new file mode 100644 index 0000000..2c4a094 --- /dev/null +++ b/client/src/main/java/client/renderer/ticked/TextureFlamesFXMono2.java @@ -0,0 +1,7 @@ +package client.renderer.ticked; + +public class TextureFlamesFXMono2 extends TextureFlamesFX2 { + public TextureFlamesFXMono2() { + super(true); + } +} diff --git a/java/src/game/renderer/ticked/TextureLavaFX.java b/client/src/main/java/client/renderer/ticked/TextureLavaFX.java similarity index 93% rename from java/src/game/renderer/ticked/TextureLavaFX.java rename to client/src/main/java/client/renderer/ticked/TextureLavaFX.java index d7a95eb..af7811d 100755 --- a/java/src/game/renderer/ticked/TextureLavaFX.java +++ b/client/src/main/java/client/renderer/ticked/TextureLavaFX.java @@ -1,7 +1,7 @@ -package game.renderer.ticked; +package client.renderer.ticked; -import game.renderer.texture.TextureTicked; -import game.util.ExtMath; +import client.renderer.texture.TextureTicked; +import common.util.ExtMath; public class TextureLavaFX extends TextureTicked { diff --git a/java/src/game/renderer/ticked/TextureLavaFlowFX.java b/client/src/main/java/client/renderer/ticked/TextureLavaFlowFX.java similarity index 94% rename from java/src/game/renderer/ticked/TextureLavaFlowFX.java rename to client/src/main/java/client/renderer/ticked/TextureLavaFlowFX.java index e9028af..2948f93 100755 --- a/java/src/game/renderer/ticked/TextureLavaFlowFX.java +++ b/client/src/main/java/client/renderer/ticked/TextureLavaFlowFX.java @@ -1,7 +1,7 @@ -package game.renderer.ticked; +package client.renderer.ticked; -import game.renderer.texture.TextureTicked; -import game.util.ExtMath; +import client.renderer.texture.TextureTicked; +import common.util.ExtMath; public class TextureLavaFlowFX extends TextureTicked { diff --git a/java/src/game/renderer/ticked/TextureWaterFX.java b/client/src/main/java/client/renderer/ticked/TextureWaterFX.java similarity index 85% rename from java/src/game/renderer/ticked/TextureWaterFX.java rename to client/src/main/java/client/renderer/ticked/TextureWaterFX.java index 0493dd1..7deb1c2 100755 --- a/java/src/game/renderer/ticked/TextureWaterFX.java +++ b/client/src/main/java/client/renderer/ticked/TextureWaterFX.java @@ -1,6 +1,6 @@ -package game.renderer.ticked; +package client.renderer.ticked; -import game.renderer.texture.TextureTicked; +import client.renderer.texture.TextureTicked; public class TextureWaterFX extends TextureTicked @@ -68,10 +68,10 @@ public class TextureWaterFX extends TextureTicked f1 = 0.0F; } float f2 = f1 * f1; - int l1 = (int)(32F + f2 * 32F); - int j2 = (int)(50F + f2 * 64F); - int k2 = 255; - int l2 = (int)(146F + f2 * 50F); + int r = (int)(32F + f2 * 32F); + int g = (int)(50F + f2 * 64F); + int b = 255; + int a = (int)(146F + f2 * 50F); // if(flag) // { // int i3 = (l1 * 30 + j2 * 59 + k2 * 11) / 100; @@ -81,7 +81,7 @@ public class TextureWaterFX extends TextureTicked // j2 = j3; // k2 = k3; // } - textureData[i1] = (l2 << 24) | (l1 << 16) | (j2 << 8) | k2; + textureData[i1] = (a << 24) | (r << 16) | (g << 8) | b; } } diff --git a/java/src/game/renderer/ticked/TextureWaterFlowFX.java b/client/src/main/java/client/renderer/ticked/TextureWaterFlowFX.java similarity index 86% rename from java/src/game/renderer/ticked/TextureWaterFlowFX.java rename to client/src/main/java/client/renderer/ticked/TextureWaterFlowFX.java index bdbe153..b28f2c1 100755 --- a/java/src/game/renderer/ticked/TextureWaterFlowFX.java +++ b/client/src/main/java/client/renderer/ticked/TextureWaterFlowFX.java @@ -1,6 +1,6 @@ -package game.renderer.ticked; +package client.renderer.ticked; -import game.renderer.texture.TextureTicked; +import client.renderer.texture.TextureTicked; public class TextureWaterFlowFX extends TextureTicked @@ -67,11 +67,11 @@ public class TextureWaterFlowFX extends TextureTicked { f1 = 0.0F; } - float f2 = f1 * f1; - int l1 = (int)(32F + f2 * 32F); - int j2 = (int)(50F + f2 * 64F); - int k2 = 255; - int l2 = (int)(146F + f2 * 50F); + float v = f1 * f1; + int r = (int)(32F + v * 32F); + int g = (int)(50F + v * 64F); + int b = 255; + int a = (int)(146F + v * 50F); // if(flag) // { // int i3 = (l1 * 30 + j2 * 59 + k2 * 11) / 100; @@ -83,7 +83,7 @@ public class TextureWaterFlowFX extends TextureTicked // } textureData[(i1 & 0x0f) | ((i1 & 0xf0) * 2)] = textureData[((i1 & 0x0f) + 16) | ((i1 & 0xf0) * 2)] = textureData[(i1 & 0x0f) | (((i1 & 0xf0) + 256) * 2)] = textureData[((i1 & 0x0f) + 16) | (((i1 & 0xf0) + 256) * 2)] = - (l2 << 24) | (l1 << 16) | (j2 << 8) | k2; + (a << 24) | (r << 16) | (g << 8) | b; } } diff --git a/java/src/game/renderer/tileentity/TileEntityBannerRenderer.java b/client/src/main/java/client/renderer/tileentity/TileEntityBannerRenderer.java similarity index 87% rename from java/src/game/renderer/tileentity/TileEntityBannerRenderer.java rename to client/src/main/java/client/renderer/tileentity/TileEntityBannerRenderer.java index 939bd81..c518892 100755 --- a/java/src/game/renderer/tileentity/TileEntityBannerRenderer.java +++ b/client/src/main/java/client/renderer/tileentity/TileEntityBannerRenderer.java @@ -1,4 +1,4 @@ -package game.renderer.tileentity; +package client.renderer.tileentity; import java.util.Iterator; import java.util.List; @@ -6,18 +6,17 @@ import java.util.Map; import org.lwjgl.opengl.GL11; -import game.collect.Lists; -import game.collect.Maps; - -import game.Game; -import game.color.DyeColor; -import game.init.Blocks; -import game.renderer.GlState; -import game.renderer.model.ModelBanner; -import game.renderer.texture.LayeredColorMaskTexture; -import game.tileentity.TileEntityBanner; -import game.util.ExtMath; -import game.world.BlockPos; +import client.Client; +import client.renderer.GlState; +import client.renderer.model.ModelBanner; +import client.renderer.texture.LayeredColorMaskTexture; +import common.collect.Lists; +import common.collect.Maps; +import common.color.DyeColor; +import common.init.Blocks; +import common.tileentity.TileEntityBanner; +import common.util.BlockPos; +import common.util.ExtMath; public class TileEntityBannerRenderer extends TileEntitySpecialRenderer { @@ -112,7 +111,7 @@ public class TileEntityBannerRenderer extends TileEntitySpecialRenderer 60000L) { - Game.getGame().getTextureManager().deleteTexture(tileentitybannerrenderer$timedbannertexture1.bannerTexture); + Client.CLIENT.getTextureManager().deleteTexture(tileentitybannerrenderer$timedbannertexture1.bannerTexture); iterator.remove(); } } @@ -134,7 +133,7 @@ public class TileEntityBannerRenderer extends TileEntitySpecialRenderer diff --git a/client/src/main/java/client/renderer/tileentity/TileEntityItemStackRenderer.java b/client/src/main/java/client/renderer/tileentity/TileEntityItemStackRenderer.java new file mode 100755 index 0000000..d470a79 --- /dev/null +++ b/client/src/main/java/client/renderer/tileentity/TileEntityItemStackRenderer.java @@ -0,0 +1,27 @@ +package client.renderer.tileentity; + +import common.init.Items; +import common.item.ItemStack; +import common.tileentity.TileEntityBanner; +import common.tileentity.TileEntityChest; + +public class TileEntityItemStackRenderer { + public static TileEntityItemStackRenderer instance = new TileEntityItemStackRenderer(); + + private final TileEntityChest chest = new TileEntityChest(0); + private final TileEntityChest trapChest = new TileEntityChest(1); + private final TileEntityBanner banner = new TileEntityBanner(); + + public void renderByItem(ItemStack stack) { + if(stack.getItem() == Items.banner) { + this.banner.setItemValues(stack); + TileEntityRendererDispatcher.instance.renderTileEntityAt(this.banner, 0.0D, 0.0D, 0.0D, 0.0F); + } + else if(stack.getItem() == Items.trapped_chest) { + TileEntityRendererDispatcher.instance.renderTileEntityAt(this.trapChest, 0.0D, 0.0D, 0.0D, 0.0F); + } + else if(stack.getItem() == Items.chest) { + TileEntityRendererDispatcher.instance.renderTileEntityAt(this.chest, 0.0D, 0.0D, 0.0D, 0.0F); + } + } +} diff --git a/java/src/game/renderer/tileentity/TileEntityPistonRenderer.java b/client/src/main/java/client/renderer/tileentity/TileEntityPistonRenderer.java similarity index 82% rename from java/src/game/renderer/tileentity/TileEntityPistonRenderer.java rename to client/src/main/java/client/renderer/tileentity/TileEntityPistonRenderer.java index 201fbad..f40c247 100755 --- a/java/src/game/renderer/tileentity/TileEntityPistonRenderer.java +++ b/client/src/main/java/client/renderer/tileentity/TileEntityPistonRenderer.java @@ -1,28 +1,27 @@ -package game.renderer.tileentity; +package client.renderer.tileentity; import org.lwjgl.opengl.GL11; -import game.Game; -import game.block.Block; -import game.block.BlockPistonBase; -import game.block.BlockPistonHead; -import game.init.Blocks; -import game.material.Material; -import game.renderer.BlockRenderer; -import game.renderer.DefaultVertexFormats; -import game.renderer.GlState; -import game.renderer.ItemRenderer; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.renderer.texture.TextureMap; -import game.tileentity.TileEntityPiston; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import client.Client; +import client.renderer.BlockRenderer; +import client.renderer.DefaultVertexFormats; +import client.renderer.GlState; +import client.renderer.ItemRenderer; +import client.renderer.RenderBuffer; +import client.renderer.Tessellator; +import client.renderer.texture.TextureMap; +import common.block.Block; +import common.block.tech.BlockPistonBase; +import common.block.tech.BlockPistonHead; +import common.init.Blocks; +import common.tileentity.TileEntityPiston; +import common.util.BlockPos; +import common.world.State; +import common.world.World; public class TileEntityPistonRenderer extends TileEntitySpecialRenderer { - private final BlockRenderer blockRenderer = Game.getGame().getBlockRendererDispatcher(); + private final BlockRenderer blockRenderer = Client.CLIENT.getBlockRendererDispatcher(); public void renderTileEntityAt(TileEntityPiston te, double x, double y, double z, float partialTicks, int destroyStage) { @@ -30,7 +29,7 @@ public class TileEntityPistonRenderer extends TileEntitySpecialRenderer tileentityspecialrenderer : this.mapSpecialRenderers.values()) diff --git a/java/src/game/renderer/tileentity/TileEntitySignRenderer.java b/client/src/main/java/client/renderer/tileentity/TileEntitySignRenderer.java similarity index 92% rename from java/src/game/renderer/tileentity/TileEntitySignRenderer.java rename to client/src/main/java/client/renderer/tileentity/TileEntitySignRenderer.java index 0d20bab..8f3ed06 100755 --- a/java/src/game/renderer/tileentity/TileEntitySignRenderer.java +++ b/client/src/main/java/client/renderer/tileentity/TileEntitySignRenderer.java @@ -1,14 +1,13 @@ -package game.renderer.tileentity; +package client.renderer.tileentity; import org.lwjgl.opengl.GL11; -import game.block.Block; -import game.gui.Font; -import game.init.Blocks; -import game.renderer.Drawing; -import game.renderer.GlState; -import game.renderer.model.ModelSign; -import game.tileentity.TileEntitySign; +import client.renderer.Drawing; +import client.renderer.GlState; +import client.renderer.model.ModelSign; +import common.block.Block; +import common.init.Blocks; +import common.tileentity.TileEntitySign; public class TileEntitySignRenderer extends TileEntitySpecialRenderer @@ -103,7 +102,7 @@ public class TileEntitySignRenderer extends TileEntitySpecialRenderer { diff --git a/client/src/main/java/client/util/FileUtils.java b/client/src/main/java/client/util/FileUtils.java new file mode 100644 index 0000000..86f2731 --- /dev/null +++ b/client/src/main/java/client/util/FileUtils.java @@ -0,0 +1,65 @@ +package client.util; + +import java.io.ByteArrayOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.Charset; + +public class FileUtils { + private static final Charset UTF_8 = Charset.forName("UTF-8"); + + public static String read(File file) throws IOException { + FileInputStream in = null; + String s; + try { + in = new FileInputStream(file); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + byte[] buffer = new byte[4096]; + long count = 0L; + int n; + for(boolean u = false; -1 != (n = in.read(buffer)); count += (long)n) { + output.write(buffer, 0, n); + } + s = new String(output.toByteArray(), UTF_8); + } + finally { + try { + if(in != null) + in.close(); + } + catch(IOException e) { + } + } + return s; + } + + public static void write(File file, String data) throws IOException { + FileOutputStream out = null; + try { + out = new FileOutputStream(file); + if(out != null) { + out.write(data.getBytes(UTF_8)); + out.close(); + } + } + finally { + try { + if(out != null) + out.close(); + } + catch(IOException e) { + } + } + } + + public static InputStream getResource(String path) throws FileNotFoundException { + InputStream in = FileUtils.class.getResourceAsStream("/" + path); + if(in == null) + throw new FileNotFoundException(path); + return in; + } +} diff --git a/client/src/main/java/client/util/Message.java b/client/src/main/java/client/util/Message.java new file mode 100644 index 0000000..284196c --- /dev/null +++ b/client/src/main/java/client/util/Message.java @@ -0,0 +1,4 @@ +package client.util; + +public record Message(String message, long time) { +} diff --git a/java/src/game/util/PerfSection.java b/client/src/main/java/client/util/PerfSection.java similarity index 95% rename from java/src/game/util/PerfSection.java rename to client/src/main/java/client/util/PerfSection.java index 581d4bd..9938445 100644 --- a/java/src/game/util/PerfSection.java +++ b/client/src/main/java/client/util/PerfSection.java @@ -1,4 +1,6 @@ -package game.util; +package client.util; + +import common.util.Util; public enum PerfSection { TIMING("Timing"), diff --git a/client/src/main/java/client/util/PlayerController.java b/client/src/main/java/client/util/PlayerController.java new file mode 100755 index 0000000..e18d64f --- /dev/null +++ b/client/src/main/java/client/util/PlayerController.java @@ -0,0 +1,314 @@ +package client.util; + +import client.Client; +import client.network.ClientPlayer; +import client.world.WorldClient; +import common.block.Block; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.EntityRegistry; +import common.item.ItemBlock; +import common.item.ItemControl; +import common.item.ItemStack; +import common.packet.CPacketAction; +import common.packet.CPacketBreak; +import common.packet.CPacketClick; +import common.packet.CPacketPlace; +import common.sound.PositionedSound; +import common.util.BlockPos; +import common.util.Facing; +import common.util.Vec3; +import common.world.State; +import common.world.World; + +public class PlayerController { + private final Client gm; + private final ClientPlayer handler; + + private BlockPos position = new BlockPos(-1, -World.MAX_SIZE_Y - 1, -1); + private ItemStack stack; + private float damage; + private float stepCounter; + private int delay; + private boolean hitting; + private int lastSelected; + private boolean interacting; + + public PlayerController(Client gm, ClientPlayer handler) { + this.gm = gm; + this.handler = handler; + } + + public boolean destroyBlock(BlockPos pos, Facing side) { + World world = this.gm.world; + State state = world.getState(pos); + Block block = state.getBlock(); + + if(block == Blocks.air) { + return false; + } + else { + world.playAuxSFX(2001, pos, BlockRegistry.getStateId(state)); + boolean flag = world.setBlockToAir(pos); + + if(flag) { + block.onBlockDestroyedByPlayer(world, pos, state); + } + + this.position = new BlockPos(this.position.getX(), -1, this.position.getZ()); + + ItemStack stack = this.gm.player.getCurrentEquippedItem(); + + if(stack != null) { + stack.onBlockDestroyed(world, block, pos, this.gm.player); + + if(stack.size == 0) { + this.gm.player.destroyCurrentEquippedItem(); + } + } + + return flag; + } + } + + public boolean clickBlock(BlockPos pos, Facing face) { + if(!World.isValidXZ(pos)) { + return false; + } + else { + ItemStack stack = this.gm.player.getHeldItem(); + if(stack != null && stack.getItem().onAction(stack, this.gm.player, this.gm.world, ItemControl.PRIMARY, pos)) { + this.interacting = true; + this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, pos, face)); + return true; + } + if(!this.hitting || !this.isHitting(pos)) { + if(this.hitting) { + this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.ABORT_DESTROY_BLOCK, this.position, face)); + } + + this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, pos, face)); + Block block = this.gm.world.getState(pos).getBlock(); + boolean flag = block != Blocks.air; + + if(flag && this.damage == 0.0F) { + block.onBlockClicked(this.gm.world, pos, this.gm.player); + } + + if(flag && block.getPlayerRelativeBlockHardness(this.gm.player, this.gm.player.worldObj, pos) >= 1.0F) { + this.destroyBlock(pos, face); + this.delay = 3; + } + else { + this.hitting = true; + this.position = pos; + this.stack = this.gm.player.getHeldItem(); + this.damage = 0.0F; + this.stepCounter = 0.0F; + this.gm.world.sendBlockBreakProgress(this.gm.player.getId(), this.position, (int)(this.damage * 10.0F) - 1); + } + } + + return true; + } + } + + public void resetProgress() { + if(this.hitting) { + this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.ABORT_DESTROY_BLOCK, this.position, Facing.DOWN)); + this.hitting = false; + this.damage = 0.0F; + this.gm.world.sendBlockBreakProgress(this.gm.player.getId(), this.position, -1); + } + } + + public void resetInteraction() { + this.interacting = false; + } + + public boolean damageBlock(BlockPos pos, Facing face) { + if(this.interacting) + return false; + this.syncItem(); + + if(this.delay > 0) { + --this.delay; + return true; + } + else if(this.isHitting(pos)) { + Block block = this.gm.world.getState(pos).getBlock(); + + if(block == Blocks.air) { + this.hitting = false; + return false; + } + else { + this.damage += block.getPlayerRelativeBlockHardness(this.gm.player, this.gm.player.worldObj, pos); + + if(this.stepCounter % 4.0F == 0.0F && block.sound.getStepSound() != null) { + this.gm.getSoundManager().playSound(new PositionedSound(block.sound.getStepSound(), 0.25F, + (float)pos.getX() + 0.5F, (float)pos.getY() + 0.5F, (float)pos.getZ() + 0.5F)); + } + + ++this.stepCounter; + + if(this.damage >= 1.0F) { + this.hitting = false; + this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.STOP_DESTROY_BLOCK, pos, face)); + this.destroyBlock(pos, face); + this.damage = 0.0F; + this.stepCounter = 0.0F; + this.delay = 5; + } + + this.gm.world.sendBlockBreakProgress(this.gm.player.getId(), this.position, (int)(this.damage * 10.0F) - 1); + return true; + } + } + else { + return this.clickBlock(pos, face); + } + } + + public void update() { + this.syncItem(); + + if(this.handler.getConnection().isChannelOpen()) { + this.handler.getConnection().processReceivedPackets(); + } + else { + this.handler.getConnection().checkDisconnected(); + } + } + + private boolean isHitting(BlockPos pos) { + ItemStack stack = this.gm.player.getHeldItem(); + boolean flag = this.stack == null && stack == null; + + if(this.stack != null && stack != null) { + flag = stack.getItem() == this.stack.getItem() + && ItemStack.areItemStackTagsEqual(stack, this.stack) + && (stack.isItemStackDamageable() || stack.getMetadata() == this.stack.getMetadata()); + } + + return pos.equals(this.position) && flag; + } + + private void syncItem() { + int slot = this.gm.player.inventory.currentItem; + + if(slot != this.lastSelected) { + this.lastSelected = slot; + this.handler.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_ITEMSLOT, this.lastSelected)); + } + } + + public boolean clickRight(EntityNPC player, WorldClient world, ItemStack stack, BlockPos pos, Facing side, Vec3 hit) { + this.syncItem(); + float f = (float)(hit.xCoord - (double)pos.getX()); + float f1 = (float)(hit.yCoord - (double)pos.getY()); + float f2 = (float)(hit.zCoord - (double)pos.getZ()); + boolean flag = false; + + if(!World.isValidXZ(pos)) { + return false; + } + else { + if(stack == null || !stack.getItem().onAction(stack, player, world, ItemControl.SECONDARY, pos)) { + State iblockstate = world.getState(pos); + + if((!player.isSneaking() || player.getHeldItem() == null) + && iblockstate.getBlock().onBlockActivated(world, pos, iblockstate, player, side, f, f1, f2)) { + flag = true; + } + + if(!flag && stack != null && stack.getItem() instanceof ItemBlock) { + ItemBlock itemblock = (ItemBlock)stack.getItem(); + + if(!itemblock.canPlaceBlockOnSide(world, pos, side, player, stack)) { + return false; + } + } + } + else { + stack.getItem().onItemUse(stack, player, world, pos, side, f, f1, f2); + flag = true; + } + + this.handler.addToSendQueue(new CPacketPlace(pos, side.getIndex(), player.inventory.getCurrentItem(), f, f1, f2)); + + if(!flag) { + if(stack == null) { + return false; + } + else { + return stack.onItemUse(player, world, pos, side, f, f1, f2); + } + } + else { + return true; + } + } + } + + public boolean sendUseItem(EntityNPC player, World world, ItemStack stack) { + this.syncItem(); + this.handler.addToSendQueue(new CPacketPlace(player.inventory.getCurrentItem())); + int size = stack.size; + ItemStack changed = stack.useItemRightClick(world, player); + + if(changed != stack || changed != null && changed.size != size) { + player.inventory.mainInventory[player.inventory.currentItem] = changed; + + if(changed.size == 0) { + player.inventory.mainInventory[player.inventory.currentItem] = null; + } + + return true; + } + else { + return false; + } + } + + public EntityNPC createPlayerEntity(WorldClient world, int type) { + EntityNPC player = (EntityNPC)EntityRegistry.createEntityByID(type, world); + player.setClientPlayer(this.handler); + return player; + } + + public void attackEntity(EntityNPC player, Entity target) { + this.syncItem(); + this.handler.addToSendQueue(new CPacketAction(CPacketAction.Action.ATTACK, target.getId())); + player.attackTargetEntityWithCurrentItem(target); + } + + public boolean interact(EntityNPC player, Entity target) { + this.syncItem(); + this.handler.addToSendQueue(new CPacketAction(CPacketAction.Action.INTERACT, target.getId())); + return player.interactWith(target); + } + + public ItemStack windowClick(int window, int slot, int button, int mode, EntityNPC player) { + short id = player.openContainer.getNextTransactionID(player.inventory); + ItemStack stack = player.openContainer.slotClick(slot, button, mode, player); + this.handler.addToSendQueue(new CPacketClick(window, slot, button, mode, stack, id)); + return stack; + } + + public void sendEnchantPacket(int window, int button) { + this.handler.addToSendQueue(new CPacketAction(CPacketAction.Action.ENCHANT_ITEM, window | (button << 8))); + } + + public void stopUsing(EntityNPC player) { + this.syncItem(); + this.handler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, Facing.DOWN)); + player.stopUsingItem(); + } + + public boolean isHittingBlock() { + return this.hitting; + } +} diff --git a/java/src/game/util/SkinConverter.java b/client/src/main/java/client/util/SkinConverter.java similarity index 95% rename from java/src/game/util/SkinConverter.java rename to client/src/main/java/client/util/SkinConverter.java index 5cb618f..dffc049 100755 --- a/java/src/game/util/SkinConverter.java +++ b/client/src/main/java/client/util/SkinConverter.java @@ -1,4 +1,4 @@ -package game.util; +package client.util; import java.awt.Color; import java.awt.Graphics; @@ -9,7 +9,7 @@ import java.io.IOException; import javax.imageio.ImageIO; -import game.log.Log; +import common.log.Log; public abstract class SkinConverter { private static BufferedImage convertSkin(BufferedImage image) { @@ -171,20 +171,20 @@ public abstract class SkinConverter { img = ImageIO.read(source); } catch(IOException e) { - Log.JNI.error(e, "Konnte kein Bild von " + source + " laden"); + Log.IO.error(e, "Konnte kein Bild von " + source + " laden"); return false; } if(img == null) { - Log.JNI.warn("Konnte kein Bild von " + source + " laden"); + Log.IO.warn("Konnte kein Bild von " + source + " laden"); return false; } - Log.JNI.info("Bild von " + source + " geladen"); + Log.IO.info("Bild von " + source + " geladen"); if(img.getWidth() == 64 && img.getHeight() == 32) { img = convertSkin(img); - Log.JNI.info("Skin " + source + " konvertiert"); + Log.IO.info("Skin " + source + " konvertiert"); } else if(img.getWidth() != 64 || img.getHeight() != 64) { - Log.JNI.warn("Falsche Bildgröße von " + source + ": " + img.getWidth() + "x" + img.getHeight()); + Log.IO.warn("Falsche Bildgröße von " + source + ": " + img.getWidth() + "x" + img.getHeight()); return false; } String name = source.getName(); @@ -195,7 +195,7 @@ public abstract class SkinConverter { name = "skin"; if(slim) { img = convertSlim(img); - Log.JNI.info("Skin " + source + " von 'Slim' konvertiert"); + Log.IO.info("Skin " + source + " von 'Slim' konvertiert"); if(!name.startsWith("slim_")) name = "slim_" + name; } @@ -217,10 +217,10 @@ public abstract class SkinConverter { ImageIO.write(img, "png", file); } catch(Exception e) { - Log.JNI.error(e, "Konnte Bild nicht speichern"); + Log.IO.error(e, "Konnte Bild nicht speichern"); return false; } - Log.JNI.info("Skin " + source + " gespeichert als " + file.getName()); + Log.IO.info("Skin " + source + " gespeichert als " + file.getName()); return true; } diff --git a/java/src/game/vars/BaseVar.java b/client/src/main/java/client/vars/BaseVar.java similarity index 97% rename from java/src/game/vars/BaseVar.java rename to client/src/main/java/client/vars/BaseVar.java index 2029a09..e6c4c33 100644 --- a/java/src/game/vars/BaseVar.java +++ b/client/src/main/java/client/vars/BaseVar.java @@ -1,4 +1,4 @@ -package game.vars; +package client.vars; import java.lang.reflect.Field; diff --git a/java/src/game/vars/BoolVar.java b/client/src/main/java/client/vars/BoolVar.java similarity index 89% rename from java/src/game/vars/BoolVar.java rename to client/src/main/java/client/vars/BoolVar.java index fb3b9aa..103f1ca 100644 --- a/java/src/game/vars/BoolVar.java +++ b/client/src/main/java/client/vars/BoolVar.java @@ -1,10 +1,11 @@ -package game.vars; +package client.vars; import java.lang.reflect.Field; -import game.color.TextColor; -import game.gui.element.Toggle; -import game.util.Util; +import client.gui.element.Toggle; +import client.gui.element.ToggleCallback; +import common.color.TextColor; +import common.util.Util; public class BoolVar extends BaseVar { public static interface BoolFunction extends VarFunction { @@ -59,7 +60,7 @@ public class BoolVar extends BaseVar { public Toggle selector(int x, int y, int w, int h) { try { - return new Toggle(x, y, w, h, this.def, this.field.getBoolean(this.object), new Toggle.Callback() { + return new Toggle(x, y, w, h, this.def, this.field.getBoolean(this.object), new ToggleCallback() { public void use(Toggle elem, boolean value) { BoolVar.this.parse("" + value); } diff --git a/java/src/game/vars/CVar.java b/client/src/main/java/client/vars/CVar.java similarity index 77% rename from java/src/game/vars/CVar.java rename to client/src/main/java/client/vars/CVar.java index bddcd04..07a86bb 100644 --- a/java/src/game/vars/CVar.java +++ b/client/src/main/java/client/vars/CVar.java @@ -1,7 +1,7 @@ -package game.vars; +package client.vars; -import game.gui.element.Element; -import game.util.Displayable; +import client.gui.element.Element; +import common.util.Displayable; public interface CVar extends Displayable { String getType(); diff --git a/java/src/game/vars/CVarCategory.java b/client/src/main/java/client/vars/CVarCategory.java similarity index 89% rename from java/src/game/vars/CVarCategory.java rename to client/src/main/java/client/vars/CVarCategory.java index 8445c25..aa40d07 100644 --- a/java/src/game/vars/CVarCategory.java +++ b/client/src/main/java/client/vars/CVarCategory.java @@ -1,6 +1,6 @@ -package game.vars; +package client.vars; -import game.color.TextColor; +import common.color.TextColor; public enum CVarCategory { SYSTEM(TextColor.RED + "system"), diff --git a/java/src/game/vars/ColorVar.java b/client/src/main/java/client/vars/ColorVar.java similarity index 66% rename from java/src/game/vars/ColorVar.java rename to client/src/main/java/client/vars/ColorVar.java index 0651922..be15feb 100644 --- a/java/src/game/vars/ColorVar.java +++ b/client/src/main/java/client/vars/ColorVar.java @@ -1,14 +1,14 @@ -package game.vars; +package client.vars; import java.lang.reflect.Field; -import game.color.TextColor; -import game.gui.Style; -import game.gui.element.Label; -import game.gui.element.Slider; -import game.gui.element.Textbox; -import game.gui.element.Textbox.Action; -import game.util.Util; +import client.gui.Style; +import client.gui.element.FieldCallback; +import client.gui.element.Label; +import client.gui.element.Slider; +import client.gui.element.FieldAction; +import common.color.TextColor; +import common.util.Util; public class ColorVar extends IntVar { private final boolean alpha; @@ -26,6 +26,8 @@ public class ColorVar extends IntVar { if(str.length() != (this.alpha ? 8 : 6)) return null; Integer value = Util.parseInt(str, -16); + if(value == null) + return null; return this.alpha || (value & 0xff000000) == 0 ? (this.alpha ? value : (0xff000000 | value)) : null; } @@ -37,14 +39,14 @@ public class ColorVar extends IntVar { throw new UnsupportedOperationException("Kann keinen Schieberegler für Farben erstellen"); } - public Label label(int x, int y, int w, int h) { - return new Label(x, y, w, h, this.display); + public Label label(int x, int y, int w) { + return new Label(x, y, w, this.display); } - public Textbox editor(int x, int y, int w, int h) { - return new Textbox(x, y, w, h, this.alpha ? 8 : 6, true, new Textbox.Callback() { - public void use(Textbox elem, Textbox.Action value) { - if(value == Action.SEND || value == Action.UNFOCUS) + public client.gui.element.Field editor(int x, int y, int w, int h) { + return new client.gui.element.Field(x, y, w, h, this.alpha ? 8 : 6, new FieldCallback() { + public void use(client.gui.element.Field elem, FieldAction value) { + if(value == FieldAction.SEND || value == FieldAction.UNFOCUS) ColorVar.this.parse(elem.getText()); } }, this.format()); diff --git a/java/src/game/vars/EnumVar.java b/client/src/main/java/client/vars/EnumVar.java similarity index 73% rename from java/src/game/vars/EnumVar.java rename to client/src/main/java/client/vars/EnumVar.java index 68900f1..5f8273f 100644 --- a/java/src/game/vars/EnumVar.java +++ b/client/src/main/java/client/vars/EnumVar.java @@ -1,13 +1,15 @@ -package game.vars; +package client.vars; import java.lang.reflect.Field; -import game.color.TextColor; -import game.gui.element.Dropdown; -import game.gui.element.Element; -import game.gui.element.Switch; -import game.properties.IStringSerializable; -import game.util.Util; +import client.gui.element.Dropdown; +import client.gui.element.DropdownCallback; +import client.gui.element.Element; +import client.gui.element.Switch; +import client.gui.element.SwitchCallback; +import common.color.TextColor; +import common.util.Identifyable; +import common.util.Util; public class EnumVar extends BaseVar { public static interface EnumFunction extends VarFunction { @@ -27,7 +29,7 @@ public class EnumVar extends BaseVar { for(T value : (T[])field.getType().getEnumConstants()) { if(sb.length() > 0) sb.append(','); - sb.append(value instanceof IStringSerializable ? ((IStringSerializable)value).getName() : value.toString()); + sb.append(value instanceof Identifyable ? ((Identifyable)value).getName() : value.toString()); } this.values = sb.toString(); try { @@ -60,7 +62,7 @@ public class EnumVar extends BaseVar { public String format() { try { T value = (T)this.field.get(this.object); - return value instanceof IStringSerializable ? ((IStringSerializable)value).getName() : value.toString(); + return value instanceof Identifyable ? ((Identifyable)value).getName() : value.toString(); } catch(IllegalArgumentException | IllegalAccessException e) { throw new RuntimeException(e); @@ -68,7 +70,7 @@ public class EnumVar extends BaseVar { } public String getDefault() { - return this.def instanceof IStringSerializable ? ((IStringSerializable)this.def).getName() : this.def.toString(); + return this.def instanceof Identifyable ? ((Identifyable)this.def).getName() : this.def.toString(); } public String getValues() { @@ -79,9 +81,9 @@ public class EnumVar extends BaseVar { if(this.useSwitch) return this.switcher(x, y, w, h); try { - return new Dropdown(x, y, w, h, false, (T[])this.field.getType().getEnumConstants(), this.def, (T)this.field.get(this.object), new Dropdown.Callback() { + return new Dropdown(x, y, w, h, false, (T[])this.field.getType().getEnumConstants(), this.def, (T)this.field.get(this.object), new DropdownCallback() { public void use(Dropdown elem, T value) { - EnumVar.this.parse(value instanceof IStringSerializable ? ((IStringSerializable)value).getName() : value.toString()); + EnumVar.this.parse(value instanceof Identifyable ? ((Identifyable)value).getName() : value.toString()); } }, this.display); } @@ -92,9 +94,9 @@ public class EnumVar extends BaseVar { public Switch switcher(int x, int y, int w, int h) { try { - return new Switch(x, y, w, h, (T[])this.field.getType().getEnumConstants(), this.def, (T)this.field.get(this.object), new Switch.Callback() { + return new Switch(x, y, w, h, (T[])this.field.getType().getEnumConstants(), this.def, (T)this.field.get(this.object), new SwitchCallback() { public void use(Switch elem, T value) { - EnumVar.this.parse(value instanceof IStringSerializable ? ((IStringSerializable)value).getName() : value.toString()); + EnumVar.this.parse(value instanceof Identifyable ? ((Identifyable)value).getName() : value.toString()); } }, this.display); } diff --git a/java/src/game/vars/FloatVar.java b/client/src/main/java/client/vars/FloatVar.java similarity index 92% rename from java/src/game/vars/FloatVar.java rename to client/src/main/java/client/vars/FloatVar.java index cbac18e..43c6a3f 100644 --- a/java/src/game/vars/FloatVar.java +++ b/client/src/main/java/client/vars/FloatVar.java @@ -1,10 +1,11 @@ -package game.vars; +package client.vars; import java.lang.reflect.Field; -import game.color.TextColor; -import game.gui.element.Slider; -import game.util.ExtMath; +import client.gui.element.Slider; +import client.gui.element.SliderFloatCallback; +import common.color.TextColor; +import common.util.ExtMath; public class FloatVar extends BaseVar { public static interface FloatFunction extends VarFunction { @@ -90,7 +91,7 @@ public class FloatVar extends BaseVar { public Slider selector(int x, int y, int w, int h) { try { - return new Slider(x, y, w, h, this.unit.equals("%") ? -1 : this.precision, this.min, this.max, this.def, this.field.getFloat(this.object), new Slider.FloatCallback() { + return new Slider(x, y, w, h, this.unit.equals("%") ? -1 : this.precision, this.min, this.max, this.def, this.field.getFloat(this.object), new SliderFloatCallback() { public void use(Slider elem, float value) { FloatVar.this.parse(String.format(FloatVar.this.format, value)); } diff --git a/java/src/game/vars/IntVar.java b/client/src/main/java/client/vars/IntVar.java similarity index 90% rename from java/src/game/vars/IntVar.java rename to client/src/main/java/client/vars/IntVar.java index 95f791d..312bd72 100644 --- a/java/src/game/vars/IntVar.java +++ b/client/src/main/java/client/vars/IntVar.java @@ -1,11 +1,12 @@ -package game.vars; +package client.vars; import java.lang.reflect.Field; -import game.color.TextColor; -import game.gui.element.Slider; -import game.util.ExtMath; -import game.util.Util; +import client.gui.element.Slider; +import client.gui.element.SliderCallback; +import common.color.TextColor; +import common.util.ExtMath; +import common.util.Util; public class IntVar extends BaseVar { public static interface IntFunction extends VarFunction { @@ -82,7 +83,7 @@ public class IntVar extends BaseVar { public Slider selector(int x, int y, int w, int h) { try { - return new Slider(x, y, w, h, this.precision, this.min, this.max, this.def, this.field.getInt(this.object), new Slider.Callback() { + return new Slider(x, y, w, h, this.precision, this.min, this.max, this.def, this.field.getInt(this.object), new SliderCallback() { public void use(Slider elem, int value) { IntVar.this.parse(IntVar.this.formatValue(value)); } diff --git a/java/src/game/vars/StringVar.java b/client/src/main/java/client/vars/StringVar.java similarity index 79% rename from java/src/game/vars/StringVar.java rename to client/src/main/java/client/vars/StringVar.java index 7c52469..8654948 100644 --- a/java/src/game/vars/StringVar.java +++ b/client/src/main/java/client/vars/StringVar.java @@ -1,11 +1,11 @@ -package game.vars; +package client.vars; import java.lang.reflect.Field; -import game.color.TextColor; -import game.gui.element.Textbox; -import game.gui.element.Textbox.Action; -import game.util.CharValidator; +import client.gui.element.FieldCallback; +import client.gui.element.FieldAction; +import common.color.TextColor; +import common.util.CharValidator; public class StringVar extends BaseVar { public static interface StringFunction extends VarFunction { @@ -67,10 +67,10 @@ public class StringVar extends BaseVar { return this.def; } - public Textbox selector(int x, int y, int w, int h) { - return new Textbox(x, y, w, h, this.maxLength, true, new Textbox.Callback() { - public void use(Textbox elem, Textbox.Action value) { - if(value == Action.SEND || value == Action.UNFOCUS) { + public client.gui.element.Field selector(int x, int y, int w, int h) { + return new client.gui.element.Field(x, y, w, h, this.maxLength, new FieldCallback() { + public void use(client.gui.element.Field elem, FieldAction value) { + if(value == FieldAction.SEND || value == FieldAction.UNFOCUS) { if(!StringVar.this.allowEmpty && elem.getText().isEmpty()) elem.setText(StringVar.this.format()); else diff --git a/java/src/game/vars/Variable.java b/client/src/main/java/client/vars/Variable.java similarity index 88% rename from java/src/game/vars/Variable.java rename to client/src/main/java/client/vars/Variable.java index 606fd9e..4c16bb8 100644 --- a/java/src/game/vars/Variable.java +++ b/client/src/main/java/client/vars/Variable.java @@ -1,4 +1,4 @@ -package game.vars; +package client.vars; import static java.lang.annotation.ElementType.FIELD; @@ -6,8 +6,8 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; -import game.util.CharValidator; -import game.vars.BaseVar.VarFunction; +import client.vars.BaseVar.VarFunction; +import common.util.CharValidator; @Target(FIELD) @Retention(value = RetentionPolicy.RUNTIME) diff --git a/java/src/game/window/Bind.java b/client/src/main/java/client/window/Bind.java similarity index 89% rename from java/src/game/window/Bind.java rename to client/src/main/java/client/window/Bind.java index 5cf89db..ce4dfd2 100644 --- a/java/src/game/window/Bind.java +++ b/client/src/main/java/client/window/Bind.java @@ -1,19 +1,19 @@ -package game.window; +package client.window; -import game.Game; -import game.color.TextColor; -import game.gui.element.Element; -import game.properties.IStringSerializable; -import game.util.Util; -import game.vars.CVar; -import game.vars.CVarCategory; +import client.Client; +import client.gui.element.Element; +import client.vars.CVar; +import client.vars.CVarCategory; +import common.color.TextColor; +import common.util.Identifyable; +import common.util.Util; -public enum Bind implements IStringSerializable, CVar { +public enum Bind implements Identifyable, CVar { FORWARD("forward", "Vorwärts", Keysym.W), LEFT("left", "Nach links", Keysym.A), BACKWARD("backward", "Rückwärts", Keysym.S), RIGHT("right", "Nach rechts", Keysym.D), - UP("up", "Aufwärts, Springen", Keysym.SPACE), + UP("up", "Aufwärts, Sprung", Keysym.SPACE), DOWN("down", "Abwärts, Langsam", Keysym.LEFT_CONTROL), FAST("fast", "Schneller", Keysym.LEFT_SHIFT), INVENTORY("inventory", "Inventar", Keysym.E), @@ -34,7 +34,7 @@ public enum Bind implements IStringSerializable, CVar { CONSOLE("console", "Konsole", Keysym.F1), COMMAND("command", "Befehl / Chat", Keysym.C), INFO("info", "Infos einblenden", Keysym.TAB), - PERSPECTIVE("perspective", "Perspektive ändern", Keysym.F5), + PERSPECTIVE("perspective", "Perspektive", Keysym.F5), ZOOM("zoom", "Kamera zoomen", Keysym.Y), MENU("menu", "Menü", Keysym.ESCAPE), SCREENSHOT("screenshot", "Bildschirmfoto", Keysym.F10), @@ -104,9 +104,9 @@ public enum Bind implements IStringSerializable, CVar { waitingFor.input = input; waitingFor = null; keyRelease = null; - Game.getGame().setDirty(); - if(Game.getGame().open != null) - Game.getGame().open.reformat(); + Client.CLIENT.setDirty(); + if(Client.CLIENT.open != null) + Client.CLIENT.open.reformat(); } } else if(keyRelease == null) { @@ -116,9 +116,9 @@ public enum Bind implements IStringSerializable, CVar { else { waitingFor.input = input; waitingFor = null; - Game.getGame().setDirty(); - if(Game.getGame().open != null) - Game.getGame().open.reformat(); + Client.CLIENT.setDirty(); + if(Client.CLIENT.open != null) + Client.CLIENT.open.reformat(); } } } diff --git a/java/src/game/window/Button.java b/client/src/main/java/client/window/Button.java similarity index 78% rename from java/src/game/window/Button.java rename to client/src/main/java/client/window/Button.java index 89cd8f8..a38c696 100644 --- a/java/src/game/window/Button.java +++ b/client/src/main/java/client/window/Button.java @@ -1,13 +1,13 @@ -package game.window; +package client.window; -import game.Game; +import client.Client; public enum Button implements Input { MOUSE_LEFT("lmb", "Linke Maustaste"), MOUSE_RIGHT("rmb", "Rechte Maustaste"), - MOUSE_MIDDLE("mmb", "Mittlere Maustaste"), - MOUSE_BTN_X("xmb", "Maustaste Seite 1"), - MOUSE_BTN_Y("ymb", "Maustaste Seite 2"), + MOUSE_MIDDLE("mmb", "Mausrad-Taste"), + MOUSE_BTN_X("xmb", "Maus Seite 1"), + MOUSE_BTN_Y("ymb", "Maus Seite 2"), MOUSE_BTN_A("m6", "Maustaste 6"), MOUSE_BTN_B("m7", "Maustaste 7"), MOUSE_BTN_C("m8", "Maustaste 8"); @@ -37,7 +37,7 @@ public enum Button implements Input { } public boolean read() { - return Game.getGame().open == null && this.down; + return Client.CLIENT.open == null && this.down; } public void setDown(boolean down) { diff --git a/java/src/game/window/DisplayMode.java b/client/src/main/java/client/window/DisplayMode.java similarity index 53% rename from java/src/game/window/DisplayMode.java rename to client/src/main/java/client/window/DisplayMode.java index c734e4d..d9dfb47 100644 --- a/java/src/game/window/DisplayMode.java +++ b/client/src/main/java/client/window/DisplayMode.java @@ -1,18 +1,6 @@ -package game.window; +package client.window; -public class DisplayMode { - public static final int VID_MODES = 28; - - public final int width; - public final int height; - public final int refresh; - - public DisplayMode(int width, int height, int refresh) { - this.width = width; - this.height = height; - this.refresh = refresh; - } - +public record DisplayMode(int width, int height, int refresh) { public String toString() { return String.format("%dx%d @ %d Hz", this.width, this.height, this.refresh); } diff --git a/client/src/main/java/client/window/Input.java b/client/src/main/java/client/window/Input.java new file mode 100644 index 0000000..f1a3d33 --- /dev/null +++ b/client/src/main/java/client/window/Input.java @@ -0,0 +1,8 @@ +package client.window; + +import common.util.Displayable; +import common.util.Identifyable; + +public interface Input extends Identifyable, Displayable { + public boolean read(); +} diff --git a/java/src/game/window/KeyEvent.java b/client/src/main/java/client/window/KeyEvent.java similarity index 69% rename from java/src/game/window/KeyEvent.java rename to client/src/main/java/client/window/KeyEvent.java index d4101ae..87ed04d 100644 --- a/java/src/game/window/KeyEvent.java +++ b/client/src/main/java/client/window/KeyEvent.java @@ -1,4 +1,4 @@ -package game.window; +package client.window; public enum KeyEvent { RELEASE, diff --git a/java/src/game/window/Keysym.java b/client/src/main/java/client/window/Keysym.java similarity index 99% rename from java/src/game/window/Keysym.java rename to client/src/main/java/client/window/Keysym.java index 0e9ffe8..0660f91 100644 --- a/java/src/game/window/Keysym.java +++ b/client/src/main/java/client/window/Keysym.java @@ -1,4 +1,4 @@ -package game.window; +package client.window; import static org.lwjgl.glfw.GLFW.*; diff --git a/java/src/game/window/Wheel.java b/client/src/main/java/client/window/Wheel.java similarity index 74% rename from java/src/game/window/Wheel.java rename to client/src/main/java/client/window/Wheel.java index fff8d68..1fc5c26 100644 --- a/java/src/game/window/Wheel.java +++ b/client/src/main/java/client/window/Wheel.java @@ -1,10 +1,10 @@ -package game.window; +package client.window; -import game.Game; +import client.Client; public enum Wheel implements Input { - SCROLL_UP("scrup", "Mausrad aufwärts"), - SCROLL_DOWN("scrdn", "Mausrad abwärts"), + SCROLL_UP("scrup", "Mausrad oben"), + SCROLL_DOWN("scrdn", "Mausrad unten"), SCROLL_LEFT("scrl", "Mausrad links"), SCROLL_RIGHT("scrr", "Mausrad rechts"); @@ -27,7 +27,7 @@ public enum Wheel implements Input { } public boolean read() { - return Game.getGame().open == null && this.used; + return Client.CLIENT.open == null && this.used; } public void setUsed() { diff --git a/java/src/game/window/Window.java b/client/src/main/java/client/window/Window.java similarity index 72% rename from java/src/game/window/Window.java rename to client/src/main/java/client/window/Window.java index a3e8d30..a0c5b90 100644 --- a/java/src/game/window/Window.java +++ b/client/src/main/java/client/window/Window.java @@ -1,7 +1,55 @@ -package game.window; +package client.window; import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks; -import static org.lwjgl.glfw.GLFW.*; +import static org.lwjgl.glfw.GLFW.GLFW_CONTEXT_DEBUG; +import static org.lwjgl.glfw.GLFW.GLFW_CURSOR; +import static org.lwjgl.glfw.GLFW.GLFW_CURSOR_DISABLED; +import static org.lwjgl.glfw.GLFW.GLFW_CURSOR_NORMAL; +import static org.lwjgl.glfw.GLFW.GLFW_DONT_CARE; +import static org.lwjgl.glfw.GLFW.GLFW_FALSE; +import static org.lwjgl.glfw.GLFW.GLFW_PRESS; +import static org.lwjgl.glfw.GLFW.GLFW_RELEASE; +import static org.lwjgl.glfw.GLFW.GLFW_REPEAT; +import static org.lwjgl.glfw.GLFW.GLFW_RESIZABLE; +import static org.lwjgl.glfw.GLFW.GLFW_TRUE; +import static org.lwjgl.glfw.GLFW.GLFW_VISIBLE; +import static org.lwjgl.glfw.GLFW.glfwCreateWindow; +import static org.lwjgl.glfw.GLFW.glfwDefaultWindowHints; +import static org.lwjgl.glfw.GLFW.glfwDestroyWindow; +import static org.lwjgl.glfw.GLFW.glfwGetClipboardString; +import static org.lwjgl.glfw.GLFW.glfwGetKey; +import static org.lwjgl.glfw.GLFW.glfwGetMonitorPos; +import static org.lwjgl.glfw.GLFW.glfwGetPrimaryMonitor; +import static org.lwjgl.glfw.GLFW.glfwGetTimerFrequency; +import static org.lwjgl.glfw.GLFW.glfwGetVideoMode; +import static org.lwjgl.glfw.GLFW.glfwGetVideoModes; +import static org.lwjgl.glfw.GLFW.glfwInit; +import static org.lwjgl.glfw.GLFW.glfwMakeContextCurrent; +import static org.lwjgl.glfw.GLFW.glfwPollEvents; +import static org.lwjgl.glfw.GLFW.glfwSetCharCallback; +import static org.lwjgl.glfw.GLFW.glfwSetClipboardString; +import static org.lwjgl.glfw.GLFW.glfwSetCursorPosCallback; +import static org.lwjgl.glfw.GLFW.glfwSetErrorCallback; +import static org.lwjgl.glfw.GLFW.glfwSetFramebufferSizeCallback; +import static org.lwjgl.glfw.GLFW.glfwSetInputMode; +import static org.lwjgl.glfw.GLFW.glfwSetKeyCallback; +import static org.lwjgl.glfw.GLFW.glfwSetMouseButtonCallback; +import static org.lwjgl.glfw.GLFW.glfwSetScrollCallback; +import static org.lwjgl.glfw.GLFW.glfwSetWindowCloseCallback; +import static org.lwjgl.glfw.GLFW.glfwSetWindowFocusCallback; +import static org.lwjgl.glfw.GLFW.glfwSetWindowIcon; +import static org.lwjgl.glfw.GLFW.glfwSetWindowMonitor; +import static org.lwjgl.glfw.GLFW.glfwSetWindowPos; +import static org.lwjgl.glfw.GLFW.glfwSetWindowPosCallback; +import static org.lwjgl.glfw.GLFW.glfwSetWindowRefreshCallback; +import static org.lwjgl.glfw.GLFW.glfwSetWindowSize; +import static org.lwjgl.glfw.GLFW.glfwSetWindowSizeLimits; +import static org.lwjgl.glfw.GLFW.glfwSetWindowTitle; +import static org.lwjgl.glfw.GLFW.glfwShowWindow; +import static org.lwjgl.glfw.GLFW.glfwSwapBuffers; +import static org.lwjgl.glfw.GLFW.glfwSwapInterval; +import static org.lwjgl.glfw.GLFW.glfwTerminate; +import static org.lwjgl.glfw.GLFW.glfwWindowHint; import static org.lwjgl.system.MemoryUtil.NULL; import java.util.ArrayList; @@ -27,7 +75,7 @@ import org.lwjgl.glfw.GLFWWindowRefreshCallback; import org.lwjgl.opengl.GL; import org.lwjgl.system.APIUtil; -import game.log.Log; +import common.log.Log; public abstract class Window { public static void setWindowed(int xpos, int ypos, int xsize, int ysize) { @@ -165,7 +213,7 @@ public abstract class Window { window = NULL; } } - public static void initWindow(int sx, int sy, int wx, int wy) { + public static void initWindow(int sx, int sy, int wx, int wy, int mx, int my) { if(window == NULL) return; long monitor = glfwGetPrimaryMonitor(); @@ -174,8 +222,8 @@ public abstract class Window { int[] y = new int[1]; if(monitor != NULL) glfwGetMonitorPos(monitor, x, y); - int xsize = (mode != null && wx > mode.width()) ? mode.width() : wx; - int ysize = (mode != null && wy > mode.height()) ? mode.height() : wy; + int xsize = (mode != null && mode.width() >= mx && wx > mode.width()) ? mode.width() : wx; + int ysize = (mode != null && mode.height() >= my && wy > mode.height()) ? mode.height() : wy; int xpos = x[0] + (mode != null ? mode.width() / 2 - xsize / 2 : 0); int ypos = y[0] + (mode != null ? mode.height() / 2 - ysize / 2 : 0); xsize = xsize < 1 ? 1 : xsize; @@ -189,6 +237,7 @@ public abstract class Window { ysize = wy; } glfwSetWindowSize(window, xsize, ysize); + glfwSetWindowSizeLimits(window, mx, my, GLFW_DONT_CARE, GLFW_DONT_CARE); glfwSetWindowPos(window, xpos, ypos); // wcf_windowed(win, xpos, ypos, xsize, ysize); // wcf_fullscreen does not move while hidden ... @@ -196,6 +245,7 @@ public abstract class Window { glfwShowWindow(window); // wcf_show(win, 1); // wcf_limits(win, 1, 1, -1, -1); + glfwSetWindowMonitor(window, NULL, xpos, ypos, xsize, ysize, GLFW_DONT_CARE); // set position twice to work around bugs in some tiling window managers } public static WindowEvent[] poll() { diff --git a/java/src/game/window/WindowAction.java b/client/src/main/java/client/window/WindowAction.java similarity index 84% rename from java/src/game/window/WindowAction.java rename to client/src/main/java/client/window/WindowAction.java index e775b65..cdba867 100644 --- a/java/src/game/window/WindowAction.java +++ b/client/src/main/java/client/window/WindowAction.java @@ -1,4 +1,4 @@ -package game.window; +package client.window; public enum WindowAction { RESIZE, diff --git a/client/src/main/java/client/window/WindowEvent.java b/client/src/main/java/client/window/WindowEvent.java new file mode 100644 index 0000000..b92f7a6 --- /dev/null +++ b/client/src/main/java/client/window/WindowEvent.java @@ -0,0 +1,4 @@ +package client.window; + +public record WindowEvent(WindowAction action, int param1, int param2) { +} diff --git a/client/src/main/java/client/world/ChunkClient.java b/client/src/main/java/client/world/ChunkClient.java new file mode 100644 index 0000000..8f59b89 --- /dev/null +++ b/client/src/main/java/client/world/ChunkClient.java @@ -0,0 +1,144 @@ +package client.world; + +import common.biome.Biome; +import common.block.Block; +import common.init.Blocks; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.NibbleArray; +import common.world.BlockArray; +import common.world.Chunk; +import common.world.World; + +public class ChunkClient extends Chunk { + public ChunkClient(World world, int x, int z) { + super(world, x, z); + } + + private void clearArrays() { + this.blocks.clearMap(); + this.blockList.clear(); + this.bottom = Integer.MAX_VALUE; + this.top = Integer.MIN_VALUE; + } + + private void genHeights() { + int top = this.top; + int bottom = this.bottom; + this.minHeight = Integer.MAX_VALUE; + + for(int x = 0; x < 16; ++x) { + for(int z = 0; z < 16; ++z) { + this.precHeight[x + (z << 4)] = -99999999; + + for(int y = top + 16; y > bottom; --y) { + Block block = this.getBlock0(x, y - 1, z); + + if(block.getLightOpacity() != 0) { + this.height[z << 4 | x] = y; + + if(y < this.minHeight) { + this.minHeight = y; + } + + break; + } + } + } + } + + this.modified = true; + } + + public boolean isEmpty(int bottom, int top) { + for(int y = bottom; y <= top; y += 16) { + BlockArray stor = this.getArray(y >> 4); + + if(stor != null ? !stor.isEmpty() : (y < 0 && this.fillerBlock != Blocks.air)) { + return false; + } + } + + return true; + } + + public void setData(byte[] data, int[] extend, boolean biomes) { + int pos = 0; + boolean sky = !this.world.dimension.hasNoLight(); + + if(biomes) { + this.clearArrays(); + } + for(int cy : extend) { + BlockArray arr = this.getArray(cy); + if(arr == null) { + arr = new BlockArray(cy << 4, sky, null); + this.setArray(arr); + } + + char[] blocks = arr.getData(); + + for(int k = 0; k < blocks.length; ++k) { + blocks[k] = (char)((data[pos + 1] & 255) << 8 | data[pos] & 255); + pos += 2; + } + } + + for(int cy : extend) { + BlockArray arr = this.getArray(cy); + if(arr != null) { + NibbleArray light = arr.getBlocklight(); + System.arraycopy(data, pos, light.getData(), 0, light.getData().length); + pos += light.getData().length; + } + } + + if(sky) { + for(int cy : extend) { + BlockArray arr = this.getArray(cy); + if(arr != null) { + NibbleArray slight = arr.getSkylight(); + System.arraycopy(data, pos, slight.getData(), 0, slight.getData().length); + pos += slight.getData().length; + } + } + } + + if(biomes) { + System.arraycopy(data, pos, this.biomes, 0, this.biomes.length); + } + + for(int cy : extend) { + BlockArray arr = this.getArray(cy); + if(arr != null) { + arr.update(); + } + } + + this.lightInit = true; + this.populated = true; + this.genHeights(); + + for(TileEntity tile : this.tiles.values()) { + tile.updateContainingBlockInfo(); + } + } + + public void setLoaded() { + this.loaded = true; + } + + public Biome getBiome(BlockPos pos) { + int x = pos.getX() & 15; + int z = pos.getZ() & 15; + return Biome.getBiomeDef(this.biomes[z << 4 | x] & 255); + } + + public void setBiome(BlockPos pos, Biome biome) { + this.biomes[((pos.getZ() & 15) << 4 | pos.getX() & 15)] = (byte)biome.id; + } + + public boolean isDummy() { + return false; + } +} diff --git a/client/src/main/java/client/world/ChunkEmpty.java b/client/src/main/java/client/world/ChunkEmpty.java new file mode 100755 index 0000000..dce55fe --- /dev/null +++ b/client/src/main/java/client/world/ChunkEmpty.java @@ -0,0 +1,172 @@ +package client.world; + +import java.util.List; +import java.util.function.Predicate; + +import common.biome.Biome; +import common.block.Block; +import common.collect.Lists; +import common.entity.Entity; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.world.LightType; +import common.world.State; + +public class ChunkEmpty extends ChunkClient { + private static final List STATES = Lists.newArrayList(); + private static final int XSTRETCH; + private static final int ZSTRETCH; + + private final boolean debug; + private final int liquidY; + private final State liquid; + private final Block liquidBlock; + private final State dummy; + private final Block dummyBlock; + + static { + for(Block block : BlockRegistry.REGISTRY) { + STATES.addAll(block.getValidStates()); + } + XSTRETCH = ExtMath.ceilf(ExtMath.sqrtf((float)STATES.size())); + ZSTRETCH = ExtMath.ceilf((float)STATES.size() / (float)XSTRETCH); + } + + private static State getDebug(int x, int z) { + State state = null; + if(x > 0 && z > 0 && x % 2 != 0 && z % 2 != 0) { + x = x / 2; + z = z / 2; + if(x <= XSTRETCH && z <= ZSTRETCH) { + int idx = ExtMath.absi(x * XSTRETCH + z); + if(idx < STATES.size()) { + state = STATES.get(idx); + } + } + } + return state; + } + + public ChunkEmpty(WorldClient world, boolean debug) { + super(world, 0, 0); + this.debug = debug; + this.liquidY = world.dimension.getSeaLevel() - 1; + this.liquid = world.dimension.getLiquid(); + this.liquidBlock = this.liquid.getBlock(); + this.dummyBlock = this.fillerBlock == Blocks.air ? Blocks.air : Blocks.bedrock; + this.dummy = this.dummyBlock.getState(); + } + + public int getHeight(int x, int z) { + return this.liquidY; + } + + public Block getBlock(BlockPos pos) { + return pos.getY() < this.liquidY ? this.dummyBlock : (pos.getY() == this.liquidY ? this.liquidBlock : Blocks.air); + } + + public int getLight(LightType type, BlockPos pos) { + return type.defValue; + } + + public void setLight(LightType type, BlockPos pos, int value) { + } + + public int getLightSub(BlockPos pos, int amount) { + return 0; + } + + public void addEntity(Entity entity) { + } + + public void removeEntity(Entity entity) { + } + + public boolean canSeeSky(BlockPos pos) { + return pos.getY() > this.liquidY; + } + + public TileEntity getTileEntity(BlockPos pos, TileEntity.EnumCreateEntityType type) { + return null; + } + + public void addTileEntity(BlockPos pos, TileEntity tile) { + } + + public void removeTileEntity(BlockPos pos) { + } + + public void getEntities(Entity exclude, BoundingBox bb, List list, Predicate pred) { + } + + public void getEntities(Class clazz, BoundingBox bb, List list, Predicate pred) { + } + + public boolean isDummy() { + return true; + } + + public boolean isEmpty(int bottom, int top) { + return top < 0 || bottom > this.liquidY; + } + + public State getState(BlockPos pos) { + if(this.debug) { + State state = pos.getY() == 1 ? getDebug(pos.getX(), pos.getZ()) : null; + return state == null ? Blocks.air.getState() : state; + } + return pos.getY() < this.liquidY ? this.dummy : (pos.getY() == this.liquidY ? this.liquid : Blocks.air.getState()); + } + + public State setState(BlockPos pos, State state) { + return null; + } + + public BlockPos getPrecipitation(BlockPos pos) { + return new BlockPos(pos.getX(), this.liquidY + 1, pos.getZ()); + } + + public void update(boolean noGaps) { + } + + public void onChunkUnload() { + } + + public boolean isPopulated() { + return true; + } + + public void setData(byte[] data, int[] extend, boolean biomes) { + } + + public Biome getBiome(BlockPos pos) { + return Biome.DEF_BIOME; + } + + public void setBiome(BlockPos pos, Biome biome) { + } + + public void resetRelight() { + } + + public void enqueueRelight() { + } + + public void checkLight() { + } + + public boolean isLoaded() { + return false; + } + + public void setLoaded() { + } + + public int getLowest() { + return 0; + } +} diff --git a/java/src/game/world/WorldClient.java b/client/src/main/java/client/world/WorldClient.java similarity index 84% rename from java/src/game/world/WorldClient.java rename to client/src/main/java/client/world/WorldClient.java index 0e01f13..dbfdf90 100755 --- a/java/src/game/world/WorldClient.java +++ b/client/src/main/java/client/world/WorldClient.java @@ -1,55 +1,64 @@ -package game.world; +package client.world; import java.util.List; import java.util.Set; -import game.collect.Lists; -import game.collect.Sets; +import client.Client; +import client.renderer.particle.EntityFX; +import client.renderer.particle.EntityFirework; +import common.biome.Biome; +import common.block.Block; +import common.collect.Lists; +import common.collect.Sets; +import common.dimension.Dimension; +import common.entity.Entity; +import common.entity.item.EntityCart; +import common.entity.npc.EntityNPC; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; +import common.init.SoundEvent; +import common.item.ItemDye; +import common.log.Log; +import common.model.ParticleType; +import common.rng.Random; +import common.sound.MovingSoundMinecart; +import common.sound.PositionedSound; +import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.ChunkPos; +import common.util.ExtMath; +import common.util.LongHashMap; +import common.util.Vec3; +import common.util.BlockPos.MutableBlockPos; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; -import game.Game; -import game.audio.MovingSoundMinecart; -import game.audio.PositionedSound; -import game.biome.Biome; -import game.block.Block; -import game.dimension.Dimension; -import game.entity.Entity; -import game.entity.item.EntityCart; -import game.entity.npc.EntityNPC; -import game.init.BlockRegistry; -import game.init.ItemRegistry; -import game.init.Items; -import game.init.SoundEvent; -import game.item.ItemDye; -import game.log.Log; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.renderer.particle.EntityFX; -import game.renderer.particle.EntityFirework; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.util.ExtMath; -import game.world.BlockPos.MutableBlockPos; - -public class WorldClient extends World +public class WorldClient extends AWorldClient { private static final int DISPLAY_RANGE = 16; - private final Game gm = Game.getGame(); + private final Client gm; + private final ChunkClient emptyChunk; private final Set entityList = Sets.newHashSet(); private final Set spawnQueue = Sets.newHashSet(); private final Set previousActive = Sets.newHashSet(); - private final LongHashMap chunkMapping = new LongHashMap(); - private final List chunkListing = Lists.newArrayList(); - private final Chunk blankChunk = new EmptyChunk(this); + private final LongHashMap chunkMapping = new LongHashMap(); + private final List chunkListing = Lists.newArrayList(); + private final Set emptyChunkListing = Sets.newHashSet(); + private final Set nextEmptyChunkListing = Sets.newHashSet(); // public final Profiler profiler; protected int lastLightning; protected Vec3 lightColor = new Vec3(0xffffff); - public WorldClient(boolean debug, Dimension dim) + public WorldClient(Client gm, Dimension dim) { - super(dim, true, debug); -// this.gm = profiler; + super(dim); + this.gm = gm; + this.emptyChunk = new ChunkEmpty(this, this.gm.debugWorld); this.calculateInitialSkylight(); this.calculateInitialWeather(); this.setGravity(this.gm.gravity); @@ -57,8 +66,42 @@ public class WorldClient extends World // this.setDifficulty(this.gm.difficulty); } + private void markReload(int cx, int cz, int range) { + this.nextEmptyChunkListing.clear(); + for(int x = cx - range; x <= cx + range; x++) { + for(int z = cz - range; z <= cz + range; z++) { + long id = LongHashMap.packInt(x, z); + if(this.chunkMapping.getValueByKey(id) != null) { + if(this.emptyChunkListing.contains(id)) { + this.emptyChunkListing.remove(id); + this.nextEmptyChunkListing.add(id); + } + continue; + } + this.chunkMapping.add(id, this.emptyChunk); + this.emptyChunkListing.remove(id); + this.nextEmptyChunkListing.add(id); + this.markBlockRangeForRenderUpdate(x << 4, -World.MAX_SIZE_Y, z << 4, (x << 4) + 15, World.MAX_SIZE_Y, (z << 4) + 15); + } + } + for(Long id : this.emptyChunkListing) { + this.chunkMapping.remove(id); + int x = LongHashMap.getX(id); + int z = LongHashMap.getZ(id); + this.markBlockRangeForRenderUpdate(x << 4, -World.MAX_SIZE_Y, z << 4, (x << 4) + 15, World.MAX_SIZE_Y, (z << 4) + 15); + } + this.emptyChunkListing.clear(); + this.emptyChunkListing.addAll(this.nextEmptyChunkListing); + } + + public void markReload() { + if(this.gm.player != null && !this.gm.charEditor) + this.markReload((int)this.gm.player.posX >> 4, (int)this.gm.player.posZ >> 4, this.gm.renderDistance + 4); + } + public void tick() { + this.markReload(); // this.info.tick(); if (this.gm.dayCycle) @@ -77,13 +120,13 @@ public class WorldClient extends World } } long time = System.currentTimeMillis(); - for (Chunk chunk : this.chunkListing) + for (ChunkClient chunk : this.chunkListing) { chunk.update(System.currentTimeMillis() - time > 5L); } if (System.currentTimeMillis() - time > 100L) { - Log.JNI.info("Warnung: Render-Chunk-Tick dauerte " + (System.currentTimeMillis() - time) + " ms"); + Log.TICK.warn("Render-Chunk-Tick dauerte " + (System.currentTimeMillis() - time) + " ms"); } this.updateBlocks(); } @@ -106,7 +149,7 @@ public class WorldClient extends World { int j = chunkcoordintpair.x * 16; int k = chunkcoordintpair.z * 16; - Chunk chunk = this.getChunk(chunkcoordintpair.x, chunkcoordintpair.z); + ChunkClient chunk = this.getChunk(chunkcoordintpair.x, chunkcoordintpair.z); chunk.enqueueRelight(); this.previousActive.add(chunkcoordintpair); ++i; @@ -121,29 +164,28 @@ public class WorldClient extends World public void doPreChunk(int x, int z, boolean load) { + long id = LongHashMap.packInt(x, z); if (load) { - if(this.chunkMapping.getValueByKey(LongHashMap.packInt(x, z)) != null) + if(this.chunkMapping.getValueByKey(id) != null) this.doPreChunk(x, z, false); - Chunk chunk = new Chunk(this, x, z); - this.chunkMapping.add(LongHashMap.packInt(x, z), chunk); + ChunkClient chunk = new ChunkClient(this, x, z); + this.chunkMapping.add(id, chunk); this.chunkListing.add(chunk); - chunk.setLoaded(true); + chunk.setLoaded(); } else { - Chunk chunk = this.getChunk(x, z); - if (!chunk.isEmpty()) - { - chunk.onChunkUnload(); - } - this.chunkMapping.remove(LongHashMap.packInt(x, z)); + ChunkClient chunk = this.getChunk(x, z); + chunk.onChunkUnload(); + this.chunkMapping.remove(id); this.chunkListing.remove(chunk); + this.emptyChunkListing.remove(id); } if (!load) { - this.markBlockRangeForRenderUpdate(x * 16, 0, z * 16, x * 16 + 15, 512, z * 16 + 15); + this.markBlockRangeForRenderUpdate(x * 16, -World.MAX_SIZE_Y, z * 16, x * 16 + 15, World.MAX_SIZE_Y, z * 16 + 15); } } @@ -218,7 +260,7 @@ public class WorldClient extends World public Entity getEntityByID(int id) { - return (Entity)(id == this.gm.thePlayer.getId() ? this.gm.thePlayer : super.getEntityByID(id)); + return (Entity)(id == this.gm.player.getId() ? this.gm.player : super.getEntityByID(id)); } public Entity removeEntityFromWorld(int entityID) @@ -340,16 +382,31 @@ public class WorldClient extends World // } } - public void makeFireworks(double x, double y, double z, double motionX, double motionY, double motionZ, NBTTagCompound compund) + public void makeFireworks(double x, double y, double z, double motionX, double motionY, double motionZ, TagObject compund) { - this.gm.effectRenderer.addEffect(new EntityFirework.StarterFX(this, x, y, z, motionX, motionY, motionZ, this.gm.effectRenderer, compund)); + this.gm.effectRenderer.addEffect(new EntityFirework.StarterFX(this.gm.world, x, y, z, motionX, motionY, motionZ, this.gm.effectRenderer, compund)); } - public Chunk getChunk(int x, int z) + public ChunkClient getChunk(int x, int z) { - Chunk chunk = this.chunkMapping.getValueByKey(LongHashMap.packInt(x, z)); - return chunk == null ? this.blankChunk : chunk; + ChunkClient chunk = this.chunkMapping.getValueByKey(LongHashMap.packInt(x, z)); + return chunk == null ? this.emptyChunk : chunk; } + + public ChunkClient getChunk(BlockPos pos) { + return this.getChunk(pos.getX() >> 4, pos.getZ() >> 4); + } + + public Biome getBiomeGenForCoords(BlockPos pos) { + if(this.isBlockLoaded(pos)) + return this.getChunk(pos).getBiome(pos); + else + return Biome.DEF_BIOME; + } + + protected boolean isLoaded(int x, int z, boolean allowEmpty) { + return allowEmpty || !this.getChunk(x, z).isDummy(); + } public String getInfo() { @@ -373,7 +430,7 @@ public class WorldClient extends World public EntityFX spawnEntityFX(ParticleType particle, boolean ignoreRange, double xCoord, double yCoord, double zCoord, double xOffset, double yOffset, double zOffset, int[] parameters) { - if (this.gm != null && this.gm.getRenderViewEntity() != null && this.gm.effectRenderer != null) + if (this.gm.getRenderViewEntity() != null) { int particleID = particle.getParticleID(); // int i = this.gm.particleSetting; @@ -394,13 +451,12 @@ public class WorldClient extends World else { double d3 = 16.0D; - return d0 * d0 + d1 * d1 + d2 * d2 > 256.0D ? null : (/* i > 1 ? null : */ this.gm.effectRenderer.spawnEffectParticle(particleID, xCoord, yCoord, zCoord, xOffset, yOffset, zOffset, parameters)); + if(d0 * d0 + d1 * d1 + d2 * d2 > 256.0D) + return null; + return this.gm.effectRenderer.spawnEffectParticle(particleID, xCoord, yCoord, zCoord, xOffset, yOffset, zOffset, parameters); } } - else - { - return null; - } + return null; } // public void broadcastSound(int soundID, BlockPos pos, int data) @@ -582,12 +638,12 @@ public class WorldClient extends World case 2001: Block block = BlockRegistry.getBlockById(data & 4095); - if (block.getMaterial() != Material.air) + if (block != Blocks.air) { this.gm.getSoundManager().playSound(new PositionedSound(block.sound.getBreakSound(), 1.0F, /* block.sound.getFrequency() * 0.8F, */ (float)blockPosIn.getX() + 0.5F, (float)blockPosIn.getY() + 0.5F, (float)blockPosIn.getZ() + 0.5F)); } - this.gm.effectRenderer.addBlockDestroyEffects(blockPosIn, block.getStateFromMeta(data >> 12 & 255)); + this.gm.effectRenderer.addBlockDestroyEffects(blockPosIn, block.getStateFromMeta(data >> 12 & 255)); break; case 2002: @@ -639,18 +695,6 @@ public class WorldClient extends World this.playSoundAtPos(blockPosIn, SoundEvent.GLASS, 1.0F); break; - case 2004: - for (int k = 0; k < 20; ++k) - { - double d3 = (double)blockPosIn.getX() + 0.5D + ((double)this.rand.floatv() - 0.5D) * 2.0D; - double d5 = (double)blockPosIn.getY() + 0.5D + ((double)this.rand.floatv() - 0.5D) * 2.0D; - double d7 = (double)blockPosIn.getZ() + 0.5D + ((double)this.rand.floatv() - 0.5D) * 2.0D; - this.spawnParticle(ParticleType.SMOKE_NORMAL, d3, d5, d7, 0.0D, 0.0D, 0.0D); - this.spawnParticle(ParticleType.FLAME, d3, d5, d7, 0.0D, 0.0D, 0.0D); - } - - return; - case 2005: ItemDye.spawnBonemealParticles(this, blockPosIn, data); } @@ -756,8 +800,8 @@ public class WorldClient extends World ExtMath.floord(entity.posZ)); Biome biome = this.getBiomeGenForCoords(pos); Vec3 vec; - if(biome.getSkyColor() != 0xffffffff) - vec = new Vec3(biome.getSkyColor()); + if(biome.skyColor != 0xffffffff) + vec = new Vec3(biome.skyColor); else vec = new Vec3(this.dimension.getSkyColor()); if(this.dimension.getType().days) { @@ -812,8 +856,8 @@ public class WorldClient extends World Vec3 color = new Vec3(this.dimension.getCloudColor()); Biome biome = this.getBiomeGenForCoords(new BlockPos(ExtMath.floord(entity.posX), ExtMath.floord(entity.posY), ExtMath.floord(entity.posZ))); - if(biome.getCloudColor() != 0xffffffff) - color = new Vec3(biome.getCloudColor()); + if(biome.cloudColor != 0xffffffff) + color = new Vec3(biome.cloudColor); float r = (float)color.xCoord; float g = (float)color.yCoord; float b = (float)color.zCoord; @@ -851,8 +895,8 @@ public class WorldClient extends World Vec3 color = new Vec3(this.dimension.getFogColor()); Biome biome = this.getBiomeGenForCoords(new BlockPos(ExtMath.floord(entity.posX), ExtMath.floord(entity.posY), ExtMath.floord(entity.posZ))); - if(biome.getFogColor() != 0xffffffff) - color = new Vec3(biome.getFogColor()); + if(biome.fogColor != 0xffffffff) + color = new Vec3(biome.fogColor); if(!this.dimension.getType().days) return color; float sun = ExtMath.clampf(ExtMath.cos(this.getCelestialAngle(partialTicks) * (float)Math.PI * 2.0F) * 2.0F + 0.5F, @@ -921,8 +965,4 @@ public class WorldClient extends World public String getDebugLoadedEntities() { return "" + this.entities.size(); } - - public boolean hasNoChunks() { - return this.chunkListing.isEmpty(); - } } diff --git a/client/src/main/resources/sounds/anvil_break.ogg b/client/src/main/resources/sounds/anvil_break.ogg new file mode 100644 index 0000000..e18b0c0 Binary files /dev/null and b/client/src/main/resources/sounds/anvil_break.ogg differ diff --git a/client/src/main/resources/sounds/anvil_land.ogg b/client/src/main/resources/sounds/anvil_land.ogg new file mode 100644 index 0000000..45f9cb3 Binary files /dev/null and b/client/src/main/resources/sounds/anvil_land.ogg differ diff --git a/client/src/main/resources/sounds/anvil_use.ogg b/client/src/main/resources/sounds/anvil_use.ogg new file mode 100644 index 0000000..f161d32 Binary files /dev/null and b/client/src/main/resources/sounds/anvil_use.ogg differ diff --git a/client/src/main/resources/sounds/bat_death.ogg b/client/src/main/resources/sounds/bat_death.ogg new file mode 100644 index 0000000..1767f74 Binary files /dev/null and b/client/src/main/resources/sounds/bat_death.ogg differ diff --git a/client/src/main/resources/sounds/bat_hurt1.ogg b/client/src/main/resources/sounds/bat_hurt1.ogg new file mode 100644 index 0000000..b9a0f83 Binary files /dev/null and b/client/src/main/resources/sounds/bat_hurt1.ogg differ diff --git a/client/src/main/resources/sounds/bat_hurt2.ogg b/client/src/main/resources/sounds/bat_hurt2.ogg new file mode 100644 index 0000000..5b822d7 Binary files /dev/null and b/client/src/main/resources/sounds/bat_hurt2.ogg differ diff --git a/client/src/main/resources/sounds/bat_hurt3.ogg b/client/src/main/resources/sounds/bat_hurt3.ogg new file mode 100644 index 0000000..bcdf9b0 Binary files /dev/null and b/client/src/main/resources/sounds/bat_hurt3.ogg differ diff --git a/client/src/main/resources/sounds/bat_hurt4.ogg b/client/src/main/resources/sounds/bat_hurt4.ogg new file mode 100644 index 0000000..8c2d7f4 Binary files /dev/null and b/client/src/main/resources/sounds/bat_hurt4.ogg differ diff --git a/client/src/main/resources/sounds/bat_idle1.ogg b/client/src/main/resources/sounds/bat_idle1.ogg new file mode 100644 index 0000000..c0cbe5a Binary files /dev/null and b/client/src/main/resources/sounds/bat_idle1.ogg differ diff --git a/client/src/main/resources/sounds/bat_idle2.ogg b/client/src/main/resources/sounds/bat_idle2.ogg new file mode 100644 index 0000000..ce4f072 Binary files /dev/null and b/client/src/main/resources/sounds/bat_idle2.ogg differ diff --git a/client/src/main/resources/sounds/bat_idle3.ogg b/client/src/main/resources/sounds/bat_idle3.ogg new file mode 100644 index 0000000..69ca797 Binary files /dev/null and b/client/src/main/resources/sounds/bat_idle3.ogg differ diff --git a/client/src/main/resources/sounds/bat_idle4.ogg b/client/src/main/resources/sounds/bat_idle4.ogg new file mode 100644 index 0000000..9b3aafa Binary files /dev/null and b/client/src/main/resources/sounds/bat_idle4.ogg differ diff --git a/client/src/main/resources/sounds/bat_takeoff.ogg b/client/src/main/resources/sounds/bat_takeoff.ogg new file mode 100644 index 0000000..e1dd956 Binary files /dev/null and b/client/src/main/resources/sounds/bat_takeoff.ogg differ diff --git a/client/src/main/resources/sounds/blast.ogg b/client/src/main/resources/sounds/blast.ogg new file mode 100644 index 0000000..574a89a Binary files /dev/null and b/client/src/main/resources/sounds/blast.ogg differ diff --git a/client/src/main/resources/sounds/blast_far.ogg b/client/src/main/resources/sounds/blast_far.ogg new file mode 100644 index 0000000..9bd7709 Binary files /dev/null and b/client/src/main/resources/sounds/blast_far.ogg differ diff --git a/client/src/main/resources/sounds/bow.ogg b/client/src/main/resources/sounds/bow.ogg new file mode 100644 index 0000000..b7779c7 Binary files /dev/null and b/client/src/main/resources/sounds/bow.ogg differ diff --git a/client/src/main/resources/sounds/bowhit1.ogg b/client/src/main/resources/sounds/bowhit1.ogg new file mode 100644 index 0000000..4e4cea4 Binary files /dev/null and b/client/src/main/resources/sounds/bowhit1.ogg differ diff --git a/client/src/main/resources/sounds/bowhit2.ogg b/client/src/main/resources/sounds/bowhit2.ogg new file mode 100644 index 0000000..d08be49 Binary files /dev/null and b/client/src/main/resources/sounds/bowhit2.ogg differ diff --git a/client/src/main/resources/sounds/bowhit3.ogg b/client/src/main/resources/sounds/bowhit3.ogg new file mode 100644 index 0000000..a97c72d Binary files /dev/null and b/client/src/main/resources/sounds/bowhit3.ogg differ diff --git a/client/src/main/resources/sounds/bowhit4.ogg b/client/src/main/resources/sounds/bowhit4.ogg new file mode 100644 index 0000000..d19c74e Binary files /dev/null and b/client/src/main/resources/sounds/bowhit4.ogg differ diff --git a/client/src/main/resources/sounds/break.ogg b/client/src/main/resources/sounds/break.ogg new file mode 100644 index 0000000..0357d24 Binary files /dev/null and b/client/src/main/resources/sounds/break.ogg differ diff --git a/client/src/main/resources/sounds/cat_hitt1.ogg b/client/src/main/resources/sounds/cat_hitt1.ogg new file mode 100644 index 0000000..2f361e4 Binary files /dev/null and b/client/src/main/resources/sounds/cat_hitt1.ogg differ diff --git a/client/src/main/resources/sounds/cat_hitt2.ogg b/client/src/main/resources/sounds/cat_hitt2.ogg new file mode 100644 index 0000000..a969987 Binary files /dev/null and b/client/src/main/resources/sounds/cat_hitt2.ogg differ diff --git a/client/src/main/resources/sounds/cat_hitt3.ogg b/client/src/main/resources/sounds/cat_hitt3.ogg new file mode 100644 index 0000000..d829d9a Binary files /dev/null and b/client/src/main/resources/sounds/cat_hitt3.ogg differ diff --git a/client/src/main/resources/sounds/cat_meow1.ogg b/client/src/main/resources/sounds/cat_meow1.ogg new file mode 100644 index 0000000..4fdd430 Binary files /dev/null and b/client/src/main/resources/sounds/cat_meow1.ogg differ diff --git a/client/src/main/resources/sounds/cat_meow2.ogg b/client/src/main/resources/sounds/cat_meow2.ogg new file mode 100644 index 0000000..686e006 Binary files /dev/null and b/client/src/main/resources/sounds/cat_meow2.ogg differ diff --git a/client/src/main/resources/sounds/cat_meow3.ogg b/client/src/main/resources/sounds/cat_meow3.ogg new file mode 100644 index 0000000..2dfcd14 Binary files /dev/null and b/client/src/main/resources/sounds/cat_meow3.ogg differ diff --git a/client/src/main/resources/sounds/cat_meow4.ogg b/client/src/main/resources/sounds/cat_meow4.ogg new file mode 100644 index 0000000..a242c9a Binary files /dev/null and b/client/src/main/resources/sounds/cat_meow4.ogg differ diff --git a/client/src/main/resources/sounds/cat_purreow1.ogg b/client/src/main/resources/sounds/cat_purreow1.ogg new file mode 100644 index 0000000..dfb5897 Binary files /dev/null and b/client/src/main/resources/sounds/cat_purreow1.ogg differ diff --git a/client/src/main/resources/sounds/cat_purreow2.ogg b/client/src/main/resources/sounds/cat_purreow2.ogg new file mode 100644 index 0000000..daaba56 Binary files /dev/null and b/client/src/main/resources/sounds/cat_purreow2.ogg differ diff --git a/client/src/main/resources/sounds/chestclosed.ogg b/client/src/main/resources/sounds/chestclosed.ogg new file mode 100644 index 0000000..a388edd Binary files /dev/null and b/client/src/main/resources/sounds/chestclosed.ogg differ diff --git a/client/src/main/resources/sounds/chestopen.ogg b/client/src/main/resources/sounds/chestopen.ogg new file mode 100644 index 0000000..c735074 Binary files /dev/null and b/client/src/main/resources/sounds/chestopen.ogg differ diff --git a/client/src/main/resources/sounds/chicken_hurt1.ogg b/client/src/main/resources/sounds/chicken_hurt1.ogg new file mode 100644 index 0000000..a347986 Binary files /dev/null and b/client/src/main/resources/sounds/chicken_hurt1.ogg differ diff --git a/client/src/main/resources/sounds/chicken_hurt2.ogg b/client/src/main/resources/sounds/chicken_hurt2.ogg new file mode 100644 index 0000000..2d018a0 Binary files /dev/null and b/client/src/main/resources/sounds/chicken_hurt2.ogg differ diff --git a/client/src/main/resources/sounds/chicken_say1.ogg b/client/src/main/resources/sounds/chicken_say1.ogg new file mode 100644 index 0000000..649fcf9 Binary files /dev/null and b/client/src/main/resources/sounds/chicken_say1.ogg differ diff --git a/client/src/main/resources/sounds/chicken_say2.ogg b/client/src/main/resources/sounds/chicken_say2.ogg new file mode 100644 index 0000000..fef786b Binary files /dev/null and b/client/src/main/resources/sounds/chicken_say2.ogg differ diff --git a/client/src/main/resources/sounds/chicken_say3.ogg b/client/src/main/resources/sounds/chicken_say3.ogg new file mode 100644 index 0000000..d058652 Binary files /dev/null and b/client/src/main/resources/sounds/chicken_say3.ogg differ diff --git a/client/src/main/resources/sounds/click.ogg b/client/src/main/resources/sounds/click.ogg new file mode 100644 index 0000000..51f80df Binary files /dev/null and b/client/src/main/resources/sounds/click.ogg differ diff --git a/client/src/main/resources/sounds/cloth1.ogg b/client/src/main/resources/sounds/cloth1.ogg new file mode 100644 index 0000000..543794d Binary files /dev/null and b/client/src/main/resources/sounds/cloth1.ogg differ diff --git a/client/src/main/resources/sounds/cloth2.ogg b/client/src/main/resources/sounds/cloth2.ogg new file mode 100644 index 0000000..dbe0ad6 Binary files /dev/null and b/client/src/main/resources/sounds/cloth2.ogg differ diff --git a/client/src/main/resources/sounds/cloth3.ogg b/client/src/main/resources/sounds/cloth3.ogg new file mode 100644 index 0000000..72b763b Binary files /dev/null and b/client/src/main/resources/sounds/cloth3.ogg differ diff --git a/client/src/main/resources/sounds/cloth4.ogg b/client/src/main/resources/sounds/cloth4.ogg new file mode 100644 index 0000000..233d5de Binary files /dev/null and b/client/src/main/resources/sounds/cloth4.ogg differ diff --git a/client/src/main/resources/sounds/cow_hurt1.ogg b/client/src/main/resources/sounds/cow_hurt1.ogg new file mode 100644 index 0000000..41c0e7c Binary files /dev/null and b/client/src/main/resources/sounds/cow_hurt1.ogg differ diff --git a/client/src/main/resources/sounds/cow_hurt2.ogg b/client/src/main/resources/sounds/cow_hurt2.ogg new file mode 100644 index 0000000..50fea21 Binary files /dev/null and b/client/src/main/resources/sounds/cow_hurt2.ogg differ diff --git a/client/src/main/resources/sounds/cow_hurt3.ogg b/client/src/main/resources/sounds/cow_hurt3.ogg new file mode 100644 index 0000000..8f46d2c Binary files /dev/null and b/client/src/main/resources/sounds/cow_hurt3.ogg differ diff --git a/client/src/main/resources/sounds/cow_say1.ogg b/client/src/main/resources/sounds/cow_say1.ogg new file mode 100644 index 0000000..017067d Binary files /dev/null and b/client/src/main/resources/sounds/cow_say1.ogg differ diff --git a/client/src/main/resources/sounds/cow_say2.ogg b/client/src/main/resources/sounds/cow_say2.ogg new file mode 100644 index 0000000..4d7dda3 Binary files /dev/null and b/client/src/main/resources/sounds/cow_say2.ogg differ diff --git a/client/src/main/resources/sounds/cow_say3.ogg b/client/src/main/resources/sounds/cow_say3.ogg new file mode 100644 index 0000000..a1dd244 Binary files /dev/null and b/client/src/main/resources/sounds/cow_say3.ogg differ diff --git a/client/src/main/resources/sounds/cow_say4.ogg b/client/src/main/resources/sounds/cow_say4.ogg new file mode 100644 index 0000000..6cd878d Binary files /dev/null and b/client/src/main/resources/sounds/cow_say4.ogg differ diff --git a/client/src/main/resources/sounds/cut.ogg b/client/src/main/resources/sounds/cut.ogg new file mode 100644 index 0000000..5643843 Binary files /dev/null and b/client/src/main/resources/sounds/cut.ogg differ diff --git a/client/src/main/resources/sounds/door_close.ogg b/client/src/main/resources/sounds/door_close.ogg new file mode 100644 index 0000000..5888d1a Binary files /dev/null and b/client/src/main/resources/sounds/door_close.ogg differ diff --git a/client/src/main/resources/sounds/door_open.ogg b/client/src/main/resources/sounds/door_open.ogg new file mode 100644 index 0000000..fa37300 Binary files /dev/null and b/client/src/main/resources/sounds/door_open.ogg differ diff --git a/client/src/main/resources/sounds/dragon_growl1.ogg b/client/src/main/resources/sounds/dragon_growl1.ogg new file mode 100644 index 0000000..8de8c81 Binary files /dev/null and b/client/src/main/resources/sounds/dragon_growl1.ogg differ diff --git a/client/src/main/resources/sounds/dragon_growl2.ogg b/client/src/main/resources/sounds/dragon_growl2.ogg new file mode 100644 index 0000000..4a8efcf Binary files /dev/null and b/client/src/main/resources/sounds/dragon_growl2.ogg differ diff --git a/client/src/main/resources/sounds/dragon_growl3.ogg b/client/src/main/resources/sounds/dragon_growl3.ogg new file mode 100644 index 0000000..d3ad63d Binary files /dev/null and b/client/src/main/resources/sounds/dragon_growl3.ogg differ diff --git a/client/src/main/resources/sounds/dragon_growl4.ogg b/client/src/main/resources/sounds/dragon_growl4.ogg new file mode 100644 index 0000000..f50567c Binary files /dev/null and b/client/src/main/resources/sounds/dragon_growl4.ogg differ diff --git a/client/src/main/resources/sounds/dragon_wings1.ogg b/client/src/main/resources/sounds/dragon_wings1.ogg new file mode 100644 index 0000000..bfbeb6c Binary files /dev/null and b/client/src/main/resources/sounds/dragon_wings1.ogg differ diff --git a/client/src/main/resources/sounds/dragon_wings2.ogg b/client/src/main/resources/sounds/dragon_wings2.ogg new file mode 100644 index 0000000..3ab732a Binary files /dev/null and b/client/src/main/resources/sounds/dragon_wings2.ogg differ diff --git a/client/src/main/resources/sounds/dragon_wings3.ogg b/client/src/main/resources/sounds/dragon_wings3.ogg new file mode 100644 index 0000000..3026a9c Binary files /dev/null and b/client/src/main/resources/sounds/dragon_wings3.ogg differ diff --git a/client/src/main/resources/sounds/dragon_wings4.ogg b/client/src/main/resources/sounds/dragon_wings4.ogg new file mode 100644 index 0000000..302b15a Binary files /dev/null and b/client/src/main/resources/sounds/dragon_wings4.ogg differ diff --git a/client/src/main/resources/sounds/dragon_wings5.ogg b/client/src/main/resources/sounds/dragon_wings5.ogg new file mode 100644 index 0000000..d4c61f0 Binary files /dev/null and b/client/src/main/resources/sounds/dragon_wings5.ogg differ diff --git a/client/src/main/resources/sounds/dragon_wings6.ogg b/client/src/main/resources/sounds/dragon_wings6.ogg new file mode 100644 index 0000000..1af680b Binary files /dev/null and b/client/src/main/resources/sounds/dragon_wings6.ogg differ diff --git a/client/src/main/resources/sounds/drink.ogg b/client/src/main/resources/sounds/drink.ogg new file mode 100644 index 0000000..b5c7352 Binary files /dev/null and b/client/src/main/resources/sounds/drink.ogg differ diff --git a/client/src/main/resources/sounds/eat1.ogg b/client/src/main/resources/sounds/eat1.ogg new file mode 100644 index 0000000..3084624 Binary files /dev/null and b/client/src/main/resources/sounds/eat1.ogg differ diff --git a/client/src/main/resources/sounds/eat2.ogg b/client/src/main/resources/sounds/eat2.ogg new file mode 100644 index 0000000..7215480 Binary files /dev/null and b/client/src/main/resources/sounds/eat2.ogg differ diff --git a/client/src/main/resources/sounds/eat3.ogg b/client/src/main/resources/sounds/eat3.ogg new file mode 100644 index 0000000..35a3179 Binary files /dev/null and b/client/src/main/resources/sounds/eat3.ogg differ diff --git a/client/src/main/resources/sounds/explode1.ogg b/client/src/main/resources/sounds/explode1.ogg new file mode 100644 index 0000000..b661d29 Binary files /dev/null and b/client/src/main/resources/sounds/explode1.ogg differ diff --git a/client/src/main/resources/sounds/explode2.ogg b/client/src/main/resources/sounds/explode2.ogg new file mode 100644 index 0000000..1a776b5 Binary files /dev/null and b/client/src/main/resources/sounds/explode2.ogg differ diff --git a/client/src/main/resources/sounds/explode3.ogg b/client/src/main/resources/sounds/explode3.ogg new file mode 100644 index 0000000..d653c75 Binary files /dev/null and b/client/src/main/resources/sounds/explode3.ogg differ diff --git a/client/src/main/resources/sounds/explode4.ogg b/client/src/main/resources/sounds/explode4.ogg new file mode 100644 index 0000000..f5e1649 Binary files /dev/null and b/client/src/main/resources/sounds/explode4.ogg differ diff --git a/client/src/main/resources/sounds/fallbig1.ogg b/client/src/main/resources/sounds/fallbig1.ogg new file mode 100644 index 0000000..cb63c8c Binary files /dev/null and b/client/src/main/resources/sounds/fallbig1.ogg differ diff --git a/client/src/main/resources/sounds/fallbig2.ogg b/client/src/main/resources/sounds/fallbig2.ogg new file mode 100644 index 0000000..25d687b Binary files /dev/null and b/client/src/main/resources/sounds/fallbig2.ogg differ diff --git a/client/src/main/resources/sounds/fallsmall.ogg b/client/src/main/resources/sounds/fallsmall.ogg new file mode 100644 index 0000000..ed9a4e9 Binary files /dev/null and b/client/src/main/resources/sounds/fallsmall.ogg differ diff --git a/client/src/main/resources/sounds/fire.ogg b/client/src/main/resources/sounds/fire.ogg new file mode 100644 index 0000000..747fe59 Binary files /dev/null and b/client/src/main/resources/sounds/fire.ogg differ diff --git a/client/src/main/resources/sounds/fireball.ogg b/client/src/main/resources/sounds/fireball.ogg new file mode 100644 index 0000000..9754da5 Binary files /dev/null and b/client/src/main/resources/sounds/fireball.ogg differ diff --git a/client/src/main/resources/sounds/fizz.ogg b/client/src/main/resources/sounds/fizz.ogg new file mode 100644 index 0000000..60f9b2f Binary files /dev/null and b/client/src/main/resources/sounds/fizz.ogg differ diff --git a/client/src/main/resources/sounds/fox_death.ogg b/client/src/main/resources/sounds/fox_death.ogg new file mode 100644 index 0000000..6619338 Binary files /dev/null and b/client/src/main/resources/sounds/fox_death.ogg differ diff --git a/client/src/main/resources/sounds/fox_hurt1.ogg b/client/src/main/resources/sounds/fox_hurt1.ogg new file mode 100644 index 0000000..52b1335 Binary files /dev/null and b/client/src/main/resources/sounds/fox_hurt1.ogg differ diff --git a/client/src/main/resources/sounds/fox_hurt2.ogg b/client/src/main/resources/sounds/fox_hurt2.ogg new file mode 100644 index 0000000..e54d9a6 Binary files /dev/null and b/client/src/main/resources/sounds/fox_hurt2.ogg differ diff --git a/client/src/main/resources/sounds/fuse.ogg b/client/src/main/resources/sounds/fuse.ogg new file mode 100644 index 0000000..6f4e821 Binary files /dev/null and b/client/src/main/resources/sounds/fuse.ogg differ diff --git a/client/src/main/resources/sounds/glass1.ogg b/client/src/main/resources/sounds/glass1.ogg new file mode 100644 index 0000000..3224a90 Binary files /dev/null and b/client/src/main/resources/sounds/glass1.ogg differ diff --git a/client/src/main/resources/sounds/glass2.ogg b/client/src/main/resources/sounds/glass2.ogg new file mode 100644 index 0000000..ba69484 Binary files /dev/null and b/client/src/main/resources/sounds/glass2.ogg differ diff --git a/client/src/main/resources/sounds/glass3.ogg b/client/src/main/resources/sounds/glass3.ogg new file mode 100644 index 0000000..a4eac8c Binary files /dev/null and b/client/src/main/resources/sounds/glass3.ogg differ diff --git a/client/src/main/resources/sounds/grass1.ogg b/client/src/main/resources/sounds/grass1.ogg new file mode 100644 index 0000000..f455ecb Binary files /dev/null and b/client/src/main/resources/sounds/grass1.ogg differ diff --git a/client/src/main/resources/sounds/grass2.ogg b/client/src/main/resources/sounds/grass2.ogg new file mode 100644 index 0000000..6aa1e15 Binary files /dev/null and b/client/src/main/resources/sounds/grass2.ogg differ diff --git a/client/src/main/resources/sounds/grass3.ogg b/client/src/main/resources/sounds/grass3.ogg new file mode 100644 index 0000000..5aad07f Binary files /dev/null and b/client/src/main/resources/sounds/grass3.ogg differ diff --git a/client/src/main/resources/sounds/grass4.ogg b/client/src/main/resources/sounds/grass4.ogg new file mode 100644 index 0000000..80f360b Binary files /dev/null and b/client/src/main/resources/sounds/grass4.ogg differ diff --git a/client/src/main/resources/sounds/gravel1.ogg b/client/src/main/resources/sounds/gravel1.ogg new file mode 100644 index 0000000..6481adc Binary files /dev/null and b/client/src/main/resources/sounds/gravel1.ogg differ diff --git a/client/src/main/resources/sounds/gravel2.ogg b/client/src/main/resources/sounds/gravel2.ogg new file mode 100644 index 0000000..3e38880 Binary files /dev/null and b/client/src/main/resources/sounds/gravel2.ogg differ diff --git a/client/src/main/resources/sounds/gravel3.ogg b/client/src/main/resources/sounds/gravel3.ogg new file mode 100644 index 0000000..bcf5d82 Binary files /dev/null and b/client/src/main/resources/sounds/gravel3.ogg differ diff --git a/client/src/main/resources/sounds/gravel4.ogg b/client/src/main/resources/sounds/gravel4.ogg new file mode 100644 index 0000000..75a72c7 Binary files /dev/null and b/client/src/main/resources/sounds/gravel4.ogg differ diff --git a/client/src/main/resources/sounds/hit1.ogg b/client/src/main/resources/sounds/hit1.ogg new file mode 100644 index 0000000..46d3fe6 Binary files /dev/null and b/client/src/main/resources/sounds/hit1.ogg differ diff --git a/client/src/main/resources/sounds/hit2.ogg b/client/src/main/resources/sounds/hit2.ogg new file mode 100644 index 0000000..e01af94 Binary files /dev/null and b/client/src/main/resources/sounds/hit2.ogg differ diff --git a/client/src/main/resources/sounds/hit3.ogg b/client/src/main/resources/sounds/hit3.ogg new file mode 100644 index 0000000..6b1e1c1 Binary files /dev/null and b/client/src/main/resources/sounds/hit3.ogg differ diff --git a/client/src/main/resources/sounds/horse_angry.ogg b/client/src/main/resources/sounds/horse_angry.ogg new file mode 100644 index 0000000..bc7618f Binary files /dev/null and b/client/src/main/resources/sounds/horse_angry.ogg differ diff --git a/client/src/main/resources/sounds/horse_breathe1.ogg b/client/src/main/resources/sounds/horse_breathe1.ogg new file mode 100644 index 0000000..8454df5 Binary files /dev/null and b/client/src/main/resources/sounds/horse_breathe1.ogg differ diff --git a/client/src/main/resources/sounds/horse_breathe2.ogg b/client/src/main/resources/sounds/horse_breathe2.ogg new file mode 100644 index 0000000..8968abe Binary files /dev/null and b/client/src/main/resources/sounds/horse_breathe2.ogg differ diff --git a/client/src/main/resources/sounds/horse_breathe3.ogg b/client/src/main/resources/sounds/horse_breathe3.ogg new file mode 100644 index 0000000..bd2f435 Binary files /dev/null and b/client/src/main/resources/sounds/horse_breathe3.ogg differ diff --git a/client/src/main/resources/sounds/horse_death.ogg b/client/src/main/resources/sounds/horse_death.ogg new file mode 100644 index 0000000..76a3326 Binary files /dev/null and b/client/src/main/resources/sounds/horse_death.ogg differ diff --git a/client/src/main/resources/sounds/horse_gallop1.ogg b/client/src/main/resources/sounds/horse_gallop1.ogg new file mode 100644 index 0000000..3565549 Binary files /dev/null and b/client/src/main/resources/sounds/horse_gallop1.ogg differ diff --git a/client/src/main/resources/sounds/horse_gallop2.ogg b/client/src/main/resources/sounds/horse_gallop2.ogg new file mode 100644 index 0000000..f257408 Binary files /dev/null and b/client/src/main/resources/sounds/horse_gallop2.ogg differ diff --git a/client/src/main/resources/sounds/horse_gallop3.ogg b/client/src/main/resources/sounds/horse_gallop3.ogg new file mode 100644 index 0000000..4c19bdb Binary files /dev/null and b/client/src/main/resources/sounds/horse_gallop3.ogg differ diff --git a/client/src/main/resources/sounds/horse_gallop4.ogg b/client/src/main/resources/sounds/horse_gallop4.ogg new file mode 100644 index 0000000..9b300ce Binary files /dev/null and b/client/src/main/resources/sounds/horse_gallop4.ogg differ diff --git a/client/src/main/resources/sounds/horse_hit1.ogg b/client/src/main/resources/sounds/horse_hit1.ogg new file mode 100644 index 0000000..4f54dfa Binary files /dev/null and b/client/src/main/resources/sounds/horse_hit1.ogg differ diff --git a/client/src/main/resources/sounds/horse_hit2.ogg b/client/src/main/resources/sounds/horse_hit2.ogg new file mode 100644 index 0000000..9d628df Binary files /dev/null and b/client/src/main/resources/sounds/horse_hit2.ogg differ diff --git a/client/src/main/resources/sounds/horse_hit3.ogg b/client/src/main/resources/sounds/horse_hit3.ogg new file mode 100644 index 0000000..c13a241 Binary files /dev/null and b/client/src/main/resources/sounds/horse_hit3.ogg differ diff --git a/client/src/main/resources/sounds/horse_hit4.ogg b/client/src/main/resources/sounds/horse_hit4.ogg new file mode 100644 index 0000000..209d0e5 Binary files /dev/null and b/client/src/main/resources/sounds/horse_hit4.ogg differ diff --git a/client/src/main/resources/sounds/horse_idle1.ogg b/client/src/main/resources/sounds/horse_idle1.ogg new file mode 100644 index 0000000..1a94e43 Binary files /dev/null and b/client/src/main/resources/sounds/horse_idle1.ogg differ diff --git a/client/src/main/resources/sounds/horse_idle2.ogg b/client/src/main/resources/sounds/horse_idle2.ogg new file mode 100644 index 0000000..d7af74f Binary files /dev/null and b/client/src/main/resources/sounds/horse_idle2.ogg differ diff --git a/client/src/main/resources/sounds/horse_idle3.ogg b/client/src/main/resources/sounds/horse_idle3.ogg new file mode 100644 index 0000000..fbf4228 Binary files /dev/null and b/client/src/main/resources/sounds/horse_idle3.ogg differ diff --git a/client/src/main/resources/sounds/horse_jump.ogg b/client/src/main/resources/sounds/horse_jump.ogg new file mode 100644 index 0000000..e1713e9 Binary files /dev/null and b/client/src/main/resources/sounds/horse_jump.ogg differ diff --git a/client/src/main/resources/sounds/horse_land.ogg b/client/src/main/resources/sounds/horse_land.ogg new file mode 100644 index 0000000..186180f Binary files /dev/null and b/client/src/main/resources/sounds/horse_land.ogg differ diff --git a/client/src/main/resources/sounds/horse_soft1.ogg b/client/src/main/resources/sounds/horse_soft1.ogg new file mode 100644 index 0000000..bb567b1 Binary files /dev/null and b/client/src/main/resources/sounds/horse_soft1.ogg differ diff --git a/client/src/main/resources/sounds/horse_soft2.ogg b/client/src/main/resources/sounds/horse_soft2.ogg new file mode 100644 index 0000000..7013efd Binary files /dev/null and b/client/src/main/resources/sounds/horse_soft2.ogg differ diff --git a/client/src/main/resources/sounds/horse_soft3.ogg b/client/src/main/resources/sounds/horse_soft3.ogg new file mode 100644 index 0000000..cfe4011 Binary files /dev/null and b/client/src/main/resources/sounds/horse_soft3.ogg differ diff --git a/client/src/main/resources/sounds/horse_soft4.ogg b/client/src/main/resources/sounds/horse_soft4.ogg new file mode 100644 index 0000000..888f4a8 Binary files /dev/null and b/client/src/main/resources/sounds/horse_soft4.ogg differ diff --git a/client/src/main/resources/sounds/horse_soft5.ogg b/client/src/main/resources/sounds/horse_soft5.ogg new file mode 100644 index 0000000..d548b5a Binary files /dev/null and b/client/src/main/resources/sounds/horse_soft5.ogg differ diff --git a/client/src/main/resources/sounds/horse_soft6.ogg b/client/src/main/resources/sounds/horse_soft6.ogg new file mode 100644 index 0000000..8a5c4aa Binary files /dev/null and b/client/src/main/resources/sounds/horse_soft6.ogg differ diff --git a/client/src/main/resources/sounds/horse_wood1.ogg b/client/src/main/resources/sounds/horse_wood1.ogg new file mode 100644 index 0000000..7888040 Binary files /dev/null and b/client/src/main/resources/sounds/horse_wood1.ogg differ diff --git a/client/src/main/resources/sounds/horse_wood2.ogg b/client/src/main/resources/sounds/horse_wood2.ogg new file mode 100644 index 0000000..5ffa309 Binary files /dev/null and b/client/src/main/resources/sounds/horse_wood2.ogg differ diff --git a/client/src/main/resources/sounds/horse_wood3.ogg b/client/src/main/resources/sounds/horse_wood3.ogg new file mode 100644 index 0000000..504bd8e Binary files /dev/null and b/client/src/main/resources/sounds/horse_wood3.ogg differ diff --git a/client/src/main/resources/sounds/horse_wood4.ogg b/client/src/main/resources/sounds/horse_wood4.ogg new file mode 100644 index 0000000..2668928 Binary files /dev/null and b/client/src/main/resources/sounds/horse_wood4.ogg differ diff --git a/client/src/main/resources/sounds/horse_wood5.ogg b/client/src/main/resources/sounds/horse_wood5.ogg new file mode 100644 index 0000000..596e1bd Binary files /dev/null and b/client/src/main/resources/sounds/horse_wood5.ogg differ diff --git a/client/src/main/resources/sounds/horse_wood6.ogg b/client/src/main/resources/sounds/horse_wood6.ogg new file mode 100644 index 0000000..3df5c94 Binary files /dev/null and b/client/src/main/resources/sounds/horse_wood6.ogg differ diff --git a/client/src/main/resources/sounds/ignite.ogg b/client/src/main/resources/sounds/ignite.ogg new file mode 100644 index 0000000..dbb4072 Binary files /dev/null and b/client/src/main/resources/sounds/ignite.ogg differ diff --git a/client/src/main/resources/sounds/large_blast.ogg b/client/src/main/resources/sounds/large_blast.ogg new file mode 100644 index 0000000..ed0a286 Binary files /dev/null and b/client/src/main/resources/sounds/large_blast.ogg differ diff --git a/client/src/main/resources/sounds/large_blast_far.ogg b/client/src/main/resources/sounds/large_blast_far.ogg new file mode 100644 index 0000000..4be6eaf Binary files /dev/null and b/client/src/main/resources/sounds/large_blast_far.ogg differ diff --git a/client/src/main/resources/sounds/launch.ogg b/client/src/main/resources/sounds/launch.ogg new file mode 100644 index 0000000..8660f29 Binary files /dev/null and b/client/src/main/resources/sounds/launch.ogg differ diff --git a/client/src/main/resources/sounds/lava.ogg b/client/src/main/resources/sounds/lava.ogg new file mode 100644 index 0000000..4a5f0c7 Binary files /dev/null and b/client/src/main/resources/sounds/lava.ogg differ diff --git a/client/src/main/resources/sounds/lavapop.ogg b/client/src/main/resources/sounds/lavapop.ogg new file mode 100644 index 0000000..aad32e6 Binary files /dev/null and b/client/src/main/resources/sounds/lavapop.ogg differ diff --git a/client/src/main/resources/sounds/levelup.ogg b/client/src/main/resources/sounds/levelup.ogg new file mode 100644 index 0000000..a52cfb4 Binary files /dev/null and b/client/src/main/resources/sounds/levelup.ogg differ diff --git a/client/src/main/resources/sounds/magma.ogg b/client/src/main/resources/sounds/magma.ogg new file mode 100644 index 0000000..c49efaa Binary files /dev/null and b/client/src/main/resources/sounds/magma.ogg differ diff --git a/client/src/main/resources/sounds/magmapop.ogg b/client/src/main/resources/sounds/magmapop.ogg new file mode 100644 index 0000000..8231976 Binary files /dev/null and b/client/src/main/resources/sounds/magmapop.ogg differ diff --git a/client/src/main/resources/sounds/metal1.ogg b/client/src/main/resources/sounds/metal1.ogg new file mode 100644 index 0000000..e9bd562 Binary files /dev/null and b/client/src/main/resources/sounds/metal1.ogg differ diff --git a/client/src/main/resources/sounds/metal2.ogg b/client/src/main/resources/sounds/metal2.ogg new file mode 100644 index 0000000..1c9938f Binary files /dev/null and b/client/src/main/resources/sounds/metal2.ogg differ diff --git a/client/src/main/resources/sounds/metal3.ogg b/client/src/main/resources/sounds/metal3.ogg new file mode 100644 index 0000000..af84cdc Binary files /dev/null and b/client/src/main/resources/sounds/metal3.ogg differ diff --git a/client/src/main/resources/sounds/metalhit1.ogg b/client/src/main/resources/sounds/metalhit1.ogg new file mode 100644 index 0000000..433ac53 Binary files /dev/null and b/client/src/main/resources/sounds/metalhit1.ogg differ diff --git a/client/src/main/resources/sounds/metalhit2.ogg b/client/src/main/resources/sounds/metalhit2.ogg new file mode 100644 index 0000000..057126f Binary files /dev/null and b/client/src/main/resources/sounds/metalhit2.ogg differ diff --git a/client/src/main/resources/sounds/minecart_base.ogg b/client/src/main/resources/sounds/minecart_base.ogg new file mode 100644 index 0000000..cf68355 Binary files /dev/null and b/client/src/main/resources/sounds/minecart_base.ogg differ diff --git a/client/src/main/resources/sounds/minecart_inside.ogg b/client/src/main/resources/sounds/minecart_inside.ogg new file mode 100644 index 0000000..083627a Binary files /dev/null and b/client/src/main/resources/sounds/minecart_inside.ogg differ diff --git a/client/src/main/resources/sounds/molten.ogg b/client/src/main/resources/sounds/molten.ogg new file mode 100644 index 0000000..1577743 Binary files /dev/null and b/client/src/main/resources/sounds/molten.ogg differ diff --git a/client/src/main/resources/sounds/note.ogg b/client/src/main/resources/sounds/note.ogg new file mode 100644 index 0000000..1c02b11 Binary files /dev/null and b/client/src/main/resources/sounds/note.ogg differ diff --git a/client/src/main/resources/sounds/old_explode.ogg b/client/src/main/resources/sounds/old_explode.ogg new file mode 100644 index 0000000..0eadea5 Binary files /dev/null and b/client/src/main/resources/sounds/old_explode.ogg differ diff --git a/client/src/main/resources/sounds/orb.ogg b/client/src/main/resources/sounds/orb.ogg new file mode 100644 index 0000000..a00df55 Binary files /dev/null and b/client/src/main/resources/sounds/orb.ogg differ diff --git a/client/src/main/resources/sounds/pig_death.ogg b/client/src/main/resources/sounds/pig_death.ogg new file mode 100644 index 0000000..f47b99c Binary files /dev/null and b/client/src/main/resources/sounds/pig_death.ogg differ diff --git a/client/src/main/resources/sounds/pig_say1.ogg b/client/src/main/resources/sounds/pig_say1.ogg new file mode 100644 index 0000000..586e10d Binary files /dev/null and b/client/src/main/resources/sounds/pig_say1.ogg differ diff --git a/client/src/main/resources/sounds/pig_say2.ogg b/client/src/main/resources/sounds/pig_say2.ogg new file mode 100644 index 0000000..32c636a Binary files /dev/null and b/client/src/main/resources/sounds/pig_say2.ogg differ diff --git a/client/src/main/resources/sounds/pig_say3.ogg b/client/src/main/resources/sounds/pig_say3.ogg new file mode 100644 index 0000000..0f1701c Binary files /dev/null and b/client/src/main/resources/sounds/pig_say3.ogg differ diff --git a/client/src/main/resources/sounds/piston_in.ogg b/client/src/main/resources/sounds/piston_in.ogg new file mode 100644 index 0000000..3e4ac84 Binary files /dev/null and b/client/src/main/resources/sounds/piston_in.ogg differ diff --git a/client/src/main/resources/sounds/piston_out.ogg b/client/src/main/resources/sounds/piston_out.ogg new file mode 100644 index 0000000..f67b0d7 Binary files /dev/null and b/client/src/main/resources/sounds/piston_out.ogg differ diff --git a/client/src/main/resources/sounds/plop.ogg b/client/src/main/resources/sounds/plop.ogg new file mode 100644 index 0000000..6186212 Binary files /dev/null and b/client/src/main/resources/sounds/plop.ogg differ diff --git a/client/src/main/resources/sounds/pop.ogg b/client/src/main/resources/sounds/pop.ogg new file mode 100644 index 0000000..757cc14 Binary files /dev/null and b/client/src/main/resources/sounds/pop.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_bunnymurder.ogg b/client/src/main/resources/sounds/rabbit_bunnymurder.ogg new file mode 100644 index 0000000..f39302b Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_bunnymurder.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_hop1.ogg b/client/src/main/resources/sounds/rabbit_hop1.ogg new file mode 100644 index 0000000..c109eec Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_hop1.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_hop2.ogg b/client/src/main/resources/sounds/rabbit_hop2.ogg new file mode 100644 index 0000000..2245c2a Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_hop2.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_hop3.ogg b/client/src/main/resources/sounds/rabbit_hop3.ogg new file mode 100644 index 0000000..9df7543 Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_hop3.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_hop4.ogg b/client/src/main/resources/sounds/rabbit_hop4.ogg new file mode 100644 index 0000000..9725659 Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_hop4.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_hurt1.ogg b/client/src/main/resources/sounds/rabbit_hurt1.ogg new file mode 100644 index 0000000..0dd07e7 Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_hurt1.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_hurt2.ogg b/client/src/main/resources/sounds/rabbit_hurt2.ogg new file mode 100644 index 0000000..5f9dc2d Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_hurt2.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_hurt3.ogg b/client/src/main/resources/sounds/rabbit_hurt3.ogg new file mode 100644 index 0000000..9b21d91 Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_hurt3.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_hurt4.ogg b/client/src/main/resources/sounds/rabbit_hurt4.ogg new file mode 100644 index 0000000..7534e91 Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_hurt4.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_idle1.ogg b/client/src/main/resources/sounds/rabbit_idle1.ogg new file mode 100644 index 0000000..412fe62 Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_idle1.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_idle2.ogg b/client/src/main/resources/sounds/rabbit_idle2.ogg new file mode 100644 index 0000000..ec63d39 Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_idle2.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_idle3.ogg b/client/src/main/resources/sounds/rabbit_idle3.ogg new file mode 100644 index 0000000..6babe45 Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_idle3.ogg differ diff --git a/client/src/main/resources/sounds/rabbit_idle4.ogg b/client/src/main/resources/sounds/rabbit_idle4.ogg new file mode 100644 index 0000000..ec13e6b Binary files /dev/null and b/client/src/main/resources/sounds/rabbit_idle4.ogg differ diff --git a/client/src/main/resources/sounds/rain1.ogg b/client/src/main/resources/sounds/rain1.ogg new file mode 100644 index 0000000..91dedae Binary files /dev/null and b/client/src/main/resources/sounds/rain1.ogg differ diff --git a/client/src/main/resources/sounds/rain2.ogg b/client/src/main/resources/sounds/rain2.ogg new file mode 100644 index 0000000..c5b504a Binary files /dev/null and b/client/src/main/resources/sounds/rain2.ogg differ diff --git a/client/src/main/resources/sounds/rain3.ogg b/client/src/main/resources/sounds/rain3.ogg new file mode 100644 index 0000000..85f369a Binary files /dev/null and b/client/src/main/resources/sounds/rain3.ogg differ diff --git a/client/src/main/resources/sounds/rain4.ogg b/client/src/main/resources/sounds/rain4.ogg new file mode 100644 index 0000000..709cce6 Binary files /dev/null and b/client/src/main/resources/sounds/rain4.ogg differ diff --git a/client/src/main/resources/sounds/sand1.ogg b/client/src/main/resources/sounds/sand1.ogg new file mode 100644 index 0000000..dd15abd Binary files /dev/null and b/client/src/main/resources/sounds/sand1.ogg differ diff --git a/client/src/main/resources/sounds/sand2.ogg b/client/src/main/resources/sounds/sand2.ogg new file mode 100644 index 0000000..040e257 Binary files /dev/null and b/client/src/main/resources/sounds/sand2.ogg differ diff --git a/client/src/main/resources/sounds/sand3.ogg b/client/src/main/resources/sounds/sand3.ogg new file mode 100644 index 0000000..ca748a0 Binary files /dev/null and b/client/src/main/resources/sounds/sand3.ogg differ diff --git a/client/src/main/resources/sounds/sand4.ogg b/client/src/main/resources/sounds/sand4.ogg new file mode 100644 index 0000000..7eb862c Binary files /dev/null and b/client/src/main/resources/sounds/sand4.ogg differ diff --git a/client/src/main/resources/sounds/sheep_say1.ogg b/client/src/main/resources/sounds/sheep_say1.ogg new file mode 100644 index 0000000..209d4d5 Binary files /dev/null and b/client/src/main/resources/sounds/sheep_say1.ogg differ diff --git a/client/src/main/resources/sounds/sheep_say2.ogg b/client/src/main/resources/sounds/sheep_say2.ogg new file mode 100644 index 0000000..ccc6f9d Binary files /dev/null and b/client/src/main/resources/sounds/sheep_say2.ogg differ diff --git a/client/src/main/resources/sounds/sheep_say3.ogg b/client/src/main/resources/sounds/sheep_say3.ogg new file mode 100644 index 0000000..80daaee Binary files /dev/null and b/client/src/main/resources/sounds/sheep_say3.ogg differ diff --git a/client/src/main/resources/sounds/slime_attack1.ogg b/client/src/main/resources/sounds/slime_attack1.ogg new file mode 100644 index 0000000..d02d32b Binary files /dev/null and b/client/src/main/resources/sounds/slime_attack1.ogg differ diff --git a/client/src/main/resources/sounds/slime_attack2.ogg b/client/src/main/resources/sounds/slime_attack2.ogg new file mode 100644 index 0000000..b70ff50 Binary files /dev/null and b/client/src/main/resources/sounds/slime_attack2.ogg differ diff --git a/client/src/main/resources/sounds/slime_big1.ogg b/client/src/main/resources/sounds/slime_big1.ogg new file mode 100644 index 0000000..db96367 Binary files /dev/null and b/client/src/main/resources/sounds/slime_big1.ogg differ diff --git a/client/src/main/resources/sounds/slime_big2.ogg b/client/src/main/resources/sounds/slime_big2.ogg new file mode 100644 index 0000000..0e10611 Binary files /dev/null and b/client/src/main/resources/sounds/slime_big2.ogg differ diff --git a/client/src/main/resources/sounds/slime_big3.ogg b/client/src/main/resources/sounds/slime_big3.ogg new file mode 100644 index 0000000..ded5b71 Binary files /dev/null and b/client/src/main/resources/sounds/slime_big3.ogg differ diff --git a/client/src/main/resources/sounds/slime_big4.ogg b/client/src/main/resources/sounds/slime_big4.ogg new file mode 100644 index 0000000..5d9b676 Binary files /dev/null and b/client/src/main/resources/sounds/slime_big4.ogg differ diff --git a/client/src/main/resources/sounds/slime_small1.ogg b/client/src/main/resources/sounds/slime_small1.ogg new file mode 100644 index 0000000..53ba864 Binary files /dev/null and b/client/src/main/resources/sounds/slime_small1.ogg differ diff --git a/client/src/main/resources/sounds/slime_small2.ogg b/client/src/main/resources/sounds/slime_small2.ogg new file mode 100644 index 0000000..94439fd Binary files /dev/null and b/client/src/main/resources/sounds/slime_small2.ogg differ diff --git a/client/src/main/resources/sounds/slime_small3.ogg b/client/src/main/resources/sounds/slime_small3.ogg new file mode 100644 index 0000000..0879955 Binary files /dev/null and b/client/src/main/resources/sounds/slime_small3.ogg differ diff --git a/client/src/main/resources/sounds/slime_small4.ogg b/client/src/main/resources/sounds/slime_small4.ogg new file mode 100644 index 0000000..e3e84a9 Binary files /dev/null and b/client/src/main/resources/sounds/slime_small4.ogg differ diff --git a/client/src/main/resources/sounds/slime_small5.ogg b/client/src/main/resources/sounds/slime_small5.ogg new file mode 100644 index 0000000..a8b38ed Binary files /dev/null and b/client/src/main/resources/sounds/slime_small5.ogg differ diff --git a/client/src/main/resources/sounds/snow1.ogg b/client/src/main/resources/sounds/snow1.ogg new file mode 100644 index 0000000..3c141d1 Binary files /dev/null and b/client/src/main/resources/sounds/snow1.ogg differ diff --git a/client/src/main/resources/sounds/snow2.ogg b/client/src/main/resources/sounds/snow2.ogg new file mode 100644 index 0000000..c955f91 Binary files /dev/null and b/client/src/main/resources/sounds/snow2.ogg differ diff --git a/client/src/main/resources/sounds/snow3.ogg b/client/src/main/resources/sounds/snow3.ogg new file mode 100644 index 0000000..2232ec0 Binary files /dev/null and b/client/src/main/resources/sounds/snow3.ogg differ diff --git a/client/src/main/resources/sounds/snow4.ogg b/client/src/main/resources/sounds/snow4.ogg new file mode 100644 index 0000000..63fbd66 Binary files /dev/null and b/client/src/main/resources/sounds/snow4.ogg differ diff --git a/client/src/main/resources/sounds/spell.ogg b/client/src/main/resources/sounds/spell.ogg new file mode 100644 index 0000000..888c676 Binary files /dev/null and b/client/src/main/resources/sounds/spell.ogg differ diff --git a/client/src/main/resources/sounds/splash.ogg b/client/src/main/resources/sounds/splash.ogg new file mode 100644 index 0000000..4b69fb6 Binary files /dev/null and b/client/src/main/resources/sounds/splash.ogg differ diff --git a/client/src/main/resources/sounds/stone1.ogg b/client/src/main/resources/sounds/stone1.ogg new file mode 100644 index 0000000..16cd366 Binary files /dev/null and b/client/src/main/resources/sounds/stone1.ogg differ diff --git a/client/src/main/resources/sounds/stone2.ogg b/client/src/main/resources/sounds/stone2.ogg new file mode 100644 index 0000000..e9b6867 Binary files /dev/null and b/client/src/main/resources/sounds/stone2.ogg differ diff --git a/client/src/main/resources/sounds/stone3.ogg b/client/src/main/resources/sounds/stone3.ogg new file mode 100644 index 0000000..a9ebdc4 Binary files /dev/null and b/client/src/main/resources/sounds/stone3.ogg differ diff --git a/client/src/main/resources/sounds/stone4.ogg b/client/src/main/resources/sounds/stone4.ogg new file mode 100644 index 0000000..630b6a3 Binary files /dev/null and b/client/src/main/resources/sounds/stone4.ogg differ diff --git a/client/src/main/resources/sounds/teleport.ogg b/client/src/main/resources/sounds/teleport.ogg new file mode 100644 index 0000000..1d49a1a Binary files /dev/null and b/client/src/main/resources/sounds/teleport.ogg differ diff --git a/client/src/main/resources/sounds/teleport_back.ogg b/client/src/main/resources/sounds/teleport_back.ogg new file mode 100644 index 0000000..d52ef96 Binary files /dev/null and b/client/src/main/resources/sounds/teleport_back.ogg differ diff --git a/client/src/main/resources/sounds/thunder1.ogg b/client/src/main/resources/sounds/thunder1.ogg new file mode 100644 index 0000000..941968d Binary files /dev/null and b/client/src/main/resources/sounds/thunder1.ogg differ diff --git a/client/src/main/resources/sounds/thunder2.ogg b/client/src/main/resources/sounds/thunder2.ogg new file mode 100644 index 0000000..4193f81 Binary files /dev/null and b/client/src/main/resources/sounds/thunder2.ogg differ diff --git a/client/src/main/resources/sounds/thunder3.ogg b/client/src/main/resources/sounds/thunder3.ogg new file mode 100644 index 0000000..af47393 Binary files /dev/null and b/client/src/main/resources/sounds/thunder3.ogg differ diff --git a/client/src/main/resources/sounds/twinkle.ogg b/client/src/main/resources/sounds/twinkle.ogg new file mode 100644 index 0000000..41a8d4d Binary files /dev/null and b/client/src/main/resources/sounds/twinkle.ogg differ diff --git a/client/src/main/resources/sounds/twinkle_far.ogg b/client/src/main/resources/sounds/twinkle_far.ogg new file mode 100644 index 0000000..df4a16f Binary files /dev/null and b/client/src/main/resources/sounds/twinkle_far.ogg differ diff --git a/client/src/main/resources/sounds/water.ogg b/client/src/main/resources/sounds/water.ogg new file mode 100644 index 0000000..c7b77c3 Binary files /dev/null and b/client/src/main/resources/sounds/water.ogg differ diff --git a/client/src/main/resources/sounds/wolf_bark1.ogg b/client/src/main/resources/sounds/wolf_bark1.ogg new file mode 100644 index 0000000..a48f426 Binary files /dev/null and b/client/src/main/resources/sounds/wolf_bark1.ogg differ diff --git a/client/src/main/resources/sounds/wolf_bark2.ogg b/client/src/main/resources/sounds/wolf_bark2.ogg new file mode 100644 index 0000000..5eea29b Binary files /dev/null and b/client/src/main/resources/sounds/wolf_bark2.ogg differ diff --git a/client/src/main/resources/sounds/wolf_bark3.ogg b/client/src/main/resources/sounds/wolf_bark3.ogg new file mode 100644 index 0000000..c97bea4 Binary files /dev/null and b/client/src/main/resources/sounds/wolf_bark3.ogg differ diff --git a/client/src/main/resources/sounds/wolf_death.ogg b/client/src/main/resources/sounds/wolf_death.ogg new file mode 100644 index 0000000..5e7461e Binary files /dev/null and b/client/src/main/resources/sounds/wolf_death.ogg differ diff --git a/client/src/main/resources/sounds/wolf_growl1.ogg b/client/src/main/resources/sounds/wolf_growl1.ogg new file mode 100644 index 0000000..6af013e Binary files /dev/null and b/client/src/main/resources/sounds/wolf_growl1.ogg differ diff --git a/client/src/main/resources/sounds/wolf_growl2.ogg b/client/src/main/resources/sounds/wolf_growl2.ogg new file mode 100644 index 0000000..f47dbbc Binary files /dev/null and b/client/src/main/resources/sounds/wolf_growl2.ogg differ diff --git a/client/src/main/resources/sounds/wolf_growl3.ogg b/client/src/main/resources/sounds/wolf_growl3.ogg new file mode 100644 index 0000000..bd72a60 Binary files /dev/null and b/client/src/main/resources/sounds/wolf_growl3.ogg differ diff --git a/client/src/main/resources/sounds/wolf_hurt1.ogg b/client/src/main/resources/sounds/wolf_hurt1.ogg new file mode 100644 index 0000000..5c16ef7 Binary files /dev/null and b/client/src/main/resources/sounds/wolf_hurt1.ogg differ diff --git a/client/src/main/resources/sounds/wolf_hurt2.ogg b/client/src/main/resources/sounds/wolf_hurt2.ogg new file mode 100644 index 0000000..12ffc4f Binary files /dev/null and b/client/src/main/resources/sounds/wolf_hurt2.ogg differ diff --git a/client/src/main/resources/sounds/wolf_hurt3.ogg b/client/src/main/resources/sounds/wolf_hurt3.ogg new file mode 100644 index 0000000..4105709 Binary files /dev/null and b/client/src/main/resources/sounds/wolf_hurt3.ogg differ diff --git a/client/src/main/resources/sounds/wolf_panting.ogg b/client/src/main/resources/sounds/wolf_panting.ogg new file mode 100644 index 0000000..e2bbc8c Binary files /dev/null and b/client/src/main/resources/sounds/wolf_panting.ogg differ diff --git a/client/src/main/resources/sounds/wolf_shake.ogg b/client/src/main/resources/sounds/wolf_shake.ogg new file mode 100644 index 0000000..bf01cc3 Binary files /dev/null and b/client/src/main/resources/sounds/wolf_shake.ogg differ diff --git a/client/src/main/resources/sounds/wolf_whine.ogg b/client/src/main/resources/sounds/wolf_whine.ogg new file mode 100644 index 0000000..32a5aea Binary files /dev/null and b/client/src/main/resources/sounds/wolf_whine.ogg differ diff --git a/client/src/main/resources/sounds/wood1.ogg b/client/src/main/resources/sounds/wood1.ogg new file mode 100644 index 0000000..762cfb0 Binary files /dev/null and b/client/src/main/resources/sounds/wood1.ogg differ diff --git a/client/src/main/resources/sounds/wood2.ogg b/client/src/main/resources/sounds/wood2.ogg new file mode 100644 index 0000000..ef6f8c4 Binary files /dev/null and b/client/src/main/resources/sounds/wood2.ogg differ diff --git a/client/src/main/resources/sounds/wood3.ogg b/client/src/main/resources/sounds/wood3.ogg new file mode 100644 index 0000000..18c0236 Binary files /dev/null and b/client/src/main/resources/sounds/wood3.ogg differ diff --git a/client/src/main/resources/sounds/wood4.ogg b/client/src/main/resources/sounds/wood4.ogg new file mode 100644 index 0000000..c493c9e Binary files /dev/null and b/client/src/main/resources/sounds/wood4.ogg differ diff --git a/client/src/main/resources/textures/armor/ardite_layer_1.png b/client/src/main/resources/textures/armor/ardite_layer_1.png new file mode 100755 index 0000000..c023172 Binary files /dev/null and b/client/src/main/resources/textures/armor/ardite_layer_1.png differ diff --git a/client/src/main/resources/textures/armor/ardite_layer_2.png b/client/src/main/resources/textures/armor/ardite_layer_2.png new file mode 100755 index 0000000..d42e019 Binary files /dev/null and b/client/src/main/resources/textures/armor/ardite_layer_2.png differ diff --git a/client/src/main/resources/textures/armor/chain_layer_1.png b/client/src/main/resources/textures/armor/chain_layer_1.png new file mode 100755 index 0000000..9f84c18 Binary files /dev/null and b/client/src/main/resources/textures/armor/chain_layer_1.png differ diff --git a/client/src/main/resources/textures/armor/chain_layer_2.png b/client/src/main/resources/textures/armor/chain_layer_2.png new file mode 100755 index 0000000..117811c Binary files /dev/null and b/client/src/main/resources/textures/armor/chain_layer_2.png differ diff --git a/client/src/main/resources/textures/armor/cloth_layer_1.png b/client/src/main/resources/textures/armor/cloth_layer_1.png new file mode 100755 index 0000000..ebcfc41 Binary files /dev/null and b/client/src/main/resources/textures/armor/cloth_layer_1.png differ diff --git a/client/src/main/resources/textures/armor/cloth_layer_1_overlay.png b/client/src/main/resources/textures/armor/cloth_layer_1_overlay.png new file mode 100755 index 0000000..5811b7c Binary files /dev/null and b/client/src/main/resources/textures/armor/cloth_layer_1_overlay.png differ diff --git a/client/src/main/resources/textures/armor/cloth_layer_2.png b/client/src/main/resources/textures/armor/cloth_layer_2.png new file mode 100755 index 0000000..8d8bba6 Binary files /dev/null and b/client/src/main/resources/textures/armor/cloth_layer_2.png differ diff --git a/client/src/main/resources/textures/armor/cloth_layer_2_overlay.png b/client/src/main/resources/textures/armor/cloth_layer_2_overlay.png new file mode 100755 index 0000000..006f553 Binary files /dev/null and b/client/src/main/resources/textures/armor/cloth_layer_2_overlay.png differ diff --git a/client/src/main/resources/textures/armor/diamond_layer_1.png b/client/src/main/resources/textures/armor/diamond_layer_1.png new file mode 100755 index 0000000..14fecf2 Binary files /dev/null and b/client/src/main/resources/textures/armor/diamond_layer_1.png differ diff --git a/client/src/main/resources/textures/armor/diamond_layer_2.png b/client/src/main/resources/textures/armor/diamond_layer_2.png new file mode 100755 index 0000000..2cca056 Binary files /dev/null and b/client/src/main/resources/textures/armor/diamond_layer_2.png differ diff --git a/client/src/main/resources/textures/armor/gold_layer_1.png b/client/src/main/resources/textures/armor/gold_layer_1.png new file mode 100755 index 0000000..6802e06 Binary files /dev/null and b/client/src/main/resources/textures/armor/gold_layer_1.png differ diff --git a/client/src/main/resources/textures/armor/gold_layer_2.png b/client/src/main/resources/textures/armor/gold_layer_2.png new file mode 100755 index 0000000..a7cf835 Binary files /dev/null and b/client/src/main/resources/textures/armor/gold_layer_2.png differ diff --git a/client/src/main/resources/textures/armor/horse_armor_diamond.png b/client/src/main/resources/textures/armor/horse_armor_diamond.png new file mode 100755 index 0000000..39068f2 Binary files /dev/null and b/client/src/main/resources/textures/armor/horse_armor_diamond.png differ diff --git a/client/src/main/resources/textures/armor/horse_armor_gold.png b/client/src/main/resources/textures/armor/horse_armor_gold.png new file mode 100755 index 0000000..4a0786d Binary files /dev/null and b/client/src/main/resources/textures/armor/horse_armor_gold.png differ diff --git a/client/src/main/resources/textures/armor/horse_armor_iron.png b/client/src/main/resources/textures/armor/horse_armor_iron.png new file mode 100755 index 0000000..533b2dd Binary files /dev/null and b/client/src/main/resources/textures/armor/horse_armor_iron.png differ diff --git a/client/src/main/resources/textures/armor/iron_layer_1.png b/client/src/main/resources/textures/armor/iron_layer_1.png new file mode 100755 index 0000000..6da6e84 Binary files /dev/null and b/client/src/main/resources/textures/armor/iron_layer_1.png differ diff --git a/client/src/main/resources/textures/armor/iron_layer_2.png b/client/src/main/resources/textures/armor/iron_layer_2.png new file mode 100755 index 0000000..fab422a Binary files /dev/null and b/client/src/main/resources/textures/armor/iron_layer_2.png differ diff --git a/client/src/main/resources/textures/armor/leather_layer_1.png b/client/src/main/resources/textures/armor/leather_layer_1.png new file mode 100755 index 0000000..39d58bc Binary files /dev/null and b/client/src/main/resources/textures/armor/leather_layer_1.png differ diff --git a/client/src/main/resources/textures/armor/leather_layer_1_overlay.png b/client/src/main/resources/textures/armor/leather_layer_1_overlay.png new file mode 100755 index 0000000..5811b7c Binary files /dev/null and b/client/src/main/resources/textures/armor/leather_layer_1_overlay.png differ diff --git a/client/src/main/resources/textures/armor/leather_layer_2.png b/client/src/main/resources/textures/armor/leather_layer_2.png new file mode 100755 index 0000000..5fdccf5 Binary files /dev/null and b/client/src/main/resources/textures/armor/leather_layer_2.png differ diff --git a/client/src/main/resources/textures/armor/leather_layer_2_overlay.png b/client/src/main/resources/textures/armor/leather_layer_2_overlay.png new file mode 100755 index 0000000..006f553 Binary files /dev/null and b/client/src/main/resources/textures/armor/leather_layer_2_overlay.png differ diff --git a/client/src/main/resources/textures/armor/nichun_layer_1.png b/client/src/main/resources/textures/armor/nichun_layer_1.png new file mode 100755 index 0000000..fe90290 Binary files /dev/null and b/client/src/main/resources/textures/armor/nichun_layer_1.png differ diff --git a/client/src/main/resources/textures/armor/nichun_layer_2.png b/client/src/main/resources/textures/armor/nichun_layer_2.png new file mode 100755 index 0000000..4c54048 Binary files /dev/null and b/client/src/main/resources/textures/armor/nichun_layer_2.png differ diff --git a/client/src/main/resources/textures/armor/thetium_layer_1.png b/client/src/main/resources/textures/armor/thetium_layer_1.png new file mode 100755 index 0000000..2336d12 Binary files /dev/null and b/client/src/main/resources/textures/armor/thetium_layer_1.png differ diff --git a/client/src/main/resources/textures/armor/thetium_layer_2.png b/client/src/main/resources/textures/armor/thetium_layer_2.png new file mode 100755 index 0000000..d5f92d1 Binary files /dev/null and b/client/src/main/resources/textures/armor/thetium_layer_2.png differ diff --git a/client/src/main/resources/textures/background.png b/client/src/main/resources/textures/background.png new file mode 100755 index 0000000..d2ac167 Binary files /dev/null and b/client/src/main/resources/textures/background.png differ diff --git a/client/src/main/resources/textures/blocks/acacia_door_bottom.png b/client/src/main/resources/textures/blocks/acacia_door_bottom.png new file mode 100755 index 0000000..2f57508 Binary files /dev/null and b/client/src/main/resources/textures/blocks/acacia_door_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/acacia_door_top.png b/client/src/main/resources/textures/blocks/acacia_door_top.png new file mode 100755 index 0000000..9b7e742 Binary files /dev/null and b/client/src/main/resources/textures/blocks/acacia_door_top.png differ diff --git a/client/src/main/resources/textures/blocks/acacia_leaves_autumn.png b/client/src/main/resources/textures/blocks/acacia_leaves_autumn.png new file mode 100755 index 0000000..c9859e5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/acacia_leaves_autumn.png differ diff --git a/client/src/main/resources/textures/blocks/acacia_leaves_snowy.png b/client/src/main/resources/textures/blocks/acacia_leaves_snowy.png new file mode 100755 index 0000000..a97a67b Binary files /dev/null and b/client/src/main/resources/textures/blocks/acacia_leaves_snowy.png differ diff --git a/client/src/main/resources/textures/blocks/acacia_leaves_spring.png b/client/src/main/resources/textures/blocks/acacia_leaves_spring.png new file mode 100755 index 0000000..d54eb17 Binary files /dev/null and b/client/src/main/resources/textures/blocks/acacia_leaves_spring.png differ diff --git a/client/src/main/resources/textures/blocks/acacia_leaves_summer.png b/client/src/main/resources/textures/blocks/acacia_leaves_summer.png new file mode 100755 index 0000000..c66ab48 Binary files /dev/null and b/client/src/main/resources/textures/blocks/acacia_leaves_summer.png differ diff --git a/client/src/main/resources/textures/blocks/acacia_leaves_winter.png b/client/src/main/resources/textures/blocks/acacia_leaves_winter.png new file mode 100755 index 0000000..3a5f4f1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/acacia_leaves_winter.png differ diff --git a/client/src/main/resources/textures/blocks/acacia_log_bark.png b/client/src/main/resources/textures/blocks/acacia_log_bark.png new file mode 100755 index 0000000..d221210 Binary files /dev/null and b/client/src/main/resources/textures/blocks/acacia_log_bark.png differ diff --git a/client/src/main/resources/textures/blocks/acacia_log_top.png b/client/src/main/resources/textures/blocks/acacia_log_top.png new file mode 100755 index 0000000..3d44878 Binary files /dev/null and b/client/src/main/resources/textures/blocks/acacia_log_top.png differ diff --git a/client/src/main/resources/textures/blocks/acacia_planks.png b/client/src/main/resources/textures/blocks/acacia_planks.png new file mode 100755 index 0000000..6858c51 Binary files /dev/null and b/client/src/main/resources/textures/blocks/acacia_planks.png differ diff --git a/client/src/main/resources/textures/blocks/acacia_sapling.png b/client/src/main/resources/textures/blocks/acacia_sapling.png new file mode 100755 index 0000000..a1215cb Binary files /dev/null and b/client/src/main/resources/textures/blocks/acacia_sapling.png differ diff --git a/client/src/main/resources/textures/blocks/acid_flow.png b/client/src/main/resources/textures/blocks/acid_flow.png new file mode 100755 index 0000000..c4f0024 Binary files /dev/null and b/client/src/main/resources/textures/blocks/acid_flow.png differ diff --git a/client/src/main/resources/textures/blocks/acid_still.png b/client/src/main/resources/textures/blocks/acid_still.png new file mode 100755 index 0000000..8193699 Binary files /dev/null and b/client/src/main/resources/textures/blocks/acid_still.png differ diff --git a/client/src/main/resources/textures/blocks/activator_rail.png b/client/src/main/resources/textures/blocks/activator_rail.png new file mode 100755 index 0000000..ce115ba Binary files /dev/null and b/client/src/main/resources/textures/blocks/activator_rail.png differ diff --git a/client/src/main/resources/textures/blocks/activator_rail_powered.png b/client/src/main/resources/textures/blocks/activator_rail_powered.png new file mode 100755 index 0000000..a3aaca9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/activator_rail_powered.png differ diff --git a/client/src/main/resources/textures/blocks/allium.png b/client/src/main/resources/textures/blocks/allium.png new file mode 100755 index 0000000..b7b5a45 Binary files /dev/null and b/client/src/main/resources/textures/blocks/allium.png differ diff --git a/client/src/main/resources/textures/blocks/aluminium_block.png b/client/src/main/resources/textures/blocks/aluminium_block.png new file mode 100755 index 0000000..7ce12c5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/aluminium_block.png differ diff --git a/client/src/main/resources/textures/blocks/aluminium_ore.png b/client/src/main/resources/textures/blocks/aluminium_ore.png new file mode 100755 index 0000000..f660f62 Binary files /dev/null and b/client/src/main/resources/textures/blocks/aluminium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/antimony_block.png b/client/src/main/resources/textures/blocks/antimony_block.png new file mode 100755 index 0000000..edcec09 Binary files /dev/null and b/client/src/main/resources/textures/blocks/antimony_block.png differ diff --git a/client/src/main/resources/textures/blocks/antimony_ore.png b/client/src/main/resources/textures/blocks/antimony_ore.png new file mode 100755 index 0000000..456b91e Binary files /dev/null and b/client/src/main/resources/textures/blocks/antimony_ore.png differ diff --git a/client/src/main/resources/textures/blocks/anvil_base.png b/client/src/main/resources/textures/blocks/anvil_base.png new file mode 100755 index 0000000..cfc1fc8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/anvil_base.png differ diff --git a/client/src/main/resources/textures/blocks/anvil_top_0.png b/client/src/main/resources/textures/blocks/anvil_top_0.png new file mode 100755 index 0000000..395dea4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/anvil_top_0.png differ diff --git a/client/src/main/resources/textures/blocks/anvil_top_1.png b/client/src/main/resources/textures/blocks/anvil_top_1.png new file mode 100755 index 0000000..eddc47f Binary files /dev/null and b/client/src/main/resources/textures/blocks/anvil_top_1.png differ diff --git a/client/src/main/resources/textures/blocks/anvil_top_2.png b/client/src/main/resources/textures/blocks/anvil_top_2.png new file mode 100755 index 0000000..6cade1f Binary files /dev/null and b/client/src/main/resources/textures/blocks/anvil_top_2.png differ diff --git a/client/src/main/resources/textures/blocks/ardite_block.png b/client/src/main/resources/textures/blocks/ardite_block.png new file mode 100755 index 0000000..5ffcd4f Binary files /dev/null and b/client/src/main/resources/textures/blocks/ardite_block.png differ diff --git a/client/src/main/resources/textures/blocks/ardite_ore.png b/client/src/main/resources/textures/blocks/ardite_ore.png new file mode 100755 index 0000000..d459bd6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/ardite_ore.png differ diff --git a/client/src/main/resources/textures/blocks/arsenic_block.png b/client/src/main/resources/textures/blocks/arsenic_block.png new file mode 100755 index 0000000..2d43573 Binary files /dev/null and b/client/src/main/resources/textures/blocks/arsenic_block.png differ diff --git a/client/src/main/resources/textures/blocks/arsenic_ore.png b/client/src/main/resources/textures/blocks/arsenic_ore.png new file mode 100755 index 0000000..6a38443 Binary files /dev/null and b/client/src/main/resources/textures/blocks/arsenic_ore.png differ diff --git a/client/src/main/resources/textures/blocks/ash.png b/client/src/main/resources/textures/blocks/ash.png new file mode 100755 index 0000000..711c838 Binary files /dev/null and b/client/src/main/resources/textures/blocks/ash.png differ diff --git a/client/src/main/resources/textures/blocks/banner.png b/client/src/main/resources/textures/blocks/banner.png new file mode 100755 index 0000000..e38d28e Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner.png differ diff --git a/client/src/main/resources/textures/blocks/banner_base.png b/client/src/main/resources/textures/blocks/banner_base.png new file mode 100755 index 0000000..bc80603 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_base.png differ diff --git a/client/src/main/resources/textures/blocks/banner_border.png b/client/src/main/resources/textures/blocks/banner_border.png new file mode 100755 index 0000000..444aeea Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_border.png differ diff --git a/client/src/main/resources/textures/blocks/banner_bricks.png b/client/src/main/resources/textures/blocks/banner_bricks.png new file mode 100755 index 0000000..544cff4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_bricks.png differ diff --git a/client/src/main/resources/textures/blocks/banner_circle.png b/client/src/main/resources/textures/blocks/banner_circle.png new file mode 100755 index 0000000..c6d3774 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_circle.png differ diff --git a/client/src/main/resources/textures/blocks/banner_cross.png b/client/src/main/resources/textures/blocks/banner_cross.png new file mode 100755 index 0000000..c18bf82 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_cross.png differ diff --git a/client/src/main/resources/textures/blocks/banner_curly_border.png b/client/src/main/resources/textures/blocks/banner_curly_border.png new file mode 100755 index 0000000..5ea188e Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_curly_border.png differ diff --git a/client/src/main/resources/textures/blocks/banner_diagonal_left.png b/client/src/main/resources/textures/blocks/banner_diagonal_left.png new file mode 100755 index 0000000..c6f45ff Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_diagonal_left.png differ diff --git a/client/src/main/resources/textures/blocks/banner_diagonal_right.png b/client/src/main/resources/textures/blocks/banner_diagonal_right.png new file mode 100755 index 0000000..23280c4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_diagonal_right.png differ diff --git a/client/src/main/resources/textures/blocks/banner_diagonal_up_left.png b/client/src/main/resources/textures/blocks/banner_diagonal_up_left.png new file mode 100755 index 0000000..b0955f2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_diagonal_up_left.png differ diff --git a/client/src/main/resources/textures/blocks/banner_diagonal_up_right.png b/client/src/main/resources/textures/blocks/banner_diagonal_up_right.png new file mode 100755 index 0000000..e8cd6b1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_diagonal_up_right.png differ diff --git a/client/src/main/resources/textures/blocks/banner_flower.png b/client/src/main/resources/textures/blocks/banner_flower.png new file mode 100755 index 0000000..67dc1ac Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_flower.png differ diff --git a/client/src/main/resources/textures/blocks/banner_gradient.png b/client/src/main/resources/textures/blocks/banner_gradient.png new file mode 100755 index 0000000..8ce9832 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_gradient.png differ diff --git a/client/src/main/resources/textures/blocks/banner_gradient_up.png b/client/src/main/resources/textures/blocks/banner_gradient_up.png new file mode 100755 index 0000000..38cf516 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_gradient_up.png differ diff --git a/client/src/main/resources/textures/blocks/banner_half_horizontal.png b/client/src/main/resources/textures/blocks/banner_half_horizontal.png new file mode 100755 index 0000000..0f6d8a7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_half_horizontal.png differ diff --git a/client/src/main/resources/textures/blocks/banner_half_horizontal_bottom.png b/client/src/main/resources/textures/blocks/banner_half_horizontal_bottom.png new file mode 100755 index 0000000..64fac36 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_half_horizontal_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/banner_half_vertical.png b/client/src/main/resources/textures/blocks/banner_half_vertical.png new file mode 100755 index 0000000..8178ea7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_half_vertical.png differ diff --git a/client/src/main/resources/textures/blocks/banner_half_vertical_right.png b/client/src/main/resources/textures/blocks/banner_half_vertical_right.png new file mode 100755 index 0000000..74089b6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_half_vertical_right.png differ diff --git a/client/src/main/resources/textures/blocks/banner_rhombus.png b/client/src/main/resources/textures/blocks/banner_rhombus.png new file mode 100755 index 0000000..abee982 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_rhombus.png differ diff --git a/client/src/main/resources/textures/blocks/banner_rune.png b/client/src/main/resources/textures/blocks/banner_rune.png new file mode 100755 index 0000000..32e7620 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_rune.png differ diff --git a/client/src/main/resources/textures/blocks/banner_skull.png b/client/src/main/resources/textures/blocks/banner_skull.png new file mode 100755 index 0000000..ddf8653 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_skull.png differ diff --git a/client/src/main/resources/textures/blocks/banner_small_stripes.png b/client/src/main/resources/textures/blocks/banner_small_stripes.png new file mode 100755 index 0000000..0abaef0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_small_stripes.png differ diff --git a/client/src/main/resources/textures/blocks/banner_square_bottom_left.png b/client/src/main/resources/textures/blocks/banner_square_bottom_left.png new file mode 100755 index 0000000..5fdd245 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_square_bottom_left.png differ diff --git a/client/src/main/resources/textures/blocks/banner_square_bottom_right.png b/client/src/main/resources/textures/blocks/banner_square_bottom_right.png new file mode 100755 index 0000000..dd64eca Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_square_bottom_right.png differ diff --git a/client/src/main/resources/textures/blocks/banner_square_top_left.png b/client/src/main/resources/textures/blocks/banner_square_top_left.png new file mode 100755 index 0000000..7628998 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_square_top_left.png differ diff --git a/client/src/main/resources/textures/blocks/banner_square_top_right.png b/client/src/main/resources/textures/blocks/banner_square_top_right.png new file mode 100755 index 0000000..4197ecb Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_square_top_right.png differ diff --git a/client/src/main/resources/textures/blocks/banner_straight_cross.png b/client/src/main/resources/textures/blocks/banner_straight_cross.png new file mode 100755 index 0000000..1b7fa7d Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_straight_cross.png differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_bottom.png b/client/src/main/resources/textures/blocks/banner_stripe_bottom.png new file mode 100755 index 0000000..5473f90 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_stripe_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_center.png b/client/src/main/resources/textures/blocks/banner_stripe_center.png new file mode 100755 index 0000000..eddba20 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_stripe_center.png differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_downleft.png b/client/src/main/resources/textures/blocks/banner_stripe_downleft.png new file mode 100755 index 0000000..d73f9b7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_stripe_downleft.png differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_downright.png b/client/src/main/resources/textures/blocks/banner_stripe_downright.png new file mode 100755 index 0000000..0b610d9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_stripe_downright.png differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_left.png b/client/src/main/resources/textures/blocks/banner_stripe_left.png new file mode 100755 index 0000000..0707d31 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_stripe_left.png differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_middle.png b/client/src/main/resources/textures/blocks/banner_stripe_middle.png new file mode 100755 index 0000000..bde988b Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_stripe_middle.png differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_right.png b/client/src/main/resources/textures/blocks/banner_stripe_right.png new file mode 100755 index 0000000..f0a8a25 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_stripe_right.png differ diff --git a/client/src/main/resources/textures/blocks/banner_stripe_top.png b/client/src/main/resources/textures/blocks/banner_stripe_top.png new file mode 100755 index 0000000..1b8e3f2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_stripe_top.png differ diff --git a/client/src/main/resources/textures/blocks/banner_thing.png b/client/src/main/resources/textures/blocks/banner_thing.png new file mode 100755 index 0000000..7ae1cbc Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_thing.png differ diff --git a/client/src/main/resources/textures/blocks/banner_triangle_bottom.png b/client/src/main/resources/textures/blocks/banner_triangle_bottom.png new file mode 100755 index 0000000..bc37930 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_triangle_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/banner_triangle_top.png b/client/src/main/resources/textures/blocks/banner_triangle_top.png new file mode 100755 index 0000000..77877c0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_triangle_top.png differ diff --git a/client/src/main/resources/textures/blocks/banner_triangles_bottom.png b/client/src/main/resources/textures/blocks/banner_triangles_bottom.png new file mode 100755 index 0000000..fe25db7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_triangles_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/banner_triangles_top.png b/client/src/main/resources/textures/blocks/banner_triangles_top.png new file mode 100755 index 0000000..f59a121 Binary files /dev/null and b/client/src/main/resources/textures/blocks/banner_triangles_top.png differ diff --git a/client/src/main/resources/textures/blocks/beacon.png b/client/src/main/resources/textures/blocks/beacon.png new file mode 100755 index 0000000..a69e59d Binary files /dev/null and b/client/src/main/resources/textures/blocks/beacon.png differ diff --git a/client/src/main/resources/textures/blocks/beacon_beam.png b/client/src/main/resources/textures/blocks/beacon_beam.png new file mode 100755 index 0000000..67545b4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/beacon_beam.png differ diff --git a/client/src/main/resources/textures/blocks/bedrock.png b/client/src/main/resources/textures/blocks/bedrock.png new file mode 100755 index 0000000..1643c99 Binary files /dev/null and b/client/src/main/resources/textures/blocks/bedrock.png differ diff --git a/client/src/main/resources/textures/blocks/birch_door_bottom.png b/client/src/main/resources/textures/blocks/birch_door_bottom.png new file mode 100755 index 0000000..2c6f7d3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/birch_door_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/birch_door_top.png b/client/src/main/resources/textures/blocks/birch_door_top.png new file mode 100755 index 0000000..1345b41 Binary files /dev/null and b/client/src/main/resources/textures/blocks/birch_door_top.png differ diff --git a/client/src/main/resources/textures/blocks/birch_leaves_autumn.png b/client/src/main/resources/textures/blocks/birch_leaves_autumn.png new file mode 100755 index 0000000..90998d3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/birch_leaves_autumn.png differ diff --git a/client/src/main/resources/textures/blocks/birch_leaves_snowy.png b/client/src/main/resources/textures/blocks/birch_leaves_snowy.png new file mode 100755 index 0000000..cbaf47d Binary files /dev/null and b/client/src/main/resources/textures/blocks/birch_leaves_snowy.png differ diff --git a/client/src/main/resources/textures/blocks/birch_leaves_spring.png b/client/src/main/resources/textures/blocks/birch_leaves_spring.png new file mode 100755 index 0000000..a6773af Binary files /dev/null and b/client/src/main/resources/textures/blocks/birch_leaves_spring.png differ diff --git a/client/src/main/resources/textures/blocks/birch_leaves_summer.png b/client/src/main/resources/textures/blocks/birch_leaves_summer.png new file mode 100755 index 0000000..2becfb1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/birch_leaves_summer.png differ diff --git a/client/src/main/resources/textures/blocks/birch_leaves_winter.png b/client/src/main/resources/textures/blocks/birch_leaves_winter.png new file mode 100755 index 0000000..afa1d69 Binary files /dev/null and b/client/src/main/resources/textures/blocks/birch_leaves_winter.png differ diff --git a/client/src/main/resources/textures/blocks/birch_log_bark.png b/client/src/main/resources/textures/blocks/birch_log_bark.png new file mode 100755 index 0000000..bfb209d Binary files /dev/null and b/client/src/main/resources/textures/blocks/birch_log_bark.png differ diff --git a/client/src/main/resources/textures/blocks/birch_log_top.png b/client/src/main/resources/textures/blocks/birch_log_top.png new file mode 100755 index 0000000..f9b94f4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/birch_log_top.png differ diff --git a/client/src/main/resources/textures/blocks/birch_planks.png b/client/src/main/resources/textures/blocks/birch_planks.png new file mode 100755 index 0000000..b113e3a Binary files /dev/null and b/client/src/main/resources/textures/blocks/birch_planks.png differ diff --git a/client/src/main/resources/textures/blocks/birch_sapling.png b/client/src/main/resources/textures/blocks/birch_sapling.png new file mode 100755 index 0000000..b0dacc5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/birch_sapling.png differ diff --git a/client/src/main/resources/textures/blocks/bismuth_block.png b/client/src/main/resources/textures/blocks/bismuth_block.png new file mode 100755 index 0000000..0e6fdc0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/bismuth_block.png differ diff --git a/client/src/main/resources/textures/blocks/bismuth_ore.png b/client/src/main/resources/textures/blocks/bismuth_ore.png new file mode 100755 index 0000000..71f8884 Binary files /dev/null and b/client/src/main/resources/textures/blocks/bismuth_ore.png differ diff --git a/client/src/main/resources/textures/blocks/black_bed_foot_end.png b/client/src/main/resources/textures/blocks/black_bed_foot_end.png new file mode 100755 index 0000000..0f9a411 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_bed_foot_end.png differ diff --git a/client/src/main/resources/textures/blocks/black_bed_foot_side.png b/client/src/main/resources/textures/blocks/black_bed_foot_side.png new file mode 100755 index 0000000..7445d59 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_bed_foot_side.png differ diff --git a/client/src/main/resources/textures/blocks/black_bed_foot_top.png b/client/src/main/resources/textures/blocks/black_bed_foot_top.png new file mode 100755 index 0000000..9813d14 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_bed_foot_top.png differ diff --git a/client/src/main/resources/textures/blocks/black_bed_head_end.png b/client/src/main/resources/textures/blocks/black_bed_head_end.png new file mode 100755 index 0000000..928e4be Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_bed_head_end.png differ diff --git a/client/src/main/resources/textures/blocks/black_bed_head_side.png b/client/src/main/resources/textures/blocks/black_bed_head_side.png new file mode 100755 index 0000000..146c073 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_bed_head_side.png differ diff --git a/client/src/main/resources/textures/blocks/black_bed_head_top.png b/client/src/main/resources/textures/blocks/black_bed_head_top.png new file mode 100755 index 0000000..c8c5c97 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_bed_head_top.png differ diff --git a/client/src/main/resources/textures/blocks/black_brick.png b/client/src/main/resources/textures/blocks/black_brick.png new file mode 100755 index 0000000..89ef692 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_brick.png differ diff --git a/client/src/main/resources/textures/blocks/black_glass.png b/client/src/main/resources/textures/blocks/black_glass.png new file mode 100755 index 0000000..06f3427 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_glass.png differ diff --git a/client/src/main/resources/textures/blocks/black_glass_pane.png b/client/src/main/resources/textures/blocks/black_glass_pane.png new file mode 100755 index 0000000..43d60c5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/black_lotus.png b/client/src/main/resources/textures/blocks/black_lotus.png new file mode 100755 index 0000000..55b4762 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_lotus.png differ diff --git a/client/src/main/resources/textures/blocks/black_metal_block.png b/client/src/main/resources/textures/blocks/black_metal_block.png new file mode 100755 index 0000000..9d0f751 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_metal_block.png differ diff --git a/client/src/main/resources/textures/blocks/black_metal_ore.png b/client/src/main/resources/textures/blocks/black_metal_ore.png new file mode 100755 index 0000000..679dbbb Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_metal_ore.png differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_bottom.png b/client/src/main/resources/textures/blocks/black_quartz_block_bottom.png new file mode 100755 index 0000000..8f6aed0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_quartz_block_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_chiseled.png b/client/src/main/resources/textures/blocks/black_quartz_block_chiseled.png new file mode 100755 index 0000000..eae475e Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_quartz_block_chiseled.png differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_chiseled_top.png b/client/src/main/resources/textures/blocks/black_quartz_block_chiseled_top.png new file mode 100755 index 0000000..bb1c5b9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_quartz_block_chiseled_top.png differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_lines.png b/client/src/main/resources/textures/blocks/black_quartz_block_lines.png new file mode 100755 index 0000000..d80fa89 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_quartz_block_lines.png differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_lines_top.png b/client/src/main/resources/textures/blocks/black_quartz_block_lines_top.png new file mode 100755 index 0000000..384a2ce Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_quartz_block_lines_top.png differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_block_side.png b/client/src/main/resources/textures/blocks/black_quartz_block_side.png new file mode 100755 index 0000000..404830b Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_quartz_block_side.png differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_ore.png b/client/src/main/resources/textures/blocks/black_quartz_ore.png new file mode 100755 index 0000000..24b6682 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_quartz_ore.png differ diff --git a/client/src/main/resources/textures/blocks/black_quartz_top.png b/client/src/main/resources/textures/blocks/black_quartz_top.png new file mode 100755 index 0000000..2eeb1ab Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_quartz_top.png differ diff --git a/client/src/main/resources/textures/blocks/black_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/black_stained_hardened_clay.png new file mode 100755 index 0000000..59da22c Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/black_wool.png b/client/src/main/resources/textures/blocks/black_wool.png new file mode 100755 index 0000000..b74d5c9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/black_wool.png differ diff --git a/client/src/main/resources/textures/blocks/blackened_cobble.png b/client/src/main/resources/textures/blocks/blackened_cobble.png new file mode 100755 index 0000000..4bf9754 Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackened_cobble.png differ diff --git a/client/src/main/resources/textures/blocks/blackened_dirt.png b/client/src/main/resources/textures/blocks/blackened_dirt.png new file mode 100755 index 0000000..9cf29ee Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackened_dirt.png differ diff --git a/client/src/main/resources/textures/blocks/blackened_soil_side.png b/client/src/main/resources/textures/blocks/blackened_soil_side.png new file mode 100755 index 0000000..0620abc Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackened_soil_side.png differ diff --git a/client/src/main/resources/textures/blocks/blackened_soil_top.png b/client/src/main/resources/textures/blocks/blackened_soil_top.png new file mode 100755 index 0000000..c27165b Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackened_soil_top.png differ diff --git a/client/src/main/resources/textures/blocks/blackened_stone.png b/client/src/main/resources/textures/blocks/blackened_stone.png new file mode 100755 index 0000000..1d0851e Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackened_stone.png differ diff --git a/client/src/main/resources/textures/blocks/blackwood_door_bottom.png b/client/src/main/resources/textures/blocks/blackwood_door_bottom.png new file mode 100755 index 0000000..7d6a3c0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackwood_door_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/blackwood_door_top.png b/client/src/main/resources/textures/blocks/blackwood_door_top.png new file mode 100755 index 0000000..e949507 Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackwood_door_top.png differ diff --git a/client/src/main/resources/textures/blocks/blackwood_leaves_autumn.png b/client/src/main/resources/textures/blocks/blackwood_leaves_autumn.png new file mode 100755 index 0000000..6ceb92c Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackwood_leaves_autumn.png differ diff --git a/client/src/main/resources/textures/blocks/blackwood_leaves_snowy.png b/client/src/main/resources/textures/blocks/blackwood_leaves_snowy.png new file mode 100755 index 0000000..7b08e6b Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackwood_leaves_snowy.png differ diff --git a/client/src/main/resources/textures/blocks/blackwood_leaves_spring.png b/client/src/main/resources/textures/blocks/blackwood_leaves_spring.png new file mode 100755 index 0000000..0c7528a Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackwood_leaves_spring.png differ diff --git a/client/src/main/resources/textures/blocks/blackwood_leaves_summer.png b/client/src/main/resources/textures/blocks/blackwood_leaves_summer.png new file mode 100755 index 0000000..b0f22cf Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackwood_leaves_summer.png differ diff --git a/client/src/main/resources/textures/blocks/blackwood_leaves_winter.png b/client/src/main/resources/textures/blocks/blackwood_leaves_winter.png new file mode 100755 index 0000000..21d5c96 Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackwood_leaves_winter.png differ diff --git a/client/src/main/resources/textures/blocks/blackwood_log_bark.png b/client/src/main/resources/textures/blocks/blackwood_log_bark.png new file mode 100755 index 0000000..4403aa6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackwood_log_bark.png differ diff --git a/client/src/main/resources/textures/blocks/blackwood_log_top.png b/client/src/main/resources/textures/blocks/blackwood_log_top.png new file mode 100755 index 0000000..9cf9fbd Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackwood_log_top.png differ diff --git a/client/src/main/resources/textures/blocks/blackwood_planks.png b/client/src/main/resources/textures/blocks/blackwood_planks.png new file mode 100755 index 0000000..f2a79c4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackwood_planks.png differ diff --git a/client/src/main/resources/textures/blocks/blackwood_sapling.png b/client/src/main/resources/textures/blocks/blackwood_sapling.png new file mode 100755 index 0000000..572c562 Binary files /dev/null and b/client/src/main/resources/textures/blocks/blackwood_sapling.png differ diff --git a/client/src/main/resources/textures/blocks/blood_brick.png b/client/src/main/resources/textures/blocks/blood_brick.png new file mode 100755 index 0000000..caaf66f Binary files /dev/null and b/client/src/main/resources/textures/blocks/blood_brick.png differ diff --git a/client/src/main/resources/textures/blocks/blood_flow.png b/client/src/main/resources/textures/blocks/blood_flow.png new file mode 100755 index 0000000..56eb9c9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/blood_flow.png differ diff --git a/client/src/main/resources/textures/blocks/blood_still.png b/client/src/main/resources/textures/blocks/blood_still.png new file mode 100755 index 0000000..c6c9761 Binary files /dev/null and b/client/src/main/resources/textures/blocks/blood_still.png differ diff --git a/client/src/main/resources/textures/blocks/blue_glass.png b/client/src/main/resources/textures/blocks/blue_glass.png new file mode 100755 index 0000000..38885de Binary files /dev/null and b/client/src/main/resources/textures/blocks/blue_glass.png differ diff --git a/client/src/main/resources/textures/blocks/blue_glass_pane.png b/client/src/main/resources/textures/blocks/blue_glass_pane.png new file mode 100755 index 0000000..55c614f Binary files /dev/null and b/client/src/main/resources/textures/blocks/blue_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/blue_mushroom.png b/client/src/main/resources/textures/blocks/blue_mushroom.png new file mode 100755 index 0000000..cf498fb Binary files /dev/null and b/client/src/main/resources/textures/blocks/blue_mushroom.png differ diff --git a/client/src/main/resources/textures/blocks/blue_orchid.png b/client/src/main/resources/textures/blocks/blue_orchid.png new file mode 100755 index 0000000..51d7fd9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/blue_orchid.png differ diff --git a/client/src/main/resources/textures/blocks/blue_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/blue_stained_hardened_clay.png new file mode 100755 index 0000000..7e38e27 Binary files /dev/null and b/client/src/main/resources/textures/blocks/blue_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/blue_wool.png b/client/src/main/resources/textures/blocks/blue_wool.png new file mode 100755 index 0000000..ce9515f Binary files /dev/null and b/client/src/main/resources/textures/blocks/blue_wool.png differ diff --git a/client/src/main/resources/textures/blocks/bookshelf.png b/client/src/main/resources/textures/blocks/bookshelf.png new file mode 100755 index 0000000..4c87f0f Binary files /dev/null and b/client/src/main/resources/textures/blocks/bookshelf.png differ diff --git a/client/src/main/resources/textures/blocks/brewing_stand.png b/client/src/main/resources/textures/blocks/brewing_stand.png new file mode 100755 index 0000000..60832aa Binary files /dev/null and b/client/src/main/resources/textures/blocks/brewing_stand.png differ diff --git a/client/src/main/resources/textures/blocks/brewing_stand_base.png b/client/src/main/resources/textures/blocks/brewing_stand_base.png new file mode 100755 index 0000000..0742fbf Binary files /dev/null and b/client/src/main/resources/textures/blocks/brewing_stand_base.png differ diff --git a/client/src/main/resources/textures/blocks/brick_block.png b/client/src/main/resources/textures/blocks/brick_block.png new file mode 100755 index 0000000..f1b6d7c Binary files /dev/null and b/client/src/main/resources/textures/blocks/brick_block.png differ diff --git a/client/src/main/resources/textures/blocks/brown_glass.png b/client/src/main/resources/textures/blocks/brown_glass.png new file mode 100755 index 0000000..259b61c Binary files /dev/null and b/client/src/main/resources/textures/blocks/brown_glass.png differ diff --git a/client/src/main/resources/textures/blocks/brown_glass_pane.png b/client/src/main/resources/textures/blocks/brown_glass_pane.png new file mode 100755 index 0000000..cbd791a Binary files /dev/null and b/client/src/main/resources/textures/blocks/brown_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/brown_mushroom.png b/client/src/main/resources/textures/blocks/brown_mushroom.png new file mode 100755 index 0000000..bf33d34 Binary files /dev/null and b/client/src/main/resources/textures/blocks/brown_mushroom.png differ diff --git a/client/src/main/resources/textures/blocks/brown_mushroom_block_cap.png b/client/src/main/resources/textures/blocks/brown_mushroom_block_cap.png new file mode 100755 index 0000000..1f52ba8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/brown_mushroom_block_cap.png differ diff --git a/client/src/main/resources/textures/blocks/brown_mushroom_block_inside.png b/client/src/main/resources/textures/blocks/brown_mushroom_block_inside.png new file mode 100755 index 0000000..f0e7a04 Binary files /dev/null and b/client/src/main/resources/textures/blocks/brown_mushroom_block_inside.png differ diff --git a/client/src/main/resources/textures/blocks/brown_mushroom_block_stem.png b/client/src/main/resources/textures/blocks/brown_mushroom_block_stem.png new file mode 100755 index 0000000..83c0840 Binary files /dev/null and b/client/src/main/resources/textures/blocks/brown_mushroom_block_stem.png differ diff --git a/client/src/main/resources/textures/blocks/brown_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/brown_stained_hardened_clay.png new file mode 100755 index 0000000..f81745f Binary files /dev/null and b/client/src/main/resources/textures/blocks/brown_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/brown_wool.png b/client/src/main/resources/textures/blocks/brown_wool.png new file mode 100755 index 0000000..b4dc3c5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/brown_wool.png differ diff --git a/client/src/main/resources/textures/blocks/cactus_bottom.png b/client/src/main/resources/textures/blocks/cactus_bottom.png new file mode 100755 index 0000000..6f10bc0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cactus_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/cactus_side.png b/client/src/main/resources/textures/blocks/cactus_side.png new file mode 100755 index 0000000..9c55503 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cactus_side.png differ diff --git a/client/src/main/resources/textures/blocks/cactus_top.png b/client/src/main/resources/textures/blocks/cactus_top.png new file mode 100755 index 0000000..f182e84 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cactus_top.png differ diff --git a/client/src/main/resources/textures/blocks/cake_bottom.png b/client/src/main/resources/textures/blocks/cake_bottom.png new file mode 100755 index 0000000..d93b15a Binary files /dev/null and b/client/src/main/resources/textures/blocks/cake_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/cake_inner.png b/client/src/main/resources/textures/blocks/cake_inner.png new file mode 100755 index 0000000..ce7ce69 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cake_inner.png differ diff --git a/client/src/main/resources/textures/blocks/cake_side.png b/client/src/main/resources/textures/blocks/cake_side.png new file mode 100755 index 0000000..343a023 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cake_side.png differ diff --git a/client/src/main/resources/textures/blocks/cake_top.png b/client/src/main/resources/textures/blocks/cake_top.png new file mode 100755 index 0000000..2947892 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cake_top.png differ diff --git a/client/src/main/resources/textures/blocks/calcium_block.png b/client/src/main/resources/textures/blocks/calcium_block.png new file mode 100755 index 0000000..8e0a79c Binary files /dev/null and b/client/src/main/resources/textures/blocks/calcium_block.png differ diff --git a/client/src/main/resources/textures/blocks/calcium_ore.png b/client/src/main/resources/textures/blocks/calcium_ore.png new file mode 100755 index 0000000..fa6fef0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/calcium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/carrot_0.png b/client/src/main/resources/textures/blocks/carrot_0.png new file mode 100755 index 0000000..c1ef732 Binary files /dev/null and b/client/src/main/resources/textures/blocks/carrot_0.png differ diff --git a/client/src/main/resources/textures/blocks/carrot_1.png b/client/src/main/resources/textures/blocks/carrot_1.png new file mode 100755 index 0000000..1275f4f Binary files /dev/null and b/client/src/main/resources/textures/blocks/carrot_1.png differ diff --git a/client/src/main/resources/textures/blocks/carrot_2.png b/client/src/main/resources/textures/blocks/carrot_2.png new file mode 100755 index 0000000..b7347df Binary files /dev/null and b/client/src/main/resources/textures/blocks/carrot_2.png differ diff --git a/client/src/main/resources/textures/blocks/carrot_3.png b/client/src/main/resources/textures/blocks/carrot_3.png new file mode 100755 index 0000000..2391be8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/carrot_3.png differ diff --git a/client/src/main/resources/textures/blocks/cauldron_bottom.png b/client/src/main/resources/textures/blocks/cauldron_bottom.png new file mode 100755 index 0000000..8328307 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cauldron_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/cauldron_inner.png b/client/src/main/resources/textures/blocks/cauldron_inner.png new file mode 100755 index 0000000..d5a30dd Binary files /dev/null and b/client/src/main/resources/textures/blocks/cauldron_inner.png differ diff --git a/client/src/main/resources/textures/blocks/cauldron_side.png b/client/src/main/resources/textures/blocks/cauldron_side.png new file mode 100755 index 0000000..df42f98 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cauldron_side.png differ diff --git a/client/src/main/resources/textures/blocks/cauldron_top.png b/client/src/main/resources/textures/blocks/cauldron_top.png new file mode 100755 index 0000000..e263fc5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cauldron_top.png differ diff --git a/client/src/main/resources/textures/blocks/cell_rock.png b/client/src/main/resources/textures/blocks/cell_rock.png new file mode 100755 index 0000000..c2a91e3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cell_rock.png differ diff --git a/client/src/main/resources/textures/blocks/cherry_door_bottom.png b/client/src/main/resources/textures/blocks/cherry_door_bottom.png new file mode 100755 index 0000000..b8909f7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cherry_door_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/cherry_door_top.png b/client/src/main/resources/textures/blocks/cherry_door_top.png new file mode 100755 index 0000000..b0160b3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cherry_door_top.png differ diff --git a/client/src/main/resources/textures/blocks/cherry_leaves_autumn.png b/client/src/main/resources/textures/blocks/cherry_leaves_autumn.png new file mode 100755 index 0000000..262a22f Binary files /dev/null and b/client/src/main/resources/textures/blocks/cherry_leaves_autumn.png differ diff --git a/client/src/main/resources/textures/blocks/cherry_leaves_snowy.png b/client/src/main/resources/textures/blocks/cherry_leaves_snowy.png new file mode 100755 index 0000000..54210a5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cherry_leaves_snowy.png differ diff --git a/client/src/main/resources/textures/blocks/cherry_leaves_spring.png b/client/src/main/resources/textures/blocks/cherry_leaves_spring.png new file mode 100755 index 0000000..fe79cff Binary files /dev/null and b/client/src/main/resources/textures/blocks/cherry_leaves_spring.png differ diff --git a/client/src/main/resources/textures/blocks/cherry_leaves_summer.png b/client/src/main/resources/textures/blocks/cherry_leaves_summer.png new file mode 100755 index 0000000..6e1b678 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cherry_leaves_summer.png differ diff --git a/client/src/main/resources/textures/blocks/cherry_leaves_winter.png b/client/src/main/resources/textures/blocks/cherry_leaves_winter.png new file mode 100755 index 0000000..abd4113 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cherry_leaves_winter.png differ diff --git a/client/src/main/resources/textures/blocks/cherry_log_bark.png b/client/src/main/resources/textures/blocks/cherry_log_bark.png new file mode 100755 index 0000000..5224cc7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cherry_log_bark.png differ diff --git a/client/src/main/resources/textures/blocks/cherry_log_top.png b/client/src/main/resources/textures/blocks/cherry_log_top.png new file mode 100755 index 0000000..e9099e6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cherry_log_top.png differ diff --git a/client/src/main/resources/textures/blocks/cherry_planks.png b/client/src/main/resources/textures/blocks/cherry_planks.png new file mode 100755 index 0000000..268aac2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cherry_planks.png differ diff --git a/client/src/main/resources/textures/blocks/cherry_sapling.png b/client/src/main/resources/textures/blocks/cherry_sapling.png new file mode 100755 index 0000000..2a149e0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cherry_sapling.png differ diff --git a/client/src/main/resources/textures/blocks/chest_normal.png b/client/src/main/resources/textures/blocks/chest_normal.png new file mode 100755 index 0000000..2e3d7fd Binary files /dev/null and b/client/src/main/resources/textures/blocks/chest_normal.png differ diff --git a/client/src/main/resources/textures/blocks/chest_normal_double.png b/client/src/main/resources/textures/blocks/chest_normal_double.png new file mode 100755 index 0000000..0168338 Binary files /dev/null and b/client/src/main/resources/textures/blocks/chest_normal_double.png differ diff --git a/client/src/main/resources/textures/blocks/chest_trapped.png b/client/src/main/resources/textures/blocks/chest_trapped.png new file mode 100755 index 0000000..3aef190 Binary files /dev/null and b/client/src/main/resources/textures/blocks/chest_trapped.png differ diff --git a/client/src/main/resources/textures/blocks/chest_trapped_double.png b/client/src/main/resources/textures/blocks/chest_trapped_double.png new file mode 100755 index 0000000..00eebe5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/chest_trapped_double.png differ diff --git a/client/src/main/resources/textures/blocks/chrome_block.png b/client/src/main/resources/textures/blocks/chrome_block.png new file mode 100755 index 0000000..d124793 Binary files /dev/null and b/client/src/main/resources/textures/blocks/chrome_block.png differ diff --git a/client/src/main/resources/textures/blocks/chrome_ore.png b/client/src/main/resources/textures/blocks/chrome_ore.png new file mode 100755 index 0000000..aaac737 Binary files /dev/null and b/client/src/main/resources/textures/blocks/chrome_ore.png differ diff --git a/client/src/main/resources/textures/blocks/cinnabar_block.png b/client/src/main/resources/textures/blocks/cinnabar_block.png new file mode 100755 index 0000000..7ba2fe9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cinnabar_block.png differ diff --git a/client/src/main/resources/textures/blocks/cinnabar_ore.png b/client/src/main/resources/textures/blocks/cinnabar_ore.png new file mode 100755 index 0000000..48f52ba Binary files /dev/null and b/client/src/main/resources/textures/blocks/cinnabar_ore.png differ diff --git a/client/src/main/resources/textures/blocks/clay.png b/client/src/main/resources/textures/blocks/clay.png new file mode 100755 index 0000000..c19e031 Binary files /dev/null and b/client/src/main/resources/textures/blocks/clay.png differ diff --git a/client/src/main/resources/textures/blocks/coal_block.png b/client/src/main/resources/textures/blocks/coal_block.png new file mode 100755 index 0000000..024404b Binary files /dev/null and b/client/src/main/resources/textures/blocks/coal_block.png differ diff --git a/client/src/main/resources/textures/blocks/coal_ore.png b/client/src/main/resources/textures/blocks/coal_ore.png new file mode 100755 index 0000000..49486d2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/coal_ore.png differ diff --git a/client/src/main/resources/textures/blocks/coarse_dirt.png b/client/src/main/resources/textures/blocks/coarse_dirt.png new file mode 100755 index 0000000..d646225 Binary files /dev/null and b/client/src/main/resources/textures/blocks/coarse_dirt.png differ diff --git a/client/src/main/resources/textures/blocks/cobalt_block.png b/client/src/main/resources/textures/blocks/cobalt_block.png new file mode 100755 index 0000000..63dd0dc Binary files /dev/null and b/client/src/main/resources/textures/blocks/cobalt_block.png differ diff --git a/client/src/main/resources/textures/blocks/cobalt_ore.png b/client/src/main/resources/textures/blocks/cobalt_ore.png new file mode 100755 index 0000000..1105968 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cobalt_ore.png differ diff --git a/client/src/main/resources/textures/blocks/cobblestone.png b/client/src/main/resources/textures/blocks/cobblestone.png new file mode 100755 index 0000000..be2a189 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cobblestone.png differ diff --git a/client/src/main/resources/textures/blocks/cocoa_0.png b/client/src/main/resources/textures/blocks/cocoa_0.png new file mode 100755 index 0000000..25892eb Binary files /dev/null and b/client/src/main/resources/textures/blocks/cocoa_0.png differ diff --git a/client/src/main/resources/textures/blocks/cocoa_1.png b/client/src/main/resources/textures/blocks/cocoa_1.png new file mode 100755 index 0000000..d0098ff Binary files /dev/null and b/client/src/main/resources/textures/blocks/cocoa_1.png differ diff --git a/client/src/main/resources/textures/blocks/cocoa_2.png b/client/src/main/resources/textures/blocks/cocoa_2.png new file mode 100755 index 0000000..db28c7b Binary files /dev/null and b/client/src/main/resources/textures/blocks/cocoa_2.png differ diff --git a/client/src/main/resources/textures/blocks/comparator_off.png b/client/src/main/resources/textures/blocks/comparator_off.png new file mode 100755 index 0000000..c9527bc Binary files /dev/null and b/client/src/main/resources/textures/blocks/comparator_off.png differ diff --git a/client/src/main/resources/textures/blocks/comparator_on.png b/client/src/main/resources/textures/blocks/comparator_on.png new file mode 100755 index 0000000..2e4fb7a Binary files /dev/null and b/client/src/main/resources/textures/blocks/comparator_on.png differ diff --git a/client/src/main/resources/textures/blocks/control_block.png b/client/src/main/resources/textures/blocks/control_block.png new file mode 100755 index 0000000..8dfa75d Binary files /dev/null and b/client/src/main/resources/textures/blocks/control_block.png differ diff --git a/client/src/main/resources/textures/blocks/copper_block.png b/client/src/main/resources/textures/blocks/copper_block.png new file mode 100755 index 0000000..3bff2a7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/copper_block.png differ diff --git a/client/src/main/resources/textures/blocks/copper_ore.png b/client/src/main/resources/textures/blocks/copper_ore.png new file mode 100755 index 0000000..a67cb93 Binary files /dev/null and b/client/src/main/resources/textures/blocks/copper_ore.png differ diff --git a/client/src/main/resources/textures/blocks/core.png b/client/src/main/resources/textures/blocks/core.png new file mode 100755 index 0000000..0e44411 Binary files /dev/null and b/client/src/main/resources/textures/blocks/core.png differ diff --git a/client/src/main/resources/textures/blocks/crafting_table_front.png b/client/src/main/resources/textures/blocks/crafting_table_front.png new file mode 100755 index 0000000..11986a4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/crafting_table_front.png differ diff --git a/client/src/main/resources/textures/blocks/crafting_table_side.png b/client/src/main/resources/textures/blocks/crafting_table_side.png new file mode 100755 index 0000000..1c678b4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/crafting_table_side.png differ diff --git a/client/src/main/resources/textures/blocks/crafting_table_top.png b/client/src/main/resources/textures/blocks/crafting_table_top.png new file mode 100755 index 0000000..5cd53a5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/crafting_table_top.png differ diff --git a/client/src/main/resources/textures/blocks/cyan_glass.png b/client/src/main/resources/textures/blocks/cyan_glass.png new file mode 100755 index 0000000..d30caa4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cyan_glass.png differ diff --git a/client/src/main/resources/textures/blocks/cyan_glass_pane.png b/client/src/main/resources/textures/blocks/cyan_glass_pane.png new file mode 100755 index 0000000..9a34b84 Binary files /dev/null and b/client/src/main/resources/textures/blocks/cyan_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/cyan_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/cyan_stained_hardened_clay.png new file mode 100755 index 0000000..b05428c Binary files /dev/null and b/client/src/main/resources/textures/blocks/cyan_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/cyan_wool.png b/client/src/main/resources/textures/blocks/cyan_wool.png new file mode 100755 index 0000000..ca0800a Binary files /dev/null and b/client/src/main/resources/textures/blocks/cyan_wool.png differ diff --git a/client/src/main/resources/textures/blocks/dandelion.png b/client/src/main/resources/textures/blocks/dandelion.png new file mode 100755 index 0000000..873e3f5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dandelion.png differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_door_bottom.png b/client/src/main/resources/textures/blocks/dark_oak_door_bottom.png new file mode 100755 index 0000000..7bb3ff2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dark_oak_door_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_door_top.png b/client/src/main/resources/textures/blocks/dark_oak_door_top.png new file mode 100755 index 0000000..27fa6cc Binary files /dev/null and b/client/src/main/resources/textures/blocks/dark_oak_door_top.png differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_leaves_autumn.png b/client/src/main/resources/textures/blocks/dark_oak_leaves_autumn.png new file mode 100755 index 0000000..aa5c4cc Binary files /dev/null and b/client/src/main/resources/textures/blocks/dark_oak_leaves_autumn.png differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_leaves_snowy.png b/client/src/main/resources/textures/blocks/dark_oak_leaves_snowy.png new file mode 100755 index 0000000..3afd95b Binary files /dev/null and b/client/src/main/resources/textures/blocks/dark_oak_leaves_snowy.png differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_leaves_spring.png b/client/src/main/resources/textures/blocks/dark_oak_leaves_spring.png new file mode 100755 index 0000000..a6773af Binary files /dev/null and b/client/src/main/resources/textures/blocks/dark_oak_leaves_spring.png differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_leaves_summer.png b/client/src/main/resources/textures/blocks/dark_oak_leaves_summer.png new file mode 100755 index 0000000..23b96b8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dark_oak_leaves_summer.png differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_leaves_winter.png b/client/src/main/resources/textures/blocks/dark_oak_leaves_winter.png new file mode 100755 index 0000000..27593e4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dark_oak_leaves_winter.png differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_log_bark.png b/client/src/main/resources/textures/blocks/dark_oak_log_bark.png new file mode 100755 index 0000000..d4da03e Binary files /dev/null and b/client/src/main/resources/textures/blocks/dark_oak_log_bark.png differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_log_top.png b/client/src/main/resources/textures/blocks/dark_oak_log_top.png new file mode 100755 index 0000000..99137b6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dark_oak_log_top.png differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_planks.png b/client/src/main/resources/textures/blocks/dark_oak_planks.png new file mode 100755 index 0000000..e3fd4ea Binary files /dev/null and b/client/src/main/resources/textures/blocks/dark_oak_planks.png differ diff --git a/client/src/main/resources/textures/blocks/dark_oak_sapling.png b/client/src/main/resources/textures/blocks/dark_oak_sapling.png new file mode 100755 index 0000000..dcf5588 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dark_oak_sapling.png differ diff --git a/client/src/main/resources/textures/blocks/darkstone.png b/client/src/main/resources/textures/blocks/darkstone.png new file mode 100755 index 0000000..db20684 Binary files /dev/null and b/client/src/main/resources/textures/blocks/darkstone.png differ diff --git a/client/src/main/resources/textures/blocks/daylight_detector_inverted_top.png b/client/src/main/resources/textures/blocks/daylight_detector_inverted_top.png new file mode 100755 index 0000000..194a30e Binary files /dev/null and b/client/src/main/resources/textures/blocks/daylight_detector_inverted_top.png differ diff --git a/client/src/main/resources/textures/blocks/daylight_detector_side.png b/client/src/main/resources/textures/blocks/daylight_detector_side.png new file mode 100755 index 0000000..ac273ea Binary files /dev/null and b/client/src/main/resources/textures/blocks/daylight_detector_side.png differ diff --git a/client/src/main/resources/textures/blocks/daylight_detector_top.png b/client/src/main/resources/textures/blocks/daylight_detector_top.png new file mode 100755 index 0000000..3bfb2da Binary files /dev/null and b/client/src/main/resources/textures/blocks/daylight_detector_top.png differ diff --git a/client/src/main/resources/textures/blocks/deadbush.png b/client/src/main/resources/textures/blocks/deadbush.png new file mode 100755 index 0000000..c64e079 Binary files /dev/null and b/client/src/main/resources/textures/blocks/deadbush.png differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_0.png b/client/src/main/resources/textures/blocks/destroy_stage_0.png new file mode 100755 index 0000000..f65b7ed Binary files /dev/null and b/client/src/main/resources/textures/blocks/destroy_stage_0.png differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_1.png b/client/src/main/resources/textures/blocks/destroy_stage_1.png new file mode 100755 index 0000000..7c91596 Binary files /dev/null and b/client/src/main/resources/textures/blocks/destroy_stage_1.png differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_2.png b/client/src/main/resources/textures/blocks/destroy_stage_2.png new file mode 100755 index 0000000..dadd6b0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/destroy_stage_2.png differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_3.png b/client/src/main/resources/textures/blocks/destroy_stage_3.png new file mode 100755 index 0000000..52a40b6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/destroy_stage_3.png differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_4.png b/client/src/main/resources/textures/blocks/destroy_stage_4.png new file mode 100755 index 0000000..e37c88a Binary files /dev/null and b/client/src/main/resources/textures/blocks/destroy_stage_4.png differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_5.png b/client/src/main/resources/textures/blocks/destroy_stage_5.png new file mode 100755 index 0000000..9590d2f Binary files /dev/null and b/client/src/main/resources/textures/blocks/destroy_stage_5.png differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_6.png b/client/src/main/resources/textures/blocks/destroy_stage_6.png new file mode 100755 index 0000000..8e490c0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/destroy_stage_6.png differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_7.png b/client/src/main/resources/textures/blocks/destroy_stage_7.png new file mode 100755 index 0000000..0b40c78 Binary files /dev/null and b/client/src/main/resources/textures/blocks/destroy_stage_7.png differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_8.png b/client/src/main/resources/textures/blocks/destroy_stage_8.png new file mode 100755 index 0000000..c0bf1de Binary files /dev/null and b/client/src/main/resources/textures/blocks/destroy_stage_8.png differ diff --git a/client/src/main/resources/textures/blocks/destroy_stage_9.png b/client/src/main/resources/textures/blocks/destroy_stage_9.png new file mode 100755 index 0000000..e3185f8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/destroy_stage_9.png differ diff --git a/client/src/main/resources/textures/blocks/detector_rail.png b/client/src/main/resources/textures/blocks/detector_rail.png new file mode 100755 index 0000000..92c1466 Binary files /dev/null and b/client/src/main/resources/textures/blocks/detector_rail.png differ diff --git a/client/src/main/resources/textures/blocks/detector_rail_powered.png b/client/src/main/resources/textures/blocks/detector_rail_powered.png new file mode 100755 index 0000000..a1c6e6b Binary files /dev/null and b/client/src/main/resources/textures/blocks/detector_rail_powered.png differ diff --git a/client/src/main/resources/textures/blocks/diamond_block.png b/client/src/main/resources/textures/blocks/diamond_block.png new file mode 100755 index 0000000..4aefc68 Binary files /dev/null and b/client/src/main/resources/textures/blocks/diamond_block.png differ diff --git a/client/src/main/resources/textures/blocks/diamond_ore.png b/client/src/main/resources/textures/blocks/diamond_ore.png new file mode 100755 index 0000000..735ecda Binary files /dev/null and b/client/src/main/resources/textures/blocks/diamond_ore.png differ diff --git a/client/src/main/resources/textures/blocks/dirt.png b/client/src/main/resources/textures/blocks/dirt.png new file mode 100755 index 0000000..d225d91 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dirt.png differ diff --git a/client/src/main/resources/textures/blocks/dirt_podzol_side.png b/client/src/main/resources/textures/blocks/dirt_podzol_side.png new file mode 100755 index 0000000..5921d37 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dirt_podzol_side.png differ diff --git a/client/src/main/resources/textures/blocks/dirt_podzol_top.png b/client/src/main/resources/textures/blocks/dirt_podzol_top.png new file mode 100755 index 0000000..ebeda86 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dirt_podzol_top.png differ diff --git a/client/src/main/resources/textures/blocks/dispenser_front_horizontal.png b/client/src/main/resources/textures/blocks/dispenser_front_horizontal.png new file mode 100755 index 0000000..3e09fde Binary files /dev/null and b/client/src/main/resources/textures/blocks/dispenser_front_horizontal.png differ diff --git a/client/src/main/resources/textures/blocks/dispenser_front_vertical.png b/client/src/main/resources/textures/blocks/dispenser_front_vertical.png new file mode 100755 index 0000000..87a7837 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dispenser_front_vertical.png differ diff --git a/client/src/main/resources/textures/blocks/double_fern_bottom.png b/client/src/main/resources/textures/blocks/double_fern_bottom.png new file mode 100755 index 0000000..6a5fa6a Binary files /dev/null and b/client/src/main/resources/textures/blocks/double_fern_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/double_fern_top.png b/client/src/main/resources/textures/blocks/double_fern_top.png new file mode 100755 index 0000000..393144c Binary files /dev/null and b/client/src/main/resources/textures/blocks/double_fern_top.png differ diff --git a/client/src/main/resources/textures/blocks/double_grass_bottom.png b/client/src/main/resources/textures/blocks/double_grass_bottom.png new file mode 100755 index 0000000..5ac15b4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/double_grass_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/double_grass_top.png b/client/src/main/resources/textures/blocks/double_grass_top.png new file mode 100755 index 0000000..1ceb3de Binary files /dev/null and b/client/src/main/resources/textures/blocks/double_grass_top.png differ diff --git a/client/src/main/resources/textures/blocks/double_rose_bottom.png b/client/src/main/resources/textures/blocks/double_rose_bottom.png new file mode 100755 index 0000000..4d59f44 Binary files /dev/null and b/client/src/main/resources/textures/blocks/double_rose_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/double_rose_top.png b/client/src/main/resources/textures/blocks/double_rose_top.png new file mode 100755 index 0000000..028aa80 Binary files /dev/null and b/client/src/main/resources/textures/blocks/double_rose_top.png differ diff --git a/client/src/main/resources/textures/blocks/double_stone_top.png b/client/src/main/resources/textures/blocks/double_stone_top.png new file mode 100755 index 0000000..090657d Binary files /dev/null and b/client/src/main/resources/textures/blocks/double_stone_top.png differ diff --git a/client/src/main/resources/textures/blocks/dragon_egg.png b/client/src/main/resources/textures/blocks/dragon_egg.png new file mode 100755 index 0000000..02af123 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dragon_egg.png differ diff --git a/client/src/main/resources/textures/blocks/dropper_front_horizontal.png b/client/src/main/resources/textures/blocks/dropper_front_horizontal.png new file mode 100755 index 0000000..7d5f260 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dropper_front_horizontal.png differ diff --git a/client/src/main/resources/textures/blocks/dropper_front_vertical.png b/client/src/main/resources/textures/blocks/dropper_front_vertical.png new file mode 100755 index 0000000..68a56c8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dropper_front_vertical.png differ diff --git a/client/src/main/resources/textures/blocks/dry_leaves.png b/client/src/main/resources/textures/blocks/dry_leaves.png new file mode 100755 index 0000000..e355797 Binary files /dev/null and b/client/src/main/resources/textures/blocks/dry_leaves.png differ diff --git a/client/src/main/resources/textures/blocks/emerald_block.png b/client/src/main/resources/textures/blocks/emerald_block.png new file mode 100755 index 0000000..dc214ee Binary files /dev/null and b/client/src/main/resources/textures/blocks/emerald_block.png differ diff --git a/client/src/main/resources/textures/blocks/emerald_ore.png b/client/src/main/resources/textures/blocks/emerald_ore.png new file mode 100755 index 0000000..a26c35f Binary files /dev/null and b/client/src/main/resources/textures/blocks/emerald_ore.png differ diff --git a/client/src/main/resources/textures/blocks/enchanting_table_bottom.png b/client/src/main/resources/textures/blocks/enchanting_table_bottom.png new file mode 100755 index 0000000..0f492aa Binary files /dev/null and b/client/src/main/resources/textures/blocks/enchanting_table_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/enchanting_table_side.png b/client/src/main/resources/textures/blocks/enchanting_table_side.png new file mode 100755 index 0000000..f2f4614 Binary files /dev/null and b/client/src/main/resources/textures/blocks/enchanting_table_side.png differ diff --git a/client/src/main/resources/textures/blocks/enchanting_table_top.png b/client/src/main/resources/textures/blocks/enchanting_table_top.png new file mode 100755 index 0000000..0d5f68f Binary files /dev/null and b/client/src/main/resources/textures/blocks/enchanting_table_top.png differ diff --git a/client/src/main/resources/textures/blocks/farmland_0.png b/client/src/main/resources/textures/blocks/farmland_0.png new file mode 100755 index 0000000..d03a0f4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/farmland_0.png differ diff --git a/client/src/main/resources/textures/blocks/farmland_1.png b/client/src/main/resources/textures/blocks/farmland_1.png new file mode 100755 index 0000000..4050940 Binary files /dev/null and b/client/src/main/resources/textures/blocks/farmland_1.png differ diff --git a/client/src/main/resources/textures/blocks/farmland_2.png b/client/src/main/resources/textures/blocks/farmland_2.png new file mode 100755 index 0000000..54ff5f7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/farmland_2.png differ diff --git a/client/src/main/resources/textures/blocks/farmland_3.png b/client/src/main/resources/textures/blocks/farmland_3.png new file mode 100755 index 0000000..bc7a656 Binary files /dev/null and b/client/src/main/resources/textures/blocks/farmland_3.png differ diff --git a/client/src/main/resources/textures/blocks/farmland_4.png b/client/src/main/resources/textures/blocks/farmland_4.png new file mode 100755 index 0000000..fbe48fd Binary files /dev/null and b/client/src/main/resources/textures/blocks/farmland_4.png differ diff --git a/client/src/main/resources/textures/blocks/farmland_5.png b/client/src/main/resources/textures/blocks/farmland_5.png new file mode 100755 index 0000000..56caa32 Binary files /dev/null and b/client/src/main/resources/textures/blocks/farmland_5.png differ diff --git a/client/src/main/resources/textures/blocks/farmland_6.png b/client/src/main/resources/textures/blocks/farmland_6.png new file mode 100755 index 0000000..29df18e Binary files /dev/null and b/client/src/main/resources/textures/blocks/farmland_6.png differ diff --git a/client/src/main/resources/textures/blocks/farmland_7.png b/client/src/main/resources/textures/blocks/farmland_7.png new file mode 100755 index 0000000..f8d460d Binary files /dev/null and b/client/src/main/resources/textures/blocks/farmland_7.png differ diff --git a/client/src/main/resources/textures/blocks/fern.png b/client/src/main/resources/textures/blocks/fern.png new file mode 100755 index 0000000..fd76950 Binary files /dev/null and b/client/src/main/resources/textures/blocks/fern.png differ diff --git a/client/src/main/resources/textures/blocks/floor_portal.png b/client/src/main/resources/textures/blocks/floor_portal.png new file mode 100755 index 0000000..f319846 Binary files /dev/null and b/client/src/main/resources/textures/blocks/floor_portal.png differ diff --git a/client/src/main/resources/textures/blocks/floor_tiles.png b/client/src/main/resources/textures/blocks/floor_tiles.png new file mode 100755 index 0000000..22a3945 Binary files /dev/null and b/client/src/main/resources/textures/blocks/floor_tiles.png differ diff --git a/client/src/main/resources/textures/blocks/floor_tiles_black.png b/client/src/main/resources/textures/blocks/floor_tiles_black.png new file mode 100755 index 0000000..393c557 Binary files /dev/null and b/client/src/main/resources/textures/blocks/floor_tiles_black.png differ diff --git a/client/src/main/resources/textures/blocks/floor_tiles_red.png b/client/src/main/resources/textures/blocks/floor_tiles_red.png new file mode 100755 index 0000000..4648be2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/floor_tiles_red.png differ diff --git a/client/src/main/resources/textures/blocks/floor_tiles_white.png b/client/src/main/resources/textures/blocks/floor_tiles_white.png new file mode 100755 index 0000000..c101721 Binary files /dev/null and b/client/src/main/resources/textures/blocks/floor_tiles_white.png differ diff --git a/client/src/main/resources/textures/blocks/flower_paeonia.png b/client/src/main/resources/textures/blocks/flower_paeonia.png new file mode 100755 index 0000000..01a92ee Binary files /dev/null and b/client/src/main/resources/textures/blocks/flower_paeonia.png differ diff --git a/client/src/main/resources/textures/blocks/flower_pot.png b/client/src/main/resources/textures/blocks/flower_pot.png new file mode 100755 index 0000000..09c2523 Binary files /dev/null and b/client/src/main/resources/textures/blocks/flower_pot.png differ diff --git a/client/src/main/resources/textures/blocks/furnace_front_off.png b/client/src/main/resources/textures/blocks/furnace_front_off.png new file mode 100755 index 0000000..0570c3a Binary files /dev/null and b/client/src/main/resources/textures/blocks/furnace_front_off.png differ diff --git a/client/src/main/resources/textures/blocks/furnace_front_on.png b/client/src/main/resources/textures/blocks/furnace_front_on.png new file mode 100755 index 0000000..92c89f3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/furnace_front_on.png differ diff --git a/client/src/main/resources/textures/blocks/furnace_side.png b/client/src/main/resources/textures/blocks/furnace_side.png new file mode 100755 index 0000000..115f73d Binary files /dev/null and b/client/src/main/resources/textures/blocks/furnace_side.png differ diff --git a/client/src/main/resources/textures/blocks/furnace_top.png b/client/src/main/resources/textures/blocks/furnace_top.png new file mode 100755 index 0000000..a3a5a08 Binary files /dev/null and b/client/src/main/resources/textures/blocks/furnace_top.png differ diff --git a/client/src/main/resources/textures/blocks/glass.png b/client/src/main/resources/textures/blocks/glass.png new file mode 100755 index 0000000..acadb01 Binary files /dev/null and b/client/src/main/resources/textures/blocks/glass.png differ diff --git a/client/src/main/resources/textures/blocks/glass_pane.png b/client/src/main/resources/textures/blocks/glass_pane.png new file mode 100755 index 0000000..02de587 Binary files /dev/null and b/client/src/main/resources/textures/blocks/glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/glowstone.png b/client/src/main/resources/textures/blocks/glowstone.png new file mode 100755 index 0000000..c7253b3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/glowstone.png differ diff --git a/client/src/main/resources/textures/blocks/gold_block.png b/client/src/main/resources/textures/blocks/gold_block.png new file mode 100755 index 0000000..4a1fa9b Binary files /dev/null and b/client/src/main/resources/textures/blocks/gold_block.png differ diff --git a/client/src/main/resources/textures/blocks/gold_ore.png b/client/src/main/resources/textures/blocks/gold_ore.png new file mode 100755 index 0000000..b1a7a55 Binary files /dev/null and b/client/src/main/resources/textures/blocks/gold_ore.png differ diff --git a/client/src/main/resources/textures/blocks/golden_rail.png b/client/src/main/resources/textures/blocks/golden_rail.png new file mode 100755 index 0000000..1fc52c3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/golden_rail.png differ diff --git a/client/src/main/resources/textures/blocks/golden_rail_powered.png b/client/src/main/resources/textures/blocks/golden_rail_powered.png new file mode 100755 index 0000000..bd343be Binary files /dev/null and b/client/src/main/resources/textures/blocks/golden_rail_powered.png differ diff --git a/client/src/main/resources/textures/blocks/goo_flow.png b/client/src/main/resources/textures/blocks/goo_flow.png new file mode 100755 index 0000000..0f5f2cc Binary files /dev/null and b/client/src/main/resources/textures/blocks/goo_flow.png differ diff --git a/client/src/main/resources/textures/blocks/goo_still.png b/client/src/main/resources/textures/blocks/goo_still.png new file mode 100755 index 0000000..5566246 Binary files /dev/null and b/client/src/main/resources/textures/blocks/goo_still.png differ diff --git a/client/src/main/resources/textures/blocks/grass_side.png b/client/src/main/resources/textures/blocks/grass_side.png new file mode 100755 index 0000000..35c021c Binary files /dev/null and b/client/src/main/resources/textures/blocks/grass_side.png differ diff --git a/client/src/main/resources/textures/blocks/grass_side_overlay.png b/client/src/main/resources/textures/blocks/grass_side_overlay.png new file mode 100755 index 0000000..fc3fa9d Binary files /dev/null and b/client/src/main/resources/textures/blocks/grass_side_overlay.png differ diff --git a/client/src/main/resources/textures/blocks/grass_side_snowed.png b/client/src/main/resources/textures/blocks/grass_side_snowed.png new file mode 100755 index 0000000..41f6197 Binary files /dev/null and b/client/src/main/resources/textures/blocks/grass_side_snowed.png differ diff --git a/client/src/main/resources/textures/blocks/grass_top.png b/client/src/main/resources/textures/blocks/grass_top.png new file mode 100755 index 0000000..db3e364 Binary files /dev/null and b/client/src/main/resources/textures/blocks/grass_top.png differ diff --git a/client/src/main/resources/textures/blocks/gravel.png b/client/src/main/resources/textures/blocks/gravel.png new file mode 100755 index 0000000..d9c5f8f Binary files /dev/null and b/client/src/main/resources/textures/blocks/gravel.png differ diff --git a/client/src/main/resources/textures/blocks/gravel_new.png b/client/src/main/resources/textures/blocks/gravel_new.png new file mode 100755 index 0000000..388e5c5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/gravel_new.png differ diff --git a/client/src/main/resources/textures/blocks/gray_glass.png b/client/src/main/resources/textures/blocks/gray_glass.png new file mode 100755 index 0000000..3f07a5d Binary files /dev/null and b/client/src/main/resources/textures/blocks/gray_glass.png differ diff --git a/client/src/main/resources/textures/blocks/gray_glass_pane.png b/client/src/main/resources/textures/blocks/gray_glass_pane.png new file mode 100755 index 0000000..bb06114 Binary files /dev/null and b/client/src/main/resources/textures/blocks/gray_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/gray_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/gray_stained_hardened_clay.png new file mode 100755 index 0000000..8f86904 Binary files /dev/null and b/client/src/main/resources/textures/blocks/gray_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/gray_wool.png b/client/src/main/resources/textures/blocks/gray_wool.png new file mode 100755 index 0000000..6409ff2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/gray_wool.png differ diff --git a/client/src/main/resources/textures/blocks/green_glass.png b/client/src/main/resources/textures/blocks/green_glass.png new file mode 100755 index 0000000..7c1f4e6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/green_glass.png differ diff --git a/client/src/main/resources/textures/blocks/green_glass_pane.png b/client/src/main/resources/textures/blocks/green_glass_pane.png new file mode 100755 index 0000000..a7d9fc7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/green_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/green_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/green_stained_hardened_clay.png new file mode 100755 index 0000000..e89162e Binary files /dev/null and b/client/src/main/resources/textures/blocks/green_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/green_wool.png b/client/src/main/resources/textures/blocks/green_wool.png new file mode 100755 index 0000000..a7be6d7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/green_wool.png differ diff --git a/client/src/main/resources/textures/blocks/gyriyn_block.png b/client/src/main/resources/textures/blocks/gyriyn_block.png new file mode 100755 index 0000000..324bc65 Binary files /dev/null and b/client/src/main/resources/textures/blocks/gyriyn_block.png differ diff --git a/client/src/main/resources/textures/blocks/gyriyn_ore.png b/client/src/main/resources/textures/blocks/gyriyn_ore.png new file mode 100755 index 0000000..463aee9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/gyriyn_ore.png differ diff --git a/client/src/main/resources/textures/blocks/hardened_clay.png b/client/src/main/resources/textures/blocks/hardened_clay.png new file mode 100755 index 0000000..2446380 Binary files /dev/null and b/client/src/main/resources/textures/blocks/hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/hay_block_side.png b/client/src/main/resources/textures/blocks/hay_block_side.png new file mode 100755 index 0000000..a2b32db Binary files /dev/null and b/client/src/main/resources/textures/blocks/hay_block_side.png differ diff --git a/client/src/main/resources/textures/blocks/hay_block_top.png b/client/src/main/resources/textures/blocks/hay_block_top.png new file mode 100755 index 0000000..1d35593 Binary files /dev/null and b/client/src/main/resources/textures/blocks/hay_block_top.png differ diff --git a/client/src/main/resources/textures/blocks/hellrock.png b/client/src/main/resources/textures/blocks/hellrock.png new file mode 100755 index 0000000..22aadc1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/hellrock.png differ diff --git a/client/src/main/resources/textures/blocks/hopper_inside.png b/client/src/main/resources/textures/blocks/hopper_inside.png new file mode 100755 index 0000000..24e8eae Binary files /dev/null and b/client/src/main/resources/textures/blocks/hopper_inside.png differ diff --git a/client/src/main/resources/textures/blocks/hopper_outside.png b/client/src/main/resources/textures/blocks/hopper_outside.png new file mode 100755 index 0000000..50ed8d5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/hopper_outside.png differ diff --git a/client/src/main/resources/textures/blocks/hopper_top.png b/client/src/main/resources/textures/blocks/hopper_top.png new file mode 100755 index 0000000..e0dbe96 Binary files /dev/null and b/client/src/main/resources/textures/blocks/hopper_top.png differ diff --git a/client/src/main/resources/textures/blocks/houstonia.png b/client/src/main/resources/textures/blocks/houstonia.png new file mode 100755 index 0000000..2f9127d Binary files /dev/null and b/client/src/main/resources/textures/blocks/houstonia.png differ diff --git a/client/src/main/resources/textures/blocks/hydrogen_flow.png b/client/src/main/resources/textures/blocks/hydrogen_flow.png new file mode 100755 index 0000000..59f93af Binary files /dev/null and b/client/src/main/resources/textures/blocks/hydrogen_flow.png differ diff --git a/client/src/main/resources/textures/blocks/hydrogen_still.png b/client/src/main/resources/textures/blocks/hydrogen_still.png new file mode 100755 index 0000000..42916be Binary files /dev/null and b/client/src/main/resources/textures/blocks/hydrogen_still.png differ diff --git a/client/src/main/resources/textures/blocks/ice.png b/client/src/main/resources/textures/blocks/ice.png new file mode 100755 index 0000000..ac946e9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/ice.png differ diff --git a/client/src/main/resources/textures/blocks/iodine_block.png b/client/src/main/resources/textures/blocks/iodine_block.png new file mode 100755 index 0000000..f7fd2da Binary files /dev/null and b/client/src/main/resources/textures/blocks/iodine_block.png differ diff --git a/client/src/main/resources/textures/blocks/iodine_ore.png b/client/src/main/resources/textures/blocks/iodine_ore.png new file mode 100755 index 0000000..533e62d Binary files /dev/null and b/client/src/main/resources/textures/blocks/iodine_ore.png differ diff --git a/client/src/main/resources/textures/blocks/iron_bars.png b/client/src/main/resources/textures/blocks/iron_bars.png new file mode 100755 index 0000000..732807f Binary files /dev/null and b/client/src/main/resources/textures/blocks/iron_bars.png differ diff --git a/client/src/main/resources/textures/blocks/iron_block.png b/client/src/main/resources/textures/blocks/iron_block.png new file mode 100755 index 0000000..7816799 Binary files /dev/null and b/client/src/main/resources/textures/blocks/iron_block.png differ diff --git a/client/src/main/resources/textures/blocks/iron_door_bottom.png b/client/src/main/resources/textures/blocks/iron_door_bottom.png new file mode 100755 index 0000000..dbc33ab Binary files /dev/null and b/client/src/main/resources/textures/blocks/iron_door_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/iron_door_top.png b/client/src/main/resources/textures/blocks/iron_door_top.png new file mode 100755 index 0000000..56878fe Binary files /dev/null and b/client/src/main/resources/textures/blocks/iron_door_top.png differ diff --git a/client/src/main/resources/textures/blocks/iron_ore.png b/client/src/main/resources/textures/blocks/iron_ore.png new file mode 100755 index 0000000..250d8bb Binary files /dev/null and b/client/src/main/resources/textures/blocks/iron_ore.png differ diff --git a/client/src/main/resources/textures/blocks/iron_trapdoor.png b/client/src/main/resources/textures/blocks/iron_trapdoor.png new file mode 100755 index 0000000..d3c974c Binary files /dev/null and b/client/src/main/resources/textures/blocks/iron_trapdoor.png differ diff --git a/client/src/main/resources/textures/blocks/itemframe_background.png b/client/src/main/resources/textures/blocks/itemframe_background.png new file mode 100755 index 0000000..b40ad65 Binary files /dev/null and b/client/src/main/resources/textures/blocks/itemframe_background.png differ diff --git a/client/src/main/resources/textures/blocks/jukebox_side.png b/client/src/main/resources/textures/blocks/jukebox_side.png new file mode 100755 index 0000000..a3c27c1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/jukebox_side.png differ diff --git a/client/src/main/resources/textures/blocks/jukebox_top.png b/client/src/main/resources/textures/blocks/jukebox_top.png new file mode 100755 index 0000000..92ddb15 Binary files /dev/null and b/client/src/main/resources/textures/blocks/jukebox_top.png differ diff --git a/client/src/main/resources/textures/blocks/jungle_door_bottom.png b/client/src/main/resources/textures/blocks/jungle_door_bottom.png new file mode 100755 index 0000000..4edfa3c Binary files /dev/null and b/client/src/main/resources/textures/blocks/jungle_door_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/jungle_door_top.png b/client/src/main/resources/textures/blocks/jungle_door_top.png new file mode 100755 index 0000000..d5201f8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/jungle_door_top.png differ diff --git a/client/src/main/resources/textures/blocks/jungle_leaves_autumn.png b/client/src/main/resources/textures/blocks/jungle_leaves_autumn.png new file mode 100755 index 0000000..2341d5d Binary files /dev/null and b/client/src/main/resources/textures/blocks/jungle_leaves_autumn.png differ diff --git a/client/src/main/resources/textures/blocks/jungle_leaves_snowy.png b/client/src/main/resources/textures/blocks/jungle_leaves_snowy.png new file mode 100755 index 0000000..0fa30b4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/jungle_leaves_snowy.png differ diff --git a/client/src/main/resources/textures/blocks/jungle_leaves_spring.png b/client/src/main/resources/textures/blocks/jungle_leaves_spring.png new file mode 100755 index 0000000..e0cb935 Binary files /dev/null and b/client/src/main/resources/textures/blocks/jungle_leaves_spring.png differ diff --git a/client/src/main/resources/textures/blocks/jungle_leaves_summer.png b/client/src/main/resources/textures/blocks/jungle_leaves_summer.png new file mode 100755 index 0000000..b053ee8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/jungle_leaves_summer.png differ diff --git a/client/src/main/resources/textures/blocks/jungle_leaves_winter.png b/client/src/main/resources/textures/blocks/jungle_leaves_winter.png new file mode 100755 index 0000000..5fe7115 Binary files /dev/null and b/client/src/main/resources/textures/blocks/jungle_leaves_winter.png differ diff --git a/client/src/main/resources/textures/blocks/jungle_log_bark.png b/client/src/main/resources/textures/blocks/jungle_log_bark.png new file mode 100755 index 0000000..0b7120a Binary files /dev/null and b/client/src/main/resources/textures/blocks/jungle_log_bark.png differ diff --git a/client/src/main/resources/textures/blocks/jungle_log_top.png b/client/src/main/resources/textures/blocks/jungle_log_top.png new file mode 100755 index 0000000..26b0361 Binary files /dev/null and b/client/src/main/resources/textures/blocks/jungle_log_top.png differ diff --git a/client/src/main/resources/textures/blocks/jungle_planks.png b/client/src/main/resources/textures/blocks/jungle_planks.png new file mode 100755 index 0000000..e3fe82d Binary files /dev/null and b/client/src/main/resources/textures/blocks/jungle_planks.png differ diff --git a/client/src/main/resources/textures/blocks/jungle_sapling.png b/client/src/main/resources/textures/blocks/jungle_sapling.png new file mode 100755 index 0000000..4e10b35 Binary files /dev/null and b/client/src/main/resources/textures/blocks/jungle_sapling.png differ diff --git a/client/src/main/resources/textures/blocks/ladder.png b/client/src/main/resources/textures/blocks/ladder.png new file mode 100755 index 0000000..e2ec5f2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/ladder.png differ diff --git a/client/src/main/resources/textures/blocks/lamp.png b/client/src/main/resources/textures/blocks/lamp.png new file mode 100755 index 0000000..9562ef3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/lamp.png differ diff --git a/client/src/main/resources/textures/blocks/lapis_block.png b/client/src/main/resources/textures/blocks/lapis_block.png new file mode 100755 index 0000000..0271489 Binary files /dev/null and b/client/src/main/resources/textures/blocks/lapis_block.png differ diff --git a/client/src/main/resources/textures/blocks/lapis_ore.png b/client/src/main/resources/textures/blocks/lapis_ore.png new file mode 100755 index 0000000..6144236 Binary files /dev/null and b/client/src/main/resources/textures/blocks/lapis_ore.png differ diff --git a/client/src/main/resources/textures/blocks/lava_flow.png b/client/src/main/resources/textures/blocks/lava_flow.png new file mode 100755 index 0000000..af07f91 Binary files /dev/null and b/client/src/main/resources/textures/blocks/lava_flow.png differ diff --git a/client/src/main/resources/textures/blocks/lava_still.png b/client/src/main/resources/textures/blocks/lava_still.png new file mode 100755 index 0000000..7d14558 Binary files /dev/null and b/client/src/main/resources/textures/blocks/lava_still.png differ diff --git a/client/src/main/resources/textures/blocks/lead_block.png b/client/src/main/resources/textures/blocks/lead_block.png new file mode 100755 index 0000000..1b8b733 Binary files /dev/null and b/client/src/main/resources/textures/blocks/lead_block.png differ diff --git a/client/src/main/resources/textures/blocks/lead_ore.png b/client/src/main/resources/textures/blocks/lead_ore.png new file mode 100755 index 0000000..b164d5b Binary files /dev/null and b/client/src/main/resources/textures/blocks/lead_ore.png differ diff --git a/client/src/main/resources/textures/blocks/lever.png b/client/src/main/resources/textures/blocks/lever.png new file mode 100755 index 0000000..051187f Binary files /dev/null and b/client/src/main/resources/textures/blocks/lever.png differ diff --git a/client/src/main/resources/textures/blocks/light_blue_glass.png b/client/src/main/resources/textures/blocks/light_blue_glass.png new file mode 100755 index 0000000..b62703d Binary files /dev/null and b/client/src/main/resources/textures/blocks/light_blue_glass.png differ diff --git a/client/src/main/resources/textures/blocks/light_blue_glass_pane.png b/client/src/main/resources/textures/blocks/light_blue_glass_pane.png new file mode 100755 index 0000000..6a0e661 Binary files /dev/null and b/client/src/main/resources/textures/blocks/light_blue_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/light_blue_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/light_blue_stained_hardened_clay.png new file mode 100755 index 0000000..3d9ebea Binary files /dev/null and b/client/src/main/resources/textures/blocks/light_blue_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/light_blue_wool.png b/client/src/main/resources/textures/blocks/light_blue_wool.png new file mode 100755 index 0000000..72d9d9e Binary files /dev/null and b/client/src/main/resources/textures/blocks/light_blue_wool.png differ diff --git a/client/src/main/resources/textures/blocks/lime_glass.png b/client/src/main/resources/textures/blocks/lime_glass.png new file mode 100755 index 0000000..f1d3c46 Binary files /dev/null and b/client/src/main/resources/textures/blocks/lime_glass.png differ diff --git a/client/src/main/resources/textures/blocks/lime_glass_pane.png b/client/src/main/resources/textures/blocks/lime_glass_pane.png new file mode 100755 index 0000000..0607d75 Binary files /dev/null and b/client/src/main/resources/textures/blocks/lime_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/lime_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/lime_stained_hardened_clay.png new file mode 100755 index 0000000..b459a0b Binary files /dev/null and b/client/src/main/resources/textures/blocks/lime_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/lime_wool.png b/client/src/main/resources/textures/blocks/lime_wool.png new file mode 100755 index 0000000..bf56389 Binary files /dev/null and b/client/src/main/resources/textures/blocks/lime_wool.png differ diff --git a/client/src/main/resources/textures/blocks/lit_redstone_lamp.png b/client/src/main/resources/textures/blocks/lit_redstone_lamp.png new file mode 100755 index 0000000..9562ef3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/lit_redstone_lamp.png differ diff --git a/client/src/main/resources/textures/blocks/lithium_block.png b/client/src/main/resources/textures/blocks/lithium_block.png new file mode 100755 index 0000000..fd5428d Binary files /dev/null and b/client/src/main/resources/textures/blocks/lithium_block.png differ diff --git a/client/src/main/resources/textures/blocks/lithium_ore.png b/client/src/main/resources/textures/blocks/lithium_ore.png new file mode 100755 index 0000000..7a64742 Binary files /dev/null and b/client/src/main/resources/textures/blocks/lithium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/magenta_glass.png b/client/src/main/resources/textures/blocks/magenta_glass.png new file mode 100755 index 0000000..5cd9945 Binary files /dev/null and b/client/src/main/resources/textures/blocks/magenta_glass.png differ diff --git a/client/src/main/resources/textures/blocks/magenta_glass_pane.png b/client/src/main/resources/textures/blocks/magenta_glass_pane.png new file mode 100755 index 0000000..5419e52 Binary files /dev/null and b/client/src/main/resources/textures/blocks/magenta_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/magenta_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/magenta_stained_hardened_clay.png new file mode 100755 index 0000000..9663106 Binary files /dev/null and b/client/src/main/resources/textures/blocks/magenta_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/magenta_wool.png b/client/src/main/resources/textures/blocks/magenta_wool.png new file mode 100755 index 0000000..3af6747 Binary files /dev/null and b/client/src/main/resources/textures/blocks/magenta_wool.png differ diff --git a/client/src/main/resources/textures/blocks/magnesium_block.png b/client/src/main/resources/textures/blocks/magnesium_block.png new file mode 100755 index 0000000..e148e89 Binary files /dev/null and b/client/src/main/resources/textures/blocks/magnesium_block.png differ diff --git a/client/src/main/resources/textures/blocks/magnesium_ore.png b/client/src/main/resources/textures/blocks/magnesium_ore.png new file mode 100755 index 0000000..a51f29b Binary files /dev/null and b/client/src/main/resources/textures/blocks/magnesium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/manganese_block.png b/client/src/main/resources/textures/blocks/manganese_block.png new file mode 100755 index 0000000..a43c937 Binary files /dev/null and b/client/src/main/resources/textures/blocks/manganese_block.png differ diff --git a/client/src/main/resources/textures/blocks/manganese_ore.png b/client/src/main/resources/textures/blocks/manganese_ore.png new file mode 100755 index 0000000..a49642c Binary files /dev/null and b/client/src/main/resources/textures/blocks/manganese_ore.png differ diff --git a/client/src/main/resources/textures/blocks/maple_door_bottom.png b/client/src/main/resources/textures/blocks/maple_door_bottom.png new file mode 100755 index 0000000..33430bf Binary files /dev/null and b/client/src/main/resources/textures/blocks/maple_door_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/maple_door_top.png b/client/src/main/resources/textures/blocks/maple_door_top.png new file mode 100755 index 0000000..2ff07a9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/maple_door_top.png differ diff --git a/client/src/main/resources/textures/blocks/maple_leaves_autumn.png b/client/src/main/resources/textures/blocks/maple_leaves_autumn.png new file mode 100755 index 0000000..18df1b2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/maple_leaves_autumn.png differ diff --git a/client/src/main/resources/textures/blocks/maple_leaves_snowy.png b/client/src/main/resources/textures/blocks/maple_leaves_snowy.png new file mode 100755 index 0000000..de9abae Binary files /dev/null and b/client/src/main/resources/textures/blocks/maple_leaves_snowy.png differ diff --git a/client/src/main/resources/textures/blocks/maple_leaves_spring.png b/client/src/main/resources/textures/blocks/maple_leaves_spring.png new file mode 100755 index 0000000..81dbf24 Binary files /dev/null and b/client/src/main/resources/textures/blocks/maple_leaves_spring.png differ diff --git a/client/src/main/resources/textures/blocks/maple_leaves_summer.png b/client/src/main/resources/textures/blocks/maple_leaves_summer.png new file mode 100755 index 0000000..ef72a94 Binary files /dev/null and b/client/src/main/resources/textures/blocks/maple_leaves_summer.png differ diff --git a/client/src/main/resources/textures/blocks/maple_leaves_winter.png b/client/src/main/resources/textures/blocks/maple_leaves_winter.png new file mode 100755 index 0000000..49230a0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/maple_leaves_winter.png differ diff --git a/client/src/main/resources/textures/blocks/maple_log_bark.png b/client/src/main/resources/textures/blocks/maple_log_bark.png new file mode 100755 index 0000000..3c91d87 Binary files /dev/null and b/client/src/main/resources/textures/blocks/maple_log_bark.png differ diff --git a/client/src/main/resources/textures/blocks/maple_log_top.png b/client/src/main/resources/textures/blocks/maple_log_top.png new file mode 100755 index 0000000..735f2df Binary files /dev/null and b/client/src/main/resources/textures/blocks/maple_log_top.png differ diff --git a/client/src/main/resources/textures/blocks/maple_planks.png b/client/src/main/resources/textures/blocks/maple_planks.png new file mode 100755 index 0000000..b12dfb8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/maple_planks.png differ diff --git a/client/src/main/resources/textures/blocks/maple_sapling.png b/client/src/main/resources/textures/blocks/maple_sapling.png new file mode 100755 index 0000000..8cae38f Binary files /dev/null and b/client/src/main/resources/textures/blocks/maple_sapling.png differ diff --git a/client/src/main/resources/textures/blocks/melon_side.png b/client/src/main/resources/textures/blocks/melon_side.png new file mode 100755 index 0000000..ec7b430 Binary files /dev/null and b/client/src/main/resources/textures/blocks/melon_side.png differ diff --git a/client/src/main/resources/textures/blocks/melon_stem.png b/client/src/main/resources/textures/blocks/melon_stem.png new file mode 100755 index 0000000..38065ef Binary files /dev/null and b/client/src/main/resources/textures/blocks/melon_stem.png differ diff --git a/client/src/main/resources/textures/blocks/melon_stem_connected.png b/client/src/main/resources/textures/blocks/melon_stem_connected.png new file mode 100755 index 0000000..6a5c10e Binary files /dev/null and b/client/src/main/resources/textures/blocks/melon_stem_connected.png differ diff --git a/client/src/main/resources/textures/blocks/melon_top.png b/client/src/main/resources/textures/blocks/melon_top.png new file mode 100755 index 0000000..65cf169 Binary files /dev/null and b/client/src/main/resources/textures/blocks/melon_top.png differ diff --git a/client/src/main/resources/textures/blocks/mercury_flow.png b/client/src/main/resources/textures/blocks/mercury_flow.png new file mode 100755 index 0000000..da22d57 Binary files /dev/null and b/client/src/main/resources/textures/blocks/mercury_flow.png differ diff --git a/client/src/main/resources/textures/blocks/mercury_still.png b/client/src/main/resources/textures/blocks/mercury_still.png new file mode 100755 index 0000000..20c948f Binary files /dev/null and b/client/src/main/resources/textures/blocks/mercury_still.png differ diff --git a/client/src/main/resources/textures/blocks/mob_spawner.png b/client/src/main/resources/textures/blocks/mob_spawner.png new file mode 100755 index 0000000..c248eec Binary files /dev/null and b/client/src/main/resources/textures/blocks/mob_spawner.png differ diff --git a/client/src/main/resources/textures/blocks/moon_cheese.png b/client/src/main/resources/textures/blocks/moon_cheese.png new file mode 100755 index 0000000..8050187 Binary files /dev/null and b/client/src/main/resources/textures/blocks/moon_cheese.png differ diff --git a/client/src/main/resources/textures/blocks/moon_rock.png b/client/src/main/resources/textures/blocks/moon_rock.png new file mode 100755 index 0000000..f61c65d Binary files /dev/null and b/client/src/main/resources/textures/blocks/moon_rock.png differ diff --git a/client/src/main/resources/textures/blocks/mossy_cobblestone.png b/client/src/main/resources/textures/blocks/mossy_cobblestone.png new file mode 100755 index 0000000..b8030d7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/mossy_cobblestone.png differ diff --git a/client/src/main/resources/textures/blocks/mycelium_side.png b/client/src/main/resources/textures/blocks/mycelium_side.png new file mode 100755 index 0000000..5547425 Binary files /dev/null and b/client/src/main/resources/textures/blocks/mycelium_side.png differ diff --git a/client/src/main/resources/textures/blocks/mycelium_top.png b/client/src/main/resources/textures/blocks/mycelium_top.png new file mode 100755 index 0000000..088a825 Binary files /dev/null and b/client/src/main/resources/textures/blocks/mycelium_top.png differ diff --git a/client/src/main/resources/textures/blocks/neodymium_block.png b/client/src/main/resources/textures/blocks/neodymium_block.png new file mode 100755 index 0000000..1faa88b Binary files /dev/null and b/client/src/main/resources/textures/blocks/neodymium_block.png differ diff --git a/client/src/main/resources/textures/blocks/neodymium_ore.png b/client/src/main/resources/textures/blocks/neodymium_ore.png new file mode 100755 index 0000000..808e448 Binary files /dev/null and b/client/src/main/resources/textures/blocks/neodymium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/neptunium_block.png b/client/src/main/resources/textures/blocks/neptunium_block.png new file mode 100755 index 0000000..4befc7a Binary files /dev/null and b/client/src/main/resources/textures/blocks/neptunium_block.png differ diff --git a/client/src/main/resources/textures/blocks/neptunium_ore.png b/client/src/main/resources/textures/blocks/neptunium_ore.png new file mode 100755 index 0000000..0df34cb Binary files /dev/null and b/client/src/main/resources/textures/blocks/neptunium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/nichun_block.png b/client/src/main/resources/textures/blocks/nichun_block.png new file mode 100755 index 0000000..a27a7df Binary files /dev/null and b/client/src/main/resources/textures/blocks/nichun_block.png differ diff --git a/client/src/main/resources/textures/blocks/nichun_ore.png b/client/src/main/resources/textures/blocks/nichun_ore.png new file mode 100755 index 0000000..8f40944 Binary files /dev/null and b/client/src/main/resources/textures/blocks/nichun_ore.png differ diff --git a/client/src/main/resources/textures/blocks/nickel_block.png b/client/src/main/resources/textures/blocks/nickel_block.png new file mode 100755 index 0000000..8e5fac4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/nickel_block.png differ diff --git a/client/src/main/resources/textures/blocks/nickel_ore.png b/client/src/main/resources/textures/blocks/nickel_ore.png new file mode 100755 index 0000000..480adeb Binary files /dev/null and b/client/src/main/resources/textures/blocks/nickel_ore.png differ diff --git a/client/src/main/resources/textures/blocks/noteblock.png b/client/src/main/resources/textures/blocks/noteblock.png new file mode 100755 index 0000000..a3c27c1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/noteblock.png differ diff --git a/client/src/main/resources/textures/blocks/nukage_flow.png b/client/src/main/resources/textures/blocks/nukage_flow.png new file mode 100755 index 0000000..0967a40 Binary files /dev/null and b/client/src/main/resources/textures/blocks/nukage_flow.png differ diff --git a/client/src/main/resources/textures/blocks/nukage_still.png b/client/src/main/resources/textures/blocks/nukage_still.png new file mode 100755 index 0000000..013efee Binary files /dev/null and b/client/src/main/resources/textures/blocks/nukage_still.png differ diff --git a/client/src/main/resources/textures/blocks/nuke_bottom.png b/client/src/main/resources/textures/blocks/nuke_bottom.png new file mode 100755 index 0000000..ed06daa Binary files /dev/null and b/client/src/main/resources/textures/blocks/nuke_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/nuke_side.png b/client/src/main/resources/textures/blocks/nuke_side.png new file mode 100755 index 0000000..4cef1c2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/nuke_side.png differ diff --git a/client/src/main/resources/textures/blocks/nuke_top.png b/client/src/main/resources/textures/blocks/nuke_top.png new file mode 100755 index 0000000..bb0764e Binary files /dev/null and b/client/src/main/resources/textures/blocks/nuke_top.png differ diff --git a/client/src/main/resources/textures/blocks/oak_door_bottom.png b/client/src/main/resources/textures/blocks/oak_door_bottom.png new file mode 100755 index 0000000..cc61731 Binary files /dev/null and b/client/src/main/resources/textures/blocks/oak_door_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/oak_door_top.png b/client/src/main/resources/textures/blocks/oak_door_top.png new file mode 100755 index 0000000..93319d5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/oak_door_top.png differ diff --git a/client/src/main/resources/textures/blocks/oak_leaves_autumn.png b/client/src/main/resources/textures/blocks/oak_leaves_autumn.png new file mode 100755 index 0000000..2960ba3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/oak_leaves_autumn.png differ diff --git a/client/src/main/resources/textures/blocks/oak_leaves_snowy.png b/client/src/main/resources/textures/blocks/oak_leaves_snowy.png new file mode 100755 index 0000000..b902f2b Binary files /dev/null and b/client/src/main/resources/textures/blocks/oak_leaves_snowy.png differ diff --git a/client/src/main/resources/textures/blocks/oak_leaves_spring.png b/client/src/main/resources/textures/blocks/oak_leaves_spring.png new file mode 100755 index 0000000..a6773af Binary files /dev/null and b/client/src/main/resources/textures/blocks/oak_leaves_spring.png differ diff --git a/client/src/main/resources/textures/blocks/oak_leaves_summer.png b/client/src/main/resources/textures/blocks/oak_leaves_summer.png new file mode 100755 index 0000000..01fe6e3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/oak_leaves_summer.png differ diff --git a/client/src/main/resources/textures/blocks/oak_leaves_winter.png b/client/src/main/resources/textures/blocks/oak_leaves_winter.png new file mode 100755 index 0000000..a732ca7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/oak_leaves_winter.png differ diff --git a/client/src/main/resources/textures/blocks/oak_log_bark.png b/client/src/main/resources/textures/blocks/oak_log_bark.png new file mode 100755 index 0000000..914cb5f Binary files /dev/null and b/client/src/main/resources/textures/blocks/oak_log_bark.png differ diff --git a/client/src/main/resources/textures/blocks/oak_log_top.png b/client/src/main/resources/textures/blocks/oak_log_top.png new file mode 100755 index 0000000..7a44e77 Binary files /dev/null and b/client/src/main/resources/textures/blocks/oak_log_top.png differ diff --git a/client/src/main/resources/textures/blocks/oak_planks.png b/client/src/main/resources/textures/blocks/oak_planks.png new file mode 100755 index 0000000..346f77d Binary files /dev/null and b/client/src/main/resources/textures/blocks/oak_planks.png differ diff --git a/client/src/main/resources/textures/blocks/oak_sapling.png b/client/src/main/resources/textures/blocks/oak_sapling.png new file mode 100755 index 0000000..1bf1bfa Binary files /dev/null and b/client/src/main/resources/textures/blocks/oak_sapling.png differ diff --git a/client/src/main/resources/textures/blocks/obsidian.png b/client/src/main/resources/textures/blocks/obsidian.png new file mode 100755 index 0000000..ff0a683 Binary files /dev/null and b/client/src/main/resources/textures/blocks/obsidian.png differ diff --git a/client/src/main/resources/textures/blocks/orange_glass.png b/client/src/main/resources/textures/blocks/orange_glass.png new file mode 100755 index 0000000..3a29e31 Binary files /dev/null and b/client/src/main/resources/textures/blocks/orange_glass.png differ diff --git a/client/src/main/resources/textures/blocks/orange_glass_pane.png b/client/src/main/resources/textures/blocks/orange_glass_pane.png new file mode 100755 index 0000000..2866571 Binary files /dev/null and b/client/src/main/resources/textures/blocks/orange_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/orange_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/orange_stained_hardened_clay.png new file mode 100755 index 0000000..40929db Binary files /dev/null and b/client/src/main/resources/textures/blocks/orange_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/orange_tulip.png b/client/src/main/resources/textures/blocks/orange_tulip.png new file mode 100755 index 0000000..6715a62 Binary files /dev/null and b/client/src/main/resources/textures/blocks/orange_tulip.png differ diff --git a/client/src/main/resources/textures/blocks/orange_wool.png b/client/src/main/resources/textures/blocks/orange_wool.png new file mode 100755 index 0000000..eefe6de Binary files /dev/null and b/client/src/main/resources/textures/blocks/orange_wool.png differ diff --git a/client/src/main/resources/textures/blocks/oxeye_daisy.png b/client/src/main/resources/textures/blocks/oxeye_daisy.png new file mode 100755 index 0000000..6d48913 Binary files /dev/null and b/client/src/main/resources/textures/blocks/oxeye_daisy.png differ diff --git a/client/src/main/resources/textures/blocks/packed_ice.png b/client/src/main/resources/textures/blocks/packed_ice.png new file mode 100755 index 0000000..50f0f34 Binary files /dev/null and b/client/src/main/resources/textures/blocks/packed_ice.png differ diff --git a/client/src/main/resources/textures/blocks/paeonia_bottom.png b/client/src/main/resources/textures/blocks/paeonia_bottom.png new file mode 100755 index 0000000..21285f5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/paeonia_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/paeonia_top.png b/client/src/main/resources/textures/blocks/paeonia_top.png new file mode 100755 index 0000000..bc68241 Binary files /dev/null and b/client/src/main/resources/textures/blocks/paeonia_top.png differ diff --git a/client/src/main/resources/textures/blocks/palladium_block.png b/client/src/main/resources/textures/blocks/palladium_block.png new file mode 100755 index 0000000..58ecb1b Binary files /dev/null and b/client/src/main/resources/textures/blocks/palladium_block.png differ diff --git a/client/src/main/resources/textures/blocks/palladium_ore.png b/client/src/main/resources/textures/blocks/palladium_ore.png new file mode 100755 index 0000000..92e8ebd Binary files /dev/null and b/client/src/main/resources/textures/blocks/palladium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/pentagram.png b/client/src/main/resources/textures/blocks/pentagram.png new file mode 100755 index 0000000..fa38f69 Binary files /dev/null and b/client/src/main/resources/textures/blocks/pentagram.png differ diff --git a/client/src/main/resources/textures/blocks/phosphor_block.png b/client/src/main/resources/textures/blocks/phosphor_block.png new file mode 100755 index 0000000..bbb3d4e Binary files /dev/null and b/client/src/main/resources/textures/blocks/phosphor_block.png differ diff --git a/client/src/main/resources/textures/blocks/phosphor_ore.png b/client/src/main/resources/textures/blocks/phosphor_ore.png new file mode 100755 index 0000000..e5e54be Binary files /dev/null and b/client/src/main/resources/textures/blocks/phosphor_ore.png differ diff --git a/client/src/main/resources/textures/blocks/pink_glass.png b/client/src/main/resources/textures/blocks/pink_glass.png new file mode 100755 index 0000000..42d8739 Binary files /dev/null and b/client/src/main/resources/textures/blocks/pink_glass.png differ diff --git a/client/src/main/resources/textures/blocks/pink_glass_pane.png b/client/src/main/resources/textures/blocks/pink_glass_pane.png new file mode 100755 index 0000000..6b6cd76 Binary files /dev/null and b/client/src/main/resources/textures/blocks/pink_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/pink_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/pink_stained_hardened_clay.png new file mode 100755 index 0000000..c21c0aa Binary files /dev/null and b/client/src/main/resources/textures/blocks/pink_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/pink_tulip.png b/client/src/main/resources/textures/blocks/pink_tulip.png new file mode 100755 index 0000000..a757bf5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/pink_tulip.png differ diff --git a/client/src/main/resources/textures/blocks/pink_wool.png b/client/src/main/resources/textures/blocks/pink_wool.png new file mode 100755 index 0000000..c2785af Binary files /dev/null and b/client/src/main/resources/textures/blocks/pink_wool.png differ diff --git a/client/src/main/resources/textures/blocks/piston_bottom.png b/client/src/main/resources/textures/blocks/piston_bottom.png new file mode 100755 index 0000000..a3a5a08 Binary files /dev/null and b/client/src/main/resources/textures/blocks/piston_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/piston_inner.png b/client/src/main/resources/textures/blocks/piston_inner.png new file mode 100755 index 0000000..1043929 Binary files /dev/null and b/client/src/main/resources/textures/blocks/piston_inner.png differ diff --git a/client/src/main/resources/textures/blocks/piston_side.png b/client/src/main/resources/textures/blocks/piston_side.png new file mode 100755 index 0000000..634f54a Binary files /dev/null and b/client/src/main/resources/textures/blocks/piston_side.png differ diff --git a/client/src/main/resources/textures/blocks/piston_top.png b/client/src/main/resources/textures/blocks/piston_top.png new file mode 100755 index 0000000..eeaadab Binary files /dev/null and b/client/src/main/resources/textures/blocks/piston_top.png differ diff --git a/client/src/main/resources/textures/blocks/piston_top_sticky.png b/client/src/main/resources/textures/blocks/piston_top_sticky.png new file mode 100755 index 0000000..6ddd4ad Binary files /dev/null and b/client/src/main/resources/textures/blocks/piston_top_sticky.png differ diff --git a/client/src/main/resources/textures/blocks/platinum_block.png b/client/src/main/resources/textures/blocks/platinum_block.png new file mode 100755 index 0000000..d1e32de Binary files /dev/null and b/client/src/main/resources/textures/blocks/platinum_block.png differ diff --git a/client/src/main/resources/textures/blocks/platinum_ore.png b/client/src/main/resources/textures/blocks/platinum_ore.png new file mode 100755 index 0000000..0f496db Binary files /dev/null and b/client/src/main/resources/textures/blocks/platinum_ore.png differ diff --git a/client/src/main/resources/textures/blocks/plutonium_block.png b/client/src/main/resources/textures/blocks/plutonium_block.png new file mode 100755 index 0000000..0ba7300 Binary files /dev/null and b/client/src/main/resources/textures/blocks/plutonium_block.png differ diff --git a/client/src/main/resources/textures/blocks/plutonium_ore.png b/client/src/main/resources/textures/blocks/plutonium_ore.png new file mode 100755 index 0000000..f5681e5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/plutonium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/poppy.png b/client/src/main/resources/textures/blocks/poppy.png new file mode 100755 index 0000000..895d78f Binary files /dev/null and b/client/src/main/resources/textures/blocks/poppy.png differ diff --git a/client/src/main/resources/textures/blocks/portal.png b/client/src/main/resources/textures/blocks/portal.png new file mode 100755 index 0000000..805331f Binary files /dev/null and b/client/src/main/resources/textures/blocks/portal.png differ diff --git a/client/src/main/resources/textures/blocks/portal_frame_bottom.png b/client/src/main/resources/textures/blocks/portal_frame_bottom.png new file mode 100755 index 0000000..9aca3ce Binary files /dev/null and b/client/src/main/resources/textures/blocks/portal_frame_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/portal_frame_orb.png b/client/src/main/resources/textures/blocks/portal_frame_orb.png new file mode 100755 index 0000000..b7eb9bb Binary files /dev/null and b/client/src/main/resources/textures/blocks/portal_frame_orb.png differ diff --git a/client/src/main/resources/textures/blocks/portal_frame_side.png b/client/src/main/resources/textures/blocks/portal_frame_side.png new file mode 100755 index 0000000..799e089 Binary files /dev/null and b/client/src/main/resources/textures/blocks/portal_frame_side.png differ diff --git a/client/src/main/resources/textures/blocks/portal_frame_top.png b/client/src/main/resources/textures/blocks/portal_frame_top.png new file mode 100755 index 0000000..ae41640 Binary files /dev/null and b/client/src/main/resources/textures/blocks/portal_frame_top.png differ diff --git a/client/src/main/resources/textures/blocks/potassium_block.png b/client/src/main/resources/textures/blocks/potassium_block.png new file mode 100755 index 0000000..3c8ee97 Binary files /dev/null and b/client/src/main/resources/textures/blocks/potassium_block.png differ diff --git a/client/src/main/resources/textures/blocks/potassium_ore.png b/client/src/main/resources/textures/blocks/potassium_ore.png new file mode 100755 index 0000000..f5925de Binary files /dev/null and b/client/src/main/resources/textures/blocks/potassium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/potato_0.png b/client/src/main/resources/textures/blocks/potato_0.png new file mode 100755 index 0000000..c1ef732 Binary files /dev/null and b/client/src/main/resources/textures/blocks/potato_0.png differ diff --git a/client/src/main/resources/textures/blocks/potato_1.png b/client/src/main/resources/textures/blocks/potato_1.png new file mode 100755 index 0000000..1275f4f Binary files /dev/null and b/client/src/main/resources/textures/blocks/potato_1.png differ diff --git a/client/src/main/resources/textures/blocks/potato_2.png b/client/src/main/resources/textures/blocks/potato_2.png new file mode 100755 index 0000000..b7347df Binary files /dev/null and b/client/src/main/resources/textures/blocks/potato_2.png differ diff --git a/client/src/main/resources/textures/blocks/potato_3.png b/client/src/main/resources/textures/blocks/potato_3.png new file mode 100755 index 0000000..d7e8185 Binary files /dev/null and b/client/src/main/resources/textures/blocks/potato_3.png differ diff --git a/client/src/main/resources/textures/blocks/praseodymium_block.png b/client/src/main/resources/textures/blocks/praseodymium_block.png new file mode 100755 index 0000000..ec1e0bd Binary files /dev/null and b/client/src/main/resources/textures/blocks/praseodymium_block.png differ diff --git a/client/src/main/resources/textures/blocks/praseodymium_ore.png b/client/src/main/resources/textures/blocks/praseodymium_ore.png new file mode 100755 index 0000000..cf831ed Binary files /dev/null and b/client/src/main/resources/textures/blocks/praseodymium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_face_off.png b/client/src/main/resources/textures/blocks/pumpkin_face_off.png new file mode 100755 index 0000000..ecef025 Binary files /dev/null and b/client/src/main/resources/textures/blocks/pumpkin_face_off.png differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_face_on.png b/client/src/main/resources/textures/blocks/pumpkin_face_on.png new file mode 100755 index 0000000..907f499 Binary files /dev/null and b/client/src/main/resources/textures/blocks/pumpkin_face_on.png differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_side.png b/client/src/main/resources/textures/blocks/pumpkin_side.png new file mode 100755 index 0000000..75dfc47 Binary files /dev/null and b/client/src/main/resources/textures/blocks/pumpkin_side.png differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_stem.png b/client/src/main/resources/textures/blocks/pumpkin_stem.png new file mode 100755 index 0000000..38065ef Binary files /dev/null and b/client/src/main/resources/textures/blocks/pumpkin_stem.png differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_stem_connected.png b/client/src/main/resources/textures/blocks/pumpkin_stem_connected.png new file mode 100755 index 0000000..6a5c10e Binary files /dev/null and b/client/src/main/resources/textures/blocks/pumpkin_stem_connected.png differ diff --git a/client/src/main/resources/textures/blocks/pumpkin_top.png b/client/src/main/resources/textures/blocks/pumpkin_top.png new file mode 100755 index 0000000..297ce3c Binary files /dev/null and b/client/src/main/resources/textures/blocks/pumpkin_top.png differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_foot_end.png b/client/src/main/resources/textures/blocks/purple_bed_foot_end.png new file mode 100755 index 0000000..8e4ed34 Binary files /dev/null and b/client/src/main/resources/textures/blocks/purple_bed_foot_end.png differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_foot_side.png b/client/src/main/resources/textures/blocks/purple_bed_foot_side.png new file mode 100755 index 0000000..f0d316c Binary files /dev/null and b/client/src/main/resources/textures/blocks/purple_bed_foot_side.png differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_foot_top.png b/client/src/main/resources/textures/blocks/purple_bed_foot_top.png new file mode 100755 index 0000000..f1274cb Binary files /dev/null and b/client/src/main/resources/textures/blocks/purple_bed_foot_top.png differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_head_end.png b/client/src/main/resources/textures/blocks/purple_bed_head_end.png new file mode 100755 index 0000000..5811c48 Binary files /dev/null and b/client/src/main/resources/textures/blocks/purple_bed_head_end.png differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_head_side.png b/client/src/main/resources/textures/blocks/purple_bed_head_side.png new file mode 100755 index 0000000..793b2dc Binary files /dev/null and b/client/src/main/resources/textures/blocks/purple_bed_head_side.png differ diff --git a/client/src/main/resources/textures/blocks/purple_bed_head_top.png b/client/src/main/resources/textures/blocks/purple_bed_head_top.png new file mode 100755 index 0000000..4285261 Binary files /dev/null and b/client/src/main/resources/textures/blocks/purple_bed_head_top.png differ diff --git a/client/src/main/resources/textures/blocks/purple_glass.png b/client/src/main/resources/textures/blocks/purple_glass.png new file mode 100755 index 0000000..fcae3d2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/purple_glass.png differ diff --git a/client/src/main/resources/textures/blocks/purple_glass_pane.png b/client/src/main/resources/textures/blocks/purple_glass_pane.png new file mode 100755 index 0000000..23e208e Binary files /dev/null and b/client/src/main/resources/textures/blocks/purple_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/purple_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/purple_stained_hardened_clay.png new file mode 100755 index 0000000..edece94 Binary files /dev/null and b/client/src/main/resources/textures/blocks/purple_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/purple_wool.png b/client/src/main/resources/textures/blocks/purple_wool.png new file mode 100755 index 0000000..76f68d6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/purple_wool.png differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_bottom.png b/client/src/main/resources/textures/blocks/quartz_block_bottom.png new file mode 100755 index 0000000..7e16c7c Binary files /dev/null and b/client/src/main/resources/textures/blocks/quartz_block_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_chiseled.png b/client/src/main/resources/textures/blocks/quartz_block_chiseled.png new file mode 100755 index 0000000..80465a1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/quartz_block_chiseled.png differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_chiseled_top.png b/client/src/main/resources/textures/blocks/quartz_block_chiseled_top.png new file mode 100755 index 0000000..44073e5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/quartz_block_chiseled_top.png differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_lines.png b/client/src/main/resources/textures/blocks/quartz_block_lines.png new file mode 100755 index 0000000..184ecd2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/quartz_block_lines.png differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_lines_top.png b/client/src/main/resources/textures/blocks/quartz_block_lines_top.png new file mode 100755 index 0000000..6d20379 Binary files /dev/null and b/client/src/main/resources/textures/blocks/quartz_block_lines_top.png differ diff --git a/client/src/main/resources/textures/blocks/quartz_block_side.png b/client/src/main/resources/textures/blocks/quartz_block_side.png new file mode 100755 index 0000000..a2cd2ca Binary files /dev/null and b/client/src/main/resources/textures/blocks/quartz_block_side.png differ diff --git a/client/src/main/resources/textures/blocks/quartz_ore.png b/client/src/main/resources/textures/blocks/quartz_ore.png new file mode 100755 index 0000000..4d758c1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/quartz_ore.png differ diff --git a/client/src/main/resources/textures/blocks/quartz_top.png b/client/src/main/resources/textures/blocks/quartz_top.png new file mode 100755 index 0000000..a2cd2ca Binary files /dev/null and b/client/src/main/resources/textures/blocks/quartz_top.png differ diff --git a/client/src/main/resources/textures/blocks/radium_block.png b/client/src/main/resources/textures/blocks/radium_block.png new file mode 100755 index 0000000..63b0d26 Binary files /dev/null and b/client/src/main/resources/textures/blocks/radium_block.png differ diff --git a/client/src/main/resources/textures/blocks/radium_ore.png b/client/src/main/resources/textures/blocks/radium_ore.png new file mode 100755 index 0000000..f9141f1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/radium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/rail.png b/client/src/main/resources/textures/blocks/rail.png new file mode 100755 index 0000000..d609236 Binary files /dev/null and b/client/src/main/resources/textures/blocks/rail.png differ diff --git a/client/src/main/resources/textures/blocks/rail_turned.png b/client/src/main/resources/textures/blocks/rail_turned.png new file mode 100755 index 0000000..f394a23 Binary files /dev/null and b/client/src/main/resources/textures/blocks/rail_turned.png differ diff --git a/client/src/main/resources/textures/blocks/red_bed_foot_end.png b/client/src/main/resources/textures/blocks/red_bed_foot_end.png new file mode 100755 index 0000000..6e1a4be Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_bed_foot_end.png differ diff --git a/client/src/main/resources/textures/blocks/red_bed_foot_side.png b/client/src/main/resources/textures/blocks/red_bed_foot_side.png new file mode 100755 index 0000000..3ce06f3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_bed_foot_side.png differ diff --git a/client/src/main/resources/textures/blocks/red_bed_foot_top.png b/client/src/main/resources/textures/blocks/red_bed_foot_top.png new file mode 100755 index 0000000..b96d357 Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_bed_foot_top.png differ diff --git a/client/src/main/resources/textures/blocks/red_bed_head_end.png b/client/src/main/resources/textures/blocks/red_bed_head_end.png new file mode 100755 index 0000000..b684c9a Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_bed_head_end.png differ diff --git a/client/src/main/resources/textures/blocks/red_bed_head_side.png b/client/src/main/resources/textures/blocks/red_bed_head_side.png new file mode 100755 index 0000000..3270b4a Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_bed_head_side.png differ diff --git a/client/src/main/resources/textures/blocks/red_bed_head_top.png b/client/src/main/resources/textures/blocks/red_bed_head_top.png new file mode 100755 index 0000000..2ab1090 Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_bed_head_top.png differ diff --git a/client/src/main/resources/textures/blocks/red_button.png b/client/src/main/resources/textures/blocks/red_button.png new file mode 100755 index 0000000..29ade3c Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_button.png differ diff --git a/client/src/main/resources/textures/blocks/red_glass.png b/client/src/main/resources/textures/blocks/red_glass.png new file mode 100755 index 0000000..db4c5eb Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_glass.png differ diff --git a/client/src/main/resources/textures/blocks/red_glass_pane.png b/client/src/main/resources/textures/blocks/red_glass_pane.png new file mode 100755 index 0000000..22b69db Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/red_mushroom.png b/client/src/main/resources/textures/blocks/red_mushroom.png new file mode 100755 index 0000000..1b332b7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_mushroom.png differ diff --git a/client/src/main/resources/textures/blocks/red_mushroom_block_cap.png b/client/src/main/resources/textures/blocks/red_mushroom_block_cap.png new file mode 100755 index 0000000..66cf12c Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_mushroom_block_cap.png differ diff --git a/client/src/main/resources/textures/blocks/red_mushroom_block_inside.png b/client/src/main/resources/textures/blocks/red_mushroom_block_inside.png new file mode 100755 index 0000000..f0e7a04 Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_mushroom_block_inside.png differ diff --git a/client/src/main/resources/textures/blocks/red_mushroom_block_stem.png b/client/src/main/resources/textures/blocks/red_mushroom_block_stem.png new file mode 100755 index 0000000..83c0840 Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_mushroom_block_stem.png differ diff --git a/client/src/main/resources/textures/blocks/red_sand.png b/client/src/main/resources/textures/blocks/red_sand.png new file mode 100755 index 0000000..b216a42 Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_sand.png differ diff --git a/client/src/main/resources/textures/blocks/red_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/red_stained_hardened_clay.png new file mode 100755 index 0000000..6561d12 Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/red_tulip.png b/client/src/main/resources/textures/blocks/red_tulip.png new file mode 100755 index 0000000..3048b63 Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_tulip.png differ diff --git a/client/src/main/resources/textures/blocks/red_wool.png b/client/src/main/resources/textures/blocks/red_wool.png new file mode 100755 index 0000000..0cff7a9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/red_wool.png differ diff --git a/client/src/main/resources/textures/blocks/redstone_block.png b/client/src/main/resources/textures/blocks/redstone_block.png new file mode 100755 index 0000000..fcf6b40 Binary files /dev/null and b/client/src/main/resources/textures/blocks/redstone_block.png differ diff --git a/client/src/main/resources/textures/blocks/redstone_dust_cross.png b/client/src/main/resources/textures/blocks/redstone_dust_cross.png new file mode 100755 index 0000000..66eba38 Binary files /dev/null and b/client/src/main/resources/textures/blocks/redstone_dust_cross.png differ diff --git a/client/src/main/resources/textures/blocks/redstone_dust_cross_overlay.png b/client/src/main/resources/textures/blocks/redstone_dust_cross_overlay.png new file mode 100755 index 0000000..96729e1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/redstone_dust_cross_overlay.png differ diff --git a/client/src/main/resources/textures/blocks/redstone_dust_line.png b/client/src/main/resources/textures/blocks/redstone_dust_line.png new file mode 100755 index 0000000..a1ae205 Binary files /dev/null and b/client/src/main/resources/textures/blocks/redstone_dust_line.png differ diff --git a/client/src/main/resources/textures/blocks/redstone_dust_line_overlay.png b/client/src/main/resources/textures/blocks/redstone_dust_line_overlay.png new file mode 100755 index 0000000..9f24cbc Binary files /dev/null and b/client/src/main/resources/textures/blocks/redstone_dust_line_overlay.png differ diff --git a/client/src/main/resources/textures/blocks/redstone_lamp.png b/client/src/main/resources/textures/blocks/redstone_lamp.png new file mode 100755 index 0000000..522765b Binary files /dev/null and b/client/src/main/resources/textures/blocks/redstone_lamp.png differ diff --git a/client/src/main/resources/textures/blocks/redstone_ore.png b/client/src/main/resources/textures/blocks/redstone_ore.png new file mode 100755 index 0000000..575a488 Binary files /dev/null and b/client/src/main/resources/textures/blocks/redstone_ore.png differ diff --git a/client/src/main/resources/textures/blocks/redstone_torch.png b/client/src/main/resources/textures/blocks/redstone_torch.png new file mode 100755 index 0000000..2983d6c Binary files /dev/null and b/client/src/main/resources/textures/blocks/redstone_torch.png differ diff --git a/client/src/main/resources/textures/blocks/reeds.png b/client/src/main/resources/textures/blocks/reeds.png new file mode 100755 index 0000000..64bbfe0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/reeds.png differ diff --git a/client/src/main/resources/textures/blocks/repeater_off.png b/client/src/main/resources/textures/blocks/repeater_off.png new file mode 100755 index 0000000..8634669 Binary files /dev/null and b/client/src/main/resources/textures/blocks/repeater_off.png differ diff --git a/client/src/main/resources/textures/blocks/repeater_on.png b/client/src/main/resources/textures/blocks/repeater_on.png new file mode 100755 index 0000000..d71d0d9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/repeater_on.png differ diff --git a/client/src/main/resources/textures/blocks/rock.png b/client/src/main/resources/textures/blocks/rock.png new file mode 100755 index 0000000..680a899 Binary files /dev/null and b/client/src/main/resources/textures/blocks/rock.png differ diff --git a/client/src/main/resources/textures/blocks/rose.png b/client/src/main/resources/textures/blocks/rose.png new file mode 100755 index 0000000..15ebba6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/rose.png differ diff --git a/client/src/main/resources/textures/blocks/ruby_block.png b/client/src/main/resources/textures/blocks/ruby_block.png new file mode 100755 index 0000000..2edc4c1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/ruby_block.png differ diff --git a/client/src/main/resources/textures/blocks/ruby_ore.png b/client/src/main/resources/textures/blocks/ruby_ore.png new file mode 100755 index 0000000..8a104cb Binary files /dev/null and b/client/src/main/resources/textures/blocks/ruby_ore.png differ diff --git a/client/src/main/resources/textures/blocks/sand.png b/client/src/main/resources/textures/blocks/sand.png new file mode 100755 index 0000000..cb7f2b9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/sand.png differ diff --git a/client/src/main/resources/textures/blocks/sandstone_all.png b/client/src/main/resources/textures/blocks/sandstone_all.png new file mode 100755 index 0000000..bb5b157 Binary files /dev/null and b/client/src/main/resources/textures/blocks/sandstone_all.png differ diff --git a/client/src/main/resources/textures/blocks/sandstone_bottom.png b/client/src/main/resources/textures/blocks/sandstone_bottom.png new file mode 100755 index 0000000..e102220 Binary files /dev/null and b/client/src/main/resources/textures/blocks/sandstone_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/sandstone_carved.png b/client/src/main/resources/textures/blocks/sandstone_carved.png new file mode 100755 index 0000000..9bd7fa1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/sandstone_carved.png differ diff --git a/client/src/main/resources/textures/blocks/sandstone_normal.png b/client/src/main/resources/textures/blocks/sandstone_normal.png new file mode 100755 index 0000000..1b79145 Binary files /dev/null and b/client/src/main/resources/textures/blocks/sandstone_normal.png differ diff --git a/client/src/main/resources/textures/blocks/sandstone_smooth.png b/client/src/main/resources/textures/blocks/sandstone_smooth.png new file mode 100755 index 0000000..ef118bd Binary files /dev/null and b/client/src/main/resources/textures/blocks/sandstone_smooth.png differ diff --git a/client/src/main/resources/textures/blocks/selenium_block.png b/client/src/main/resources/textures/blocks/selenium_block.png new file mode 100755 index 0000000..2268527 Binary files /dev/null and b/client/src/main/resources/textures/blocks/selenium_block.png differ diff --git a/client/src/main/resources/textures/blocks/selenium_ore.png b/client/src/main/resources/textures/blocks/selenium_ore.png new file mode 100755 index 0000000..fd7f9a4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/selenium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/sign.png b/client/src/main/resources/textures/blocks/sign.png new file mode 100755 index 0000000..e22e2f7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/sign.png differ diff --git a/client/src/main/resources/textures/blocks/silicon_block.png b/client/src/main/resources/textures/blocks/silicon_block.png new file mode 100755 index 0000000..a5cd9ec Binary files /dev/null and b/client/src/main/resources/textures/blocks/silicon_block.png differ diff --git a/client/src/main/resources/textures/blocks/silicon_ore.png b/client/src/main/resources/textures/blocks/silicon_ore.png new file mode 100755 index 0000000..dbd76bb Binary files /dev/null and b/client/src/main/resources/textures/blocks/silicon_ore.png differ diff --git a/client/src/main/resources/textures/blocks/silver_block.png b/client/src/main/resources/textures/blocks/silver_block.png new file mode 100755 index 0000000..23542a9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/silver_block.png differ diff --git a/client/src/main/resources/textures/blocks/silver_glass.png b/client/src/main/resources/textures/blocks/silver_glass.png new file mode 100755 index 0000000..8461664 Binary files /dev/null and b/client/src/main/resources/textures/blocks/silver_glass.png differ diff --git a/client/src/main/resources/textures/blocks/silver_glass_pane.png b/client/src/main/resources/textures/blocks/silver_glass_pane.png new file mode 100755 index 0000000..f226ecc Binary files /dev/null and b/client/src/main/resources/textures/blocks/silver_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/silver_ore.png b/client/src/main/resources/textures/blocks/silver_ore.png new file mode 100755 index 0000000..305c58c Binary files /dev/null and b/client/src/main/resources/textures/blocks/silver_ore.png differ diff --git a/client/src/main/resources/textures/blocks/silver_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/silver_stained_hardened_clay.png new file mode 100755 index 0000000..eae07f2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/silver_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/silver_wool.png b/client/src/main/resources/textures/blocks/silver_wool.png new file mode 100755 index 0000000..756d9b0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/silver_wool.png differ diff --git a/client/src/main/resources/textures/blocks/skull_back.png b/client/src/main/resources/textures/blocks/skull_back.png new file mode 100644 index 0000000..eb5bada Binary files /dev/null and b/client/src/main/resources/textures/blocks/skull_back.png differ diff --git a/client/src/main/resources/textures/blocks/skull_bottom.png b/client/src/main/resources/textures/blocks/skull_bottom.png new file mode 100644 index 0000000..4dcb71b Binary files /dev/null and b/client/src/main/resources/textures/blocks/skull_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/skull_front.png b/client/src/main/resources/textures/blocks/skull_front.png new file mode 100644 index 0000000..12d4a2c Binary files /dev/null and b/client/src/main/resources/textures/blocks/skull_front.png differ diff --git a/client/src/main/resources/textures/blocks/skull_left.png b/client/src/main/resources/textures/blocks/skull_left.png new file mode 100644 index 0000000..988f674 Binary files /dev/null and b/client/src/main/resources/textures/blocks/skull_left.png differ diff --git a/client/src/main/resources/textures/blocks/skull_right.png b/client/src/main/resources/textures/blocks/skull_right.png new file mode 100644 index 0000000..b23ea4c Binary files /dev/null and b/client/src/main/resources/textures/blocks/skull_right.png differ diff --git a/client/src/main/resources/textures/blocks/skull_top.png b/client/src/main/resources/textures/blocks/skull_top.png new file mode 100644 index 0000000..f4a484c Binary files /dev/null and b/client/src/main/resources/textures/blocks/skull_top.png differ diff --git a/client/src/main/resources/textures/blocks/slime.png b/client/src/main/resources/textures/blocks/slime.png new file mode 100755 index 0000000..6dbe5cb Binary files /dev/null and b/client/src/main/resources/textures/blocks/slime.png differ diff --git a/client/src/main/resources/textures/blocks/slime_flow.png b/client/src/main/resources/textures/blocks/slime_flow.png new file mode 100755 index 0000000..83634df Binary files /dev/null and b/client/src/main/resources/textures/blocks/slime_flow.png differ diff --git a/client/src/main/resources/textures/blocks/slime_still.png b/client/src/main/resources/textures/blocks/slime_still.png new file mode 100755 index 0000000..6de7593 Binary files /dev/null and b/client/src/main/resources/textures/blocks/slime_still.png differ diff --git a/client/src/main/resources/textures/blocks/smooth_rock.png b/client/src/main/resources/textures/blocks/smooth_rock.png new file mode 100755 index 0000000..a77809c Binary files /dev/null and b/client/src/main/resources/textures/blocks/smooth_rock.png differ diff --git a/client/src/main/resources/textures/blocks/snow.png b/client/src/main/resources/textures/blocks/snow.png new file mode 100755 index 0000000..5c146cd Binary files /dev/null and b/client/src/main/resources/textures/blocks/snow.png differ diff --git a/client/src/main/resources/textures/blocks/sodium_block.png b/client/src/main/resources/textures/blocks/sodium_block.png new file mode 100755 index 0000000..c4a7e11 Binary files /dev/null and b/client/src/main/resources/textures/blocks/sodium_block.png differ diff --git a/client/src/main/resources/textures/blocks/sodium_ore.png b/client/src/main/resources/textures/blocks/sodium_ore.png new file mode 100755 index 0000000..aa462ba Binary files /dev/null and b/client/src/main/resources/textures/blocks/sodium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/soul_sand.png b/client/src/main/resources/textures/blocks/soul_sand.png new file mode 100755 index 0000000..fca7e8f Binary files /dev/null and b/client/src/main/resources/textures/blocks/soul_sand.png differ diff --git a/client/src/main/resources/textures/blocks/soul_wart_0.png b/client/src/main/resources/textures/blocks/soul_wart_0.png new file mode 100755 index 0000000..514a95b Binary files /dev/null and b/client/src/main/resources/textures/blocks/soul_wart_0.png differ diff --git a/client/src/main/resources/textures/blocks/soul_wart_1.png b/client/src/main/resources/textures/blocks/soul_wart_1.png new file mode 100755 index 0000000..b4ad0d1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/soul_wart_1.png differ diff --git a/client/src/main/resources/textures/blocks/soul_wart_2.png b/client/src/main/resources/textures/blocks/soul_wart_2.png new file mode 100755 index 0000000..b9b6743 Binary files /dev/null and b/client/src/main/resources/textures/blocks/soul_wart_2.png differ diff --git a/client/src/main/resources/textures/blocks/sponge.png b/client/src/main/resources/textures/blocks/sponge.png new file mode 100755 index 0000000..33062d7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/sponge.png differ diff --git a/client/src/main/resources/textures/blocks/springwater_flow.png b/client/src/main/resources/textures/blocks/springwater_flow.png new file mode 100755 index 0000000..19dcfef Binary files /dev/null and b/client/src/main/resources/textures/blocks/springwater_flow.png differ diff --git a/client/src/main/resources/textures/blocks/springwater_still.png b/client/src/main/resources/textures/blocks/springwater_still.png new file mode 100755 index 0000000..fdd9eab Binary files /dev/null and b/client/src/main/resources/textures/blocks/springwater_still.png differ diff --git a/client/src/main/resources/textures/blocks/spruce_door_bottom.png b/client/src/main/resources/textures/blocks/spruce_door_bottom.png new file mode 100755 index 0000000..5faa6e7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/spruce_door_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/spruce_door_top.png b/client/src/main/resources/textures/blocks/spruce_door_top.png new file mode 100755 index 0000000..38e2717 Binary files /dev/null and b/client/src/main/resources/textures/blocks/spruce_door_top.png differ diff --git a/client/src/main/resources/textures/blocks/spruce_leaves_autumn.png b/client/src/main/resources/textures/blocks/spruce_leaves_autumn.png new file mode 100755 index 0000000..c90d2fa Binary files /dev/null and b/client/src/main/resources/textures/blocks/spruce_leaves_autumn.png differ diff --git a/client/src/main/resources/textures/blocks/spruce_leaves_snowy.png b/client/src/main/resources/textures/blocks/spruce_leaves_snowy.png new file mode 100755 index 0000000..5498df4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/spruce_leaves_snowy.png differ diff --git a/client/src/main/resources/textures/blocks/spruce_leaves_spring.png b/client/src/main/resources/textures/blocks/spruce_leaves_spring.png new file mode 100755 index 0000000..602eab8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/spruce_leaves_spring.png differ diff --git a/client/src/main/resources/textures/blocks/spruce_leaves_summer.png b/client/src/main/resources/textures/blocks/spruce_leaves_summer.png new file mode 100755 index 0000000..44456fb Binary files /dev/null and b/client/src/main/resources/textures/blocks/spruce_leaves_summer.png differ diff --git a/client/src/main/resources/textures/blocks/spruce_leaves_winter.png b/client/src/main/resources/textures/blocks/spruce_leaves_winter.png new file mode 100755 index 0000000..5db74d9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/spruce_leaves_winter.png differ diff --git a/client/src/main/resources/textures/blocks/spruce_log_bark.png b/client/src/main/resources/textures/blocks/spruce_log_bark.png new file mode 100755 index 0000000..dc1aa2f Binary files /dev/null and b/client/src/main/resources/textures/blocks/spruce_log_bark.png differ diff --git a/client/src/main/resources/textures/blocks/spruce_log_top.png b/client/src/main/resources/textures/blocks/spruce_log_top.png new file mode 100755 index 0000000..280c64e Binary files /dev/null and b/client/src/main/resources/textures/blocks/spruce_log_top.png differ diff --git a/client/src/main/resources/textures/blocks/spruce_planks.png b/client/src/main/resources/textures/blocks/spruce_planks.png new file mode 100755 index 0000000..f45fa94 Binary files /dev/null and b/client/src/main/resources/textures/blocks/spruce_planks.png differ diff --git a/client/src/main/resources/textures/blocks/spruce_sapling.png b/client/src/main/resources/textures/blocks/spruce_sapling.png new file mode 100755 index 0000000..5767d48 Binary files /dev/null and b/client/src/main/resources/textures/blocks/spruce_sapling.png differ diff --git a/client/src/main/resources/textures/blocks/stone.png b/client/src/main/resources/textures/blocks/stone.png new file mode 100755 index 0000000..bf63ad3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/stone.png differ diff --git a/client/src/main/resources/textures/blocks/stone_slab_side.png b/client/src/main/resources/textures/blocks/stone_slab_side.png new file mode 100755 index 0000000..fe2a204 Binary files /dev/null and b/client/src/main/resources/textures/blocks/stone_slab_side.png differ diff --git a/client/src/main/resources/textures/blocks/stonebrick_chiseled.png b/client/src/main/resources/textures/blocks/stonebrick_chiseled.png new file mode 100755 index 0000000..b7e88db Binary files /dev/null and b/client/src/main/resources/textures/blocks/stonebrick_chiseled.png differ diff --git a/client/src/main/resources/textures/blocks/stonebrick_cracked.png b/client/src/main/resources/textures/blocks/stonebrick_cracked.png new file mode 100755 index 0000000..918a884 Binary files /dev/null and b/client/src/main/resources/textures/blocks/stonebrick_cracked.png differ diff --git a/client/src/main/resources/textures/blocks/stonebrick_default.png b/client/src/main/resources/textures/blocks/stonebrick_default.png new file mode 100755 index 0000000..69138cf Binary files /dev/null and b/client/src/main/resources/textures/blocks/stonebrick_default.png differ diff --git a/client/src/main/resources/textures/blocks/stonebrick_mossy.png b/client/src/main/resources/textures/blocks/stonebrick_mossy.png new file mode 100755 index 0000000..5b9fe37 Binary files /dev/null and b/client/src/main/resources/textures/blocks/stonebrick_mossy.png differ diff --git a/client/src/main/resources/textures/blocks/sulfur_block.png b/client/src/main/resources/textures/blocks/sulfur_block.png new file mode 100755 index 0000000..868d044 Binary files /dev/null and b/client/src/main/resources/textures/blocks/sulfur_block.png differ diff --git a/client/src/main/resources/textures/blocks/sulfur_ore.png b/client/src/main/resources/textures/blocks/sulfur_ore.png new file mode 100755 index 0000000..27c662f Binary files /dev/null and b/client/src/main/resources/textures/blocks/sulfur_ore.png differ diff --git a/client/src/main/resources/textures/blocks/sunflower_back.png b/client/src/main/resources/textures/blocks/sunflower_back.png new file mode 100755 index 0000000..d488923 Binary files /dev/null and b/client/src/main/resources/textures/blocks/sunflower_back.png differ diff --git a/client/src/main/resources/textures/blocks/sunflower_bottom.png b/client/src/main/resources/textures/blocks/sunflower_bottom.png new file mode 100755 index 0000000..8a12ebe Binary files /dev/null and b/client/src/main/resources/textures/blocks/sunflower_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/sunflower_front.png b/client/src/main/resources/textures/blocks/sunflower_front.png new file mode 100755 index 0000000..699e34f Binary files /dev/null and b/client/src/main/resources/textures/blocks/sunflower_front.png differ diff --git a/client/src/main/resources/textures/blocks/sunflower_top.png b/client/src/main/resources/textures/blocks/sunflower_top.png new file mode 100755 index 0000000..4d14203 Binary files /dev/null and b/client/src/main/resources/textures/blocks/sunflower_top.png differ diff --git a/client/src/main/resources/textures/blocks/syringa_bottom.png b/client/src/main/resources/textures/blocks/syringa_bottom.png new file mode 100755 index 0000000..5b880b5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/syringa_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/syringa_top.png b/client/src/main/resources/textures/blocks/syringa_top.png new file mode 100755 index 0000000..b00751f Binary files /dev/null and b/client/src/main/resources/textures/blocks/syringa_top.png differ diff --git a/client/src/main/resources/textures/blocks/tall_grass.png b/client/src/main/resources/textures/blocks/tall_grass.png new file mode 100755 index 0000000..2869848 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tall_grass.png differ diff --git a/client/src/main/resources/textures/blocks/thetium_block.png b/client/src/main/resources/textures/blocks/thetium_block.png new file mode 100755 index 0000000..b71f8d6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/thetium_block.png differ diff --git a/client/src/main/resources/textures/blocks/thetium_ore.png b/client/src/main/resources/textures/blocks/thetium_ore.png new file mode 100755 index 0000000..c93156c Binary files /dev/null and b/client/src/main/resources/textures/blocks/thetium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/tian.png b/client/src/main/resources/textures/blocks/tian.png new file mode 100755 index 0000000..93dd028 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian.png differ diff --git a/client/src/main/resources/textures/blocks/tian_door_bottom.png b/client/src/main/resources/textures/blocks/tian_door_bottom.png new file mode 100755 index 0000000..9bac389 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_door_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/tian_door_top.png b/client/src/main/resources/textures/blocks/tian_door_top.png new file mode 100755 index 0000000..23f3d05 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_door_top.png differ diff --git a/client/src/main/resources/textures/blocks/tian_leaves_autumn.png b/client/src/main/resources/textures/blocks/tian_leaves_autumn.png new file mode 100755 index 0000000..5ed6cec Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_leaves_autumn.png differ diff --git a/client/src/main/resources/textures/blocks/tian_leaves_snowy.png b/client/src/main/resources/textures/blocks/tian_leaves_snowy.png new file mode 100755 index 0000000..dfdd888 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_leaves_snowy.png differ diff --git a/client/src/main/resources/textures/blocks/tian_leaves_spring.png b/client/src/main/resources/textures/blocks/tian_leaves_spring.png new file mode 100755 index 0000000..d02db7b Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_leaves_spring.png differ diff --git a/client/src/main/resources/textures/blocks/tian_leaves_summer.png b/client/src/main/resources/textures/blocks/tian_leaves_summer.png new file mode 100755 index 0000000..77ea69e Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_leaves_summer.png differ diff --git a/client/src/main/resources/textures/blocks/tian_leaves_winter.png b/client/src/main/resources/textures/blocks/tian_leaves_winter.png new file mode 100755 index 0000000..148d95b Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_leaves_winter.png differ diff --git a/client/src/main/resources/textures/blocks/tian_log_bark.png b/client/src/main/resources/textures/blocks/tian_log_bark.png new file mode 100755 index 0000000..50653f5 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_log_bark.png differ diff --git a/client/src/main/resources/textures/blocks/tian_log_top.png b/client/src/main/resources/textures/blocks/tian_log_top.png new file mode 100755 index 0000000..b2f0c47 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_log_top.png differ diff --git a/client/src/main/resources/textures/blocks/tian_planks.png b/client/src/main/resources/textures/blocks/tian_planks.png new file mode 100755 index 0000000..74fce78 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_planks.png differ diff --git a/client/src/main/resources/textures/blocks/tian_reactor_bottom.png b/client/src/main/resources/textures/blocks/tian_reactor_bottom.png new file mode 100755 index 0000000..3302315 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_reactor_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/tian_reactor_front.png b/client/src/main/resources/textures/blocks/tian_reactor_front.png new file mode 100755 index 0000000..3c27a73 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_reactor_front.png differ diff --git a/client/src/main/resources/textures/blocks/tian_reactor_side.png b/client/src/main/resources/textures/blocks/tian_reactor_side.png new file mode 100755 index 0000000..b684f4e Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_reactor_side.png differ diff --git a/client/src/main/resources/textures/blocks/tian_reactor_top.png b/client/src/main/resources/textures/blocks/tian_reactor_top.png new file mode 100755 index 0000000..a564e61 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_reactor_top.png differ diff --git a/client/src/main/resources/textures/blocks/tian_sapling.png b/client/src/main/resources/textures/blocks/tian_sapling.png new file mode 100755 index 0000000..e1f9383 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_sapling.png differ diff --git a/client/src/main/resources/textures/blocks/tian_soil_side.png b/client/src/main/resources/textures/blocks/tian_soil_side.png new file mode 100755 index 0000000..5ca5164 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_soil_side.png differ diff --git a/client/src/main/resources/textures/blocks/tian_soil_side_snowed.png b/client/src/main/resources/textures/blocks/tian_soil_side_snowed.png new file mode 100755 index 0000000..22618b8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_soil_side_snowed.png differ diff --git a/client/src/main/resources/textures/blocks/tian_soil_top.png b/client/src/main/resources/textures/blocks/tian_soil_top.png new file mode 100755 index 0000000..07d6a69 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tian_soil_top.png differ diff --git a/client/src/main/resources/textures/blocks/tin_block.png b/client/src/main/resources/textures/blocks/tin_block.png new file mode 100755 index 0000000..8d87037 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tin_block.png differ diff --git a/client/src/main/resources/textures/blocks/tin_ore.png b/client/src/main/resources/textures/blocks/tin_ore.png new file mode 100755 index 0000000..b486c3d Binary files /dev/null and b/client/src/main/resources/textures/blocks/tin_ore.png differ diff --git a/client/src/main/resources/textures/blocks/titanium_block.png b/client/src/main/resources/textures/blocks/titanium_block.png new file mode 100755 index 0000000..ae94a63 Binary files /dev/null and b/client/src/main/resources/textures/blocks/titanium_block.png differ diff --git a/client/src/main/resources/textures/blocks/titanium_ore.png b/client/src/main/resources/textures/blocks/titanium_ore.png new file mode 100755 index 0000000..7b7a84e Binary files /dev/null and b/client/src/main/resources/textures/blocks/titanium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom.png b/client/src/main/resources/textures/blocks/tnt_bottom.png new file mode 100755 index 0000000..cc2e586 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_bottom.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_1.png b/client/src/main/resources/textures/blocks/tnt_bottom_1.png new file mode 100755 index 0000000..73b4902 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_bottom_1.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_2.png b/client/src/main/resources/textures/blocks/tnt_bottom_2.png new file mode 100755 index 0000000..6b21137 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_bottom_2.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_3.png b/client/src/main/resources/textures/blocks/tnt_bottom_3.png new file mode 100755 index 0000000..7760631 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_bottom_3.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_4.png b/client/src/main/resources/textures/blocks/tnt_bottom_4.png new file mode 100755 index 0000000..c2f6753 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_bottom_4.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_5.png b/client/src/main/resources/textures/blocks/tnt_bottom_5.png new file mode 100755 index 0000000..6d28c6f Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_bottom_5.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_6.png b/client/src/main/resources/textures/blocks/tnt_bottom_6.png new file mode 100755 index 0000000..bc8e98b Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_bottom_6.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_bottom_7.png b/client/src/main/resources/textures/blocks/tnt_bottom_7.png new file mode 100755 index 0000000..6a15f16 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_bottom_7.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_side.png b/client/src/main/resources/textures/blocks/tnt_side.png new file mode 100755 index 0000000..21109fb Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_side.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_1.png b/client/src/main/resources/textures/blocks/tnt_side_1.png new file mode 100755 index 0000000..d5c8b46 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_side_1.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_2.png b/client/src/main/resources/textures/blocks/tnt_side_2.png new file mode 100755 index 0000000..d4faa00 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_side_2.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_3.png b/client/src/main/resources/textures/blocks/tnt_side_3.png new file mode 100755 index 0000000..26ab9e7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_side_3.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_4.png b/client/src/main/resources/textures/blocks/tnt_side_4.png new file mode 100755 index 0000000..bff7a07 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_side_4.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_5.png b/client/src/main/resources/textures/blocks/tnt_side_5.png new file mode 100755 index 0000000..25d0cb4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_side_5.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_6.png b/client/src/main/resources/textures/blocks/tnt_side_6.png new file mode 100755 index 0000000..63c727e Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_side_6.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_side_7.png b/client/src/main/resources/textures/blocks/tnt_side_7.png new file mode 100755 index 0000000..68bb687 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_side_7.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_top.png b/client/src/main/resources/textures/blocks/tnt_top.png new file mode 100755 index 0000000..ceb44b6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_top.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_1.png b/client/src/main/resources/textures/blocks/tnt_top_1.png new file mode 100755 index 0000000..32b478a Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_top_1.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_2.png b/client/src/main/resources/textures/blocks/tnt_top_2.png new file mode 100755 index 0000000..35f1973 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_top_2.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_3.png b/client/src/main/resources/textures/blocks/tnt_top_3.png new file mode 100755 index 0000000..ceb38e6 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_top_3.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_4.png b/client/src/main/resources/textures/blocks/tnt_top_4.png new file mode 100755 index 0000000..5dffddb Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_top_4.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_5.png b/client/src/main/resources/textures/blocks/tnt_top_5.png new file mode 100755 index 0000000..0768549 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_top_5.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_6.png b/client/src/main/resources/textures/blocks/tnt_top_6.png new file mode 100755 index 0000000..85aa03d Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_top_6.png differ diff --git a/client/src/main/resources/textures/blocks/tnt_top_7.png b/client/src/main/resources/textures/blocks/tnt_top_7.png new file mode 100755 index 0000000..17aad64 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tnt_top_7.png differ diff --git a/client/src/main/resources/textures/blocks/torch.png b/client/src/main/resources/textures/blocks/torch.png new file mode 100755 index 0000000..a2ce41b Binary files /dev/null and b/client/src/main/resources/textures/blocks/torch.png differ diff --git a/client/src/main/resources/textures/blocks/trapdoor.png b/client/src/main/resources/textures/blocks/trapdoor.png new file mode 100755 index 0000000..4eadefc Binary files /dev/null and b/client/src/main/resources/textures/blocks/trapdoor.png differ diff --git a/client/src/main/resources/textures/blocks/trip_wire.png b/client/src/main/resources/textures/blocks/trip_wire.png new file mode 100755 index 0000000..42126b8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/trip_wire.png differ diff --git a/client/src/main/resources/textures/blocks/tripwire_hook.png b/client/src/main/resources/textures/blocks/tripwire_hook.png new file mode 100755 index 0000000..fbd464d Binary files /dev/null and b/client/src/main/resources/textures/blocks/tripwire_hook.png differ diff --git a/client/src/main/resources/textures/blocks/tungsten_block.png b/client/src/main/resources/textures/blocks/tungsten_block.png new file mode 100755 index 0000000..6e3ff08 Binary files /dev/null and b/client/src/main/resources/textures/blocks/tungsten_block.png differ diff --git a/client/src/main/resources/textures/blocks/tungsten_ore.png b/client/src/main/resources/textures/blocks/tungsten_ore.png new file mode 100755 index 0000000..662ad3f Binary files /dev/null and b/client/src/main/resources/textures/blocks/tungsten_ore.png differ diff --git a/client/src/main/resources/textures/blocks/unlit_redstone_torch.png b/client/src/main/resources/textures/blocks/unlit_redstone_torch.png new file mode 100755 index 0000000..635eabd Binary files /dev/null and b/client/src/main/resources/textures/blocks/unlit_redstone_torch.png differ diff --git a/client/src/main/resources/textures/blocks/uranium_block.png b/client/src/main/resources/textures/blocks/uranium_block.png new file mode 100755 index 0000000..2101f95 Binary files /dev/null and b/client/src/main/resources/textures/blocks/uranium_block.png differ diff --git a/client/src/main/resources/textures/blocks/uranium_ore.png b/client/src/main/resources/textures/blocks/uranium_ore.png new file mode 100755 index 0000000..5930c47 Binary files /dev/null and b/client/src/main/resources/textures/blocks/uranium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/vanadium_block.png b/client/src/main/resources/textures/blocks/vanadium_block.png new file mode 100755 index 0000000..0b039e7 Binary files /dev/null and b/client/src/main/resources/textures/blocks/vanadium_block.png differ diff --git a/client/src/main/resources/textures/blocks/vanadium_ore.png b/client/src/main/resources/textures/blocks/vanadium_ore.png new file mode 100755 index 0000000..82288f2 Binary files /dev/null and b/client/src/main/resources/textures/blocks/vanadium_ore.png differ diff --git a/client/src/main/resources/textures/blocks/vine.png b/client/src/main/resources/textures/blocks/vine.png new file mode 100755 index 0000000..df5e435 Binary files /dev/null and b/client/src/main/resources/textures/blocks/vine.png differ diff --git a/client/src/main/resources/textures/blocks/warp_chest_front.png b/client/src/main/resources/textures/blocks/warp_chest_front.png new file mode 100755 index 0000000..d7ae02d Binary files /dev/null and b/client/src/main/resources/textures/blocks/warp_chest_front.png differ diff --git a/client/src/main/resources/textures/blocks/warp_chest_side.png b/client/src/main/resources/textures/blocks/warp_chest_side.png new file mode 100755 index 0000000..4b07cd4 Binary files /dev/null and b/client/src/main/resources/textures/blocks/warp_chest_side.png differ diff --git a/client/src/main/resources/textures/blocks/warp_chest_top.png b/client/src/main/resources/textures/blocks/warp_chest_top.png new file mode 100755 index 0000000..5b12f22 Binary files /dev/null and b/client/src/main/resources/textures/blocks/warp_chest_top.png differ diff --git a/client/src/main/resources/textures/blocks/waterlily.png b/client/src/main/resources/textures/blocks/waterlily.png new file mode 100755 index 0000000..f6c84f8 Binary files /dev/null and b/client/src/main/resources/textures/blocks/waterlily.png differ diff --git a/client/src/main/resources/textures/blocks/web.png b/client/src/main/resources/textures/blocks/web.png new file mode 100755 index 0000000..7c097f1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/web.png differ diff --git a/client/src/main/resources/textures/blocks/wheat_0.png b/client/src/main/resources/textures/blocks/wheat_0.png new file mode 100755 index 0000000..185af6f Binary files /dev/null and b/client/src/main/resources/textures/blocks/wheat_0.png differ diff --git a/client/src/main/resources/textures/blocks/wheat_1.png b/client/src/main/resources/textures/blocks/wheat_1.png new file mode 100755 index 0000000..67588c1 Binary files /dev/null and b/client/src/main/resources/textures/blocks/wheat_1.png differ diff --git a/client/src/main/resources/textures/blocks/wheat_2.png b/client/src/main/resources/textures/blocks/wheat_2.png new file mode 100755 index 0000000..3d33792 Binary files /dev/null and b/client/src/main/resources/textures/blocks/wheat_2.png differ diff --git a/client/src/main/resources/textures/blocks/wheat_3.png b/client/src/main/resources/textures/blocks/wheat_3.png new file mode 100755 index 0000000..4649f78 Binary files /dev/null and b/client/src/main/resources/textures/blocks/wheat_3.png differ diff --git a/client/src/main/resources/textures/blocks/wheat_4.png b/client/src/main/resources/textures/blocks/wheat_4.png new file mode 100755 index 0000000..ac04b52 Binary files /dev/null and b/client/src/main/resources/textures/blocks/wheat_4.png differ diff --git a/client/src/main/resources/textures/blocks/wheat_5.png b/client/src/main/resources/textures/blocks/wheat_5.png new file mode 100755 index 0000000..1ea81ac Binary files /dev/null and b/client/src/main/resources/textures/blocks/wheat_5.png differ diff --git a/client/src/main/resources/textures/blocks/wheat_6.png b/client/src/main/resources/textures/blocks/wheat_6.png new file mode 100755 index 0000000..cb5f195 Binary files /dev/null and b/client/src/main/resources/textures/blocks/wheat_6.png differ diff --git a/client/src/main/resources/textures/blocks/wheat_7.png b/client/src/main/resources/textures/blocks/wheat_7.png new file mode 100755 index 0000000..7acafb3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/wheat_7.png differ diff --git a/client/src/main/resources/textures/blocks/white_bed_foot_end.png b/client/src/main/resources/textures/blocks/white_bed_foot_end.png new file mode 100755 index 0000000..c6e8288 Binary files /dev/null and b/client/src/main/resources/textures/blocks/white_bed_foot_end.png differ diff --git a/client/src/main/resources/textures/blocks/white_bed_foot_side.png b/client/src/main/resources/textures/blocks/white_bed_foot_side.png new file mode 100755 index 0000000..5ff5f6a Binary files /dev/null and b/client/src/main/resources/textures/blocks/white_bed_foot_side.png differ diff --git a/client/src/main/resources/textures/blocks/white_bed_foot_top.png b/client/src/main/resources/textures/blocks/white_bed_foot_top.png new file mode 100755 index 0000000..dff0b58 Binary files /dev/null and b/client/src/main/resources/textures/blocks/white_bed_foot_top.png differ diff --git a/client/src/main/resources/textures/blocks/white_bed_head_end.png b/client/src/main/resources/textures/blocks/white_bed_head_end.png new file mode 100755 index 0000000..ea6e623 Binary files /dev/null and b/client/src/main/resources/textures/blocks/white_bed_head_end.png differ diff --git a/client/src/main/resources/textures/blocks/white_bed_head_side.png b/client/src/main/resources/textures/blocks/white_bed_head_side.png new file mode 100755 index 0000000..b70c1bb Binary files /dev/null and b/client/src/main/resources/textures/blocks/white_bed_head_side.png differ diff --git a/client/src/main/resources/textures/blocks/white_bed_head_top.png b/client/src/main/resources/textures/blocks/white_bed_head_top.png new file mode 100755 index 0000000..571ac4e Binary files /dev/null and b/client/src/main/resources/textures/blocks/white_bed_head_top.png differ diff --git a/client/src/main/resources/textures/blocks/white_glass.png b/client/src/main/resources/textures/blocks/white_glass.png new file mode 100755 index 0000000..696c5aa Binary files /dev/null and b/client/src/main/resources/textures/blocks/white_glass.png differ diff --git a/client/src/main/resources/textures/blocks/white_glass_pane.png b/client/src/main/resources/textures/blocks/white_glass_pane.png new file mode 100755 index 0000000..9a273c3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/white_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/white_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/white_stained_hardened_clay.png new file mode 100755 index 0000000..8066af0 Binary files /dev/null and b/client/src/main/resources/textures/blocks/white_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/white_tulip.png b/client/src/main/resources/textures/blocks/white_tulip.png new file mode 100755 index 0000000..6aa12a9 Binary files /dev/null and b/client/src/main/resources/textures/blocks/white_tulip.png differ diff --git a/client/src/main/resources/textures/blocks/white_wool.png b/client/src/main/resources/textures/blocks/white_wool.png new file mode 100755 index 0000000..abc7999 Binary files /dev/null and b/client/src/main/resources/textures/blocks/white_wool.png differ diff --git a/client/src/main/resources/textures/blocks/yellow_glass.png b/client/src/main/resources/textures/blocks/yellow_glass.png new file mode 100755 index 0000000..8e48e12 Binary files /dev/null and b/client/src/main/resources/textures/blocks/yellow_glass.png differ diff --git a/client/src/main/resources/textures/blocks/yellow_glass_pane.png b/client/src/main/resources/textures/blocks/yellow_glass_pane.png new file mode 100755 index 0000000..1c8580f Binary files /dev/null and b/client/src/main/resources/textures/blocks/yellow_glass_pane.png differ diff --git a/client/src/main/resources/textures/blocks/yellow_stained_hardened_clay.png b/client/src/main/resources/textures/blocks/yellow_stained_hardened_clay.png new file mode 100755 index 0000000..5da4687 Binary files /dev/null and b/client/src/main/resources/textures/blocks/yellow_stained_hardened_clay.png differ diff --git a/client/src/main/resources/textures/blocks/yellow_wool.png b/client/src/main/resources/textures/blocks/yellow_wool.png new file mode 100755 index 0000000..4babaaa Binary files /dev/null and b/client/src/main/resources/textures/blocks/yellow_wool.png differ diff --git a/client/src/main/resources/textures/blocks/zinc_block.png b/client/src/main/resources/textures/blocks/zinc_block.png new file mode 100755 index 0000000..1d8b62c Binary files /dev/null and b/client/src/main/resources/textures/blocks/zinc_block.png differ diff --git a/client/src/main/resources/textures/blocks/zinc_ore.png b/client/src/main/resources/textures/blocks/zinc_ore.png new file mode 100755 index 0000000..1a696f3 Binary files /dev/null and b/client/src/main/resources/textures/blocks/zinc_ore.png differ diff --git a/client/src/main/resources/textures/entity/alucard_1.png b/client/src/main/resources/textures/entity/alucard_1.png new file mode 100755 index 0000000..dc84802 Binary files /dev/null and b/client/src/main/resources/textures/entity/alucard_1.png differ diff --git a/client/src/main/resources/textures/entity/alucard_2.png b/client/src/main/resources/textures/entity/alucard_2.png new file mode 100755 index 0000000..5ba72ff Binary files /dev/null and b/client/src/main/resources/textures/entity/alucard_2.png differ diff --git a/client/src/main/resources/textures/entity/arachnoid.png b/client/src/main/resources/textures/entity/arachnoid.png new file mode 100755 index 0000000..ae9d939 Binary files /dev/null and b/client/src/main/resources/textures/entity/arachnoid.png differ diff --git a/client/src/main/resources/textures/entity/arrow.png b/client/src/main/resources/textures/entity/arrow.png new file mode 100755 index 0000000..3afa604 Binary files /dev/null and b/client/src/main/resources/textures/entity/arrow.png differ diff --git a/client/src/main/resources/textures/entity/bat.png b/client/src/main/resources/textures/entity/bat.png new file mode 100755 index 0000000..803860e Binary files /dev/null and b/client/src/main/resources/textures/entity/bat.png differ diff --git a/client/src/main/resources/textures/entity/bloodelf.png b/client/src/main/resources/textures/entity/bloodelf.png new file mode 100755 index 0000000..d84ab98 Binary files /dev/null and b/client/src/main/resources/textures/entity/bloodelf.png differ diff --git a/client/src/main/resources/textures/entity/boat.png b/client/src/main/resources/textures/entity/boat.png new file mode 100755 index 0000000..9b58965 Binary files /dev/null and b/client/src/main/resources/textures/entity/boat.png differ diff --git a/client/src/main/resources/textures/entity/box.png b/client/src/main/resources/textures/entity/box.png new file mode 100755 index 0000000..707a8cd Binary files /dev/null and b/client/src/main/resources/textures/entity/box.png differ diff --git a/client/src/main/resources/textures/entity/box_brittle.png b/client/src/main/resources/textures/entity/box_brittle.png new file mode 100755 index 0000000..806cedb Binary files /dev/null and b/client/src/main/resources/textures/entity/box_brittle.png differ diff --git a/client/src/main/resources/textures/entity/bullet.png b/client/src/main/resources/textures/entity/bullet.png new file mode 100755 index 0000000..fe61c93 Binary files /dev/null and b/client/src/main/resources/textures/entity/bullet.png differ diff --git a/client/src/main/resources/textures/entity/cape_bloodelf.png b/client/src/main/resources/textures/entity/cape_bloodelf.png new file mode 100755 index 0000000..69d039d Binary files /dev/null and b/client/src/main/resources/textures/entity/cape_bloodelf.png differ diff --git a/client/src/main/resources/textures/entity/cat_black.png b/client/src/main/resources/textures/entity/cat_black.png new file mode 100755 index 0000000..422908f Binary files /dev/null and b/client/src/main/resources/textures/entity/cat_black.png differ diff --git a/client/src/main/resources/textures/entity/cat_ocelot.png b/client/src/main/resources/textures/entity/cat_ocelot.png new file mode 100755 index 0000000..6b5064e Binary files /dev/null and b/client/src/main/resources/textures/entity/cat_ocelot.png differ diff --git a/client/src/main/resources/textures/entity/cat_red.png b/client/src/main/resources/textures/entity/cat_red.png new file mode 100755 index 0000000..17b6de5 Binary files /dev/null and b/client/src/main/resources/textures/entity/cat_red.png differ diff --git a/client/src/main/resources/textures/entity/cat_siamese.png b/client/src/main/resources/textures/entity/cat_siamese.png new file mode 100755 index 0000000..cfed948 Binary files /dev/null and b/client/src/main/resources/textures/entity/cat_siamese.png differ diff --git a/client/src/main/resources/textures/entity/char.png b/client/src/main/resources/textures/entity/char.png new file mode 100755 index 0000000..54aa400 Binary files /dev/null and b/client/src/main/resources/textures/entity/char.png differ diff --git a/client/src/main/resources/textures/entity/charge.png b/client/src/main/resources/textures/entity/charge.png new file mode 100755 index 0000000..119f6ff Binary files /dev/null and b/client/src/main/resources/textures/entity/charge.png differ diff --git a/client/src/main/resources/textures/entity/chicken.png b/client/src/main/resources/textures/entity/chicken.png new file mode 100755 index 0000000..e24d550 Binary files /dev/null and b/client/src/main/resources/textures/entity/chicken.png differ diff --git a/client/src/main/resources/textures/entity/cow.png b/client/src/main/resources/textures/entity/cow.png new file mode 100755 index 0000000..f1320c3 Binary files /dev/null and b/client/src/main/resources/textures/entity/cow.png differ diff --git a/client/src/main/resources/textures/entity/crystal.png b/client/src/main/resources/textures/entity/crystal.png new file mode 100755 index 0000000..94ad169 Binary files /dev/null and b/client/src/main/resources/textures/entity/crystal.png differ diff --git a/client/src/main/resources/textures/entity/crystal_beam.png b/client/src/main/resources/textures/entity/crystal_beam.png new file mode 100755 index 0000000..1259a5d Binary files /dev/null and b/client/src/main/resources/textures/entity/crystal_beam.png differ diff --git a/client/src/main/resources/textures/entity/darkmage.png b/client/src/main/resources/textures/entity/darkmage.png new file mode 100755 index 0000000..7b9c894 Binary files /dev/null and b/client/src/main/resources/textures/entity/darkmage.png differ diff --git a/client/src/main/resources/textures/entity/donkey.png b/client/src/main/resources/textures/entity/donkey.png new file mode 100755 index 0000000..b94bc63 Binary files /dev/null and b/client/src/main/resources/textures/entity/donkey.png differ diff --git a/client/src/main/resources/textures/entity/dracula_1.png b/client/src/main/resources/textures/entity/dracula_1.png new file mode 100755 index 0000000..873e000 Binary files /dev/null and b/client/src/main/resources/textures/entity/dracula_1.png differ diff --git a/client/src/main/resources/textures/entity/dracula_2.png b/client/src/main/resources/textures/entity/dracula_2.png new file mode 100755 index 0000000..186359f Binary files /dev/null and b/client/src/main/resources/textures/entity/dracula_2.png differ diff --git a/client/src/main/resources/textures/entity/dracula_3.png b/client/src/main/resources/textures/entity/dracula_3.png new file mode 100755 index 0000000..26f2892 Binary files /dev/null and b/client/src/main/resources/textures/entity/dracula_3.png differ diff --git a/client/src/main/resources/textures/entity/dracula_4.png b/client/src/main/resources/textures/entity/dracula_4.png new file mode 100755 index 0000000..41a1b6f Binary files /dev/null and b/client/src/main/resources/textures/entity/dracula_4.png differ diff --git a/client/src/main/resources/textures/entity/dracula_5.png b/client/src/main/resources/textures/entity/dracula_5.png new file mode 100755 index 0000000..0e127de Binary files /dev/null and b/client/src/main/resources/textures/entity/dracula_5.png differ diff --git a/client/src/main/resources/textures/entity/dracula_6.png b/client/src/main/resources/textures/entity/dracula_6.png new file mode 100755 index 0000000..a57b625 Binary files /dev/null and b/client/src/main/resources/textures/entity/dracula_6.png differ diff --git a/client/src/main/resources/textures/entity/dragon.png b/client/src/main/resources/textures/entity/dragon.png new file mode 100755 index 0000000..b8a680c Binary files /dev/null and b/client/src/main/resources/textures/entity/dragon.png differ diff --git a/client/src/main/resources/textures/entity/dragon_eyes.png b/client/src/main/resources/textures/entity/dragon_eyes.png new file mode 100755 index 0000000..147b303 Binary files /dev/null and b/client/src/main/resources/textures/entity/dragon_eyes.png differ diff --git a/client/src/main/resources/textures/entity/dwarf.png b/client/src/main/resources/textures/entity/dwarf.png new file mode 100755 index 0000000..e72cf1a Binary files /dev/null and b/client/src/main/resources/textures/entity/dwarf.png differ diff --git a/client/src/main/resources/textures/entity/experience_orb.png b/client/src/main/resources/textures/entity/experience_orb.png new file mode 100755 index 0000000..92f9d0f Binary files /dev/null and b/client/src/main/resources/textures/entity/experience_orb.png differ diff --git a/client/src/main/resources/textures/entity/explosion.png b/client/src/main/resources/textures/entity/explosion.png new file mode 100755 index 0000000..c309409 Binary files /dev/null and b/client/src/main/resources/textures/entity/explosion.png differ diff --git a/client/src/main/resources/textures/entity/firedemon.png b/client/src/main/resources/textures/entity/firedemon.png new file mode 100755 index 0000000..a4d86f6 Binary files /dev/null and b/client/src/main/resources/textures/entity/firedemon.png differ diff --git a/client/src/main/resources/textures/entity/fox.png b/client/src/main/resources/textures/entity/fox.png new file mode 100755 index 0000000..61ee1a8 Binary files /dev/null and b/client/src/main/resources/textures/entity/fox.png differ diff --git a/client/src/main/resources/textures/entity/gargoyle.png b/client/src/main/resources/textures/entity/gargoyle.png new file mode 100755 index 0000000..069000e Binary files /dev/null and b/client/src/main/resources/textures/entity/gargoyle.png differ diff --git a/client/src/main/resources/textures/entity/goblin.png b/client/src/main/resources/textures/entity/goblin.png new file mode 100755 index 0000000..6ea2805 Binary files /dev/null and b/client/src/main/resources/textures/entity/goblin.png differ diff --git a/client/src/main/resources/textures/entity/hacker.png b/client/src/main/resources/textures/entity/hacker.png new file mode 100755 index 0000000..34beb80 Binary files /dev/null and b/client/src/main/resources/textures/entity/hacker.png differ diff --git a/client/src/main/resources/textures/entity/haunter.png b/client/src/main/resources/textures/entity/haunter.png new file mode 100755 index 0000000..4b2696b Binary files /dev/null and b/client/src/main/resources/textures/entity/haunter.png differ diff --git a/client/src/main/resources/textures/entity/herobrine.png b/client/src/main/resources/textures/entity/herobrine.png new file mode 100755 index 0000000..f2934fa Binary files /dev/null and b/client/src/main/resources/textures/entity/herobrine.png differ diff --git a/client/src/main/resources/textures/entity/highelf.png b/client/src/main/resources/textures/entity/highelf.png new file mode 100755 index 0000000..cc90ae2 Binary files /dev/null and b/client/src/main/resources/textures/entity/highelf.png differ diff --git a/client/src/main/resources/textures/entity/horse_black.png b/client/src/main/resources/textures/entity/horse_black.png new file mode 100755 index 0000000..dde716e Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_black.png differ diff --git a/client/src/main/resources/textures/entity/horse_brown.png b/client/src/main/resources/textures/entity/horse_brown.png new file mode 100755 index 0000000..ec0158f Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_brown.png differ diff --git a/client/src/main/resources/textures/entity/horse_chestnut.png b/client/src/main/resources/textures/entity/horse_chestnut.png new file mode 100755 index 0000000..40322ff Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_chestnut.png differ diff --git a/client/src/main/resources/textures/entity/horse_creamy.png b/client/src/main/resources/textures/entity/horse_creamy.png new file mode 100755 index 0000000..bc42bcc Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_creamy.png differ diff --git a/client/src/main/resources/textures/entity/horse_darkbrown.png b/client/src/main/resources/textures/entity/horse_darkbrown.png new file mode 100755 index 0000000..b38e914 Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_darkbrown.png differ diff --git a/client/src/main/resources/textures/entity/horse_gray.png b/client/src/main/resources/textures/entity/horse_gray.png new file mode 100755 index 0000000..4987532 Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_gray.png differ diff --git a/client/src/main/resources/textures/entity/horse_markings_blackdots.png b/client/src/main/resources/textures/entity/horse_markings_blackdots.png new file mode 100755 index 0000000..7320648 Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_markings_blackdots.png differ diff --git a/client/src/main/resources/textures/entity/horse_markings_white.png b/client/src/main/resources/textures/entity/horse_markings_white.png new file mode 100755 index 0000000..b1f0a69 Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_markings_white.png differ diff --git a/client/src/main/resources/textures/entity/horse_markings_whitedots.png b/client/src/main/resources/textures/entity/horse_markings_whitedots.png new file mode 100755 index 0000000..20e1954 Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_markings_whitedots.png differ diff --git a/client/src/main/resources/textures/entity/horse_markings_whitefield.png b/client/src/main/resources/textures/entity/horse_markings_whitefield.png new file mode 100755 index 0000000..baa2c06 Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_markings_whitefield.png differ diff --git a/client/src/main/resources/textures/entity/horse_skeleton.png b/client/src/main/resources/textures/entity/horse_skeleton.png new file mode 100755 index 0000000..29d4ed5 Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_skeleton.png differ diff --git a/client/src/main/resources/textures/entity/horse_white.png b/client/src/main/resources/textures/entity/horse_white.png new file mode 100755 index 0000000..e90e6e7 Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_white.png differ diff --git a/client/src/main/resources/textures/entity/horse_zombie.png b/client/src/main/resources/textures/entity/horse_zombie.png new file mode 100755 index 0000000..22d55fa Binary files /dev/null and b/client/src/main/resources/textures/entity/horse_zombie.png differ diff --git a/client/src/main/resources/textures/entity/jiang_cheng.png b/client/src/main/resources/textures/entity/jiang_cheng.png new file mode 100755 index 0000000..77f3dbe Binary files /dev/null and b/client/src/main/resources/textures/entity/jiang_cheng.png differ diff --git a/client/src/main/resources/textures/entity/knight_1.png b/client/src/main/resources/textures/entity/knight_1.png new file mode 100755 index 0000000..95e88b5 Binary files /dev/null and b/client/src/main/resources/textures/entity/knight_1.png differ diff --git a/client/src/main/resources/textures/entity/knight_2.png b/client/src/main/resources/textures/entity/knight_2.png new file mode 100755 index 0000000..6f40960 Binary files /dev/null and b/client/src/main/resources/textures/entity/knight_2.png differ diff --git a/client/src/main/resources/textures/entity/knight_3.png b/client/src/main/resources/textures/entity/knight_3.png new file mode 100755 index 0000000..75aecd4 Binary files /dev/null and b/client/src/main/resources/textures/entity/knight_3.png differ diff --git a/client/src/main/resources/textures/entity/knight_4.png b/client/src/main/resources/textures/entity/knight_4.png new file mode 100755 index 0000000..4628a9e Binary files /dev/null and b/client/src/main/resources/textures/entity/knight_4.png differ diff --git a/client/src/main/resources/textures/entity/knight_5.png b/client/src/main/resources/textures/entity/knight_5.png new file mode 100755 index 0000000..2594ebb Binary files /dev/null and b/client/src/main/resources/textures/entity/knight_5.png differ diff --git a/client/src/main/resources/textures/entity/knight_6.png b/client/src/main/resources/textures/entity/knight_6.png new file mode 100755 index 0000000..56a2faf Binary files /dev/null and b/client/src/main/resources/textures/entity/knight_6.png differ diff --git a/client/src/main/resources/textures/entity/knight_7.png b/client/src/main/resources/textures/entity/knight_7.png new file mode 100755 index 0000000..31d5612 Binary files /dev/null and b/client/src/main/resources/textures/entity/knight_7.png differ diff --git a/client/src/main/resources/textures/entity/knight_8.png b/client/src/main/resources/textures/entity/knight_8.png new file mode 100755 index 0000000..9920477 Binary files /dev/null and b/client/src/main/resources/textures/entity/knight_8.png differ diff --git a/client/src/main/resources/textures/entity/lan_wangji.png b/client/src/main/resources/textures/entity/lan_wangji.png new file mode 100755 index 0000000..d950a26 Binary files /dev/null and b/client/src/main/resources/textures/entity/lan_wangji.png differ diff --git a/client/src/main/resources/textures/entity/lead_knot.png b/client/src/main/resources/textures/entity/lead_knot.png new file mode 100755 index 0000000..ab4d3b3 Binary files /dev/null and b/client/src/main/resources/textures/entity/lead_knot.png differ diff --git a/client/src/main/resources/textures/entity/luo_binghe.png b/client/src/main/resources/textures/entity/luo_binghe.png new file mode 100755 index 0000000..ac18863 Binary files /dev/null and b/client/src/main/resources/textures/entity/luo_binghe.png differ diff --git a/client/src/main/resources/textures/entity/mage_1.png b/client/src/main/resources/textures/entity/mage_1.png new file mode 100755 index 0000000..bfd2698 Binary files /dev/null and b/client/src/main/resources/textures/entity/mage_1.png differ diff --git a/client/src/main/resources/textures/entity/mage_2.png b/client/src/main/resources/textures/entity/mage_2.png new file mode 100755 index 0000000..3540f15 Binary files /dev/null and b/client/src/main/resources/textures/entity/mage_2.png differ diff --git a/client/src/main/resources/textures/entity/mage_3.png b/client/src/main/resources/textures/entity/mage_3.png new file mode 100755 index 0000000..b7ea9ad Binary files /dev/null and b/client/src/main/resources/textures/entity/mage_3.png differ diff --git a/client/src/main/resources/textures/entity/mage_4.png b/client/src/main/resources/textures/entity/mage_4.png new file mode 100755 index 0000000..b4f997a Binary files /dev/null and b/client/src/main/resources/textures/entity/mage_4.png differ diff --git a/client/src/main/resources/textures/entity/mage_5.png b/client/src/main/resources/textures/entity/mage_5.png new file mode 100755 index 0000000..12111f7 Binary files /dev/null and b/client/src/main/resources/textures/entity/mage_5.png differ diff --git a/client/src/main/resources/textures/entity/mage_6.png b/client/src/main/resources/textures/entity/mage_6.png new file mode 100755 index 0000000..b84d670 Binary files /dev/null and b/client/src/main/resources/textures/entity/mage_6.png differ diff --git a/client/src/main/resources/textures/entity/magma.png b/client/src/main/resources/textures/entity/magma.png new file mode 100755 index 0000000..20f0dd6 Binary files /dev/null and b/client/src/main/resources/textures/entity/magma.png differ diff --git a/client/src/main/resources/textures/entity/marine.png b/client/src/main/resources/textures/entity/marine.png new file mode 100755 index 0000000..29a53f3 Binary files /dev/null and b/client/src/main/resources/textures/entity/marine.png differ diff --git a/client/src/main/resources/textures/entity/marine_black_templar.png b/client/src/main/resources/textures/entity/marine_black_templar.png new file mode 100755 index 0000000..1d2392c Binary files /dev/null and b/client/src/main/resources/textures/entity/marine_black_templar.png differ diff --git a/client/src/main/resources/textures/entity/metalhead.png b/client/src/main/resources/textures/entity/metalhead.png new file mode 100755 index 0000000..dd94a82 Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_1.png b/client/src/main/resources/textures/entity/metalhead_1.png new file mode 100755 index 0000000..f015fb5 Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_1.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_10.png b/client/src/main/resources/textures/entity/metalhead_10.png new file mode 100755 index 0000000..db8f206 Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_10.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_11.png b/client/src/main/resources/textures/entity/metalhead_11.png new file mode 100755 index 0000000..05e9c9e Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_11.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_12.png b/client/src/main/resources/textures/entity/metalhead_12.png new file mode 100755 index 0000000..c9ff664 Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_12.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_13.png b/client/src/main/resources/textures/entity/metalhead_13.png new file mode 100755 index 0000000..3694463 Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_13.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_14.png b/client/src/main/resources/textures/entity/metalhead_14.png new file mode 100755 index 0000000..aae134a Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_14.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_2.png b/client/src/main/resources/textures/entity/metalhead_2.png new file mode 100755 index 0000000..eb1078c Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_2.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_3.png b/client/src/main/resources/textures/entity/metalhead_3.png new file mode 100755 index 0000000..1426644 Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_3.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_4.png b/client/src/main/resources/textures/entity/metalhead_4.png new file mode 100755 index 0000000..dadacd3 Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_4.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_5.png b/client/src/main/resources/textures/entity/metalhead_5.png new file mode 100755 index 0000000..b3149ae Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_5.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_6.png b/client/src/main/resources/textures/entity/metalhead_6.png new file mode 100755 index 0000000..177f4d8 Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_6.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_7.png b/client/src/main/resources/textures/entity/metalhead_7.png new file mode 100755 index 0000000..422a5a4 Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_7.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_8.png b/client/src/main/resources/textures/entity/metalhead_8.png new file mode 100755 index 0000000..f54ef56 Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_8.png differ diff --git a/client/src/main/resources/textures/entity/metalhead_9.png b/client/src/main/resources/textures/entity/metalhead_9.png new file mode 100755 index 0000000..363da10 Binary files /dev/null and b/client/src/main/resources/textures/entity/metalhead_9.png differ diff --git a/client/src/main/resources/textures/entity/minecart.png b/client/src/main/resources/textures/entity/minecart.png new file mode 100755 index 0000000..7ad7b54 Binary files /dev/null and b/client/src/main/resources/textures/entity/minecart.png differ diff --git a/client/src/main/resources/textures/entity/mooshroom.png b/client/src/main/resources/textures/entity/mooshroom.png new file mode 100755 index 0000000..3d68286 Binary files /dev/null and b/client/src/main/resources/textures/entity/mooshroom.png differ diff --git a/client/src/main/resources/textures/entity/mouse.png b/client/src/main/resources/textures/entity/mouse.png new file mode 100755 index 0000000..f916857 Binary files /dev/null and b/client/src/main/resources/textures/entity/mouse.png differ diff --git a/client/src/main/resources/textures/entity/mule.png b/client/src/main/resources/textures/entity/mule.png new file mode 100755 index 0000000..241bdaa Binary files /dev/null and b/client/src/main/resources/textures/entity/mule.png differ diff --git a/client/src/main/resources/textures/entity/orc_1.png b/client/src/main/resources/textures/entity/orc_1.png new file mode 100755 index 0000000..5dcd58f Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_1.png differ diff --git a/client/src/main/resources/textures/entity/orc_10.png b/client/src/main/resources/textures/entity/orc_10.png new file mode 100755 index 0000000..688d918 Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_10.png differ diff --git a/client/src/main/resources/textures/entity/orc_11.png b/client/src/main/resources/textures/entity/orc_11.png new file mode 100755 index 0000000..e5f1651 Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_11.png differ diff --git a/client/src/main/resources/textures/entity/orc_12.png b/client/src/main/resources/textures/entity/orc_12.png new file mode 100755 index 0000000..8fb304e Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_12.png differ diff --git a/client/src/main/resources/textures/entity/orc_2.png b/client/src/main/resources/textures/entity/orc_2.png new file mode 100755 index 0000000..bdfa7eb Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_2.png differ diff --git a/client/src/main/resources/textures/entity/orc_3.png b/client/src/main/resources/textures/entity/orc_3.png new file mode 100755 index 0000000..4f1e74d Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_3.png differ diff --git a/client/src/main/resources/textures/entity/orc_4.png b/client/src/main/resources/textures/entity/orc_4.png new file mode 100755 index 0000000..c21e646 Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_4.png differ diff --git a/client/src/main/resources/textures/entity/orc_5.png b/client/src/main/resources/textures/entity/orc_5.png new file mode 100755 index 0000000..016a69c Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_5.png differ diff --git a/client/src/main/resources/textures/entity/orc_6.png b/client/src/main/resources/textures/entity/orc_6.png new file mode 100755 index 0000000..e1564fc Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_6.png differ diff --git a/client/src/main/resources/textures/entity/orc_7.png b/client/src/main/resources/textures/entity/orc_7.png new file mode 100755 index 0000000..3812f0f Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_7.png differ diff --git a/client/src/main/resources/textures/entity/orc_8.png b/client/src/main/resources/textures/entity/orc_8.png new file mode 100755 index 0000000..969fc54 Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_8.png differ diff --git a/client/src/main/resources/textures/entity/orc_9.png b/client/src/main/resources/textures/entity/orc_9.png new file mode 100755 index 0000000..305bfef Binary files /dev/null and b/client/src/main/resources/textures/entity/orc_9.png differ diff --git a/client/src/main/resources/textures/entity/peasant_1.png b/client/src/main/resources/textures/entity/peasant_1.png new file mode 100755 index 0000000..e5bd7ae Binary files /dev/null and b/client/src/main/resources/textures/entity/peasant_1.png differ diff --git a/client/src/main/resources/textures/entity/peasant_2.png b/client/src/main/resources/textures/entity/peasant_2.png new file mode 100755 index 0000000..d7ad244 Binary files /dev/null and b/client/src/main/resources/textures/entity/peasant_2.png differ diff --git a/client/src/main/resources/textures/entity/peasant_3.png b/client/src/main/resources/textures/entity/peasant_3.png new file mode 100755 index 0000000..5896c0b Binary files /dev/null and b/client/src/main/resources/textures/entity/peasant_3.png differ diff --git a/client/src/main/resources/textures/entity/peasant_4.png b/client/src/main/resources/textures/entity/peasant_4.png new file mode 100755 index 0000000..5d0510b Binary files /dev/null and b/client/src/main/resources/textures/entity/peasant_4.png differ diff --git a/client/src/main/resources/textures/entity/peasant_5.png b/client/src/main/resources/textures/entity/peasant_5.png new file mode 100755 index 0000000..ff8a65c Binary files /dev/null and b/client/src/main/resources/textures/entity/peasant_5.png differ diff --git a/client/src/main/resources/textures/entity/peasant_6.png b/client/src/main/resources/textures/entity/peasant_6.png new file mode 100755 index 0000000..9d482e0 Binary files /dev/null and b/client/src/main/resources/textures/entity/peasant_6.png differ diff --git a/client/src/main/resources/textures/entity/pig.png b/client/src/main/resources/textures/entity/pig.png new file mode 100755 index 0000000..0a9532f Binary files /dev/null and b/client/src/main/resources/textures/entity/pig.png differ diff --git a/client/src/main/resources/textures/entity/pig_saddle.png b/client/src/main/resources/textures/entity/pig_saddle.png new file mode 100755 index 0000000..640ea76 Binary files /dev/null and b/client/src/main/resources/textures/entity/pig_saddle.png differ diff --git a/client/src/main/resources/textures/entity/power_rod.png b/client/src/main/resources/textures/entity/power_rod.png new file mode 100755 index 0000000..ef61249 Binary files /dev/null and b/client/src/main/resources/textures/entity/power_rod.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_black.png b/client/src/main/resources/textures/entity/rabbit_black.png new file mode 100755 index 0000000..1203cb9 Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_black.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_black_splotched.png b/client/src/main/resources/textures/entity/rabbit_black_splotched.png new file mode 100755 index 0000000..d5e626b Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_black_splotched.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_brown.png b/client/src/main/resources/textures/entity/rabbit_brown.png new file mode 100755 index 0000000..ffa0870 Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_brown.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_caerbannog.png b/client/src/main/resources/textures/entity/rabbit_caerbannog.png new file mode 100755 index 0000000..778bfc7 Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_caerbannog.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_dark.png b/client/src/main/resources/textures/entity/rabbit_dark.png new file mode 100755 index 0000000..e97f4d8 Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_dark.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_dark_gray.png b/client/src/main/resources/textures/entity/rabbit_dark_gray.png new file mode 100755 index 0000000..d0524f4 Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_dark_gray.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_gold.png b/client/src/main/resources/textures/entity/rabbit_gold.png new file mode 100755 index 0000000..595e6f7 Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_gold.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_gray.png b/client/src/main/resources/textures/entity/rabbit_gray.png new file mode 100755 index 0000000..66ee205 Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_gray.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_salt.png b/client/src/main/resources/textures/entity/rabbit_salt.png new file mode 100755 index 0000000..2232ef0 Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_salt.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_toast.png b/client/src/main/resources/textures/entity/rabbit_toast.png new file mode 100755 index 0000000..b1bb70d Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_toast.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_white.png b/client/src/main/resources/textures/entity/rabbit_white.png new file mode 100755 index 0000000..bb6cd9e Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_white.png differ diff --git a/client/src/main/resources/textures/entity/rabbit_white_splotched.png b/client/src/main/resources/textures/entity/rabbit_white_splotched.png new file mode 100755 index 0000000..196ac00 Binary files /dev/null and b/client/src/main/resources/textures/entity/rabbit_white_splotched.png differ diff --git a/client/src/main/resources/textures/entity/sen.png b/client/src/main/resources/textures/entity/sen.png new file mode 100755 index 0000000..df769e3 Binary files /dev/null and b/client/src/main/resources/textures/entity/sen.png differ diff --git a/client/src/main/resources/textures/entity/sheep.png b/client/src/main/resources/textures/entity/sheep.png new file mode 100755 index 0000000..d9fe93f Binary files /dev/null and b/client/src/main/resources/textures/entity/sheep.png differ diff --git a/client/src/main/resources/textures/entity/sheep_fur.png b/client/src/main/resources/textures/entity/sheep_fur.png new file mode 100755 index 0000000..623340b Binary files /dev/null and b/client/src/main/resources/textures/entity/sheep_fur.png differ diff --git a/client/src/main/resources/textures/entity/shen_qingqiu.png b/client/src/main/resources/textures/entity/shen_qingqiu.png new file mode 100755 index 0000000..298ed46 Binary files /dev/null and b/client/src/main/resources/textures/entity/shen_qingqiu.png differ diff --git a/client/src/main/resources/textures/entity/skull.png b/client/src/main/resources/textures/entity/skull.png new file mode 100755 index 0000000..98b76c7 Binary files /dev/null and b/client/src/main/resources/textures/entity/skull.png differ diff --git a/client/src/main/resources/textures/entity/slime.png b/client/src/main/resources/textures/entity/slime.png new file mode 100755 index 0000000..96edcf6 Binary files /dev/null and b/client/src/main/resources/textures/entity/slime.png differ diff --git a/client/src/main/resources/textures/entity/spirit.png b/client/src/main/resources/textures/entity/spirit.png new file mode 100755 index 0000000..f50ba0a Binary files /dev/null and b/client/src/main/resources/textures/entity/spirit.png differ diff --git a/client/src/main/resources/textures/entity/squid.png b/client/src/main/resources/textures/entity/squid.png new file mode 100755 index 0000000..f285388 Binary files /dev/null and b/client/src/main/resources/textures/entity/squid.png differ diff --git a/client/src/main/resources/textures/entity/thranduil.png b/client/src/main/resources/textures/entity/thranduil.png new file mode 100755 index 0000000..cbf1a9c Binary files /dev/null and b/client/src/main/resources/textures/entity/thranduil.png differ diff --git a/client/src/main/resources/textures/entity/tiefling.png b/client/src/main/resources/textures/entity/tiefling.png new file mode 100755 index 0000000..85eddec Binary files /dev/null and b/client/src/main/resources/textures/entity/tiefling.png differ diff --git a/client/src/main/resources/textures/entity/trollface.png b/client/src/main/resources/textures/entity/trollface.png new file mode 100755 index 0000000..dd8da12 Binary files /dev/null and b/client/src/main/resources/textures/entity/trollface.png differ diff --git a/client/src/main/resources/textures/entity/undead_1.png b/client/src/main/resources/textures/entity/undead_1.png new file mode 100755 index 0000000..68de7d5 Binary files /dev/null and b/client/src/main/resources/textures/entity/undead_1.png differ diff --git a/client/src/main/resources/textures/entity/undead_2.png b/client/src/main/resources/textures/entity/undead_2.png new file mode 100755 index 0000000..a99da35 Binary files /dev/null and b/client/src/main/resources/textures/entity/undead_2.png differ diff --git a/client/src/main/resources/textures/entity/undead_3.png b/client/src/main/resources/textures/entity/undead_3.png new file mode 100755 index 0000000..a841c5d Binary files /dev/null and b/client/src/main/resources/textures/entity/undead_3.png differ diff --git a/client/src/main/resources/textures/entity/undead_4.png b/client/src/main/resources/textures/entity/undead_4.png new file mode 100755 index 0000000..69dc132 Binary files /dev/null and b/client/src/main/resources/textures/entity/undead_4.png differ diff --git a/client/src/main/resources/textures/entity/unknown.png b/client/src/main/resources/textures/entity/unknown.png new file mode 100755 index 0000000..a2b5aad Binary files /dev/null and b/client/src/main/resources/textures/entity/unknown.png differ diff --git a/client/src/main/resources/textures/entity/vampire_1.png b/client/src/main/resources/textures/entity/vampire_1.png new file mode 100755 index 0000000..db3537e Binary files /dev/null and b/client/src/main/resources/textures/entity/vampire_1.png differ diff --git a/client/src/main/resources/textures/entity/vampire_2.png b/client/src/main/resources/textures/entity/vampire_2.png new file mode 100755 index 0000000..86ef231 Binary files /dev/null and b/client/src/main/resources/textures/entity/vampire_2.png differ diff --git a/client/src/main/resources/textures/entity/vampire_3.png b/client/src/main/resources/textures/entity/vampire_3.png new file mode 100755 index 0000000..b2b20df Binary files /dev/null and b/client/src/main/resources/textures/entity/vampire_3.png differ diff --git a/client/src/main/resources/textures/entity/vampire_4.png b/client/src/main/resources/textures/entity/vampire_4.png new file mode 100755 index 0000000..bee7d07 Binary files /dev/null and b/client/src/main/resources/textures/entity/vampire_4.png differ diff --git a/client/src/main/resources/textures/entity/vampire_5.png b/client/src/main/resources/textures/entity/vampire_5.png new file mode 100755 index 0000000..f6e1e30 Binary files /dev/null and b/client/src/main/resources/textures/entity/vampire_5.png differ diff --git a/client/src/main/resources/textures/entity/vampire_6.png b/client/src/main/resources/textures/entity/vampire_6.png new file mode 100755 index 0000000..91c15a7 Binary files /dev/null and b/client/src/main/resources/textures/entity/vampire_6.png differ diff --git a/client/src/main/resources/textures/entity/vampire_7.png b/client/src/main/resources/textures/entity/vampire_7.png new file mode 100755 index 0000000..ba901a9 Binary files /dev/null and b/client/src/main/resources/textures/entity/vampire_7.png differ diff --git a/client/src/main/resources/textures/entity/vampire_8.png b/client/src/main/resources/textures/entity/vampire_8.png new file mode 100755 index 0000000..e4023cb Binary files /dev/null and b/client/src/main/resources/textures/entity/vampire_8.png differ diff --git a/client/src/main/resources/textures/entity/wei_wuxian.png b/client/src/main/resources/textures/entity/wei_wuxian.png new file mode 100755 index 0000000..763fe53 Binary files /dev/null and b/client/src/main/resources/textures/entity/wei_wuxian.png differ diff --git a/client/src/main/resources/textures/entity/wolf.png b/client/src/main/resources/textures/entity/wolf.png new file mode 100755 index 0000000..f37ef81 Binary files /dev/null and b/client/src/main/resources/textures/entity/wolf.png differ diff --git a/client/src/main/resources/textures/entity/wolf_angry.png b/client/src/main/resources/textures/entity/wolf_angry.png new file mode 100755 index 0000000..7891ce9 Binary files /dev/null and b/client/src/main/resources/textures/entity/wolf_angry.png differ diff --git a/client/src/main/resources/textures/entity/wolf_collar.png b/client/src/main/resources/textures/entity/wolf_collar.png new file mode 100755 index 0000000..ae1c920 Binary files /dev/null and b/client/src/main/resources/textures/entity/wolf_collar.png differ diff --git a/client/src/main/resources/textures/entity/wolf_tame.png b/client/src/main/resources/textures/entity/wolf_tame.png new file mode 100755 index 0000000..f1236d2 Binary files /dev/null and b/client/src/main/resources/textures/entity/wolf_tame.png differ diff --git a/client/src/main/resources/textures/entity/woodelf.png b/client/src/main/resources/textures/entity/woodelf.png new file mode 100755 index 0000000..38f1f64 Binary files /dev/null and b/client/src/main/resources/textures/entity/woodelf.png differ diff --git a/client/src/main/resources/textures/entity/zombie_1.png b/client/src/main/resources/textures/entity/zombie_1.png new file mode 100755 index 0000000..f1624f8 Binary files /dev/null and b/client/src/main/resources/textures/entity/zombie_1.png differ diff --git a/client/src/main/resources/textures/entity/zombie_2.png b/client/src/main/resources/textures/entity/zombie_2.png new file mode 100755 index 0000000..2560175 Binary files /dev/null and b/client/src/main/resources/textures/entity/zombie_2.png differ diff --git a/client/src/main/resources/textures/entity/zombie_3.png b/client/src/main/resources/textures/entity/zombie_3.png new file mode 100755 index 0000000..88f490f Binary files /dev/null and b/client/src/main/resources/textures/entity/zombie_3.png differ diff --git a/client/src/main/resources/textures/entity/zombie_4.png b/client/src/main/resources/textures/entity/zombie_4.png new file mode 100755 index 0000000..e2572ca Binary files /dev/null and b/client/src/main/resources/textures/entity/zombie_4.png differ diff --git a/client/src/main/resources/textures/entity/zombie_5.png b/client/src/main/resources/textures/entity/zombie_5.png new file mode 100755 index 0000000..3e61dc0 Binary files /dev/null and b/client/src/main/resources/textures/entity/zombie_5.png differ diff --git a/client/src/main/resources/textures/entity/zombie_6.png b/client/src/main/resources/textures/entity/zombie_6.png new file mode 100755 index 0000000..65d110d Binary files /dev/null and b/client/src/main/resources/textures/entity/zombie_6.png differ diff --git a/client/src/main/resources/textures/font.png b/client/src/main/resources/textures/font.png new file mode 100644 index 0000000..a100b48 Binary files /dev/null and b/client/src/main/resources/textures/font.png differ diff --git a/client/src/main/resources/textures/font_tiny.png b/client/src/main/resources/textures/font_tiny.png new file mode 100644 index 0000000..3d1c6d9 Binary files /dev/null and b/client/src/main/resources/textures/font_tiny.png differ diff --git a/client/src/main/resources/textures/glint.png b/client/src/main/resources/textures/glint.png new file mode 100755 index 0000000..f9ca97c Binary files /dev/null and b/client/src/main/resources/textures/glint.png differ diff --git a/client/src/main/resources/textures/items/acacia_door.png b/client/src/main/resources/textures/items/acacia_door.png new file mode 100755 index 0000000..c903484 Binary files /dev/null and b/client/src/main/resources/textures/items/acacia_door.png differ diff --git a/client/src/main/resources/textures/items/acid_bucket.png b/client/src/main/resources/textures/items/acid_bucket.png new file mode 100755 index 0000000..b193778 Binary files /dev/null and b/client/src/main/resources/textures/items/acid_bucket.png differ diff --git a/client/src/main/resources/textures/items/ahrd_fragment.png b/client/src/main/resources/textures/items/ahrd_fragment.png new file mode 100755 index 0000000..ae6872c Binary files /dev/null and b/client/src/main/resources/textures/items/ahrd_fragment.png differ diff --git a/client/src/main/resources/textures/items/aluminium_ingot.png b/client/src/main/resources/textures/items/aluminium_ingot.png new file mode 100755 index 0000000..00918f1 Binary files /dev/null and b/client/src/main/resources/textures/items/aluminium_ingot.png differ diff --git a/client/src/main/resources/textures/items/antimony_powder.png b/client/src/main/resources/textures/items/antimony_powder.png new file mode 100755 index 0000000..1e789ab Binary files /dev/null and b/client/src/main/resources/textures/items/antimony_powder.png differ diff --git a/client/src/main/resources/textures/items/apple.png b/client/src/main/resources/textures/items/apple.png new file mode 100755 index 0000000..6f908bb Binary files /dev/null and b/client/src/main/resources/textures/items/apple.png differ diff --git a/client/src/main/resources/textures/items/ardite_boots.png b/client/src/main/resources/textures/items/ardite_boots.png new file mode 100755 index 0000000..9ec9196 Binary files /dev/null and b/client/src/main/resources/textures/items/ardite_boots.png differ diff --git a/client/src/main/resources/textures/items/ardite_chestplate.png b/client/src/main/resources/textures/items/ardite_chestplate.png new file mode 100755 index 0000000..6c19842 Binary files /dev/null and b/client/src/main/resources/textures/items/ardite_chestplate.png differ diff --git a/client/src/main/resources/textures/items/ardite_helmet.png b/client/src/main/resources/textures/items/ardite_helmet.png new file mode 100755 index 0000000..c74ed53 Binary files /dev/null and b/client/src/main/resources/textures/items/ardite_helmet.png differ diff --git a/client/src/main/resources/textures/items/ardite_leggings.png b/client/src/main/resources/textures/items/ardite_leggings.png new file mode 100755 index 0000000..b531357 Binary files /dev/null and b/client/src/main/resources/textures/items/ardite_leggings.png differ diff --git a/client/src/main/resources/textures/items/ardite_sword.png b/client/src/main/resources/textures/items/ardite_sword.png new file mode 100755 index 0000000..f806379 Binary files /dev/null and b/client/src/main/resources/textures/items/ardite_sword.png differ diff --git a/client/src/main/resources/textures/items/arrow.png b/client/src/main/resources/textures/items/arrow.png new file mode 100755 index 0000000..4f748a0 Binary files /dev/null and b/client/src/main/resources/textures/items/arrow.png differ diff --git a/client/src/main/resources/textures/items/arsenic_powder.png b/client/src/main/resources/textures/items/arsenic_powder.png new file mode 100755 index 0000000..670d1ac Binary files /dev/null and b/client/src/main/resources/textures/items/arsenic_powder.png differ diff --git a/client/src/main/resources/textures/items/baked_potato.png b/client/src/main/resources/textures/items/baked_potato.png new file mode 100755 index 0000000..e4d765b Binary files /dev/null and b/client/src/main/resources/textures/items/baked_potato.png differ diff --git a/client/src/main/resources/textures/items/banhammer.png b/client/src/main/resources/textures/items/banhammer.png new file mode 100755 index 0000000..674391b Binary files /dev/null and b/client/src/main/resources/textures/items/banhammer.png differ diff --git a/client/src/main/resources/textures/items/beef.png b/client/src/main/resources/textures/items/beef.png new file mode 100755 index 0000000..c9ab891 Binary files /dev/null and b/client/src/main/resources/textures/items/beef.png differ diff --git a/client/src/main/resources/textures/items/birch_door.png b/client/src/main/resources/textures/items/birch_door.png new file mode 100755 index 0000000..7c88c41 Binary files /dev/null and b/client/src/main/resources/textures/items/birch_door.png differ diff --git a/client/src/main/resources/textures/items/bismuth_ingot.png b/client/src/main/resources/textures/items/bismuth_ingot.png new file mode 100755 index 0000000..f2db74b Binary files /dev/null and b/client/src/main/resources/textures/items/bismuth_ingot.png differ diff --git a/client/src/main/resources/textures/items/black_bed.png b/client/src/main/resources/textures/items/black_bed.png new file mode 100755 index 0000000..b1dea4b Binary files /dev/null and b/client/src/main/resources/textures/items/black_bed.png differ diff --git a/client/src/main/resources/textures/items/black_metal_ingot.png b/client/src/main/resources/textures/items/black_metal_ingot.png new file mode 100755 index 0000000..ecd0a75 Binary files /dev/null and b/client/src/main/resources/textures/items/black_metal_ingot.png differ diff --git a/client/src/main/resources/textures/items/black_quartz.png b/client/src/main/resources/textures/items/black_quartz.png new file mode 100755 index 0000000..67a0ec8 Binary files /dev/null and b/client/src/main/resources/textures/items/black_quartz.png differ diff --git a/client/src/main/resources/textures/items/blackbrick.png b/client/src/main/resources/textures/items/blackbrick.png new file mode 100755 index 0000000..63839ad Binary files /dev/null and b/client/src/main/resources/textures/items/blackbrick.png differ diff --git a/client/src/main/resources/textures/items/blackwood_door.png b/client/src/main/resources/textures/items/blackwood_door.png new file mode 100755 index 0000000..7f44747 Binary files /dev/null and b/client/src/main/resources/textures/items/blackwood_door.png differ diff --git a/client/src/main/resources/textures/items/blaze_powder.png b/client/src/main/resources/textures/items/blaze_powder.png new file mode 100755 index 0000000..89c57d6 Binary files /dev/null and b/client/src/main/resources/textures/items/blaze_powder.png differ diff --git a/client/src/main/resources/textures/items/blaze_rod.png b/client/src/main/resources/textures/items/blaze_rod.png new file mode 100755 index 0000000..7050e10 Binary files /dev/null and b/client/src/main/resources/textures/items/blaze_rod.png differ diff --git a/client/src/main/resources/textures/items/blood_bucket.png b/client/src/main/resources/textures/items/blood_bucket.png new file mode 100755 index 0000000..793c5bc Binary files /dev/null and b/client/src/main/resources/textures/items/blood_bucket.png differ diff --git a/client/src/main/resources/textures/items/bloodbrick.png b/client/src/main/resources/textures/items/bloodbrick.png new file mode 100755 index 0000000..e9c14ed Binary files /dev/null and b/client/src/main/resources/textures/items/bloodbrick.png differ diff --git a/client/src/main/resources/textures/items/boat.png b/client/src/main/resources/textures/items/boat.png new file mode 100755 index 0000000..235e0a2 Binary files /dev/null and b/client/src/main/resources/textures/items/boat.png differ diff --git a/client/src/main/resources/textures/items/bolt.png b/client/src/main/resources/textures/items/bolt.png new file mode 100755 index 0000000..665dcf2 Binary files /dev/null and b/client/src/main/resources/textures/items/bolt.png differ diff --git a/client/src/main/resources/textures/items/boltgun.png b/client/src/main/resources/textures/items/boltgun.png new file mode 100755 index 0000000..096094a Binary files /dev/null and b/client/src/main/resources/textures/items/boltgun.png differ diff --git a/client/src/main/resources/textures/items/bone.png b/client/src/main/resources/textures/items/bone.png new file mode 100755 index 0000000..3faca89 Binary files /dev/null and b/client/src/main/resources/textures/items/bone.png differ diff --git a/client/src/main/resources/textures/items/book.png b/client/src/main/resources/textures/items/book.png new file mode 100755 index 0000000..f791ae4 Binary files /dev/null and b/client/src/main/resources/textures/items/book.png differ diff --git a/client/src/main/resources/textures/items/bow.png b/client/src/main/resources/textures/items/bow.png new file mode 100755 index 0000000..d709b9c Binary files /dev/null and b/client/src/main/resources/textures/items/bow.png differ diff --git a/client/src/main/resources/textures/items/bow_pulling_0.png b/client/src/main/resources/textures/items/bow_pulling_0.png new file mode 100755 index 0000000..2022aab Binary files /dev/null and b/client/src/main/resources/textures/items/bow_pulling_0.png differ diff --git a/client/src/main/resources/textures/items/bow_pulling_1.png b/client/src/main/resources/textures/items/bow_pulling_1.png new file mode 100755 index 0000000..a132079 Binary files /dev/null and b/client/src/main/resources/textures/items/bow_pulling_1.png differ diff --git a/client/src/main/resources/textures/items/bow_pulling_2.png b/client/src/main/resources/textures/items/bow_pulling_2.png new file mode 100755 index 0000000..d459e68 Binary files /dev/null and b/client/src/main/resources/textures/items/bow_pulling_2.png differ diff --git a/client/src/main/resources/textures/items/bowl.png b/client/src/main/resources/textures/items/bowl.png new file mode 100755 index 0000000..63d16ad Binary files /dev/null and b/client/src/main/resources/textures/items/bowl.png differ diff --git a/client/src/main/resources/textures/items/bread.png b/client/src/main/resources/textures/items/bread.png new file mode 100755 index 0000000..5a28f14 Binary files /dev/null and b/client/src/main/resources/textures/items/bread.png differ diff --git a/client/src/main/resources/textures/items/brewing_stand.png b/client/src/main/resources/textures/items/brewing_stand.png new file mode 100755 index 0000000..97db9af Binary files /dev/null and b/client/src/main/resources/textures/items/brewing_stand.png differ diff --git a/client/src/main/resources/textures/items/brick.png b/client/src/main/resources/textures/items/brick.png new file mode 100755 index 0000000..11e74be Binary files /dev/null and b/client/src/main/resources/textures/items/brick.png differ diff --git a/client/src/main/resources/textures/items/bucket.png b/client/src/main/resources/textures/items/bucket.png new file mode 100755 index 0000000..f8e5369 Binary files /dev/null and b/client/src/main/resources/textures/items/bucket.png differ diff --git a/client/src/main/resources/textures/items/burning_soul.png b/client/src/main/resources/textures/items/burning_soul.png new file mode 100755 index 0000000..924cc58 Binary files /dev/null and b/client/src/main/resources/textures/items/burning_soul.png differ diff --git a/client/src/main/resources/textures/items/cake.png b/client/src/main/resources/textures/items/cake.png new file mode 100755 index 0000000..46e94b8 Binary files /dev/null and b/client/src/main/resources/textures/items/cake.png differ diff --git a/client/src/main/resources/textures/items/calcium_powder.png b/client/src/main/resources/textures/items/calcium_powder.png new file mode 100755 index 0000000..1e13afe Binary files /dev/null and b/client/src/main/resources/textures/items/calcium_powder.png differ diff --git a/client/src/main/resources/textures/items/camera.png b/client/src/main/resources/textures/items/camera.png new file mode 100755 index 0000000..3ab9d10 Binary files /dev/null and b/client/src/main/resources/textures/items/camera.png differ diff --git a/client/src/main/resources/textures/items/carrot.png b/client/src/main/resources/textures/items/carrot.png new file mode 100755 index 0000000..2d08aab Binary files /dev/null and b/client/src/main/resources/textures/items/carrot.png differ diff --git a/client/src/main/resources/textures/items/carrot_on_a_stick.png b/client/src/main/resources/textures/items/carrot_on_a_stick.png new file mode 100755 index 0000000..9e88571 Binary files /dev/null and b/client/src/main/resources/textures/items/carrot_on_a_stick.png differ diff --git a/client/src/main/resources/textures/items/cauldron.png b/client/src/main/resources/textures/items/cauldron.png new file mode 100755 index 0000000..e3186eb Binary files /dev/null and b/client/src/main/resources/textures/items/cauldron.png differ diff --git a/client/src/main/resources/textures/items/chain.png b/client/src/main/resources/textures/items/chain.png new file mode 100755 index 0000000..f80079d Binary files /dev/null and b/client/src/main/resources/textures/items/chain.png differ diff --git a/client/src/main/resources/textures/items/chain_boots.png b/client/src/main/resources/textures/items/chain_boots.png new file mode 100755 index 0000000..54a4a15 Binary files /dev/null and b/client/src/main/resources/textures/items/chain_boots.png differ diff --git a/client/src/main/resources/textures/items/chain_chestplate.png b/client/src/main/resources/textures/items/chain_chestplate.png new file mode 100755 index 0000000..cd2115a Binary files /dev/null and b/client/src/main/resources/textures/items/chain_chestplate.png differ diff --git a/client/src/main/resources/textures/items/chain_helmet.png b/client/src/main/resources/textures/items/chain_helmet.png new file mode 100755 index 0000000..a143338 Binary files /dev/null and b/client/src/main/resources/textures/items/chain_helmet.png differ diff --git a/client/src/main/resources/textures/items/chain_leggings.png b/client/src/main/resources/textures/items/chain_leggings.png new file mode 100755 index 0000000..dae4b26 Binary files /dev/null and b/client/src/main/resources/textures/items/chain_leggings.png differ diff --git a/client/src/main/resources/textures/items/charcoal.png b/client/src/main/resources/textures/items/charcoal.png new file mode 100755 index 0000000..20d5b25 Binary files /dev/null and b/client/src/main/resources/textures/items/charcoal.png differ diff --git a/client/src/main/resources/textures/items/charge_crystal.png b/client/src/main/resources/textures/items/charge_crystal.png new file mode 100755 index 0000000..1e03365 Binary files /dev/null and b/client/src/main/resources/textures/items/charge_crystal.png differ diff --git a/client/src/main/resources/textures/items/charged_orb.png b/client/src/main/resources/textures/items/charged_orb.png new file mode 100755 index 0000000..75d0d08 Binary files /dev/null and b/client/src/main/resources/textures/items/charged_orb.png differ diff --git a/client/src/main/resources/textures/items/cherry_door.png b/client/src/main/resources/textures/items/cherry_door.png new file mode 100755 index 0000000..f6fa2b8 Binary files /dev/null and b/client/src/main/resources/textures/items/cherry_door.png differ diff --git a/client/src/main/resources/textures/items/chest_minecart.png b/client/src/main/resources/textures/items/chest_minecart.png new file mode 100755 index 0000000..78a3778 Binary files /dev/null and b/client/src/main/resources/textures/items/chest_minecart.png differ diff --git a/client/src/main/resources/textures/items/chick_magnet.png b/client/src/main/resources/textures/items/chick_magnet.png new file mode 100755 index 0000000..ebeb8fa Binary files /dev/null and b/client/src/main/resources/textures/items/chick_magnet.png differ diff --git a/client/src/main/resources/textures/items/chicken.png b/client/src/main/resources/textures/items/chicken.png new file mode 100755 index 0000000..6d25922 Binary files /dev/null and b/client/src/main/resources/textures/items/chicken.png differ diff --git a/client/src/main/resources/textures/items/chrome_ingot.png b/client/src/main/resources/textures/items/chrome_ingot.png new file mode 100755 index 0000000..74ad0db Binary files /dev/null and b/client/src/main/resources/textures/items/chrome_ingot.png differ diff --git a/client/src/main/resources/textures/items/cinnabar.png b/client/src/main/resources/textures/items/cinnabar.png new file mode 100755 index 0000000..8e2298a Binary files /dev/null and b/client/src/main/resources/textures/items/cinnabar.png differ diff --git a/client/src/main/resources/textures/items/clay_ball.png b/client/src/main/resources/textures/items/clay_ball.png new file mode 100755 index 0000000..5103d6c Binary files /dev/null and b/client/src/main/resources/textures/items/clay_ball.png differ diff --git a/client/src/main/resources/textures/items/clock.png b/client/src/main/resources/textures/items/clock.png new file mode 100755 index 0000000..1ec0fff Binary files /dev/null and b/client/src/main/resources/textures/items/clock.png differ diff --git a/client/src/main/resources/textures/items/cloth_boots.png b/client/src/main/resources/textures/items/cloth_boots.png new file mode 100755 index 0000000..84d8fd9 Binary files /dev/null and b/client/src/main/resources/textures/items/cloth_boots.png differ diff --git a/client/src/main/resources/textures/items/cloth_boots_overlay.png b/client/src/main/resources/textures/items/cloth_boots_overlay.png new file mode 100755 index 0000000..4a1d868 Binary files /dev/null and b/client/src/main/resources/textures/items/cloth_boots_overlay.png differ diff --git a/client/src/main/resources/textures/items/cloth_chestplate.png b/client/src/main/resources/textures/items/cloth_chestplate.png new file mode 100755 index 0000000..e534aef Binary files /dev/null and b/client/src/main/resources/textures/items/cloth_chestplate.png differ diff --git a/client/src/main/resources/textures/items/cloth_chestplate_overlay.png b/client/src/main/resources/textures/items/cloth_chestplate_overlay.png new file mode 100755 index 0000000..6fa801f Binary files /dev/null and b/client/src/main/resources/textures/items/cloth_chestplate_overlay.png differ diff --git a/client/src/main/resources/textures/items/cloth_helmet.png b/client/src/main/resources/textures/items/cloth_helmet.png new file mode 100755 index 0000000..6daf551 Binary files /dev/null and b/client/src/main/resources/textures/items/cloth_helmet.png differ diff --git a/client/src/main/resources/textures/items/cloth_helmet_overlay.png b/client/src/main/resources/textures/items/cloth_helmet_overlay.png new file mode 100755 index 0000000..e8a0625 Binary files /dev/null and b/client/src/main/resources/textures/items/cloth_helmet_overlay.png differ diff --git a/client/src/main/resources/textures/items/cloth_leggings.png b/client/src/main/resources/textures/items/cloth_leggings.png new file mode 100755 index 0000000..fc38cf2 Binary files /dev/null and b/client/src/main/resources/textures/items/cloth_leggings.png differ diff --git a/client/src/main/resources/textures/items/cloth_leggings_overlay.png b/client/src/main/resources/textures/items/cloth_leggings_overlay.png new file mode 100755 index 0000000..22598f0 Binary files /dev/null and b/client/src/main/resources/textures/items/cloth_leggings_overlay.png differ diff --git a/client/src/main/resources/textures/items/clownfish.png b/client/src/main/resources/textures/items/clownfish.png new file mode 100755 index 0000000..41df72f Binary files /dev/null and b/client/src/main/resources/textures/items/clownfish.png differ diff --git a/client/src/main/resources/textures/items/coal.png b/client/src/main/resources/textures/items/coal.png new file mode 100755 index 0000000..5563b6f Binary files /dev/null and b/client/src/main/resources/textures/items/coal.png differ diff --git a/client/src/main/resources/textures/items/cobalt_ingot.png b/client/src/main/resources/textures/items/cobalt_ingot.png new file mode 100755 index 0000000..a7ddf17 Binary files /dev/null and b/client/src/main/resources/textures/items/cobalt_ingot.png differ diff --git a/client/src/main/resources/textures/items/cod.png b/client/src/main/resources/textures/items/cod.png new file mode 100755 index 0000000..32996bf Binary files /dev/null and b/client/src/main/resources/textures/items/cod.png differ diff --git a/client/src/main/resources/textures/items/comparator.png b/client/src/main/resources/textures/items/comparator.png new file mode 100755 index 0000000..28b8eec Binary files /dev/null and b/client/src/main/resources/textures/items/comparator.png differ diff --git a/client/src/main/resources/textures/items/cooked_beef.png b/client/src/main/resources/textures/items/cooked_beef.png new file mode 100755 index 0000000..2df9bbf Binary files /dev/null and b/client/src/main/resources/textures/items/cooked_beef.png differ diff --git a/client/src/main/resources/textures/items/cooked_chicken.png b/client/src/main/resources/textures/items/cooked_chicken.png new file mode 100755 index 0000000..890b5b3 Binary files /dev/null and b/client/src/main/resources/textures/items/cooked_chicken.png differ diff --git a/client/src/main/resources/textures/items/cooked_cod.png b/client/src/main/resources/textures/items/cooked_cod.png new file mode 100755 index 0000000..87564c7 Binary files /dev/null and b/client/src/main/resources/textures/items/cooked_cod.png differ diff --git a/client/src/main/resources/textures/items/cooked_porkchop.png b/client/src/main/resources/textures/items/cooked_porkchop.png new file mode 100755 index 0000000..605d3f5 Binary files /dev/null and b/client/src/main/resources/textures/items/cooked_porkchop.png differ diff --git a/client/src/main/resources/textures/items/cooked_salmon.png b/client/src/main/resources/textures/items/cooked_salmon.png new file mode 100755 index 0000000..fb765ed Binary files /dev/null and b/client/src/main/resources/textures/items/cooked_salmon.png differ diff --git a/client/src/main/resources/textures/items/cookie.png b/client/src/main/resources/textures/items/cookie.png new file mode 100755 index 0000000..01fe56b Binary files /dev/null and b/client/src/main/resources/textures/items/cookie.png differ diff --git a/client/src/main/resources/textures/items/copper_ingot.png b/client/src/main/resources/textures/items/copper_ingot.png new file mode 100755 index 0000000..22c02cd Binary files /dev/null and b/client/src/main/resources/textures/items/copper_ingot.png differ diff --git a/client/src/main/resources/textures/items/dark_lighter.png b/client/src/main/resources/textures/items/dark_lighter.png new file mode 100755 index 0000000..60242f4 Binary files /dev/null and b/client/src/main/resources/textures/items/dark_lighter.png differ diff --git a/client/src/main/resources/textures/items/dark_oak_door.png b/client/src/main/resources/textures/items/dark_oak_door.png new file mode 100755 index 0000000..7862d9a Binary files /dev/null and b/client/src/main/resources/textures/items/dark_oak_door.png differ diff --git a/client/src/main/resources/textures/items/darkstone_fragment.png b/client/src/main/resources/textures/items/darkstone_fragment.png new file mode 100755 index 0000000..4603084 Binary files /dev/null and b/client/src/main/resources/textures/items/darkstone_fragment.png differ diff --git a/client/src/main/resources/textures/items/diamond.png b/client/src/main/resources/textures/items/diamond.png new file mode 100755 index 0000000..10e70a0 Binary files /dev/null and b/client/src/main/resources/textures/items/diamond.png differ diff --git a/client/src/main/resources/textures/items/diamond_axe.png b/client/src/main/resources/textures/items/diamond_axe.png new file mode 100755 index 0000000..7627f87 Binary files /dev/null and b/client/src/main/resources/textures/items/diamond_axe.png differ diff --git a/client/src/main/resources/textures/items/diamond_boots.png b/client/src/main/resources/textures/items/diamond_boots.png new file mode 100755 index 0000000..70d9e5f Binary files /dev/null and b/client/src/main/resources/textures/items/diamond_boots.png differ diff --git a/client/src/main/resources/textures/items/diamond_chestplate.png b/client/src/main/resources/textures/items/diamond_chestplate.png new file mode 100755 index 0000000..afdff93 Binary files /dev/null and b/client/src/main/resources/textures/items/diamond_chestplate.png differ diff --git a/client/src/main/resources/textures/items/diamond_helmet.png b/client/src/main/resources/textures/items/diamond_helmet.png new file mode 100755 index 0000000..1c88592 Binary files /dev/null and b/client/src/main/resources/textures/items/diamond_helmet.png differ diff --git a/client/src/main/resources/textures/items/diamond_hoe.png b/client/src/main/resources/textures/items/diamond_hoe.png new file mode 100755 index 0000000..c9a97e0 Binary files /dev/null and b/client/src/main/resources/textures/items/diamond_hoe.png differ diff --git a/client/src/main/resources/textures/items/diamond_horse_armor.png b/client/src/main/resources/textures/items/diamond_horse_armor.png new file mode 100755 index 0000000..b281aad Binary files /dev/null and b/client/src/main/resources/textures/items/diamond_horse_armor.png differ diff --git a/client/src/main/resources/textures/items/diamond_leggings.png b/client/src/main/resources/textures/items/diamond_leggings.png new file mode 100755 index 0000000..a99c896 Binary files /dev/null and b/client/src/main/resources/textures/items/diamond_leggings.png differ diff --git a/client/src/main/resources/textures/items/diamond_pickaxe.png b/client/src/main/resources/textures/items/diamond_pickaxe.png new file mode 100755 index 0000000..c279828 Binary files /dev/null and b/client/src/main/resources/textures/items/diamond_pickaxe.png differ diff --git a/client/src/main/resources/textures/items/diamond_shears.png b/client/src/main/resources/textures/items/diamond_shears.png new file mode 100755 index 0000000..775a536 Binary files /dev/null and b/client/src/main/resources/textures/items/diamond_shears.png differ diff --git a/client/src/main/resources/textures/items/diamond_shovel.png b/client/src/main/resources/textures/items/diamond_shovel.png new file mode 100755 index 0000000..e4a8992 Binary files /dev/null and b/client/src/main/resources/textures/items/diamond_shovel.png differ diff --git a/client/src/main/resources/textures/items/diamond_sword.png b/client/src/main/resources/textures/items/diamond_sword.png new file mode 100755 index 0000000..2a1552d Binary files /dev/null and b/client/src/main/resources/textures/items/diamond_sword.png differ diff --git a/client/src/main/resources/textures/items/die_d10_side.png b/client/src/main/resources/textures/items/die_d10_side.png new file mode 100755 index 0000000..c928f91 Binary files /dev/null and b/client/src/main/resources/textures/items/die_d10_side.png differ diff --git a/client/src/main/resources/textures/items/die_d10_top.png b/client/src/main/resources/textures/items/die_d10_top.png new file mode 100755 index 0000000..531447a Binary files /dev/null and b/client/src/main/resources/textures/items/die_d10_top.png differ diff --git a/client/src/main/resources/textures/items/die_d12_side.png b/client/src/main/resources/textures/items/die_d12_side.png new file mode 100755 index 0000000..4ff1b07 Binary files /dev/null and b/client/src/main/resources/textures/items/die_d12_side.png differ diff --git a/client/src/main/resources/textures/items/die_d12_top.png b/client/src/main/resources/textures/items/die_d12_top.png new file mode 100755 index 0000000..d9ef587 Binary files /dev/null and b/client/src/main/resources/textures/items/die_d12_top.png differ diff --git a/client/src/main/resources/textures/items/die_d20_side.png b/client/src/main/resources/textures/items/die_d20_side.png new file mode 100755 index 0000000..596b72b Binary files /dev/null and b/client/src/main/resources/textures/items/die_d20_side.png differ diff --git a/client/src/main/resources/textures/items/die_d20_top.png b/client/src/main/resources/textures/items/die_d20_top.png new file mode 100755 index 0000000..ed89d74 Binary files /dev/null and b/client/src/main/resources/textures/items/die_d20_top.png differ diff --git a/client/src/main/resources/textures/items/die_d4_side.png b/client/src/main/resources/textures/items/die_d4_side.png new file mode 100755 index 0000000..d7cb196 Binary files /dev/null and b/client/src/main/resources/textures/items/die_d4_side.png differ diff --git a/client/src/main/resources/textures/items/die_d4_top.png b/client/src/main/resources/textures/items/die_d4_top.png new file mode 100755 index 0000000..d023ba4 Binary files /dev/null and b/client/src/main/resources/textures/items/die_d4_top.png differ diff --git a/client/src/main/resources/textures/items/die_d6_side.png b/client/src/main/resources/textures/items/die_d6_side.png new file mode 100755 index 0000000..50d4deb Binary files /dev/null and b/client/src/main/resources/textures/items/die_d6_side.png differ diff --git a/client/src/main/resources/textures/items/die_d6_top.png b/client/src/main/resources/textures/items/die_d6_top.png new file mode 100755 index 0000000..14f29e8 Binary files /dev/null and b/client/src/main/resources/textures/items/die_d6_top.png differ diff --git a/client/src/main/resources/textures/items/die_d8_side.png b/client/src/main/resources/textures/items/die_d8_side.png new file mode 100755 index 0000000..787620d Binary files /dev/null and b/client/src/main/resources/textures/items/die_d8_side.png differ diff --git a/client/src/main/resources/textures/items/die_d8_top.png b/client/src/main/resources/textures/items/die_d8_top.png new file mode 100755 index 0000000..e48306a Binary files /dev/null and b/client/src/main/resources/textures/items/die_d8_top.png differ diff --git a/client/src/main/resources/textures/items/dye_black.png b/client/src/main/resources/textures/items/dye_black.png new file mode 100755 index 0000000..162715a Binary files /dev/null and b/client/src/main/resources/textures/items/dye_black.png differ diff --git a/client/src/main/resources/textures/items/dye_blue.png b/client/src/main/resources/textures/items/dye_blue.png new file mode 100755 index 0000000..4713983 Binary files /dev/null and b/client/src/main/resources/textures/items/dye_blue.png differ diff --git a/client/src/main/resources/textures/items/dye_brown.png b/client/src/main/resources/textures/items/dye_brown.png new file mode 100755 index 0000000..62eae8d Binary files /dev/null and b/client/src/main/resources/textures/items/dye_brown.png differ diff --git a/client/src/main/resources/textures/items/dye_cyan.png b/client/src/main/resources/textures/items/dye_cyan.png new file mode 100755 index 0000000..901c1a6 Binary files /dev/null and b/client/src/main/resources/textures/items/dye_cyan.png differ diff --git a/client/src/main/resources/textures/items/dye_gray.png b/client/src/main/resources/textures/items/dye_gray.png new file mode 100755 index 0000000..38dc3cc Binary files /dev/null and b/client/src/main/resources/textures/items/dye_gray.png differ diff --git a/client/src/main/resources/textures/items/dye_green.png b/client/src/main/resources/textures/items/dye_green.png new file mode 100755 index 0000000..009e058 Binary files /dev/null and b/client/src/main/resources/textures/items/dye_green.png differ diff --git a/client/src/main/resources/textures/items/dye_light_blue.png b/client/src/main/resources/textures/items/dye_light_blue.png new file mode 100755 index 0000000..ef58a5f Binary files /dev/null and b/client/src/main/resources/textures/items/dye_light_blue.png differ diff --git a/client/src/main/resources/textures/items/dye_lime.png b/client/src/main/resources/textures/items/dye_lime.png new file mode 100755 index 0000000..c7c91f9 Binary files /dev/null and b/client/src/main/resources/textures/items/dye_lime.png differ diff --git a/client/src/main/resources/textures/items/dye_magenta.png b/client/src/main/resources/textures/items/dye_magenta.png new file mode 100755 index 0000000..fbf9f64 Binary files /dev/null and b/client/src/main/resources/textures/items/dye_magenta.png differ diff --git a/client/src/main/resources/textures/items/dye_orange.png b/client/src/main/resources/textures/items/dye_orange.png new file mode 100755 index 0000000..1cc564f Binary files /dev/null and b/client/src/main/resources/textures/items/dye_orange.png differ diff --git a/client/src/main/resources/textures/items/dye_pink.png b/client/src/main/resources/textures/items/dye_pink.png new file mode 100755 index 0000000..a82bb54 Binary files /dev/null and b/client/src/main/resources/textures/items/dye_pink.png differ diff --git a/client/src/main/resources/textures/items/dye_purple.png b/client/src/main/resources/textures/items/dye_purple.png new file mode 100755 index 0000000..ebe58dc Binary files /dev/null and b/client/src/main/resources/textures/items/dye_purple.png differ diff --git a/client/src/main/resources/textures/items/dye_red.png b/client/src/main/resources/textures/items/dye_red.png new file mode 100755 index 0000000..2d1a742 Binary files /dev/null and b/client/src/main/resources/textures/items/dye_red.png differ diff --git a/client/src/main/resources/textures/items/dye_silver.png b/client/src/main/resources/textures/items/dye_silver.png new file mode 100755 index 0000000..d08f399 Binary files /dev/null and b/client/src/main/resources/textures/items/dye_silver.png differ diff --git a/client/src/main/resources/textures/items/dye_white.png b/client/src/main/resources/textures/items/dye_white.png new file mode 100755 index 0000000..5b1833b Binary files /dev/null and b/client/src/main/resources/textures/items/dye_white.png differ diff --git a/client/src/main/resources/textures/items/dye_yellow.png b/client/src/main/resources/textures/items/dye_yellow.png new file mode 100755 index 0000000..95e0673 Binary files /dev/null and b/client/src/main/resources/textures/items/dye_yellow.png differ diff --git a/client/src/main/resources/textures/items/dynamite.png b/client/src/main/resources/textures/items/dynamite.png new file mode 100755 index 0000000..868a3dc Binary files /dev/null and b/client/src/main/resources/textures/items/dynamite.png differ diff --git a/client/src/main/resources/textures/items/dynamite_1.png b/client/src/main/resources/textures/items/dynamite_1.png new file mode 100755 index 0000000..e7c2f6a Binary files /dev/null and b/client/src/main/resources/textures/items/dynamite_1.png differ diff --git a/client/src/main/resources/textures/items/dynamite_2.png b/client/src/main/resources/textures/items/dynamite_2.png new file mode 100755 index 0000000..df99e60 Binary files /dev/null and b/client/src/main/resources/textures/items/dynamite_2.png differ diff --git a/client/src/main/resources/textures/items/dynamite_3.png b/client/src/main/resources/textures/items/dynamite_3.png new file mode 100755 index 0000000..a2179ff Binary files /dev/null and b/client/src/main/resources/textures/items/dynamite_3.png differ diff --git a/client/src/main/resources/textures/items/dynamite_4.png b/client/src/main/resources/textures/items/dynamite_4.png new file mode 100755 index 0000000..c748595 Binary files /dev/null and b/client/src/main/resources/textures/items/dynamite_4.png differ diff --git a/client/src/main/resources/textures/items/dynamite_5.png b/client/src/main/resources/textures/items/dynamite_5.png new file mode 100755 index 0000000..d0ad1ae Binary files /dev/null and b/client/src/main/resources/textures/items/dynamite_5.png differ diff --git a/client/src/main/resources/textures/items/dynamite_6.png b/client/src/main/resources/textures/items/dynamite_6.png new file mode 100755 index 0000000..249af2e Binary files /dev/null and b/client/src/main/resources/textures/items/dynamite_6.png differ diff --git a/client/src/main/resources/textures/items/dynamite_7.png b/client/src/main/resources/textures/items/dynamite_7.png new file mode 100755 index 0000000..e190689 Binary files /dev/null and b/client/src/main/resources/textures/items/dynamite_7.png differ diff --git a/client/src/main/resources/textures/items/egg.png b/client/src/main/resources/textures/items/egg.png new file mode 100755 index 0000000..a6fe2bf Binary files /dev/null and b/client/src/main/resources/textures/items/egg.png differ diff --git a/client/src/main/resources/textures/items/emerald.png b/client/src/main/resources/textures/items/emerald.png new file mode 100755 index 0000000..98d953e Binary files /dev/null and b/client/src/main/resources/textures/items/emerald.png differ diff --git a/client/src/main/resources/textures/items/empty_armor_slot_boots.png b/client/src/main/resources/textures/items/empty_armor_slot_boots.png new file mode 100755 index 0000000..fd7e05f Binary files /dev/null and b/client/src/main/resources/textures/items/empty_armor_slot_boots.png differ diff --git a/client/src/main/resources/textures/items/empty_armor_slot_chestplate.png b/client/src/main/resources/textures/items/empty_armor_slot_chestplate.png new file mode 100755 index 0000000..6e632b9 Binary files /dev/null and b/client/src/main/resources/textures/items/empty_armor_slot_chestplate.png differ diff --git a/client/src/main/resources/textures/items/empty_armor_slot_helmet.png b/client/src/main/resources/textures/items/empty_armor_slot_helmet.png new file mode 100755 index 0000000..3a455f3 Binary files /dev/null and b/client/src/main/resources/textures/items/empty_armor_slot_helmet.png differ diff --git a/client/src/main/resources/textures/items/empty_armor_slot_leggings.png b/client/src/main/resources/textures/items/empty_armor_slot_leggings.png new file mode 100755 index 0000000..28b2c49 Binary files /dev/null and b/client/src/main/resources/textures/items/empty_armor_slot_leggings.png differ diff --git a/client/src/main/resources/textures/items/enchanted_book.png b/client/src/main/resources/textures/items/enchanted_book.png new file mode 100755 index 0000000..8742bee Binary files /dev/null and b/client/src/main/resources/textures/items/enchanted_book.png differ diff --git a/client/src/main/resources/textures/items/experience_bottle.png b/client/src/main/resources/textures/items/experience_bottle.png new file mode 100755 index 0000000..ae4214f Binary files /dev/null and b/client/src/main/resources/textures/items/experience_bottle.png differ diff --git a/client/src/main/resources/textures/items/exterminator.png b/client/src/main/resources/textures/items/exterminator.png new file mode 100755 index 0000000..33b54c5 Binary files /dev/null and b/client/src/main/resources/textures/items/exterminator.png differ diff --git a/client/src/main/resources/textures/items/feather.png b/client/src/main/resources/textures/items/feather.png new file mode 100755 index 0000000..d4c3be5 Binary files /dev/null and b/client/src/main/resources/textures/items/feather.png differ diff --git a/client/src/main/resources/textures/items/fermented_spider_eye.png b/client/src/main/resources/textures/items/fermented_spider_eye.png new file mode 100755 index 0000000..226ffb8 Binary files /dev/null and b/client/src/main/resources/textures/items/fermented_spider_eye.png differ diff --git a/client/src/main/resources/textures/items/filled_map.png b/client/src/main/resources/textures/items/filled_map.png new file mode 100755 index 0000000..1381e21 Binary files /dev/null and b/client/src/main/resources/textures/items/filled_map.png differ diff --git a/client/src/main/resources/textures/items/fire_charge.png b/client/src/main/resources/textures/items/fire_charge.png new file mode 100755 index 0000000..d62a6f4 Binary files /dev/null and b/client/src/main/resources/textures/items/fire_charge.png differ diff --git a/client/src/main/resources/textures/items/firework_charge.png b/client/src/main/resources/textures/items/firework_charge.png new file mode 100755 index 0000000..5c89362 Binary files /dev/null and b/client/src/main/resources/textures/items/firework_charge.png differ diff --git a/client/src/main/resources/textures/items/firework_charge_overlay.png b/client/src/main/resources/textures/items/firework_charge_overlay.png new file mode 100755 index 0000000..d8b91a9 Binary files /dev/null and b/client/src/main/resources/textures/items/firework_charge_overlay.png differ diff --git a/client/src/main/resources/textures/items/fireworks.png b/client/src/main/resources/textures/items/fireworks.png new file mode 100755 index 0000000..f1e07fd Binary files /dev/null and b/client/src/main/resources/textures/items/fireworks.png differ diff --git a/client/src/main/resources/textures/items/fishing_rod.png b/client/src/main/resources/textures/items/fishing_rod.png new file mode 100755 index 0000000..d4b53f0 Binary files /dev/null and b/client/src/main/resources/textures/items/fishing_rod.png differ diff --git a/client/src/main/resources/textures/items/fishing_rod_cast.png b/client/src/main/resources/textures/items/fishing_rod_cast.png new file mode 100755 index 0000000..a5ab378 Binary files /dev/null and b/client/src/main/resources/textures/items/fishing_rod_cast.png differ diff --git a/client/src/main/resources/textures/items/flint.png b/client/src/main/resources/textures/items/flint.png new file mode 100755 index 0000000..5f51093 Binary files /dev/null and b/client/src/main/resources/textures/items/flint.png differ diff --git a/client/src/main/resources/textures/items/flint_and_steel.png b/client/src/main/resources/textures/items/flint_and_steel.png new file mode 100755 index 0000000..77bc340 Binary files /dev/null and b/client/src/main/resources/textures/items/flint_and_steel.png differ diff --git a/client/src/main/resources/textures/items/flower_pot.png b/client/src/main/resources/textures/items/flower_pot.png new file mode 100755 index 0000000..c4f26d2 Binary files /dev/null and b/client/src/main/resources/textures/items/flower_pot.png differ diff --git a/client/src/main/resources/textures/items/furnace_minecart.png b/client/src/main/resources/textures/items/furnace_minecart.png new file mode 100755 index 0000000..5478f25 Binary files /dev/null and b/client/src/main/resources/textures/items/furnace_minecart.png differ diff --git a/client/src/main/resources/textures/items/ghast_tear.png b/client/src/main/resources/textures/items/ghast_tear.png new file mode 100755 index 0000000..e5c741f Binary files /dev/null and b/client/src/main/resources/textures/items/ghast_tear.png differ diff --git a/client/src/main/resources/textures/items/ghi_fragment.png b/client/src/main/resources/textures/items/ghi_fragment.png new file mode 100755 index 0000000..c89a930 Binary files /dev/null and b/client/src/main/resources/textures/items/ghi_fragment.png differ diff --git a/client/src/main/resources/textures/items/glowstone_dust.png b/client/src/main/resources/textures/items/glowstone_dust.png new file mode 100755 index 0000000..edd93a6 Binary files /dev/null and b/client/src/main/resources/textures/items/glowstone_dust.png differ diff --git a/client/src/main/resources/textures/items/gold_axe.png b/client/src/main/resources/textures/items/gold_axe.png new file mode 100755 index 0000000..0f47b60 Binary files /dev/null and b/client/src/main/resources/textures/items/gold_axe.png differ diff --git a/client/src/main/resources/textures/items/gold_boots.png b/client/src/main/resources/textures/items/gold_boots.png new file mode 100755 index 0000000..f6033d2 Binary files /dev/null and b/client/src/main/resources/textures/items/gold_boots.png differ diff --git a/client/src/main/resources/textures/items/gold_chestplate.png b/client/src/main/resources/textures/items/gold_chestplate.png new file mode 100755 index 0000000..e36076a Binary files /dev/null and b/client/src/main/resources/textures/items/gold_chestplate.png differ diff --git a/client/src/main/resources/textures/items/gold_helmet.png b/client/src/main/resources/textures/items/gold_helmet.png new file mode 100755 index 0000000..9eb89a0 Binary files /dev/null and b/client/src/main/resources/textures/items/gold_helmet.png differ diff --git a/client/src/main/resources/textures/items/gold_hoe.png b/client/src/main/resources/textures/items/gold_hoe.png new file mode 100755 index 0000000..1685d47 Binary files /dev/null and b/client/src/main/resources/textures/items/gold_hoe.png differ diff --git a/client/src/main/resources/textures/items/gold_horse_armor.png b/client/src/main/resources/textures/items/gold_horse_armor.png new file mode 100755 index 0000000..7c5c3a5 Binary files /dev/null and b/client/src/main/resources/textures/items/gold_horse_armor.png differ diff --git a/client/src/main/resources/textures/items/gold_ingot.png b/client/src/main/resources/textures/items/gold_ingot.png new file mode 100755 index 0000000..ea781e7 Binary files /dev/null and b/client/src/main/resources/textures/items/gold_ingot.png differ diff --git a/client/src/main/resources/textures/items/gold_leggings.png b/client/src/main/resources/textures/items/gold_leggings.png new file mode 100755 index 0000000..da23771 Binary files /dev/null and b/client/src/main/resources/textures/items/gold_leggings.png differ diff --git a/client/src/main/resources/textures/items/gold_nugget.png b/client/src/main/resources/textures/items/gold_nugget.png new file mode 100755 index 0000000..3a9a2fe Binary files /dev/null and b/client/src/main/resources/textures/items/gold_nugget.png differ diff --git a/client/src/main/resources/textures/items/gold_pickaxe.png b/client/src/main/resources/textures/items/gold_pickaxe.png new file mode 100755 index 0000000..ecccafe Binary files /dev/null and b/client/src/main/resources/textures/items/gold_pickaxe.png differ diff --git a/client/src/main/resources/textures/items/gold_shears.png b/client/src/main/resources/textures/items/gold_shears.png new file mode 100755 index 0000000..ea1b1ee Binary files /dev/null and b/client/src/main/resources/textures/items/gold_shears.png differ diff --git a/client/src/main/resources/textures/items/gold_shovel.png b/client/src/main/resources/textures/items/gold_shovel.png new file mode 100755 index 0000000..150cbb9 Binary files /dev/null and b/client/src/main/resources/textures/items/gold_shovel.png differ diff --git a/client/src/main/resources/textures/items/gold_sword.png b/client/src/main/resources/textures/items/gold_sword.png new file mode 100755 index 0000000..0ddef04 Binary files /dev/null and b/client/src/main/resources/textures/items/gold_sword.png differ diff --git a/client/src/main/resources/textures/items/golden_apple.png b/client/src/main/resources/textures/items/golden_apple.png new file mode 100755 index 0000000..6201989 Binary files /dev/null and b/client/src/main/resources/textures/items/golden_apple.png differ diff --git a/client/src/main/resources/textures/items/golden_carrot.png b/client/src/main/resources/textures/items/golden_carrot.png new file mode 100755 index 0000000..e0f1ea6 Binary files /dev/null and b/client/src/main/resources/textures/items/golden_carrot.png differ diff --git a/client/src/main/resources/textures/items/goo_bucket.png b/client/src/main/resources/textures/items/goo_bucket.png new file mode 100755 index 0000000..a67246c Binary files /dev/null and b/client/src/main/resources/textures/items/goo_bucket.png differ diff --git a/client/src/main/resources/textures/items/gunpowder.png b/client/src/main/resources/textures/items/gunpowder.png new file mode 100755 index 0000000..73cadec Binary files /dev/null and b/client/src/main/resources/textures/items/gunpowder.png differ diff --git a/client/src/main/resources/textures/items/gyriyn_axe.png b/client/src/main/resources/textures/items/gyriyn_axe.png new file mode 100755 index 0000000..cd1a52d Binary files /dev/null and b/client/src/main/resources/textures/items/gyriyn_axe.png differ diff --git a/client/src/main/resources/textures/items/gyriyn_hoe.png b/client/src/main/resources/textures/items/gyriyn_hoe.png new file mode 100755 index 0000000..f7a730e Binary files /dev/null and b/client/src/main/resources/textures/items/gyriyn_hoe.png differ diff --git a/client/src/main/resources/textures/items/gyriyn_pickaxe.png b/client/src/main/resources/textures/items/gyriyn_pickaxe.png new file mode 100755 index 0000000..9efb11f Binary files /dev/null and b/client/src/main/resources/textures/items/gyriyn_pickaxe.png differ diff --git a/client/src/main/resources/textures/items/gyriyn_shears.png b/client/src/main/resources/textures/items/gyriyn_shears.png new file mode 100755 index 0000000..1863648 Binary files /dev/null and b/client/src/main/resources/textures/items/gyriyn_shears.png differ diff --git a/client/src/main/resources/textures/items/gyriyn_shovel.png b/client/src/main/resources/textures/items/gyriyn_shovel.png new file mode 100755 index 0000000..7769434 Binary files /dev/null and b/client/src/main/resources/textures/items/gyriyn_shovel.png differ diff --git a/client/src/main/resources/textures/items/hopper.png b/client/src/main/resources/textures/items/hopper.png new file mode 100755 index 0000000..f8b244f Binary files /dev/null and b/client/src/main/resources/textures/items/hopper.png differ diff --git a/client/src/main/resources/textures/items/hopper_minecart.png b/client/src/main/resources/textures/items/hopper_minecart.png new file mode 100755 index 0000000..8a138fb Binary files /dev/null and b/client/src/main/resources/textures/items/hopper_minecart.png differ diff --git a/client/src/main/resources/textures/items/hydrogen_bucket.png b/client/src/main/resources/textures/items/hydrogen_bucket.png new file mode 100755 index 0000000..cba7641 Binary files /dev/null and b/client/src/main/resources/textures/items/hydrogen_bucket.png differ diff --git a/client/src/main/resources/textures/items/info_wand.png b/client/src/main/resources/textures/items/info_wand.png new file mode 100755 index 0000000..63fcda9 Binary files /dev/null and b/client/src/main/resources/textures/items/info_wand.png differ diff --git a/client/src/main/resources/textures/items/iodine_powder.png b/client/src/main/resources/textures/items/iodine_powder.png new file mode 100755 index 0000000..41cbca1 Binary files /dev/null and b/client/src/main/resources/textures/items/iodine_powder.png differ diff --git a/client/src/main/resources/textures/items/iron_axe.png b/client/src/main/resources/textures/items/iron_axe.png new file mode 100755 index 0000000..8bf133e Binary files /dev/null and b/client/src/main/resources/textures/items/iron_axe.png differ diff --git a/client/src/main/resources/textures/items/iron_boots.png b/client/src/main/resources/textures/items/iron_boots.png new file mode 100755 index 0000000..b69ca05 Binary files /dev/null and b/client/src/main/resources/textures/items/iron_boots.png differ diff --git a/client/src/main/resources/textures/items/iron_chestplate.png b/client/src/main/resources/textures/items/iron_chestplate.png new file mode 100755 index 0000000..e7993ce Binary files /dev/null and b/client/src/main/resources/textures/items/iron_chestplate.png differ diff --git a/client/src/main/resources/textures/items/iron_door.png b/client/src/main/resources/textures/items/iron_door.png new file mode 100755 index 0000000..5dcbe38 Binary files /dev/null and b/client/src/main/resources/textures/items/iron_door.png differ diff --git a/client/src/main/resources/textures/items/iron_helmet.png b/client/src/main/resources/textures/items/iron_helmet.png new file mode 100755 index 0000000..65e64cc Binary files /dev/null and b/client/src/main/resources/textures/items/iron_helmet.png differ diff --git a/client/src/main/resources/textures/items/iron_hoe.png b/client/src/main/resources/textures/items/iron_hoe.png new file mode 100755 index 0000000..28d4c36 Binary files /dev/null and b/client/src/main/resources/textures/items/iron_hoe.png differ diff --git a/client/src/main/resources/textures/items/iron_horse_armor.png b/client/src/main/resources/textures/items/iron_horse_armor.png new file mode 100755 index 0000000..5d697d1 Binary files /dev/null and b/client/src/main/resources/textures/items/iron_horse_armor.png differ diff --git a/client/src/main/resources/textures/items/iron_ingot.png b/client/src/main/resources/textures/items/iron_ingot.png new file mode 100755 index 0000000..3833fa0 Binary files /dev/null and b/client/src/main/resources/textures/items/iron_ingot.png differ diff --git a/client/src/main/resources/textures/items/iron_leggings.png b/client/src/main/resources/textures/items/iron_leggings.png new file mode 100755 index 0000000..ad53673 Binary files /dev/null and b/client/src/main/resources/textures/items/iron_leggings.png differ diff --git a/client/src/main/resources/textures/items/iron_pickaxe.png b/client/src/main/resources/textures/items/iron_pickaxe.png new file mode 100755 index 0000000..d21440b Binary files /dev/null and b/client/src/main/resources/textures/items/iron_pickaxe.png differ diff --git a/client/src/main/resources/textures/items/iron_shears.png b/client/src/main/resources/textures/items/iron_shears.png new file mode 100755 index 0000000..f9c6de1 Binary files /dev/null and b/client/src/main/resources/textures/items/iron_shears.png differ diff --git a/client/src/main/resources/textures/items/iron_shovel.png b/client/src/main/resources/textures/items/iron_shovel.png new file mode 100755 index 0000000..079b236 Binary files /dev/null and b/client/src/main/resources/textures/items/iron_shovel.png differ diff --git a/client/src/main/resources/textures/items/iron_sword.png b/client/src/main/resources/textures/items/iron_sword.png new file mode 100755 index 0000000..4d49c5a Binary files /dev/null and b/client/src/main/resources/textures/items/iron_sword.png differ diff --git a/client/src/main/resources/textures/items/item_frame.png b/client/src/main/resources/textures/items/item_frame.png new file mode 100755 index 0000000..261c98a Binary files /dev/null and b/client/src/main/resources/textures/items/item_frame.png differ diff --git a/client/src/main/resources/textures/items/jungle_door.png b/client/src/main/resources/textures/items/jungle_door.png new file mode 100755 index 0000000..cb3753d Binary files /dev/null and b/client/src/main/resources/textures/items/jungle_door.png differ diff --git a/client/src/main/resources/textures/items/key.png b/client/src/main/resources/textures/items/key.png new file mode 100755 index 0000000..3dbcfb8 Binary files /dev/null and b/client/src/main/resources/textures/items/key.png differ diff --git a/client/src/main/resources/textures/items/lava_bucket.png b/client/src/main/resources/textures/items/lava_bucket.png new file mode 100755 index 0000000..13a1957 Binary files /dev/null and b/client/src/main/resources/textures/items/lava_bucket.png differ diff --git a/client/src/main/resources/textures/items/lead.png b/client/src/main/resources/textures/items/lead.png new file mode 100755 index 0000000..0ef5312 Binary files /dev/null and b/client/src/main/resources/textures/items/lead.png differ diff --git a/client/src/main/resources/textures/items/lead_ingot.png b/client/src/main/resources/textures/items/lead_ingot.png new file mode 100755 index 0000000..48d97a9 Binary files /dev/null and b/client/src/main/resources/textures/items/lead_ingot.png differ diff --git a/client/src/main/resources/textures/items/leather.png b/client/src/main/resources/textures/items/leather.png new file mode 100755 index 0000000..13dc199 Binary files /dev/null and b/client/src/main/resources/textures/items/leather.png differ diff --git a/client/src/main/resources/textures/items/leather_boots.png b/client/src/main/resources/textures/items/leather_boots.png new file mode 100755 index 0000000..eecca82 Binary files /dev/null and b/client/src/main/resources/textures/items/leather_boots.png differ diff --git a/client/src/main/resources/textures/items/leather_boots_overlay.png b/client/src/main/resources/textures/items/leather_boots_overlay.png new file mode 100755 index 0000000..4a1d868 Binary files /dev/null and b/client/src/main/resources/textures/items/leather_boots_overlay.png differ diff --git a/client/src/main/resources/textures/items/leather_chestplate.png b/client/src/main/resources/textures/items/leather_chestplate.png new file mode 100755 index 0000000..d11e2fd Binary files /dev/null and b/client/src/main/resources/textures/items/leather_chestplate.png differ diff --git a/client/src/main/resources/textures/items/leather_chestplate_overlay.png b/client/src/main/resources/textures/items/leather_chestplate_overlay.png new file mode 100755 index 0000000..6fa801f Binary files /dev/null and b/client/src/main/resources/textures/items/leather_chestplate_overlay.png differ diff --git a/client/src/main/resources/textures/items/leather_helmet.png b/client/src/main/resources/textures/items/leather_helmet.png new file mode 100755 index 0000000..5f90fc0 Binary files /dev/null and b/client/src/main/resources/textures/items/leather_helmet.png differ diff --git a/client/src/main/resources/textures/items/leather_helmet_overlay.png b/client/src/main/resources/textures/items/leather_helmet_overlay.png new file mode 100755 index 0000000..e8a0625 Binary files /dev/null and b/client/src/main/resources/textures/items/leather_helmet_overlay.png differ diff --git a/client/src/main/resources/textures/items/leather_leggings.png b/client/src/main/resources/textures/items/leather_leggings.png new file mode 100755 index 0000000..1220322 Binary files /dev/null and b/client/src/main/resources/textures/items/leather_leggings.png differ diff --git a/client/src/main/resources/textures/items/leather_leggings_overlay.png b/client/src/main/resources/textures/items/leather_leggings_overlay.png new file mode 100755 index 0000000..22598f0 Binary files /dev/null and b/client/src/main/resources/textures/items/leather_leggings_overlay.png differ diff --git a/client/src/main/resources/textures/items/lightning_wand.png b/client/src/main/resources/textures/items/lightning_wand.png new file mode 100755 index 0000000..b51ed3d Binary files /dev/null and b/client/src/main/resources/textures/items/lightning_wand.png differ diff --git a/client/src/main/resources/textures/items/lithium_ingot.png b/client/src/main/resources/textures/items/lithium_ingot.png new file mode 100755 index 0000000..8da1957 Binary files /dev/null and b/client/src/main/resources/textures/items/lithium_ingot.png differ diff --git a/client/src/main/resources/textures/items/magma_bucket.png b/client/src/main/resources/textures/items/magma_bucket.png new file mode 100755 index 0000000..dc76d26 Binary files /dev/null and b/client/src/main/resources/textures/items/magma_bucket.png differ diff --git a/client/src/main/resources/textures/items/magma_cream.png b/client/src/main/resources/textures/items/magma_cream.png new file mode 100755 index 0000000..b2be210 Binary files /dev/null and b/client/src/main/resources/textures/items/magma_cream.png differ diff --git a/client/src/main/resources/textures/items/magnesium_powder.png b/client/src/main/resources/textures/items/magnesium_powder.png new file mode 100755 index 0000000..21098a6 Binary files /dev/null and b/client/src/main/resources/textures/items/magnesium_powder.png differ diff --git a/client/src/main/resources/textures/items/magnet.png b/client/src/main/resources/textures/items/magnet.png new file mode 100755 index 0000000..93d0518 Binary files /dev/null and b/client/src/main/resources/textures/items/magnet.png differ diff --git a/client/src/main/resources/textures/items/manganese_ingot.png b/client/src/main/resources/textures/items/manganese_ingot.png new file mode 100755 index 0000000..e8b7efa Binary files /dev/null and b/client/src/main/resources/textures/items/manganese_ingot.png differ diff --git a/client/src/main/resources/textures/items/map.png b/client/src/main/resources/textures/items/map.png new file mode 100755 index 0000000..8dc6e58 Binary files /dev/null and b/client/src/main/resources/textures/items/map.png differ diff --git a/client/src/main/resources/textures/items/maple_door.png b/client/src/main/resources/textures/items/maple_door.png new file mode 100755 index 0000000..4c33b8f Binary files /dev/null and b/client/src/main/resources/textures/items/maple_door.png differ diff --git a/client/src/main/resources/textures/items/melon.png b/client/src/main/resources/textures/items/melon.png new file mode 100755 index 0000000..590f47a Binary files /dev/null and b/client/src/main/resources/textures/items/melon.png differ diff --git a/client/src/main/resources/textures/items/melon_stem.png b/client/src/main/resources/textures/items/melon_stem.png new file mode 100755 index 0000000..ef84499 Binary files /dev/null and b/client/src/main/resources/textures/items/melon_stem.png differ diff --git a/client/src/main/resources/textures/items/mercury_bucket.png b/client/src/main/resources/textures/items/mercury_bucket.png new file mode 100755 index 0000000..084003b Binary files /dev/null and b/client/src/main/resources/textures/items/mercury_bucket.png differ diff --git a/client/src/main/resources/textures/items/milk_bucket.png b/client/src/main/resources/textures/items/milk_bucket.png new file mode 100755 index 0000000..c77d92c Binary files /dev/null and b/client/src/main/resources/textures/items/milk_bucket.png differ diff --git a/client/src/main/resources/textures/items/minecart.png b/client/src/main/resources/textures/items/minecart.png new file mode 100755 index 0000000..2046f2b Binary files /dev/null and b/client/src/main/resources/textures/items/minecart.png differ diff --git a/client/src/main/resources/textures/items/minecart_command_block.png b/client/src/main/resources/textures/items/minecart_command_block.png new file mode 100755 index 0000000..c597ee7 Binary files /dev/null and b/client/src/main/resources/textures/items/minecart_command_block.png differ diff --git a/client/src/main/resources/textures/items/mushroom_stew.png b/client/src/main/resources/textures/items/mushroom_stew.png new file mode 100755 index 0000000..5598bc7 Binary files /dev/null and b/client/src/main/resources/textures/items/mushroom_stew.png differ diff --git a/client/src/main/resources/textures/items/mutton_cooked.png b/client/src/main/resources/textures/items/mutton_cooked.png new file mode 100755 index 0000000..e1b62dc Binary files /dev/null and b/client/src/main/resources/textures/items/mutton_cooked.png differ diff --git a/client/src/main/resources/textures/items/mutton_raw.png b/client/src/main/resources/textures/items/mutton_raw.png new file mode 100755 index 0000000..1222ff4 Binary files /dev/null and b/client/src/main/resources/textures/items/mutton_raw.png differ diff --git a/client/src/main/resources/textures/items/name_tag.png b/client/src/main/resources/textures/items/name_tag.png new file mode 100755 index 0000000..a88f559 Binary files /dev/null and b/client/src/main/resources/textures/items/name_tag.png differ diff --git a/client/src/main/resources/textures/items/navigator.png b/client/src/main/resources/textures/items/navigator.png new file mode 100755 index 0000000..3715ee4 Binary files /dev/null and b/client/src/main/resources/textures/items/navigator.png differ diff --git a/client/src/main/resources/textures/items/neodymium_ingot.png b/client/src/main/resources/textures/items/neodymium_ingot.png new file mode 100755 index 0000000..b015a96 Binary files /dev/null and b/client/src/main/resources/textures/items/neodymium_ingot.png differ diff --git a/client/src/main/resources/textures/items/neptunium_ingot.png b/client/src/main/resources/textures/items/neptunium_ingot.png new file mode 100755 index 0000000..0f5070e Binary files /dev/null and b/client/src/main/resources/textures/items/neptunium_ingot.png differ diff --git a/client/src/main/resources/textures/items/nichun_axe.png b/client/src/main/resources/textures/items/nichun_axe.png new file mode 100755 index 0000000..b14dbf8 Binary files /dev/null and b/client/src/main/resources/textures/items/nichun_axe.png differ diff --git a/client/src/main/resources/textures/items/nichun_boots.png b/client/src/main/resources/textures/items/nichun_boots.png new file mode 100755 index 0000000..0755025 Binary files /dev/null and b/client/src/main/resources/textures/items/nichun_boots.png differ diff --git a/client/src/main/resources/textures/items/nichun_chestplate.png b/client/src/main/resources/textures/items/nichun_chestplate.png new file mode 100755 index 0000000..1da9d89 Binary files /dev/null and b/client/src/main/resources/textures/items/nichun_chestplate.png differ diff --git a/client/src/main/resources/textures/items/nichun_helmet.png b/client/src/main/resources/textures/items/nichun_helmet.png new file mode 100755 index 0000000..23fd417 Binary files /dev/null and b/client/src/main/resources/textures/items/nichun_helmet.png differ diff --git a/client/src/main/resources/textures/items/nichun_hoe.png b/client/src/main/resources/textures/items/nichun_hoe.png new file mode 100755 index 0000000..d7baa35 Binary files /dev/null and b/client/src/main/resources/textures/items/nichun_hoe.png differ diff --git a/client/src/main/resources/textures/items/nichun_leggings.png b/client/src/main/resources/textures/items/nichun_leggings.png new file mode 100755 index 0000000..df7722f Binary files /dev/null and b/client/src/main/resources/textures/items/nichun_leggings.png differ diff --git a/client/src/main/resources/textures/items/nichun_pickaxe.png b/client/src/main/resources/textures/items/nichun_pickaxe.png new file mode 100755 index 0000000..a474eef Binary files /dev/null and b/client/src/main/resources/textures/items/nichun_pickaxe.png differ diff --git a/client/src/main/resources/textures/items/nichun_shears.png b/client/src/main/resources/textures/items/nichun_shears.png new file mode 100755 index 0000000..683d22a Binary files /dev/null and b/client/src/main/resources/textures/items/nichun_shears.png differ diff --git a/client/src/main/resources/textures/items/nichun_shovel.png b/client/src/main/resources/textures/items/nichun_shovel.png new file mode 100755 index 0000000..10316e8 Binary files /dev/null and b/client/src/main/resources/textures/items/nichun_shovel.png differ diff --git a/client/src/main/resources/textures/items/nichun_sword.png b/client/src/main/resources/textures/items/nichun_sword.png new file mode 100755 index 0000000..6707be1 Binary files /dev/null and b/client/src/main/resources/textures/items/nichun_sword.png differ diff --git a/client/src/main/resources/textures/items/nickel_ingot.png b/client/src/main/resources/textures/items/nickel_ingot.png new file mode 100755 index 0000000..d0ef7b0 Binary files /dev/null and b/client/src/main/resources/textures/items/nickel_ingot.png differ diff --git a/client/src/main/resources/textures/items/nieh_fragment.png b/client/src/main/resources/textures/items/nieh_fragment.png new file mode 100755 index 0000000..5f63fda Binary files /dev/null and b/client/src/main/resources/textures/items/nieh_fragment.png differ diff --git a/client/src/main/resources/textures/items/npc_spawner.png b/client/src/main/resources/textures/items/npc_spawner.png new file mode 100755 index 0000000..8e54c3d Binary files /dev/null and b/client/src/main/resources/textures/items/npc_spawner.png differ diff --git a/client/src/main/resources/textures/items/npc_spawner_overlay.png b/client/src/main/resources/textures/items/npc_spawner_overlay.png new file mode 100755 index 0000000..fad661e Binary files /dev/null and b/client/src/main/resources/textures/items/npc_spawner_overlay.png differ diff --git a/client/src/main/resources/textures/items/nukage_bucket.png b/client/src/main/resources/textures/items/nukage_bucket.png new file mode 100755 index 0000000..6825ae7 Binary files /dev/null and b/client/src/main/resources/textures/items/nukage_bucket.png differ diff --git a/client/src/main/resources/textures/items/oak_door.png b/client/src/main/resources/textures/items/oak_door.png new file mode 100755 index 0000000..43683f8 Binary files /dev/null and b/client/src/main/resources/textures/items/oak_door.png differ diff --git a/client/src/main/resources/textures/items/orb.png b/client/src/main/resources/textures/items/orb.png new file mode 100755 index 0000000..0bc9b66 Binary files /dev/null and b/client/src/main/resources/textures/items/orb.png differ diff --git a/client/src/main/resources/textures/items/painting.png b/client/src/main/resources/textures/items/painting.png new file mode 100755 index 0000000..b394f30 Binary files /dev/null and b/client/src/main/resources/textures/items/painting.png differ diff --git a/client/src/main/resources/textures/items/palladium_ingot.png b/client/src/main/resources/textures/items/palladium_ingot.png new file mode 100755 index 0000000..fad3197 Binary files /dev/null and b/client/src/main/resources/textures/items/palladium_ingot.png differ diff --git a/client/src/main/resources/textures/items/paper.png b/client/src/main/resources/textures/items/paper.png new file mode 100755 index 0000000..a1d9c7e Binary files /dev/null and b/client/src/main/resources/textures/items/paper.png differ diff --git a/client/src/main/resources/textures/items/phosphor_powder.png b/client/src/main/resources/textures/items/phosphor_powder.png new file mode 100755 index 0000000..df5d136 Binary files /dev/null and b/client/src/main/resources/textures/items/phosphor_powder.png differ diff --git a/client/src/main/resources/textures/items/platinum_ingot.png b/client/src/main/resources/textures/items/platinum_ingot.png new file mode 100755 index 0000000..d39193e Binary files /dev/null and b/client/src/main/resources/textures/items/platinum_ingot.png differ diff --git a/client/src/main/resources/textures/items/plutonium_ingot.png b/client/src/main/resources/textures/items/plutonium_ingot.png new file mode 100755 index 0000000..9ba95db Binary files /dev/null and b/client/src/main/resources/textures/items/plutonium_ingot.png differ diff --git a/client/src/main/resources/textures/items/poisonous_potato.png b/client/src/main/resources/textures/items/poisonous_potato.png new file mode 100755 index 0000000..6f154af Binary files /dev/null and b/client/src/main/resources/textures/items/poisonous_potato.png differ diff --git a/client/src/main/resources/textures/items/porkchop.png b/client/src/main/resources/textures/items/porkchop.png new file mode 100755 index 0000000..7e83c1a Binary files /dev/null and b/client/src/main/resources/textures/items/porkchop.png differ diff --git a/client/src/main/resources/textures/items/potassium_powder.png b/client/src/main/resources/textures/items/potassium_powder.png new file mode 100755 index 0000000..da32e5d Binary files /dev/null and b/client/src/main/resources/textures/items/potassium_powder.png differ diff --git a/client/src/main/resources/textures/items/potato.png b/client/src/main/resources/textures/items/potato.png new file mode 100755 index 0000000..c1d8541 Binary files /dev/null and b/client/src/main/resources/textures/items/potato.png differ diff --git a/client/src/main/resources/textures/items/potion_bottle_drinkable.png b/client/src/main/resources/textures/items/potion_bottle_drinkable.png new file mode 100755 index 0000000..87339d7 Binary files /dev/null and b/client/src/main/resources/textures/items/potion_bottle_drinkable.png differ diff --git a/client/src/main/resources/textures/items/potion_bottle_empty.png b/client/src/main/resources/textures/items/potion_bottle_empty.png new file mode 100755 index 0000000..87339d7 Binary files /dev/null and b/client/src/main/resources/textures/items/potion_bottle_empty.png differ diff --git a/client/src/main/resources/textures/items/potion_bottle_splash.png b/client/src/main/resources/textures/items/potion_bottle_splash.png new file mode 100755 index 0000000..03b1f90 Binary files /dev/null and b/client/src/main/resources/textures/items/potion_bottle_splash.png differ diff --git a/client/src/main/resources/textures/items/potion_overlay.png b/client/src/main/resources/textures/items/potion_overlay.png new file mode 100755 index 0000000..61864e9 Binary files /dev/null and b/client/src/main/resources/textures/items/potion_overlay.png differ diff --git a/client/src/main/resources/textures/items/praseodymium_ingot.png b/client/src/main/resources/textures/items/praseodymium_ingot.png new file mode 100755 index 0000000..c98d7f8 Binary files /dev/null and b/client/src/main/resources/textures/items/praseodymium_ingot.png differ diff --git a/client/src/main/resources/textures/items/pufferfish.png b/client/src/main/resources/textures/items/pufferfish.png new file mode 100755 index 0000000..aadbd88 Binary files /dev/null and b/client/src/main/resources/textures/items/pufferfish.png differ diff --git a/client/src/main/resources/textures/items/pumpkin_pie.png b/client/src/main/resources/textures/items/pumpkin_pie.png new file mode 100755 index 0000000..c21a032 Binary files /dev/null and b/client/src/main/resources/textures/items/pumpkin_pie.png differ diff --git a/client/src/main/resources/textures/items/pumpkin_stem.png b/client/src/main/resources/textures/items/pumpkin_stem.png new file mode 100755 index 0000000..8d8f076 Binary files /dev/null and b/client/src/main/resources/textures/items/pumpkin_stem.png differ diff --git a/client/src/main/resources/textures/items/purple_bed.png b/client/src/main/resources/textures/items/purple_bed.png new file mode 100755 index 0000000..72fddd4 Binary files /dev/null and b/client/src/main/resources/textures/items/purple_bed.png differ diff --git a/client/src/main/resources/textures/items/quartz.png b/client/src/main/resources/textures/items/quartz.png new file mode 100755 index 0000000..e403446 Binary files /dev/null and b/client/src/main/resources/textures/items/quartz.png differ diff --git a/client/src/main/resources/textures/items/quiver.png b/client/src/main/resources/textures/items/quiver.png new file mode 100755 index 0000000..818f728 Binary files /dev/null and b/client/src/main/resources/textures/items/quiver.png differ diff --git a/client/src/main/resources/textures/items/radium_ingot.png b/client/src/main/resources/textures/items/radium_ingot.png new file mode 100755 index 0000000..75d7c14 Binary files /dev/null and b/client/src/main/resources/textures/items/radium_ingot.png differ diff --git a/client/src/main/resources/textures/items/record_old.png b/client/src/main/resources/textures/items/record_old.png new file mode 100755 index 0000000..343ebb5 Binary files /dev/null and b/client/src/main/resources/textures/items/record_old.png differ diff --git a/client/src/main/resources/textures/items/red_bed.png b/client/src/main/resources/textures/items/red_bed.png new file mode 100755 index 0000000..22a4cf0 Binary files /dev/null and b/client/src/main/resources/textures/items/red_bed.png differ diff --git a/client/src/main/resources/textures/items/redstone.png b/client/src/main/resources/textures/items/redstone.png new file mode 100755 index 0000000..6da938b Binary files /dev/null and b/client/src/main/resources/textures/items/redstone.png differ diff --git a/client/src/main/resources/textures/items/reeds.png b/client/src/main/resources/textures/items/reeds.png new file mode 100755 index 0000000..40872c6 Binary files /dev/null and b/client/src/main/resources/textures/items/reeds.png differ diff --git a/client/src/main/resources/textures/items/repeater.png b/client/src/main/resources/textures/items/repeater.png new file mode 100755 index 0000000..7a07381 Binary files /dev/null and b/client/src/main/resources/textures/items/repeater.png differ diff --git a/client/src/main/resources/textures/items/rotten_flesh.png b/client/src/main/resources/textures/items/rotten_flesh.png new file mode 100755 index 0000000..3f39998 Binary files /dev/null and b/client/src/main/resources/textures/items/rotten_flesh.png differ diff --git a/client/src/main/resources/textures/items/ruby.png b/client/src/main/resources/textures/items/ruby.png new file mode 100755 index 0000000..4f288d9 Binary files /dev/null and b/client/src/main/resources/textures/items/ruby.png differ diff --git a/client/src/main/resources/textures/items/saddle.png b/client/src/main/resources/textures/items/saddle.png new file mode 100755 index 0000000..b12eafa Binary files /dev/null and b/client/src/main/resources/textures/items/saddle.png differ diff --git a/client/src/main/resources/textures/items/salmon.png b/client/src/main/resources/textures/items/salmon.png new file mode 100755 index 0000000..68bcd69 Binary files /dev/null and b/client/src/main/resources/textures/items/salmon.png differ diff --git a/client/src/main/resources/textures/items/selenium_powder.png b/client/src/main/resources/textures/items/selenium_powder.png new file mode 100755 index 0000000..2529161 Binary files /dev/null and b/client/src/main/resources/textures/items/selenium_powder.png differ diff --git a/client/src/main/resources/textures/items/sign.png b/client/src/main/resources/textures/items/sign.png new file mode 100755 index 0000000..9b6e2ee Binary files /dev/null and b/client/src/main/resources/textures/items/sign.png differ diff --git a/client/src/main/resources/textures/items/silicon_ingot.png b/client/src/main/resources/textures/items/silicon_ingot.png new file mode 100755 index 0000000..814f4b1 Binary files /dev/null and b/client/src/main/resources/textures/items/silicon_ingot.png differ diff --git a/client/src/main/resources/textures/items/silver_ingot.png b/client/src/main/resources/textures/items/silver_ingot.png new file mode 100755 index 0000000..940067f Binary files /dev/null and b/client/src/main/resources/textures/items/silver_ingot.png differ diff --git a/client/src/main/resources/textures/items/skull.png b/client/src/main/resources/textures/items/skull.png new file mode 100644 index 0000000..835979f Binary files /dev/null and b/client/src/main/resources/textures/items/skull.png differ diff --git a/client/src/main/resources/textures/items/slime_ball.png b/client/src/main/resources/textures/items/slime_ball.png new file mode 100755 index 0000000..46478ee Binary files /dev/null and b/client/src/main/resources/textures/items/slime_ball.png differ diff --git a/client/src/main/resources/textures/items/slime_bucket.png b/client/src/main/resources/textures/items/slime_bucket.png new file mode 100755 index 0000000..a57c6c2 Binary files /dev/null and b/client/src/main/resources/textures/items/slime_bucket.png differ diff --git a/client/src/main/resources/textures/items/snowball.png b/client/src/main/resources/textures/items/snowball.png new file mode 100755 index 0000000..340c639 Binary files /dev/null and b/client/src/main/resources/textures/items/snowball.png differ diff --git a/client/src/main/resources/textures/items/sodium_powder.png b/client/src/main/resources/textures/items/sodium_powder.png new file mode 100755 index 0000000..1c9e774 Binary files /dev/null and b/client/src/main/resources/textures/items/sodium_powder.png differ diff --git a/client/src/main/resources/textures/items/soul_wart.png b/client/src/main/resources/textures/items/soul_wart.png new file mode 100755 index 0000000..09da1e3 Binary files /dev/null and b/client/src/main/resources/textures/items/soul_wart.png differ diff --git a/client/src/main/resources/textures/items/spawn_egg.png b/client/src/main/resources/textures/items/spawn_egg.png new file mode 100755 index 0000000..26cc6b2 Binary files /dev/null and b/client/src/main/resources/textures/items/spawn_egg.png differ diff --git a/client/src/main/resources/textures/items/spawn_egg_overlay.png b/client/src/main/resources/textures/items/spawn_egg_overlay.png new file mode 100755 index 0000000..83ec78f Binary files /dev/null and b/client/src/main/resources/textures/items/spawn_egg_overlay.png differ diff --git a/client/src/main/resources/textures/items/speckled_melon.png b/client/src/main/resources/textures/items/speckled_melon.png new file mode 100755 index 0000000..dee1bf5 Binary files /dev/null and b/client/src/main/resources/textures/items/speckled_melon.png differ diff --git a/client/src/main/resources/textures/items/spider_eye.png b/client/src/main/resources/textures/items/spider_eye.png new file mode 100755 index 0000000..35d8584 Binary files /dev/null and b/client/src/main/resources/textures/items/spider_eye.png differ diff --git a/client/src/main/resources/textures/items/springwater_bucket.png b/client/src/main/resources/textures/items/springwater_bucket.png new file mode 100755 index 0000000..75e0382 Binary files /dev/null and b/client/src/main/resources/textures/items/springwater_bucket.png differ diff --git a/client/src/main/resources/textures/items/spruce_door.png b/client/src/main/resources/textures/items/spruce_door.png new file mode 100755 index 0000000..4eddb7e Binary files /dev/null and b/client/src/main/resources/textures/items/spruce_door.png differ diff --git a/client/src/main/resources/textures/items/stick.png b/client/src/main/resources/textures/items/stick.png new file mode 100755 index 0000000..6f8ce13 Binary files /dev/null and b/client/src/main/resources/textures/items/stick.png differ diff --git a/client/src/main/resources/textures/items/stone_axe.png b/client/src/main/resources/textures/items/stone_axe.png new file mode 100755 index 0000000..fb33584 Binary files /dev/null and b/client/src/main/resources/textures/items/stone_axe.png differ diff --git a/client/src/main/resources/textures/items/stone_hoe.png b/client/src/main/resources/textures/items/stone_hoe.png new file mode 100755 index 0000000..d46b272 Binary files /dev/null and b/client/src/main/resources/textures/items/stone_hoe.png differ diff --git a/client/src/main/resources/textures/items/stone_pickaxe.png b/client/src/main/resources/textures/items/stone_pickaxe.png new file mode 100755 index 0000000..19a8e50 Binary files /dev/null and b/client/src/main/resources/textures/items/stone_pickaxe.png differ diff --git a/client/src/main/resources/textures/items/stone_shovel.png b/client/src/main/resources/textures/items/stone_shovel.png new file mode 100755 index 0000000..8e1c0c2 Binary files /dev/null and b/client/src/main/resources/textures/items/stone_shovel.png differ diff --git a/client/src/main/resources/textures/items/stone_sword.png b/client/src/main/resources/textures/items/stone_sword.png new file mode 100755 index 0000000..5810dfd Binary files /dev/null and b/client/src/main/resources/textures/items/stone_sword.png differ diff --git a/client/src/main/resources/textures/items/string.png b/client/src/main/resources/textures/items/string.png new file mode 100755 index 0000000..0b04ddb Binary files /dev/null and b/client/src/main/resources/textures/items/string.png differ diff --git a/client/src/main/resources/textures/items/sugar.png b/client/src/main/resources/textures/items/sugar.png new file mode 100755 index 0000000..0864df9 Binary files /dev/null and b/client/src/main/resources/textures/items/sugar.png differ diff --git a/client/src/main/resources/textures/items/sulfur_powder.png b/client/src/main/resources/textures/items/sulfur_powder.png new file mode 100755 index 0000000..5c1a8f1 Binary files /dev/null and b/client/src/main/resources/textures/items/sulfur_powder.png differ diff --git a/client/src/main/resources/textures/items/thetium_axe.png b/client/src/main/resources/textures/items/thetium_axe.png new file mode 100755 index 0000000..111c2a6 Binary files /dev/null and b/client/src/main/resources/textures/items/thetium_axe.png differ diff --git a/client/src/main/resources/textures/items/thetium_boots.png b/client/src/main/resources/textures/items/thetium_boots.png new file mode 100755 index 0000000..a6f0540 Binary files /dev/null and b/client/src/main/resources/textures/items/thetium_boots.png differ diff --git a/client/src/main/resources/textures/items/thetium_chestplate.png b/client/src/main/resources/textures/items/thetium_chestplate.png new file mode 100755 index 0000000..2f70677 Binary files /dev/null and b/client/src/main/resources/textures/items/thetium_chestplate.png differ diff --git a/client/src/main/resources/textures/items/thetium_helmet.png b/client/src/main/resources/textures/items/thetium_helmet.png new file mode 100755 index 0000000..7536212 Binary files /dev/null and b/client/src/main/resources/textures/items/thetium_helmet.png differ diff --git a/client/src/main/resources/textures/items/thetium_hoe.png b/client/src/main/resources/textures/items/thetium_hoe.png new file mode 100755 index 0000000..86e8c29 Binary files /dev/null and b/client/src/main/resources/textures/items/thetium_hoe.png differ diff --git a/client/src/main/resources/textures/items/thetium_leggings.png b/client/src/main/resources/textures/items/thetium_leggings.png new file mode 100755 index 0000000..dbf82eb Binary files /dev/null and b/client/src/main/resources/textures/items/thetium_leggings.png differ diff --git a/client/src/main/resources/textures/items/thetium_pickaxe.png b/client/src/main/resources/textures/items/thetium_pickaxe.png new file mode 100755 index 0000000..02054d0 Binary files /dev/null and b/client/src/main/resources/textures/items/thetium_pickaxe.png differ diff --git a/client/src/main/resources/textures/items/thetium_shears.png b/client/src/main/resources/textures/items/thetium_shears.png new file mode 100755 index 0000000..a4014ac Binary files /dev/null and b/client/src/main/resources/textures/items/thetium_shears.png differ diff --git a/client/src/main/resources/textures/items/thetium_shovel.png b/client/src/main/resources/textures/items/thetium_shovel.png new file mode 100755 index 0000000..6a46a34 Binary files /dev/null and b/client/src/main/resources/textures/items/thetium_shovel.png differ diff --git a/client/src/main/resources/textures/items/thetium_sword.png b/client/src/main/resources/textures/items/thetium_sword.png new file mode 100755 index 0000000..26591f1 Binary files /dev/null and b/client/src/main/resources/textures/items/thetium_sword.png differ diff --git a/client/src/main/resources/textures/items/thi_fragment.png b/client/src/main/resources/textures/items/thi_fragment.png new file mode 100755 index 0000000..90abf54 Binary files /dev/null and b/client/src/main/resources/textures/items/thi_fragment.png differ diff --git a/client/src/main/resources/textures/items/tian_door.png b/client/src/main/resources/textures/items/tian_door.png new file mode 100755 index 0000000..0e8353e Binary files /dev/null and b/client/src/main/resources/textures/items/tian_door.png differ diff --git a/client/src/main/resources/textures/items/tin_ingot.png b/client/src/main/resources/textures/items/tin_ingot.png new file mode 100755 index 0000000..95eb514 Binary files /dev/null and b/client/src/main/resources/textures/items/tin_ingot.png differ diff --git a/client/src/main/resources/textures/items/titanium_ingot.png b/client/src/main/resources/textures/items/titanium_ingot.png new file mode 100755 index 0000000..24fbe4b Binary files /dev/null and b/client/src/main/resources/textures/items/titanium_ingot.png differ diff --git a/client/src/main/resources/textures/items/tnt_minecart.png b/client/src/main/resources/textures/items/tnt_minecart.png new file mode 100755 index 0000000..561279b Binary files /dev/null and b/client/src/main/resources/textures/items/tnt_minecart.png differ diff --git a/client/src/main/resources/textures/items/tungsten_ingot.png b/client/src/main/resources/textures/items/tungsten_ingot.png new file mode 100755 index 0000000..a10133d Binary files /dev/null and b/client/src/main/resources/textures/items/tungsten_ingot.png differ diff --git a/client/src/main/resources/textures/items/uranium_ingot.png b/client/src/main/resources/textures/items/uranium_ingot.png new file mode 100755 index 0000000..c8dcafe Binary files /dev/null and b/client/src/main/resources/textures/items/uranium_ingot.png differ diff --git a/client/src/main/resources/textures/items/vanadium_ingot.png b/client/src/main/resources/textures/items/vanadium_ingot.png new file mode 100755 index 0000000..e6c7044 Binary files /dev/null and b/client/src/main/resources/textures/items/vanadium_ingot.png differ diff --git a/client/src/main/resources/textures/items/wand.png b/client/src/main/resources/textures/items/wand.png new file mode 100755 index 0000000..2cb6dd7 Binary files /dev/null and b/client/src/main/resources/textures/items/wand.png differ diff --git a/client/src/main/resources/textures/items/water_bucket.png b/client/src/main/resources/textures/items/water_bucket.png new file mode 100755 index 0000000..2f36acc Binary files /dev/null and b/client/src/main/resources/textures/items/water_bucket.png differ diff --git a/client/src/main/resources/textures/items/weather_token_chilled.png b/client/src/main/resources/textures/items/weather_token_chilled.png new file mode 100755 index 0000000..6a28224 Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_chilled.png differ diff --git a/client/src/main/resources/textures/items/weather_token_clear.png b/client/src/main/resources/textures/items/weather_token_clear.png new file mode 100755 index 0000000..8bb3884 Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_clear.png differ diff --git a/client/src/main/resources/textures/items/weather_token_cold.png b/client/src/main/resources/textures/items/weather_token_cold.png new file mode 100755 index 0000000..679c1d4 Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_cold.png differ diff --git a/client/src/main/resources/textures/items/weather_token_fire.png b/client/src/main/resources/textures/items/weather_token_fire.png new file mode 100755 index 0000000..409b12c Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_fire.png differ diff --git a/client/src/main/resources/textures/items/weather_token_fog.png b/client/src/main/resources/textures/items/weather_token_fog.png new file mode 100755 index 0000000..0e71a00 Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_fog.png differ diff --git a/client/src/main/resources/textures/items/weather_token_frost.png b/client/src/main/resources/textures/items/weather_token_frost.png new file mode 100755 index 0000000..8785594 Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_frost.png differ diff --git a/client/src/main/resources/textures/items/weather_token_hail.png b/client/src/main/resources/textures/items/weather_token_hail.png new file mode 100755 index 0000000..8314060 Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_hail.png differ diff --git a/client/src/main/resources/textures/items/weather_token_hailstorm.png b/client/src/main/resources/textures/items/weather_token_hailstorm.png new file mode 100755 index 0000000..61a53ad Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_hailstorm.png differ diff --git a/client/src/main/resources/textures/items/weather_token_hot.png b/client/src/main/resources/textures/items/weather_token_hot.png new file mode 100755 index 0000000..f611325 Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_hot.png differ diff --git a/client/src/main/resources/textures/items/weather_token_ice.png b/client/src/main/resources/textures/items/weather_token_ice.png new file mode 100755 index 0000000..9f7a9ed Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_ice.png differ diff --git a/client/src/main/resources/textures/items/weather_token_iceage.png b/client/src/main/resources/textures/items/weather_token_iceage.png new file mode 100755 index 0000000..8022792 Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_iceage.png differ diff --git a/client/src/main/resources/textures/items/weather_token_inferno.png b/client/src/main/resources/textures/items/weather_token_inferno.png new file mode 100755 index 0000000..c5aadcc Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_inferno.png differ diff --git a/client/src/main/resources/textures/items/weather_token_rain.png b/client/src/main/resources/textures/items/weather_token_rain.png new file mode 100755 index 0000000..944670b Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_rain.png differ diff --git a/client/src/main/resources/textures/items/weather_token_snow.png b/client/src/main/resources/textures/items/weather_token_snow.png new file mode 100755 index 0000000..d6321d9 Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_snow.png differ diff --git a/client/src/main/resources/textures/items/weather_token_snowstorm.png b/client/src/main/resources/textures/items/weather_token_snowstorm.png new file mode 100755 index 0000000..5a2bb68 Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_snowstorm.png differ diff --git a/client/src/main/resources/textures/items/weather_token_storm.png b/client/src/main/resources/textures/items/weather_token_storm.png new file mode 100755 index 0000000..cad9126 Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_storm.png differ diff --git a/client/src/main/resources/textures/items/weather_token_thunder.png b/client/src/main/resources/textures/items/weather_token_thunder.png new file mode 100755 index 0000000..198988c Binary files /dev/null and b/client/src/main/resources/textures/items/weather_token_thunder.png differ diff --git a/client/src/main/resources/textures/items/wheat.png b/client/src/main/resources/textures/items/wheat.png new file mode 100755 index 0000000..83d23a6 Binary files /dev/null and b/client/src/main/resources/textures/items/wheat.png differ diff --git a/client/src/main/resources/textures/items/wheats.png b/client/src/main/resources/textures/items/wheats.png new file mode 100755 index 0000000..bbd2fd9 Binary files /dev/null and b/client/src/main/resources/textures/items/wheats.png differ diff --git a/client/src/main/resources/textures/items/white_bed.png b/client/src/main/resources/textures/items/white_bed.png new file mode 100755 index 0000000..d45a87f Binary files /dev/null and b/client/src/main/resources/textures/items/white_bed.png differ diff --git a/client/src/main/resources/textures/items/wood_axe.png b/client/src/main/resources/textures/items/wood_axe.png new file mode 100755 index 0000000..3a19203 Binary files /dev/null and b/client/src/main/resources/textures/items/wood_axe.png differ diff --git a/client/src/main/resources/textures/items/wood_hoe.png b/client/src/main/resources/textures/items/wood_hoe.png new file mode 100755 index 0000000..de1c7a6 Binary files /dev/null and b/client/src/main/resources/textures/items/wood_hoe.png differ diff --git a/client/src/main/resources/textures/items/wood_pickaxe.png b/client/src/main/resources/textures/items/wood_pickaxe.png new file mode 100755 index 0000000..ebc6756 Binary files /dev/null and b/client/src/main/resources/textures/items/wood_pickaxe.png differ diff --git a/client/src/main/resources/textures/items/wood_shovel.png b/client/src/main/resources/textures/items/wood_shovel.png new file mode 100755 index 0000000..b057911 Binary files /dev/null and b/client/src/main/resources/textures/items/wood_shovel.png differ diff --git a/client/src/main/resources/textures/items/wood_sword.png b/client/src/main/resources/textures/items/wood_sword.png new file mode 100755 index 0000000..c04dc0a Binary files /dev/null and b/client/src/main/resources/textures/items/wood_sword.png differ diff --git a/client/src/main/resources/textures/items/writable_book.png b/client/src/main/resources/textures/items/writable_book.png new file mode 100755 index 0000000..fa95246 Binary files /dev/null and b/client/src/main/resources/textures/items/writable_book.png differ diff --git a/client/src/main/resources/textures/items/written_book.png b/client/src/main/resources/textures/items/written_book.png new file mode 100755 index 0000000..b2a2aa8 Binary files /dev/null and b/client/src/main/resources/textures/items/written_book.png differ diff --git a/client/src/main/resources/textures/items/zinc_ingot.png b/client/src/main/resources/textures/items/zinc_ingot.png new file mode 100755 index 0000000..10e8650 Binary files /dev/null and b/client/src/main/resources/textures/items/zinc_ingot.png differ diff --git a/client/src/main/resources/textures/world/clouds.png b/client/src/main/resources/textures/world/clouds.png new file mode 100755 index 0000000..a67c44d Binary files /dev/null and b/client/src/main/resources/textures/world/clouds.png differ diff --git a/client/src/main/resources/textures/world/clouds_dense.png b/client/src/main/resources/textures/world/clouds_dense.png new file mode 100755 index 0000000..992d0f4 Binary files /dev/null and b/client/src/main/resources/textures/world/clouds_dense.png differ diff --git a/client/src/main/resources/textures/world/foliage.png b/client/src/main/resources/textures/world/foliage.png new file mode 100755 index 0000000..54c2429 Binary files /dev/null and b/client/src/main/resources/textures/world/foliage.png differ diff --git a/client/src/main/resources/textures/world/forcefield.png b/client/src/main/resources/textures/world/forcefield.png new file mode 100755 index 0000000..3129f07 Binary files /dev/null and b/client/src/main/resources/textures/world/forcefield.png differ diff --git a/client/src/main/resources/textures/world/grass.png b/client/src/main/resources/textures/world/grass.png new file mode 100755 index 0000000..118a69a Binary files /dev/null and b/client/src/main/resources/textures/world/grass.png differ diff --git a/client/src/main/resources/textures/world/hail.png b/client/src/main/resources/textures/world/hail.png new file mode 100755 index 0000000..b354828 Binary files /dev/null and b/client/src/main/resources/textures/world/hail.png differ diff --git a/client/src/main/resources/textures/world/molten.png b/client/src/main/resources/textures/world/molten.png new file mode 100755 index 0000000..59678b4 Binary files /dev/null and b/client/src/main/resources/textures/world/molten.png differ diff --git a/client/src/main/resources/textures/world/moon_phases.png b/client/src/main/resources/textures/world/moon_phases.png new file mode 100755 index 0000000..cdba8d1 Binary files /dev/null and b/client/src/main/resources/textures/world/moon_phases.png differ diff --git a/client/src/main/resources/textures/world/particles.png b/client/src/main/resources/textures/world/particles.png new file mode 100755 index 0000000..447156f Binary files /dev/null and b/client/src/main/resources/textures/world/particles.png differ diff --git a/client/src/main/resources/textures/world/rain.png b/client/src/main/resources/textures/world/rain.png new file mode 100755 index 0000000..e9dc16c Binary files /dev/null and b/client/src/main/resources/textures/world/rain.png differ diff --git a/client/src/main/resources/textures/world/rain_new.png b/client/src/main/resources/textures/world/rain_new.png new file mode 100755 index 0000000..2dc4b1c Binary files /dev/null and b/client/src/main/resources/textures/world/rain_new.png differ diff --git a/client/src/main/resources/textures/world/snow.png b/client/src/main/resources/textures/world/snow.png new file mode 100755 index 0000000..1898903 Binary files /dev/null and b/client/src/main/resources/textures/world/snow.png differ diff --git a/client/src/main/resources/textures/world/sun.png b/client/src/main/resources/textures/world/sun.png new file mode 100755 index 0000000..08de644 Binary files /dev/null and b/client/src/main/resources/textures/world/sun.png differ diff --git a/common/build.gradle.kts b/common/build.gradle.kts new file mode 100644 index 0000000..4676aad --- /dev/null +++ b/common/build.gradle.kts @@ -0,0 +1,10 @@ + +plugins { + `java-library` +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} diff --git a/common/src/main/java/common/Version.java b/common/src/main/java/common/Version.java new file mode 100644 index 0000000..bc57bfa --- /dev/null +++ b/common/src/main/java/common/Version.java @@ -0,0 +1,11 @@ +package common; + +import common.util.ReleaseType; + +public abstract class Version { + public static final String NAME = "TCR"; + public static final ReleaseType RELEASE = ReleaseType.DEV; + public static final int MAJOR = 2; + public static final int MINOR = 3; + public static final int PATCH = 0; +} diff --git a/java/src/game/ai/AIFireballAttack.java b/common/src/main/java/common/ai/AIFireballAttack.java similarity index 92% rename from java/src/game/ai/AIFireballAttack.java rename to common/src/main/java/common/ai/AIFireballAttack.java index ec933eb..87a3b8d 100755 --- a/java/src/game/ai/AIFireballAttack.java +++ b/common/src/main/java/common/ai/AIFireballAttack.java @@ -1,13 +1,13 @@ -package game.ai; +package common.ai; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityFireball; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.item.ItemStack; -import game.world.BlockPos; -import game.world.Vec3; -import game.world.World; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityFireball; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.item.ItemStack; +import common.util.BlockPos; +import common.util.Vec3; +import common.world.World; public class AIFireballAttack extends EntityAIBase { diff --git a/java/src/game/ai/AIFlyingBoxAttack.java b/common/src/main/java/common/ai/AIFlyingBoxAttack.java similarity index 94% rename from java/src/game/ai/AIFlyingBoxAttack.java rename to common/src/main/java/common/ai/AIFlyingBoxAttack.java index f7825b6..444a1dd 100755 --- a/java/src/game/ai/AIFlyingBoxAttack.java +++ b/common/src/main/java/common/ai/AIFlyingBoxAttack.java @@ -1,9 +1,9 @@ -package game.ai; +package common.ai; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityBox; -import game.entity.types.EntityLiving; -import game.world.BlockPos; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityBox; +import common.entity.types.EntityLiving; +import common.util.BlockPos; public class AIFlyingBoxAttack extends EntityAIBase { diff --git a/java/src/game/ai/AIRangedAttack.java b/common/src/main/java/common/ai/AIRangedAttack.java similarity index 96% rename from java/src/game/ai/AIRangedAttack.java rename to common/src/main/java/common/ai/AIRangedAttack.java index 6104b95..caf7d72 100755 --- a/java/src/game/ai/AIRangedAttack.java +++ b/common/src/main/java/common/ai/AIRangedAttack.java @@ -1,8 +1,8 @@ -package game.ai; +package common.ai; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.util.ExtMath; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.util.ExtMath; public class AIRangedAttack extends EntityAIBase { diff --git a/java/src/game/ai/AISmallFireballAttack.java b/common/src/main/java/common/ai/AISmallFireballAttack.java similarity index 95% rename from java/src/game/ai/AISmallFireballAttack.java rename to common/src/main/java/common/ai/AISmallFireballAttack.java index ce27ce7..ed9c9b2 100755 --- a/java/src/game/ai/AISmallFireballAttack.java +++ b/common/src/main/java/common/ai/AISmallFireballAttack.java @@ -1,9 +1,9 @@ -package game.ai; +package common.ai; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityFireCharge; -import game.entity.types.EntityLiving; -import game.world.BlockPos; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityFireCharge; +import common.entity.types.EntityLiving; +import common.util.BlockPos; public class AISmallFireballAttack extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIAttackOnCollide.java b/common/src/main/java/common/ai/EntityAIAttackOnCollide.java similarity index 96% rename from java/src/game/ai/EntityAIAttackOnCollide.java rename to common/src/main/java/common/ai/EntityAIAttackOnCollide.java index 3c21879..ba225f2 100755 --- a/java/src/game/ai/EntityAIAttackOnCollide.java +++ b/common/src/main/java/common/ai/EntityAIAttackOnCollide.java @@ -1,10 +1,10 @@ -package game.ai; +package common.ai; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.pathfinding.PathEntity; -import game.world.BlockPos; -import game.world.World; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.pathfinding.PathEntity; +import common.util.BlockPos; +import common.world.World; public class EntityAIAttackOnCollide extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIAvoidEntity.java b/common/src/main/java/common/ai/EntityAIAvoidEntity.java similarity index 94% rename from java/src/game/ai/EntityAIAvoidEntity.java rename to common/src/main/java/common/ai/EntityAIAvoidEntity.java index 79e15c4..2e26f2b 100755 --- a/java/src/game/ai/EntityAIAvoidEntity.java +++ b/common/src/main/java/common/ai/EntityAIAvoidEntity.java @@ -1,15 +1,14 @@ -package game.ai; +package common.ai; import java.util.List; - import java.util.function.Predicate; -import game.util.Predicates; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.pathfinding.PathEntity; -import game.pathfinding.PathNavigate; -import game.world.Vec3; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.pathfinding.PathEntity; +import common.pathfinding.PathNavigate; +import common.util.Predicates; +import common.util.Vec3; public class EntityAIAvoidEntity extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIBase.java b/common/src/main/java/common/ai/EntityAIBase.java similarity index 98% rename from java/src/game/ai/EntityAIBase.java rename to common/src/main/java/common/ai/EntityAIBase.java index 3b706ea..9eccf20 100755 --- a/java/src/game/ai/EntityAIBase.java +++ b/common/src/main/java/common/ai/EntityAIBase.java @@ -1,4 +1,4 @@ -package game.ai; +package common.ai; public abstract class EntityAIBase { diff --git a/java/src/game/ai/EntityAIBeg.java b/common/src/main/java/common/ai/EntityAIBeg.java similarity index 92% rename from java/src/game/ai/EntityAIBeg.java rename to common/src/main/java/common/ai/EntityAIBeg.java index 5347d54..752e455 100755 --- a/java/src/game/ai/EntityAIBeg.java +++ b/common/src/main/java/common/ai/EntityAIBeg.java @@ -1,10 +1,10 @@ -package game.ai; +package common.ai; -import game.entity.animal.EntityWolf; -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.item.ItemStack; -import game.world.World; +import common.entity.animal.EntityWolf; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.item.ItemStack; +import common.world.World; public class EntityAIBeg extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIControlledByPlayer.java b/common/src/main/java/common/ai/EntityAIControlledByPlayer.java similarity index 91% rename from java/src/game/ai/EntityAIControlledByPlayer.java rename to common/src/main/java/common/ai/EntityAIControlledByPlayer.java index dcee7b8..7b4bed0 100755 --- a/java/src/game/ai/EntityAIControlledByPlayer.java +++ b/common/src/main/java/common/ai/EntityAIControlledByPlayer.java @@ -1,16 +1,16 @@ -package game.ai; +package common.ai; -import game.block.Block; -import game.block.BlockSlab; -import game.block.BlockStairs; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.item.ItemStack; -import game.material.Material; -import game.pathfinding.WalkNodeProcessor; -import game.util.ExtMath; -import game.world.BlockPos; +import common.block.Block; +import common.block.artificial.BlockSlab; +import common.block.artificial.BlockStairs; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.Items; +import common.item.ItemStack; +import common.pathfinding.WalkNodeProcessor; +import common.util.BlockPos; +import common.util.ExtMath; public class EntityAIControlledByPlayer extends EntityAIBase { @@ -162,7 +162,7 @@ public class EntityAIControlledByPlayer extends EntityAIBase if (i != l || k != i1) { Block block = this.thisEntity.worldObj.getState(new BlockPos(i, j, k)).getBlock(); - boolean flag = !this.isStairOrSlab(block) && (block.getMaterial() != Material.air || !this.isStairOrSlab(this.thisEntity.worldObj.getState(new BlockPos(i, j - 1, k)).getBlock())); + boolean flag = !this.isStairOrSlab(block) && (block != Blocks.air || !this.isStairOrSlab(this.thisEntity.worldObj.getState(new BlockPos(i, j - 1, k)).getBlock())); if (flag && 0 == WalkNodeProcessor.getColliding(this.thisEntity.worldObj, this.thisEntity, l, j, i1, j1, k1, l1, false, false, true) && 1 == WalkNodeProcessor.getColliding(this.thisEntity.worldObj, this.thisEntity, i, j + 1, k, j1, k1, l1, false, false, true) && 1 == WalkNodeProcessor.getColliding(this.thisEntity.worldObj, this.thisEntity, l, j + 1, i1, j1, k1, l1, false, false, true)) { @@ -178,7 +178,7 @@ public class EntityAIControlledByPlayer extends EntityAIBase { itemstack.damageItem(1, entityplayer); - if (itemstack.stackSize == 0) + if (itemstack.size == 0) { ItemStack itemstack1 = new ItemStack(Items.fishing_rod); itemstack1.setTagCompound(itemstack.getTagCompound()); diff --git a/java/src/game/ai/EntityAIDoorInteract.java b/common/src/main/java/common/ai/EntityAIDoorInteract.java similarity index 90% rename from java/src/game/ai/EntityAIDoorInteract.java rename to common/src/main/java/common/ai/EntityAIDoorInteract.java index 2a11706..e98a1f4 100755 --- a/java/src/game/ai/EntityAIDoorInteract.java +++ b/common/src/main/java/common/ai/EntityAIDoorInteract.java @@ -1,13 +1,13 @@ -package game.ai; +package common.ai; -import game.block.Block; -import game.block.BlockDoor; -import game.entity.types.EntityLiving; -import game.material.Material; -import game.pathfinding.PathEntity; -import game.pathfinding.PathNavigateGround; -import game.pathfinding.PathPoint; -import game.world.BlockPos; +import common.block.Block; +import common.block.Material; +import common.block.artificial.BlockDoor; +import common.entity.types.EntityLiving; +import common.pathfinding.PathEntity; +import common.pathfinding.PathNavigateGround; +import common.pathfinding.PathPoint; +import common.util.BlockPos; public abstract class EntityAIDoorInteract extends EntityAIBase { @@ -113,6 +113,6 @@ public abstract class EntityAIDoorInteract extends EntityAIBase private BlockDoor getBlockDoor(BlockPos pos) { Block block = this.theEntity.worldObj.getState(pos).getBlock(); - return block instanceof BlockDoor && block.getMaterial() == Material.wood ? (BlockDoor)block : null; + return block instanceof BlockDoor && block.getMaterial() == Material.WOOD ? (BlockDoor)block : null; } } diff --git a/java/src/game/ai/EntityAIEatGrass.java b/common/src/main/java/common/ai/EntityAIEatGrass.java similarity index 72% rename from java/src/game/ai/EntityAIEatGrass.java rename to common/src/main/java/common/ai/EntityAIEatGrass.java index 9886e91..47e76e4 100755 --- a/java/src/game/ai/EntityAIEatGrass.java +++ b/common/src/main/java/common/ai/EntityAIEatGrass.java @@ -1,22 +1,16 @@ -package game.ai; +package common.ai; -import java.util.function.Predicate; -import game.util.Predicates; - -import game.block.BlockTallGrass; -import game.entity.animal.EntitySheep; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.Config; -import game.pattern.BlockStateHelper; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.foliage.BlockTallGrass; +import common.entity.animal.EntitySheep; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.World; public class EntityAIEatGrass extends EntityAIBase { - private static final Predicate field_179505_b = BlockStateHelper.forBlock(Blocks.tallgrass).where(BlockTallGrass.TYPE, Predicates.equalTo(BlockTallGrass.EnumType.GRASS)); - private EntitySheep grassEaterEntity; private World entityWorld; int eatingGrassTimer; @@ -40,7 +34,9 @@ public class EntityAIEatGrass extends EntityAIBase else { BlockPos blockpos = new BlockPos(this.grassEaterEntity.posX, this.grassEaterEntity.posY, this.grassEaterEntity.posZ); - return field_179505_b.test(this.entityWorld.getState(blockpos)) ? true : this.entityWorld.getState(blockpos.down()).getBlock() == Blocks.grass; + State state = this.entityWorld.getState(blockpos); + return (state.getBlock() == Blocks.tallgrass && state.getValue(BlockTallGrass.TYPE) == BlockTallGrass.EnumType.GRASS) || + this.entityWorld.getState(blockpos.down()).getBlock() == Blocks.grass; } } @@ -89,14 +85,15 @@ public class EntityAIEatGrass extends EntityAIBase { BlockPos blockpos = new BlockPos(this.grassEaterEntity.posX, this.grassEaterEntity.posY, this.grassEaterEntity.posZ); - if (field_179505_b.test(this.entityWorld.getState(blockpos))) + State state = this.entityWorld.getState(blockpos); + if (state.getBlock() == Blocks.tallgrass && state.getValue(BlockTallGrass.TYPE) == BlockTallGrass.EnumType.GRASS) { - if (Config.mobGrief) + if (Vars.mobGrief) { this.entityWorld.destroyBlock(blockpos, false); } - this.grassEaterEntity.eatGrassBonus(); + this.grassEaterEntity.eatGrass(); } else { @@ -104,13 +101,13 @@ public class EntityAIEatGrass extends EntityAIBase if (this.entityWorld.getState(blockpos1).getBlock() == Blocks.grass) { - if (Config.mobGrief) + if (Vars.mobGrief) { this.entityWorld.playAuxSFX(2001, blockpos1, BlockRegistry.getIdFromBlock(Blocks.grass)); this.entityWorld.setState(blockpos1, Blocks.dirt.getState(), 2); } - this.grassEaterEntity.eatGrassBonus(); + this.grassEaterEntity.eatGrass(); } } } diff --git a/java/src/game/ai/EntityAIExplode.java b/common/src/main/java/common/ai/EntityAIExplode.java similarity index 93% rename from java/src/game/ai/EntityAIExplode.java rename to common/src/main/java/common/ai/EntityAIExplode.java index d5223b7..16ec2a4 100755 --- a/java/src/game/ai/EntityAIExplode.java +++ b/common/src/main/java/common/ai/EntityAIExplode.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.npc.EntityHaunter; -import game.entity.types.EntityLiving; +import common.entity.npc.EntityHaunter; +import common.entity.types.EntityLiving; public class EntityAIExplode extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIFindEntityNearest.java b/common/src/main/java/common/ai/EntityAIFindEntityNearest.java similarity index 90% rename from java/src/game/ai/EntityAIFindEntityNearest.java rename to common/src/main/java/common/ai/EntityAIFindEntityNearest.java index 99ee83e..5be7b82 100755 --- a/java/src/game/ai/EntityAIFindEntityNearest.java +++ b/common/src/main/java/common/ai/EntityAIFindEntityNearest.java @@ -1,13 +1,10 @@ -package game.ai; +package common.ai; import java.util.Collections; import java.util.List; - import java.util.function.Predicate; -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; +import common.entity.types.EntityLiving; public class EntityAIFindEntityNearest extends EntityAIBase { @@ -106,7 +103,6 @@ public class EntityAIFindEntityNearest extends EntityAIBase protected double getFollowRange() { - AttributeInstance iattributeinstance = this.mob.getEntityAttribute(Attributes.FOLLOW_RANGE); - return iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue(); + return (double)this.mob.getPathingRange(); } } diff --git a/java/src/game/ai/EntityAIFleeSun.java b/common/src/main/java/common/ai/EntityAIFleeSun.java similarity index 90% rename from java/src/game/ai/EntityAIFleeSun.java rename to common/src/main/java/common/ai/EntityAIFleeSun.java index 135d923..85c8c7e 100755 --- a/java/src/game/ai/EntityAIFleeSun.java +++ b/common/src/main/java/common/ai/EntityAIFleeSun.java @@ -1,11 +1,11 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Vec3; -import game.world.World; -import game.world.WorldServer; +import common.entity.types.EntityLiving; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Vec3; +import common.world.World; +import common.world.AWorldServer; public class EntityAIFleeSun extends EntityAIBase { @@ -29,7 +29,7 @@ public class EntityAIFleeSun extends EntityAIBase */ public boolean shouldExecute() { - if (!((WorldServer)this.theWorld).isDaytime()) + if (!((AWorldServer)this.theWorld).isDaytime()) { return false; } diff --git a/java/src/game/ai/EntityAIFollowOwner.java b/common/src/main/java/common/ai/EntityAIFollowOwner.java similarity index 93% rename from java/src/game/ai/EntityAIFollowOwner.java rename to common/src/main/java/common/ai/EntityAIFollowOwner.java index 6e30917..0d03d68 100755 --- a/java/src/game/ai/EntityAIFollowOwner.java +++ b/common/src/main/java/common/ai/EntityAIFollowOwner.java @@ -1,10 +1,10 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.entity.types.EntityTameable; -import game.pathfinding.PathNavigate; -import game.pathfinding.PathNavigateGround; -import game.world.World; +import common.entity.types.EntityLiving; +import common.entity.types.EntityTameable; +import common.pathfinding.PathNavigate; +import common.pathfinding.PathNavigateGround; +import common.world.World; public class EntityAIFollowOwner extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIFollowParent.java b/common/src/main/java/common/ai/EntityAIFollowParent.java similarity index 97% rename from java/src/game/ai/EntityAIFollowParent.java rename to common/src/main/java/common/ai/EntityAIFollowParent.java index c7db17e..d61e1f5 100755 --- a/java/src/game/ai/EntityAIFollowParent.java +++ b/common/src/main/java/common/ai/EntityAIFollowParent.java @@ -1,8 +1,8 @@ -package game.ai; +package common.ai; import java.util.List; -import game.entity.types.EntityAnimal; +import common.entity.types.EntityAnimal; public class EntityAIFollowParent extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIHarvestFarmland.java b/common/src/main/java/common/ai/EntityAIHarvestFarmland.java similarity index 97% rename from java/src/game/ai/EntityAIHarvestFarmland.java rename to common/src/main/java/common/ai/EntityAIHarvestFarmland.java index a35503f..9ea311b 100755 --- a/java/src/game/ai/EntityAIHarvestFarmland.java +++ b/common/src/main/java/common/ai/EntityAIHarvestFarmland.java @@ -1,8 +1,8 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.world.BlockPos; -import game.world.World; +import common.entity.types.EntityLiving; +import common.util.BlockPos; +import common.world.World; public class EntityAIHarvestFarmland extends EntityAIMoveToBlock { diff --git a/java/src/game/ai/EntityAIHurtByTarget.java b/common/src/main/java/common/ai/EntityAIHurtByTarget.java similarity index 96% rename from java/src/game/ai/EntityAIHurtByTarget.java rename to common/src/main/java/common/ai/EntityAIHurtByTarget.java index 51ab111..c4ae5e8 100755 --- a/java/src/game/ai/EntityAIHurtByTarget.java +++ b/common/src/main/java/common/ai/EntityAIHurtByTarget.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.world.BoundingBox; +import common.entity.types.EntityLiving; +import common.util.BoundingBox; public class EntityAIHurtByTarget extends EntityAITarget { diff --git a/java/src/game/ai/EntityAILeapAtTarget.java b/common/src/main/java/common/ai/EntityAILeapAtTarget.java similarity index 95% rename from java/src/game/ai/EntityAILeapAtTarget.java rename to common/src/main/java/common/ai/EntityAILeapAtTarget.java index f772265..8b62906 100755 --- a/java/src/game/ai/EntityAILeapAtTarget.java +++ b/common/src/main/java/common/ai/EntityAILeapAtTarget.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.util.ExtMath; +import common.entity.types.EntityLiving; +import common.util.ExtMath; public class EntityAILeapAtTarget extends EntityAIBase { diff --git a/java/src/game/ai/EntityAILookAtTalkingPlayer.java b/common/src/main/java/common/ai/EntityAILookAtTalkingPlayer.java similarity index 90% rename from java/src/game/ai/EntityAILookAtTalkingPlayer.java rename to common/src/main/java/common/ai/EntityAILookAtTalkingPlayer.java index d268ddc..ce521e0 100755 --- a/java/src/game/ai/EntityAILookAtTalkingPlayer.java +++ b/common/src/main/java/common/ai/EntityAILookAtTalkingPlayer.java @@ -1,6 +1,6 @@ -package game.ai; +package common.ai; -import game.entity.npc.EntityNPC; +import common.entity.npc.EntityNPC; public class EntityAILookAtTalkingPlayer extends EntityAIWatchClosest { diff --git a/java/src/game/ai/EntityAILookIdle.java b/common/src/main/java/common/ai/EntityAILookIdle.java similarity index 96% rename from java/src/game/ai/EntityAILookIdle.java rename to common/src/main/java/common/ai/EntityAILookIdle.java index c8858f4..59f9f1b 100755 --- a/java/src/game/ai/EntityAILookIdle.java +++ b/common/src/main/java/common/ai/EntityAILookIdle.java @@ -1,6 +1,6 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; +import common.entity.types.EntityLiving; public class EntityAILookIdle extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIMate.java b/common/src/main/java/common/ai/EntityAIMate.java similarity index 93% rename from java/src/game/ai/EntityAIMate.java rename to common/src/main/java/common/ai/EntityAIMate.java index cbe3146..be5d9e8 100755 --- a/java/src/game/ai/EntityAIMate.java +++ b/common/src/main/java/common/ai/EntityAIMate.java @@ -1,15 +1,15 @@ -package game.ai; +package common.ai; import java.util.List; -import game.entity.item.EntityXp; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.init.Config; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.World; +import common.entity.item.EntityXp; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.model.ParticleType; +import common.rng.Random; +import common.vars.Vars; +import common.world.World; public class EntityAIMate extends EntityAIBase { @@ -158,7 +158,7 @@ public class EntityAIMate extends EntityAIBase this.theWorld.spawnParticle(ParticleType.HEART, this.theAnimal.posX + d3, this.theAnimal.posY + d4, this.theAnimal.posZ + d5, d0, d1, d2); } - if (entityplayer != null && Config.breedingXP) // FIX xp + if (entityplayer != null && Vars.breedingXP) // FIX xp { this.theWorld.spawnEntityInWorld(new EntityXp(this.theWorld, this.theAnimal.posX, this.theAnimal.posY, this.theAnimal.posZ, random.zrange(7) + 1)); } diff --git a/java/src/game/ai/EntityAIMoveIndoors.java b/common/src/main/java/common/ai/EntityAIMoveIndoors.java similarity index 82% rename from java/src/game/ai/EntityAIMoveIndoors.java rename to common/src/main/java/common/ai/EntityAIMoveIndoors.java index abc69f3..a5294db 100755 --- a/java/src/game/ai/EntityAIMoveIndoors.java +++ b/common/src/main/java/common/ai/EntityAIMoveIndoors.java @@ -1,11 +1,11 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.village.Village; -import game.village.VillageDoorInfo; -import game.world.BlockPos; -import game.world.Vec3; -import game.world.WorldServer; +import common.entity.types.EntityLiving; +import common.util.BlockPos; +import common.util.Vec3; +import common.village.Village; +import common.village.VillageDoorInfo; +import common.world.AWorldServer; public class EntityAIMoveIndoors extends EntityAIBase { @@ -27,7 +27,7 @@ public class EntityAIMoveIndoors extends EntityAIBase { BlockPos blockpos = new BlockPos(this.entityObj); - if ((!((WorldServer)this.entityObj.worldObj).isDaytime() /* || this.entityObj.worldObj.isRaining() && !this.entityObj.worldObj.getBiomeGenForCoords(blockpos).canRain() */) && !this.entityObj.worldObj.dimension.hasNoLight()) + if ((!((AWorldServer)this.entityObj.worldObj).isDaytime() /* || this.entityObj.worldObj.isRaining() && !this.entityObj.worldObj.getBiomeGenForCoords(blockpos).canRain() */) && !this.entityObj.worldObj.dimension.hasNoLight()) { if (this.entityObj.getRNG().zrange(50) != 0) { @@ -39,7 +39,7 @@ public class EntityAIMoveIndoors extends EntityAIBase } else { - Village village = ((WorldServer)this.entityObj.worldObj).getNearestVillage(blockpos, 14); + Village village = ((AWorldServer)this.entityObj.worldObj).getNearestVillage(blockpos, 14); if (village == null) { diff --git a/java/src/game/ai/EntityAIMoveThroughVillage.java b/common/src/main/java/common/ai/EntityAIMoveThroughVillage.java similarity index 89% rename from java/src/game/ai/EntityAIMoveThroughVillage.java rename to common/src/main/java/common/ai/EntityAIMoveThroughVillage.java index 2085b57..2ebfcb6 100755 --- a/java/src/game/ai/EntityAIMoveThroughVillage.java +++ b/common/src/main/java/common/ai/EntityAIMoveThroughVillage.java @@ -1,18 +1,17 @@ -package game.ai; +package common.ai; import java.util.List; -import game.collect.Lists; - -import game.entity.types.EntityLiving; -import game.pathfinding.PathEntity; -import game.pathfinding.PathNavigateGround; -import game.util.ExtMath; -import game.village.Village; -import game.village.VillageDoorInfo; -import game.world.BlockPos; -import game.world.Vec3; -import game.world.WorldServer; +import common.collect.Lists; +import common.entity.types.EntityLiving; +import common.pathfinding.PathEntity; +import common.pathfinding.PathNavigateGround; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Vec3; +import common.village.Village; +import common.village.VillageDoorInfo; +import common.world.AWorldServer; public class EntityAIMoveThroughVillage extends EntityAIBase { @@ -45,13 +44,13 @@ public class EntityAIMoveThroughVillage extends EntityAIBase { this.resizeDoorList(); - if (this.isNocturnal && ((WorldServer)this.theEntity.worldObj).isDaytime()) + if (this.isNocturnal && ((AWorldServer)this.theEntity.worldObj).isDaytime()) { return false; } else { - Village village = ((WorldServer)this.theEntity.worldObj).getNearestVillage(new BlockPos(this.theEntity), 0); + Village village = ((AWorldServer)this.theEntity.worldObj).getNearestVillage(new BlockPos(this.theEntity), 0); if (village == null) { diff --git a/java/src/game/ai/EntityAIMoveToBlock.java b/common/src/main/java/common/ai/EntityAIMoveToBlock.java similarity index 97% rename from java/src/game/ai/EntityAIMoveToBlock.java rename to common/src/main/java/common/ai/EntityAIMoveToBlock.java index 25d3d75..2eb4c0f 100755 --- a/java/src/game/ai/EntityAIMoveToBlock.java +++ b/common/src/main/java/common/ai/EntityAIMoveToBlock.java @@ -1,8 +1,8 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.world.BlockPos; -import game.world.World; +import common.entity.types.EntityLiving; +import common.util.BlockPos; +import common.world.World; public abstract class EntityAIMoveToBlock extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIMoveTowardsRestriction.java b/common/src/main/java/common/ai/EntityAIMoveTowardsRestriction.java similarity index 93% rename from java/src/game/ai/EntityAIMoveTowardsRestriction.java rename to common/src/main/java/common/ai/EntityAIMoveTowardsRestriction.java index 900d49b..5df934d 100755 --- a/java/src/game/ai/EntityAIMoveTowardsRestriction.java +++ b/common/src/main/java/common/ai/EntityAIMoveTowardsRestriction.java @@ -1,8 +1,8 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.world.BlockPos; -import game.world.Vec3; +import common.entity.types.EntityLiving; +import common.util.BlockPos; +import common.util.Vec3; public class EntityAIMoveTowardsRestriction extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIMoveTowardsTarget.java b/common/src/main/java/common/ai/EntityAIMoveTowardsTarget.java similarity index 96% rename from java/src/game/ai/EntityAIMoveTowardsTarget.java rename to common/src/main/java/common/ai/EntityAIMoveTowardsTarget.java index c85bd02..a77254d 100755 --- a/java/src/game/ai/EntityAIMoveTowardsTarget.java +++ b/common/src/main/java/common/ai/EntityAIMoveTowardsTarget.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.world.Vec3; +import common.entity.types.EntityLiving; +import common.util.Vec3; public class EntityAIMoveTowardsTarget extends EntityAIBase { diff --git a/java/src/game/ai/EntityAINagPlayer.java b/common/src/main/java/common/ai/EntityAINagPlayer.java similarity index 91% rename from java/src/game/ai/EntityAINagPlayer.java rename to common/src/main/java/common/ai/EntityAINagPlayer.java index b880895..e83c0c0 100755 --- a/java/src/game/ai/EntityAINagPlayer.java +++ b/common/src/main/java/common/ai/EntityAINagPlayer.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.npc.EntityNPC; -import game.inventory.ContainerMerchant; +import common.entity.npc.EntityNPC; +import common.inventory.ContainerMerchant; public class EntityAINagPlayer extends EntityAIBase { diff --git a/java/src/game/ai/EntityAINearestAttackableTarget.java b/common/src/main/java/common/ai/EntityAINearestAttackableTarget.java similarity index 98% rename from java/src/game/ai/EntityAINearestAttackableTarget.java rename to common/src/main/java/common/ai/EntityAINearestAttackableTarget.java index 1ffbcf6..05d3245 100755 --- a/java/src/game/ai/EntityAINearestAttackableTarget.java +++ b/common/src/main/java/common/ai/EntityAINearestAttackableTarget.java @@ -1,13 +1,12 @@ -package game.ai; +package common.ai; import java.util.Collections; import java.util.Comparator; import java.util.List; - import java.util.function.Predicate; -import game.entity.Entity; -import game.entity.types.EntityLiving; +import common.entity.Entity; +import common.entity.types.EntityLiving; public class EntityAINearestAttackableTarget extends EntityAITarget { diff --git a/java/src/game/ai/EntityAINpcInteract.java b/common/src/main/java/common/ai/EntityAINpcInteract.java similarity index 95% rename from java/src/game/ai/EntityAINpcInteract.java rename to common/src/main/java/common/ai/EntityAINpcInteract.java index 82c5c4c..99849a0 100755 --- a/java/src/game/ai/EntityAINpcInteract.java +++ b/common/src/main/java/common/ai/EntityAINpcInteract.java @@ -1,6 +1,6 @@ -package game.ai; +package common.ai; -import game.entity.npc.EntityNPC; +import common.entity.npc.EntityNPC; public class EntityAINpcInteract extends EntityAIWatchClosest2 { diff --git a/java/src/game/ai/EntityAINpcMate.java b/common/src/main/java/common/ai/EntityAINpcMate.java similarity index 89% rename from java/src/game/ai/EntityAINpcMate.java rename to common/src/main/java/common/ai/EntityAINpcMate.java index ee555de..639566c 100755 --- a/java/src/game/ai/EntityAINpcMate.java +++ b/common/src/main/java/common/ai/EntityAINpcMate.java @@ -1,9 +1,9 @@ -package game.ai; +package common.ai; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.world.World; -import game.world.WorldServer; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.world.World; +import common.world.AWorldServer; public class EntityAINpcMate extends EntityAIBase { @@ -33,7 +33,7 @@ public class EntityAINpcMate extends EntityAIBase { if (this.npc.getIsWillingToMate(true)) { - Entity entity = ((WorldServer)this.worldObj).findNearestEntityWithinAABB(EntityNPC.class, this.npc.getEntityBoundingBox().expand(8.0D, 3.0D, 8.0D), this.npc); + Entity entity = ((AWorldServer)this.worldObj).findNearestEntityWithinAABB(EntityNPC.class, this.npc.getEntityBoundingBox().expand(8.0D, 3.0D, 8.0D), this.npc); if (entity == null) { diff --git a/java/src/game/ai/EntityAIOcelotAttack.java b/common/src/main/java/common/ai/EntityAIOcelotAttack.java similarity index 96% rename from java/src/game/ai/EntityAIOcelotAttack.java rename to common/src/main/java/common/ai/EntityAIOcelotAttack.java index cb48c13..87c61e8 100755 --- a/java/src/game/ai/EntityAIOcelotAttack.java +++ b/common/src/main/java/common/ai/EntityAIOcelotAttack.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.world.World; +import common.entity.types.EntityLiving; +import common.world.World; public class EntityAIOcelotAttack extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIOcelotSit.java b/common/src/main/java/common/ai/EntityAIOcelotSit.java similarity index 88% rename from java/src/game/ai/EntityAIOcelotSit.java rename to common/src/main/java/common/ai/EntityAIOcelotSit.java index cfa2b7e..407c6fd 100755 --- a/java/src/game/ai/EntityAIOcelotSit.java +++ b/common/src/main/java/common/ai/EntityAIOcelotSit.java @@ -1,14 +1,14 @@ -package game.ai; +package common.ai; -import game.block.Block; -import game.block.BlockBed; -import game.entity.animal.EntityOcelot; -import game.init.Blocks; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityChest; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.artificial.BlockBed; +import common.entity.animal.EntityOcelot; +import common.init.Blocks; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityChest; +import common.util.BlockPos; +import common.world.State; +import common.world.World; public class EntityAIOcelotSit extends EntityAIMoveToBlock { diff --git a/java/src/game/ai/EntityAIOpenDoor.java b/common/src/main/java/common/ai/EntityAIOpenDoor.java similarity index 95% rename from java/src/game/ai/EntityAIOpenDoor.java rename to common/src/main/java/common/ai/EntityAIOpenDoor.java index 50879d0..7956a61 100755 --- a/java/src/game/ai/EntityAIOpenDoor.java +++ b/common/src/main/java/common/ai/EntityAIOpenDoor.java @@ -1,6 +1,6 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; +import common.entity.types.EntityLiving; public class EntityAIOpenDoor extends EntityAIDoorInteract { diff --git a/java/src/game/ai/EntityAIOwnerHurtByTarget.java b/common/src/main/java/common/ai/EntityAIOwnerHurtByTarget.java similarity index 94% rename from java/src/game/ai/EntityAIOwnerHurtByTarget.java rename to common/src/main/java/common/ai/EntityAIOwnerHurtByTarget.java index 0230e15..70c3b95 100755 --- a/java/src/game/ai/EntityAIOwnerHurtByTarget.java +++ b/common/src/main/java/common/ai/EntityAIOwnerHurtByTarget.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.entity.types.EntityTameable; +import common.entity.types.EntityLiving; +import common.entity.types.EntityTameable; public class EntityAIOwnerHurtByTarget extends EntityAITarget { diff --git a/java/src/game/ai/EntityAIOwnerHurtTarget.java b/common/src/main/java/common/ai/EntityAIOwnerHurtTarget.java similarity index 93% rename from java/src/game/ai/EntityAIOwnerHurtTarget.java rename to common/src/main/java/common/ai/EntityAIOwnerHurtTarget.java index 8dc2e2a..27d9d53 100755 --- a/java/src/game/ai/EntityAIOwnerHurtTarget.java +++ b/common/src/main/java/common/ai/EntityAIOwnerHurtTarget.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.entity.types.EntityTameable; +import common.entity.types.EntityLiving; +import common.entity.types.EntityTameable; public class EntityAIOwnerHurtTarget extends EntityAITarget { diff --git a/java/src/game/ai/EntityAIPanic.java b/common/src/main/java/common/ai/EntityAIPanic.java similarity index 94% rename from java/src/game/ai/EntityAIPanic.java rename to common/src/main/java/common/ai/EntityAIPanic.java index 0735848..7848752 100755 --- a/java/src/game/ai/EntityAIPanic.java +++ b/common/src/main/java/common/ai/EntityAIPanic.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.world.Vec3; +import common.entity.types.EntityLiving; +import common.util.Vec3; public class EntityAIPanic extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIPlay.java b/common/src/main/java/common/ai/EntityAIPlay.java similarity index 93% rename from java/src/game/ai/EntityAIPlay.java rename to common/src/main/java/common/ai/EntityAIPlay.java index 83fec8f..f64d219 100755 --- a/java/src/game/ai/EntityAIPlay.java +++ b/common/src/main/java/common/ai/EntityAIPlay.java @@ -1,10 +1,10 @@ -package game.ai; +package common.ai; import java.util.List; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.world.Vec3; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.util.Vec3; public class EntityAIPlay extends EntityAIBase { private EntityNPC entity; diff --git a/java/src/game/ai/EntityAIRestrictOpenDoor.java b/common/src/main/java/common/ai/EntityAIRestrictOpenDoor.java similarity index 76% rename from java/src/game/ai/EntityAIRestrictOpenDoor.java rename to common/src/main/java/common/ai/EntityAIRestrictOpenDoor.java index 94991dc..15235cb 100755 --- a/java/src/game/ai/EntityAIRestrictOpenDoor.java +++ b/common/src/main/java/common/ai/EntityAIRestrictOpenDoor.java @@ -1,11 +1,11 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.pathfinding.PathNavigateGround; -import game.village.Village; -import game.village.VillageDoorInfo; -import game.world.BlockPos; -import game.world.WorldServer; +import common.entity.types.EntityLiving; +import common.pathfinding.PathNavigateGround; +import common.util.BlockPos; +import common.village.Village; +import common.village.VillageDoorInfo; +import common.world.AWorldServer; public class EntityAIRestrictOpenDoor extends EntityAIBase { @@ -27,14 +27,14 @@ public class EntityAIRestrictOpenDoor extends EntityAIBase */ public boolean shouldExecute() { - if (((WorldServer)this.entityObj.worldObj).isDaytime()) + if (((AWorldServer)this.entityObj.worldObj).isDaytime()) { return false; } else { BlockPos blockpos = new BlockPos(this.entityObj); - Village village = ((WorldServer)this.entityObj.worldObj).getNearestVillage(blockpos, 16); + Village village = ((AWorldServer)this.entityObj.worldObj).getNearestVillage(blockpos, 16); if (village == null) { @@ -53,7 +53,7 @@ public class EntityAIRestrictOpenDoor extends EntityAIBase */ public boolean continueExecuting() { - return ((WorldServer)this.entityObj.worldObj).isDaytime() ? false : !this.frontDoor.getIsDetachedFromVillageFlag() && this.frontDoor.isIndoorSide(new BlockPos(this.entityObj)); + return ((AWorldServer)this.entityObj.worldObj).isDaytime() ? false : !this.frontDoor.getIsDetachedFromVillageFlag() && this.frontDoor.isIndoorSide(new BlockPos(this.entityObj)); } /** diff --git a/java/src/game/ai/EntityAIRestrictSun.java b/common/src/main/java/common/ai/EntityAIRestrictSun.java similarity index 76% rename from java/src/game/ai/EntityAIRestrictSun.java rename to common/src/main/java/common/ai/EntityAIRestrictSun.java index 80068d0..50e2901 100755 --- a/java/src/game/ai/EntityAIRestrictSun.java +++ b/common/src/main/java/common/ai/EntityAIRestrictSun.java @@ -1,8 +1,8 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.pathfinding.PathNavigateGround; -import game.world.WorldServer; +import common.entity.types.EntityLiving; +import common.pathfinding.PathNavigateGround; +import common.world.AWorldServer; public class EntityAIRestrictSun extends EntityAIBase { @@ -18,7 +18,7 @@ public class EntityAIRestrictSun extends EntityAIBase */ public boolean shouldExecute() { - return ((WorldServer)this.theEntity.worldObj).isDaytime(); + return ((AWorldServer)this.theEntity.worldObj).isDaytime(); } /** diff --git a/java/src/game/ai/EntityAIRunAroundLikeCrazy.java b/common/src/main/java/common/ai/EntityAIRunAroundLikeCrazy.java similarity index 94% rename from java/src/game/ai/EntityAIRunAroundLikeCrazy.java rename to common/src/main/java/common/ai/EntityAIRunAroundLikeCrazy.java index baaeb2c..08680dd 100755 --- a/java/src/game/ai/EntityAIRunAroundLikeCrazy.java +++ b/common/src/main/java/common/ai/EntityAIRunAroundLikeCrazy.java @@ -1,9 +1,9 @@ -package game.ai; +package common.ai; -import game.entity.Entity; -import game.entity.animal.EntityHorse; -import game.entity.npc.EntityNPC; -import game.world.Vec3; +import common.entity.Entity; +import common.entity.animal.EntityHorse; +import common.entity.npc.EntityNPC; +import common.util.Vec3; public class EntityAIRunAroundLikeCrazy extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIShareItems.java b/common/src/main/java/common/ai/EntityAIShareItems.java similarity index 83% rename from java/src/game/ai/EntityAIShareItems.java rename to common/src/main/java/common/ai/EntityAIShareItems.java index e0bda32..a43c792 100755 --- a/java/src/game/ai/EntityAIShareItems.java +++ b/common/src/main/java/common/ai/EntityAIShareItems.java @@ -1,12 +1,12 @@ -package game.ai; +package common.ai; -import game.entity.item.EntityItem; -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.inventory.InventoryBasic; -import game.item.Item; -import game.item.ItemStack; -import game.util.ExtMath; +import common.entity.item.EntityItem; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.inventory.InventoryBasic; +import common.item.Item; +import common.item.ItemStack; +import common.util.ExtMath; public class EntityAIShareItems extends EntityAIWatchClosest2 { @@ -60,21 +60,21 @@ public class EntityAIShareItems extends EntityAIWatchClosest2 { Item item = itemstack.getItem(); - if ((item == Items.bread || item == Items.potato || item == Items.carrot) && itemstack.stackSize > 3) + if ((item == Items.bread || item == Items.potato || item == Items.carrot) && itemstack.size > 3) { - int l = itemstack.stackSize / 2; - itemstack.stackSize -= l; + int l = itemstack.size / 2; + itemstack.size -= l; itemstack1 = new ItemStack(item, l, itemstack.getMetadata()); } - else if (item == Items.wheats && itemstack.stackSize > 5) + else if (item == Items.wheats && itemstack.size > 5) { - int j = itemstack.stackSize / 2 / 3 * 3; + int j = itemstack.size / 2 / 3 * 3; int k = j / 3; - itemstack.stackSize -= j; + itemstack.size -= j; itemstack1 = new ItemStack(Items.bread, k, 0); } - if (itemstack.stackSize <= 0) + if (itemstack.size <= 0) { inventorybasic.setInventorySlotContents(i, (ItemStack)null); } diff --git a/java/src/game/ai/EntityAISit.java b/common/src/main/java/common/ai/EntityAISit.java similarity index 93% rename from java/src/game/ai/EntityAISit.java rename to common/src/main/java/common/ai/EntityAISit.java index 48d0b4f..6ffb567 100755 --- a/java/src/game/ai/EntityAISit.java +++ b/common/src/main/java/common/ai/EntityAISit.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.entity.types.EntityTameable; +import common.entity.types.EntityLiving; +import common.entity.types.EntityTameable; public class EntityAISit extends EntityAIBase { diff --git a/java/src/game/ai/EntityAISwimming.java b/common/src/main/java/common/ai/EntityAISwimming.java similarity index 87% rename from java/src/game/ai/EntityAISwimming.java rename to common/src/main/java/common/ai/EntityAISwimming.java index eb7e86a..b7a6193 100755 --- a/java/src/game/ai/EntityAISwimming.java +++ b/common/src/main/java/common/ai/EntityAISwimming.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.pathfinding.PathNavigateGround; +import common.entity.types.EntityLiving; +import common.pathfinding.PathNavigateGround; public class EntityAISwimming extends EntityAIBase { diff --git a/java/src/game/ai/EntityAITakePlace.java b/common/src/main/java/common/ai/EntityAITakePlace.java similarity index 84% rename from java/src/game/ai/EntityAITakePlace.java rename to common/src/main/java/common/ai/EntityAITakePlace.java index 564c713..7741361 100755 --- a/java/src/game/ai/EntityAITakePlace.java +++ b/common/src/main/java/common/ai/EntityAITakePlace.java @@ -1,21 +1,19 @@ -package game.ai; +package common.ai; import java.util.Map; -import game.collect.Maps; - -import game.block.Block; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Config; -import game.init.ItemRegistry; -import game.item.ItemStack; -import game.material.Material; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.collect.Maps; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.item.ItemStack; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import common.vars.Vars; +import common.world.State; +import common.world.World; public class EntityAITakePlace extends EntityAIBase { @@ -30,12 +28,12 @@ public class EntityAITakePlace extends EntityAIBase } public StackKey(ItemStack stack) { - this.item = ItemRegistry.REGISTRY.getNameForObject(stack.getItem()).toString(); + this.item = ItemRegistry.getNameFromItem(stack.getItem()).toString(); this.meta = stack.getItem().getMaxDamage() <= 0 ? stack.getMetadata() : -1; } // public boolean isSame(ItemStack stack) { -// return this.item.equals(ItemRegistry.REGISTRY.getNameForObject(stack.getItem()).toString()) && +// return this.item.equals(ItemRegistry.getNameFromItem(stack.getItem()).toString()) && // (stack.getItem().getMaxDamage() > 0 || stack.getMetadata() == this.meta); // } @@ -81,7 +79,7 @@ public class EntityAITakePlace extends EntityAIBase public boolean shouldExecute() { - if(!Config.mobGrief || this.entity.getAttackTarget() != null) + if(!Vars.mobGrief || this.entity.getAttackTarget() != null) return false; if(this.entity.getHeldItem() == null) { this.place = false; @@ -109,15 +107,15 @@ public class EntityAITakePlace extends EntityAIBase Block replace = world.getState(blockpos).getBlock(); Block below = world.getState(blockpos.down()).getBlock(); State state = PLACEABLE.get(new StackKey(this.entity.getHeldItem())); - if (state.getBlock().canPlaceBlockAt(world, blockpos) && replace.getMaterial() == Material.air && - below.getMaterial() != Material.air && below.isFullCube()) + if (state.getBlock().canPlaceBlockAt(world, blockpos) && replace == Blocks.air && + below != Blocks.air && below.isFullCube()) { this.entity.getLookHelper().setLookPosition((double)i + 0.5, (double)j + 0.5, (double)k + 0.5, 10.0F, (float)this.entity.getVerticalFaceSpeed()); this.entity.swingItem(); world.setState(blockpos, state, 3); - --stack.stackSize; - if(stack.stackSize <= 0) + --stack.size; + if(stack.size <= 0) this.entity.setItemNoUpdate(0, null); } } @@ -127,14 +125,14 @@ public class EntityAITakePlace extends EntityAIBase if (STEALABLE.containsKey(state) && (this.entity.getHeldItem() == null || (ItemStack.areItemsEqual(STEALABLE.get(state), - this.entity.getHeldItem()) && this.entity.getHeldItem().stackSize < this.entity.getHeldItem().getMaxStackSize()))) + this.entity.getHeldItem()) && this.entity.getHeldItem().size < this.entity.getHeldItem().getMaxStackSize()))) { this.entity.getLookHelper().setLookPosition((double)i + 0.5, (double)j + 0.5, (double)k + 0.5, 10.0F, (float)this.entity.getVerticalFaceSpeed()); this.entity.swingItem(); world.setState(blockpos, Blocks.air.getState()); if(this.entity.getHeldItem() != null) - ++this.entity.getHeldItem().stackSize; + ++this.entity.getHeldItem().size; else this.entity.setItemNoUpdate(0, STEALABLE.get(state).copy()); } diff --git a/java/src/game/ai/EntityAITarget.java b/common/src/main/java/common/ai/EntityAITarget.java similarity index 90% rename from java/src/game/ai/EntityAITarget.java rename to common/src/main/java/common/ai/EntityAITarget.java index 506cf60..fae31b0 100755 --- a/java/src/game/ai/EntityAITarget.java +++ b/common/src/main/java/common/ai/EntityAITarget.java @@ -1,14 +1,12 @@ -package game.ai; +package common.ai; -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; -import game.entity.types.IEntityOwnable; -import game.init.Config; -import game.pathfinding.PathEntity; -import game.pathfinding.PathPoint; -import game.util.ExtMath; -import game.world.BlockPos; +import common.entity.types.EntityLiving; +import common.entity.types.IEntityOwnable; +import common.pathfinding.PathEntity; +import common.pathfinding.PathPoint; +import common.util.BlockPos; +import common.util.ExtMath; +import common.vars.Vars; public abstract class EntityAITarget extends EntityAIBase { @@ -99,7 +97,7 @@ public abstract class EntityAITarget extends EntityAIBase } } - return Config.mobAttacks; + return Vars.mobAttacks; } // } } @@ -107,8 +105,7 @@ public abstract class EntityAITarget extends EntityAIBase protected double getTargetDistance() { - AttributeInstance iattributeinstance = this.taskOwner.getEntityAttribute(Attributes.FOLLOW_RANGE); - return iattributeinstance == null ? 16.0D : iattributeinstance.getAttributeValue(); + return (double)this.taskOwner.getPathingRange(); } /** @@ -146,7 +143,7 @@ public abstract class EntityAITarget extends EntityAIBase { return false; } - else if (!Config.infight && target.getClass() == attacker.getClass()) + else if (!Vars.infight && target.getClass() == attacker.getClass()) { return false; } @@ -174,7 +171,7 @@ public abstract class EntityAITarget extends EntityAIBase return false; // } } - else if (!Config.mobAttacks) + else if (!Vars.mobAttacks) { return false; } diff --git a/java/src/game/ai/EntityAITargetNonTamed.java b/common/src/main/java/common/ai/EntityAITargetNonTamed.java similarity index 86% rename from java/src/game/ai/EntityAITargetNonTamed.java rename to common/src/main/java/common/ai/EntityAITargetNonTamed.java index 4b9fd5b..2b0cfc3 100755 --- a/java/src/game/ai/EntityAITargetNonTamed.java +++ b/common/src/main/java/common/ai/EntityAITargetNonTamed.java @@ -1,9 +1,9 @@ -package game.ai; +package common.ai; import java.util.function.Predicate; -import game.entity.types.EntityLiving; -import game.entity.types.EntityTameable; +import common.entity.types.EntityLiving; +import common.entity.types.EntityTameable; public class EntityAITargetNonTamed extends EntityAINearestAttackableTarget { diff --git a/java/src/game/ai/EntityAITasks.java b/common/src/main/java/common/ai/EntityAITasks.java similarity index 99% rename from java/src/game/ai/EntityAITasks.java rename to common/src/main/java/common/ai/EntityAITasks.java index 3db2a95..98f50c9 100755 --- a/java/src/game/ai/EntityAITasks.java +++ b/common/src/main/java/common/ai/EntityAITasks.java @@ -1,9 +1,9 @@ -package game.ai; +package common.ai; import java.util.Iterator; import java.util.List; -import game.collect.Lists; +import common.collect.Lists; public class EntityAITasks { diff --git a/java/src/game/ai/EntityAITempt.java b/common/src/main/java/common/ai/EntityAITempt.java similarity index 96% rename from java/src/game/ai/EntityAITempt.java rename to common/src/main/java/common/ai/EntityAITempt.java index ff230ba..a7008c7 100755 --- a/java/src/game/ai/EntityAITempt.java +++ b/common/src/main/java/common/ai/EntityAITempt.java @@ -1,10 +1,10 @@ -package game.ai; +package common.ai; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.item.Item; -import game.item.ItemStack; -import game.pathfinding.PathNavigateGround; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.item.Item; +import common.item.ItemStack; +import common.pathfinding.PathNavigateGround; public class EntityAITempt extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIWander.java b/common/src/main/java/common/ai/EntityAIWander.java similarity index 96% rename from java/src/game/ai/EntityAIWander.java rename to common/src/main/java/common/ai/EntityAIWander.java index 29e1c68..79067a6 100755 --- a/java/src/game/ai/EntityAIWander.java +++ b/common/src/main/java/common/ai/EntityAIWander.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.world.Vec3; +import common.entity.types.EntityLiving; +import common.util.Vec3; public class EntityAIWander extends EntityAIBase { diff --git a/java/src/game/ai/EntityAIWatchClosest.java b/common/src/main/java/common/ai/EntityAIWatchClosest.java similarity index 88% rename from java/src/game/ai/EntityAIWatchClosest.java rename to common/src/main/java/common/ai/EntityAIWatchClosest.java index 54c17a7..43c1703 100755 --- a/java/src/game/ai/EntityAIWatchClosest.java +++ b/common/src/main/java/common/ai/EntityAIWatchClosest.java @@ -1,8 +1,8 @@ -package game.ai; +package common.ai; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.world.WorldServer; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.world.AWorldServer; public class EntityAIWatchClosest extends EntityAIBase { @@ -57,7 +57,7 @@ public class EntityAIWatchClosest extends EntityAIBase } else { - this.closestEntity = ((WorldServer)this.theWatcher.worldObj).findNearestEntityWithinAABB(this.watchedClass, this.theWatcher.getEntityBoundingBox().expand((double)this.maxDistanceForPlayer, 3.0D, (double)this.maxDistanceForPlayer), this.theWatcher); + this.closestEntity = ((AWorldServer)this.theWatcher.worldObj).findNearestEntityWithinAABB(this.watchedClass, this.theWatcher.getEntityBoundingBox().expand((double)this.maxDistanceForPlayer, 3.0D, (double)this.maxDistanceForPlayer), this.theWatcher); } return this.closestEntity != null; diff --git a/java/src/game/ai/EntityAIWatchClosest2.java b/common/src/main/java/common/ai/EntityAIWatchClosest2.java similarity index 78% rename from java/src/game/ai/EntityAIWatchClosest2.java rename to common/src/main/java/common/ai/EntityAIWatchClosest2.java index 8991e82..0684c41 100755 --- a/java/src/game/ai/EntityAIWatchClosest2.java +++ b/common/src/main/java/common/ai/EntityAIWatchClosest2.java @@ -1,7 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.Entity; -import game.entity.types.EntityLiving; +import common.entity.Entity; +import common.entity.types.EntityLiving; public class EntityAIWatchClosest2 extends EntityAIWatchClosest { diff --git a/java/src/game/ai/EntityJumpHelper.java b/common/src/main/java/common/ai/EntityJumpHelper.java similarity index 88% rename from java/src/game/ai/EntityJumpHelper.java rename to common/src/main/java/common/ai/EntityJumpHelper.java index 461cff0..cf9b91c 100755 --- a/java/src/game/ai/EntityJumpHelper.java +++ b/common/src/main/java/common/ai/EntityJumpHelper.java @@ -1,6 +1,6 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; +import common.entity.types.EntityLiving; public class EntityJumpHelper { diff --git a/java/src/game/ai/EntityLookHelper.java b/common/src/main/java/common/ai/EntityLookHelper.java similarity index 96% rename from java/src/game/ai/EntityLookHelper.java rename to common/src/main/java/common/ai/EntityLookHelper.java index e2a5243..26e5d7e 100755 --- a/java/src/game/ai/EntityLookHelper.java +++ b/common/src/main/java/common/ai/EntityLookHelper.java @@ -1,8 +1,8 @@ -package game.ai; +package common.ai; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.util.ExtMath; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.util.ExtMath; public class EntityLookHelper { diff --git a/java/src/game/ai/EntityMoveHelper.java b/common/src/main/java/common/ai/EntityMoveHelper.java similarity index 92% rename from java/src/game/ai/EntityMoveHelper.java rename to common/src/main/java/common/ai/EntityMoveHelper.java index a7f8e5c..e5b5e08 100755 --- a/java/src/game/ai/EntityMoveHelper.java +++ b/common/src/main/java/common/ai/EntityMoveHelper.java @@ -1,8 +1,7 @@ -package game.ai; +package common.ai; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; -import game.util.ExtMath; +import common.entity.types.EntityLiving; +import common.util.ExtMath; public class EntityMoveHelper { @@ -63,7 +62,7 @@ public class EntityMoveHelper { float f = (float)(ExtMath.atan2(d1, d0) * 180.0D / Math.PI) - 90.0F; this.entity.rotYaw = this.limitAngle(this.entity.rotYaw, f, 30.0F); - this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getEntityAttribute(Attributes.MOVEMENT_SPEED).getAttributeValue())); + this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getMovementSpeed())); if (d2 > 0.0D && d0 * d0 + d1 * d1 < 1.0D) { diff --git a/java/src/game/ai/EntitySenses.java b/common/src/main/java/common/ai/EntitySenses.java similarity index 91% rename from java/src/game/ai/EntitySenses.java rename to common/src/main/java/common/ai/EntitySenses.java index e9c257d..b0aa429 100755 --- a/java/src/game/ai/EntitySenses.java +++ b/common/src/main/java/common/ai/EntitySenses.java @@ -1,11 +1,10 @@ -package game.ai; +package common.ai; import java.util.List; -import game.collect.Lists; - -import game.entity.Entity; -import game.entity.types.EntityLiving; +import common.collect.Lists; +import common.entity.Entity; +import common.entity.types.EntityLiving; public class EntitySenses { diff --git a/java/src/game/ai/RandomPositionGenerator.java b/common/src/main/java/common/ai/RandomPositionGenerator.java similarity index 96% rename from java/src/game/ai/RandomPositionGenerator.java rename to common/src/main/java/common/ai/RandomPositionGenerator.java index 57712ba..54b1bae 100755 --- a/java/src/game/ai/RandomPositionGenerator.java +++ b/common/src/main/java/common/ai/RandomPositionGenerator.java @@ -1,10 +1,10 @@ -package game.ai; +package common.ai; -import game.entity.types.EntityLiving; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Vec3; +import common.entity.types.EntityLiving; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Vec3; public class RandomPositionGenerator { diff --git a/common/src/main/java/common/attributes/Attribute.java b/common/src/main/java/common/attributes/Attribute.java new file mode 100755 index 0000000..571529a --- /dev/null +++ b/common/src/main/java/common/attributes/Attribute.java @@ -0,0 +1,17 @@ +package common.attributes; + +public enum Attribute { + RADIATION("Strahlung"), + RADIATION_RESISTANCE("Strahlungsresistenz"), + MAGIC_RESISTANCE("Magieresistenz"); + + private final String display; + + private Attribute(String display) { + this.display = display; + } + + public String toString() { + return this.display; + } +} diff --git a/common/src/main/java/common/attributes/AttributeMap.java b/common/src/main/java/common/attributes/AttributeMap.java new file mode 100755 index 0000000..dfa8512 --- /dev/null +++ b/common/src/main/java/common/attributes/AttributeMap.java @@ -0,0 +1,60 @@ +package common.attributes; + +import java.util.Map; +import java.util.Map.Entry; + +import common.collect.Maps; + +public class AttributeMap { + private class AttributeInstance { + private final Map slots = Maps.newHashMap(); + + private boolean update = true; + private float value; + + public void applyModifier(int slot, float amount) { + this.slots.put(slot, amount); + this.update = true; + } + + public void removeModifier(int slot) { + if(this.slots.remove(slot) != null) + this.update = true; + } + + public float getAttributeValue() { + if(this.update) { + this.value = 0.0f; + for(Float mod : this.slots.values()) { + this.value += mod; + } + this.update = false; + } + return this.value; + } + } + + private final Map attributes = Maps.newHashMap(); + + public AttributeMap() { + for(Attribute attribute : Attribute.values()) { + this.attributes.put(attribute, new AttributeInstance()); + } + } + + public float get(Attribute attribute) { + return this.attributes.get(attribute).getAttributeValue(); + } + + public void remove(Map modifiers, int slot) { + for(Entry entry : modifiers.entrySet()) { + this.attributes.get(entry.getKey()).removeModifier(slot); + } + } + + public void add(Map modifiers, int slot, int amount) { + for(Entry entry : modifiers.entrySet()) { + this.attributes.get(entry.getKey()).applyModifier(slot, entry.getValue() * (float)amount); + } + } +} diff --git a/common/src/main/java/common/attributes/UsageSlot.java b/common/src/main/java/common/attributes/UsageSlot.java new file mode 100644 index 0000000..2873075 --- /dev/null +++ b/common/src/main/java/common/attributes/UsageSlot.java @@ -0,0 +1,38 @@ +package common.attributes; + +public enum UsageSlot { + HAND(0), HEAD(4, 0), BODY(3, 1), LEGS(2, 2), FEET(1, 3), INVENTORY(-1); + + private static final UsageSlot[] LOOKUP = new UsageSlot[UsageSlot.values().length]; + + private final int index; + private final int armor; + + static { + for(UsageSlot slot : values()) { + if(slot.index >= 0) + LOOKUP[slot.index] = slot; + } + } + + private UsageSlot(int index, int armor) { + this.index = index; + this.armor = armor; + } + + private UsageSlot(int index) { + this(index, -1); + } + + public int getIndex() { + return this.index; + } + + public int getArmorSlot() { + return this.armor; + } + + public static UsageSlot getByIndex(int index) { + return index < 0 || index >= LOOKUP.length ? null : LOOKUP[index]; + } +} diff --git a/common/src/main/java/common/biome/Biome.java b/common/src/main/java/common/biome/Biome.java new file mode 100644 index 0000000..92a4d66 --- /dev/null +++ b/common/src/main/java/common/biome/Biome.java @@ -0,0 +1,235 @@ +package common.biome; + +import java.util.List; +import java.util.Map; + +import common.collect.Lists; +import common.collect.Maps; +import common.color.Colorizer; +import common.log.Log; +import common.rng.PerlinGen; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; + +public enum Biome { + NONE(0, "none", "", 0x000000), + PLAINS(1, "plains", "Ebene", 0x8db360, 12.0f, 40.0f), + DESERT(2, "desert", "Wüste", 0xfa9418, 60.0f, 0.0f), + EXTREMEHILLS(3, "extremeHills", "Extremes Bergland", 0x606060, -12.0f, 30.0f), + FOREST(4, "forest", "Wald", 0x056621, 8.0f, 80.0f), + TAIGA(5, "taiga", "Taiga", 0x0b6659, -10.0f, 80.0f), + SWAMPLAND(6, "swampland", "Sumpf", 0x07f9b2, 12.0f, 90.0f, 0xe0ffae, 0xffffffff, 6975545), + RIVER(7, "river", "Fluss", 0x0000ff), + EXTERMINATED(8, "exterminated", "Ausgelöscht", 0x000000, 150.0f, 0.0f, 0x202020, 0x303030, 0x303030, 0x101010, 0x303030, 0x000000), + SPACE(9, "space", "Leere des Weltraums", 0x000000, 0.0f, 0.0f), + FROZENSEA(10, "frozenSea", "Vereister See", 0x9090a0, -20.0f), + FROZENRIVER(11, "frozenRiver", "Vereister Fluss", 0xa0a0ff, -20.0f), + ICEPLAINS(12, "icePlains", "Eisebene", 0xffffff, -20.0f), + ICEMOUNTAINS(13, "iceMountains", "Vereistes Bergland", 0xa0a0a0, -20.0f), + MUSHROOMPLAINS(14, "mushroomPlains", "Pilzland", 0xff00ff, 16.0f, 100.0f), + BLACKENED(15, "blackened", "Schwarz", 0x000000, 0.0f, 0.0f, 0x000000, 0x303030, 0x303030), + BEACH(16, "beach", "Strand", 0xfade55, 12.0f, 40.0f), + DESERTHILLS(17, "desertHills", "Wüsten-Bergland", 0xd25f12, 60.0f, 0.0f), + FORESTHILLS(18, "forestHills", "Wald-Bergland", 0x22551c, 8.0f, 80.0f), + TAIGAHILLS(19, "taigaHills", "Taiga-Bergland", 0x163933, -10.0f, 80.0f), + EXTREMEHILLSEDGE(20, "extremeHillsEdge", "Extremes Bergland Gr.", 0x72789a, -12.0f, 30.0f), + JUNGLE(21, "jungle", "Urwald", 0x537b09, 18.0f, 90.0f), + JUNGLEHILLS(22, "jungleHills", "Urwald-Bergland", 0x2c4205, 18.0f, 90.0f), + JUNGLEEDGE(23, "jungleEdge", "Urwald Gr.", 0x628b17, 18.0f, 80.0f), + SEA(24, "sea", "See", 0x000070), + STONEBEACH(25, "stoneBeach", "Steinstrand", 0xa2a284, -12.0f, 30.0f), + COLDBEACH(26, "coldBeach", "Vereister Strand", 0xfaf0c0, -18.0f, 30.0f), + BIRCHFOREST(27, "birchForest", "Birkenwald", 0x307444, 4.0f, 60.0f), + BIRCHFORESTHILLS(28, "birchForestHills", "Birkenwald-Bergland", 0x1f5f32, 4.0f, 60.0f), + ROOFEDFOREST(29, "roofedForest", "Dichter Wald", 0x40511a, 8.0f, 80.0f), + COLDTAIGA(30, "coldTaiga", "Vereiste Taiga", 0x31554a, -40.0f, 40.0f), + COLDTAIGAHILLS(31, "coldTaigaHills", "Vereistes Taiga-Bergland", 0x243f36, -40.0f, 40.0f), + MEGATAIGA(32, "megaTaiga", "Hohe Taiga", 0x596651, -8.0f, 80.0f), + MEGATAIGAHILLS(33, "megaTaigaHills", "Hohes Taiga-Bergland", 0x454f3e, -8.0f, 80.0f), + EXTREMEHILLSPLUS(34, "extremeHillsPlus", "Extremes Bergland +", 0x507050, -12.0f, 30.0f), + SAVANNA(35, "savanna", "Savanne", 0xbdb25f, 28.0f, 0.0f), + SAVANNAPLATEAU(36, "savannaPlateau", "Savannen-Plateau", 0xa79d64, 20.0f, 0.0f), + MESA(37, "mesa", "Mesa", 0xd94515, 0.0f, 0.0f, 0xffffff, 9470285, 10387789), + MESAPLATEAUF(38, "mesaPlateauF", "Mesa-Waldplateau", 0xb09765, 0.0f, 0.0f, 0xffffff, 9470285, 10387789), + MESAPLATEAU(39, "mesaPlateau", "Mesa-Plateau", 0xca8c65, 0.0f, 0.0f, 0xffffff, 9470285, 10387789), + SNOWLAND(40, "snowLand", "Eisland", 0xffffff, 0.0f, 100.0f), + TIAN(41, "tian", "Tian", 0x808080, 0.0f, 80.0f), + ELVENFOREST(42, "elvenForest", "Elbenwald", 0x059821, 8.0f, 90.0f), + UPPERHELL(43, "upperHell", "Übergang in die Hölle", 0xff0000, 0.0f, 0.0f, 0x000000, 0x000000, 0x000000), + LOWERHELL(44, "lowerHell", "Abgrund der Hölle", 0xff0000, 0.0f, 0.0f, 0x000000, 0x000000, 0x000000), + HELLHILLS(45, "hellHills", "Bergland der Hölle", 0xff0000, 0.0f, 0.0f, 0x000000, 0x000000, 0x000000), + SOULPLAINS(46, "soulPlains", "Seelenland", 0xff0000, 0.0f, 0.0f, 0x000000, 0x000000, 0x000000), + ASHLAND(47, "ashLand", "Verbrannt", 0xff0000, 0.0f, 0.0f, 0x000000, 0x000000, 0x000000), + MOON(48, "moon", "Mondoberfläche", 0xa0a0a0, 0.0f, 0.0f), + CHAOS(49, "chaos", "Chaos", 0xff00ff), + + DESERTM(130, "desertM", "Wüste M", 0xfa9418, 60.0f, 0.0f), + EXTREMEHILLSM(131, "extremeHillsM", "Extremes Bergland M", 0x606060, -12.0f, 30.0f), + FLOWERFOREST(132, "flowerForest", "Blumenwald", 0x6a7425, 8.0f, 80.0f), + TAIGAM(133, "taigaM", "Taiga M", 0x0b6659, -10.0f, 80.0f), + SWAMPLANDM(134, "swamplandM", "Sumpf M", 0x07f9b2, 12.0f, 90.0f, 0xe0ffae, 0xffffffff, 6975545), + ICEPLAINSSPIKES(140, "icePlainsSpikes", "Eisebene + Spitzen", 0xd2ffff, -20.0f), + JUNGLEM(149, "jungleM", "Urwald M", 0x537b09, 18.0f, 90.0f), + JUNGLEEDGEM(151, "jungleEdgeM", "Urwald Gr. M", 0x628b17, 18.0f, 80.0f), + BIRCHFORESTM(155, "birchForestM", "Birkenwald M", 0x307444, 4.0f, 60.0f), + BIRCHFORESTHILLSM(156, "birchForestHillsM", "Birkenwald-Bergland M", 0x1f5f32, 4.0f, 60.0f), + ROOFEDFORESTM(157, "roofedForestM", "Dichter Wald M", 0x40511a, 8.0f, 80.0f), + COLDTAIGAM(158, "coldTaigaM", "Vereiste Taiga M", 0x31554a, -40.0f, 40.0f), + MEGASPRUCETAIGA(160, "megaSpruceTaiga", "Hohe Fichtentaiga", 0x596651, -10.0f, 80.0f), + REDWOODTAIGAHILLSM(161, "redwoodTaigaHillsM", "Mammutbaumtaiga", 0x596651, -10.0f, 80.0f), + EXTREMEHILLSPLUSM(162, "extremeHillsPlusM", "Extremes Bergland + M", 0x507050, -12.0f, 30.0f), + SAVANNAM(163, "savannaM", "Savanne M", 0xbdb25f, 24.0f, 0.0f), + SAVANNAPLATEAUM(164, "savannaPlateauM", "Savannen-Plateau M", 0xa79d64, 20.0f, 0.0f), + MESABRYCE(165, "mesaBryce", "Mesa (Bryce)", 0xd94515, 0.0f, 0.0f, 0xffffff, 9470285, 10387789), + MESAPLATEAUFM(166, "mesaPlateauFM", "Mesa-Waldplateau M", 0xb09765, 0.0f, 0.0f, 0xffffff, 9470285, 10387789), + MESAPLATEAUM(167, "mesaPlateauM", "Mesa-Plateau M", 0xca8c65, 0.0f, 0.0f, 0xffffff, 9470285, 10387789); + + public static final Biome DEF_BIOME = FOREST; + private static final PerlinGen TEMP_NOISE = new PerlinGen(new Random(836430928262265276L), 1); + private static final PerlinGen COLOR_NOISE = new PerlinGen(new Random(6549321755809421L), 1); + private static final Biome[] BIOMES = new Biome[256]; + private static final Map LOOKUP = Maps.newTreeMap(); + + public final int id; + public final String name; + public final String display; + public final int color; + public final float temperature; + public final float humidity; + public final int waterColor; + public final int grassColor; + public final int foliageColor; + public final int skyColor; + public final int fogColor; + public final int cloudColor; + + static { + for(Biome biome : values()) { + BIOMES[biome.id] = biome; + if(LOOKUP.containsKey(biome.name.toLowerCase())) + throw new IllegalStateException("Biom \"" + biome.name + "\" ist als ID " + LOOKUP.get(biome.name.toLowerCase()).id + " und " + biome.id + " definiert"); + LOOKUP.put(biome.name.toLowerCase(), biome); + } + } + + public static Biome getBiome(int id) + { + if (id >= 0 && id < BIOMES.length) + { + return BIOMES[id]; + } + else + { + Log.TICK.warn("Biom-ID ist nicht im Bereich: " + id + ", verwende " + DEF_BIOME.id + " (" + DEF_BIOME.name + ")"); + return DEF_BIOME; + } + } + + public static Biome getBiomeDef(int id) + { + if (id >= 0 && id < BIOMES.length) + { + Biome biome = BIOMES[id]; + return biome == null ? DEF_BIOME : biome; + } + else + { + Log.TICK.warn("Biom-ID ist nicht im Bereich: " + id + ", verwende " + DEF_BIOME.id + " (" + DEF_BIOME.name + ")"); + return DEF_BIOME; + } + } + + public static List getBiomeNames() { + return Lists.newArrayList(LOOKUP.keySet()); + } + + public static Biome findByName(String name) { + Biome biome = LOOKUP.get(name.toLowerCase().replace(" ", "").replace("_", "")); + if(biome == null) { + int z; + try { + z = Integer.parseInt(name); + } + catch(NumberFormatException e) { + return DEF_BIOME; + } + return z < 0 || z >= BIOMES.length || BIOMES[z] == null ? DEF_BIOME : BIOMES[z]; + } + return biome; + } + + private Biome(int id, String name, String display, int color, float temperature, float humidity, int waterColor, int grassColor, int foliageColor, int skyColor, int fogColor, int cloudColor) { + this.id = id; + this.name = name; + this.display = display; + this.temperature = temperature; + this.humidity = humidity; + this.color = color; + this.waterColor = waterColor; + this.grassColor = grassColor; + this.foliageColor = foliageColor; + this.skyColor = skyColor; + this.fogColor = fogColor; + this.cloudColor = cloudColor; + } + + private Biome(int id, String name, String display, int color, float temperature, float humidity, int waterColor, int grassColor, int foliageColor) { + this(id, name, display, color, temperature, humidity, waterColor, grassColor, foliageColor, 0xffffffff, 0xffffffff, 0xffffffff); + } + + private Biome(int id, String name, String display, int color, float temperature, float humidity) { + this(id, name, display, color, temperature, humidity, 0xffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff); + } + + private Biome(int id, String name, String display, int color, float temperature) { + this(id, name, display, color, temperature, 50.0f, 0xffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff); + } + + private Biome(int id, String name, String display, int color) { + this(id, name, display, color, 0.0f, 50.0f, 0xffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff); + } + + public final float getTemperature(BlockPos pos) { + if(pos.getY() > 64) { + float f = (float)(TEMP_NOISE.generate((double)pos.getX() * 1.0D / 8.0D, (double)pos.getZ() * 1.0D / 8.0D) * 4.0D); + return this.temperature - (f + (float)pos.getY() - 64.0F) / 15.0f; + } + return this.temperature; + } + + public float getFactor() { + float f = this.humidity * 0.01f * ((this.temperature + 14.0f) / 40.0f + 0.15f); + return f > 1.0f ? 1.0f : f; + } + + public boolean isHighHumidity() { + return this.humidity > 85.0f; + } + + // skycolor = ((temp + 14) / 40 + 0.15) / 3 + + public int getGrassColorAtPos(BlockPos pos) { + if(this.grassColor != 0xffffffff) + return this.grassColor; + if(this == SWAMPLAND || this == SWAMPLANDM) { + double d0 = COLOR_NOISE.generate((double)pos.getX() * 0.0225D, (double)pos.getZ() * 0.0225D); + return d0 < -0.1D ? 5011004 : 6975545; + } + if(this == ELVENFOREST) + return Colorizer.getGrassColor(1.0f, this.humidity * 0.01f); + double d0 = (double)ExtMath.clampf((this.getTemperature(pos) + 14.0f) / 40.0f + 0.15f, 0.0F, 1.0F); + double d1 = (double)ExtMath.clampf(this.humidity * 0.01f, 0.0F, 1.0F); + return this == ROOFEDFOREST || this == ROOFEDFORESTM ? (Colorizer.getGrassColor(d0, d1) & 16711422) + 2634762 >> 1 : Colorizer.getGrassColor(d0, d1); + } + + public int getFoliageColorAtPos(BlockPos pos) { + if(this.foliageColor != 0xffffffff) + return this.foliageColor; + if(this == ELVENFOREST) + return Colorizer.getFoliageColor(1.0f, this.humidity * 0.01f); + double d0 = (double)ExtMath.clampf((this.getTemperature(pos) + 14.0f) / 40.0f + 0.15f, 0.0F, 1.0F); + double d1 = (double)ExtMath.clampf(this.humidity * 0.01f, 0.0F, 1.0F); + return Colorizer.getFoliageColor(d0, d1); + } +} diff --git a/common/src/main/java/common/biome/IBiome.java b/common/src/main/java/common/biome/IBiome.java new file mode 100644 index 0000000..27027f1 --- /dev/null +++ b/common/src/main/java/common/biome/IBiome.java @@ -0,0 +1,47 @@ +package common.biome; + +import common.init.BlockRegistry; +import common.rng.Random; +import common.util.BlockPos; +import common.world.AWorldServer; +import common.world.State; + +public interface IBiome { + public static abstract class BiomeProvider { + private static BiomeProvider provider = new BiomeProvider() { + public IBiome getBiome(Biome base) { + return new IBiome() { + public State getFiller() { + return BlockRegistry.getRegisteredBlock("air").getState(); + } + public State getTop() { + return BlockRegistry.getRegisteredBlock("air").getState(); + } + public void growGrass(AWorldServer worldIn, BlockPos pos, State state, Random rand) { + } + public boolean generateBigMushroom(AWorldServer worldIn, BlockPos pos, State state, Random rand) { + return false; + } + public void generateTree(AWorldServer worldIn, BlockPos pos, State state, Random rand) { + } + }; + } + }; + + public abstract IBiome getBiome(Biome base); + } + + public static void setProvider(BiomeProvider provider) { + BiomeProvider.provider = provider; + } + + public static IBiome getBiome(Biome base) { + return BiomeProvider.provider.getBiome(base); + } + + void growGrass(AWorldServer worldIn, BlockPos pos, State state, Random rand); + boolean generateBigMushroom(AWorldServer worldIn, BlockPos pos, State state, Random rand); + void generateTree(AWorldServer worldIn, BlockPos pos, State state, Random rand); + State getFiller(); + State getTop(); +} \ No newline at end of file diff --git a/common/src/main/java/common/block/Block.java b/common/src/main/java/common/block/Block.java new file mode 100755 index 0000000..e7d2cc6 --- /dev/null +++ b/common/src/main/java/common/block/Block.java @@ -0,0 +1,1015 @@ +package common.block; + +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.function.Function; + +import common.block.artificial.BlockSlab; +import common.collect.ImmutableList; +import common.collect.ImmutableMap; +import common.collect.Iterables; +import common.collect.Lists; +import common.collect.Maps; +import common.collect.UnmodifiableIterator; +import common.enchantment.EnchantmentHelper; +import common.entity.Entity; +import common.entity.item.EntityItem; +import common.entity.item.EntityXp; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.ItemRegistry; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.properties.IProperty; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Facing; +import common.util.HitPosition; +import common.util.Vec3; +import common.util.HitPosition.ObjectType; +import common.vars.Vars; +import common.world.Explosion; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; + +public class Block { + private static class Product implements Iterable { + private final Class clazz; + private final Iterable[] iterables; + + private Product(Class clazz, Iterable[] iterables) { + this.clazz = clazz; + this.iterables = iterables; + } + + public Iterator iterator() { + return (Iterator)(this.iterables.length <= 0 ? Collections.singletonList((T[])createArray(this.clazz, 0)).iterator() + : new Product.ProductIterator(this.clazz, this.iterables)); + } + + static class ProductIterator extends UnmodifiableIterator { + private int index; + private final Iterable[] iterables; + private final Iterator[] iterators; + private final T[] results; + + private ProductIterator(Class clazz, Iterable[] iterables) { + this.index = -2; + this.iterables = iterables; + this.iterators = (Iterator[])createArray(Iterator.class, this.iterables.length); + + for(int i = 0; i < this.iterables.length; ++i) { + this.iterators[i] = iterables[i].iterator(); + } + + this.results = createArray(clazz, this.iterators.length); + } + + private void endOfData() { + this.index = -1; + Arrays.fill(this.iterators, (Object)null); + Arrays.fill(this.results, (Object)null); + } + + public boolean hasNext() { + if(this.index == -2) { + this.index = 0; + + for(Iterator iterator : this.iterators) { + if(!iterator.hasNext()) { + this.endOfData(); + break; + } + } + + return true; + } + else { + if(this.index >= this.iterators.length) { + for(this.index = this.iterators.length - 1; this.index >= 0; --this.index) { + Iterator iterator = this.iterators[this.index]; + + if(iterator.hasNext()) { + break; + } + + if(this.index == 0) { + this.endOfData(); + break; + } + + iterator = this.iterables[this.index].iterator(); + this.iterators[this.index] = iterator; + + if(!iterator.hasNext()) { + this.endOfData(); + break; + } + } + } + + return this.index >= 0; + } + } + + public T[] next() { + if(!this.hasNext()) { + throw new NoSuchElementException(); + } + else { + while(this.index < this.iterators.length) { + this.results[this.index] = this.iterators[this.index].next(); + ++this.index; + } + + return (T[])((Object[])this.results.clone()); + } + } + } + } + + private static class GetList implements Function> { + private GetList() { + } + + public List apply(Object[] data) { + return Arrays.asList((T[])data); + } + } + + private final ImmutableList properties; + private final ImmutableList states; + protected final Material material; + + protected boolean fullBlock; + protected boolean translucent; + protected boolean sumBrightness; + protected boolean axeHarvest; + protected boolean shovelHarvest; + protected boolean ticked; + protected boolean hasTile; + protected int lightOpacity; + protected int lightValue; + protected int miningLevel; + protected int shearsEfficiency; + protected float blockHardness; + protected float blockResistance; + protected float radiation; + public float slipperiness; + protected double minX; + protected double minY; + protected double minZ; + protected double maxX; + protected double maxY; + protected double maxZ; + private State defaultState; + private String display; + private CheatTab tab; + public SoundType sound; + + private static Iterable> cartesianProduct(Iterable> sets) { + return arraysAsLists(cartesianProduct(Object.class, sets)); + } + + private static Iterable cartesianProduct(Class clazz, Iterable> sets) { + return new Product(clazz, (Iterable[])toArray(Iterable.class, sets)); + } + + private static Iterable> arraysAsLists(Iterable arrays) { + return Iterables.transform(arrays, new GetList()); + } + + private static T[] toArray(Class clazz, Iterable it) { + List list = Lists.newArrayList(); + + for(T t : it) { + list.add(t); + } + + return (T[])((Object[])list.toArray(createArray(clazz, list.size()))); + } + + private static T[] createArray(Class clazz, int size) { + return (T[])((Object[])((Object[])Array.newInstance(clazz, size))); + } + + private static Map createMap(Iterable keys, Iterable values) { + return populateMap(keys, values, Maps.newLinkedHashMap()); + } + + private static Map populateMap(Iterable keys, Iterable values, Map map) { + Iterator iterator = values.iterator(); + + for(IProperty prop : keys) { + map.put(prop, iterator.next()); + } + + if(iterator.hasNext()) { + throw new NoSuchElementException(); + } + else { + return map; + } + } + + private static List> getAllowedValues(List properties) { + List> list = Lists.>newArrayList(); + for(int z = 0; z < properties.size(); z++) { + list.add((properties.get(z)).getAllowedValues()); + } + return list; + } + + private static ImmutableList getPropertyList(IProperty[] properties) { + Arrays.sort(properties, new Comparator() { + public int compare(IProperty p1, IProperty p2) { + return p1.getName().compareTo(p2.getName()); + } + }); + return ImmutableList.copyOf(properties); + } + + private static ImmutableList getStateList(List properties, Block block) { + Map, State> map = Maps., State>newLinkedHashMap(); + List list = Lists.newArrayList(); + for(List allowed : cartesianProduct(getAllowedValues(properties))) { + Map props = createMap(properties, allowed); + State state = new State(block, ImmutableMap.copyOf(props)); + map.put(props, state); + list.add(state); + } + for(State state : list) { + state.buildTable(map); + } + return ImmutableList.copyOf(list); + } + + public Block(Material material) { + this.miningLevel = (material == Material.SOLID || material == Material.HEAVY) ? 0 : -1; + this.axeHarvest = material == Material.WOOD || material == Material.PLANT || material == Material.BUSH || material == Material.SOFT; + this.shearsEfficiency = (material == Material.LEAVES || material == Material.FLUFF) ? 3 : -1; + this.sound = SoundType.STONE; + this.slipperiness = 0.6F; + this.material = material; + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + this.fullBlock = this.isOpaqueCube(); + this.lightOpacity = this.isOpaqueCube() ? 255 : 0; + this.translucent = !material.blocksLight(); + this.properties = getPropertyList(this.getProperties()); + this.states = getStateList(this.properties, this); + this.setDefaultState(this.getBaseState()); + } + + public Block setStepSound(SoundType sound) { + this.sound = sound; + return this; + } + + public Block setLightOpacity(int opacity) { + this.lightOpacity = opacity; + return this; + } + + public Block setLightLevel(float value) { + this.lightValue = (int)(15.0F * value); + return this; + } + + public Block setResistance(float resistance) { + this.blockResistance = resistance * 3.0F; + return this; + } + + public Block setHardness(float hardness) { + this.blockHardness = hardness; + + if(this.blockResistance < hardness * 5.0F) { + this.blockResistance = hardness * 5.0F; + } + + return this; + } + + protected Block setTickRandomly() { + this.ticked = true; + return this; + } + + public Block setDisplay(String name) { + this.display = name; + return this; + } + + public Block setTab(CheatTab tab) { + this.tab = tab; + return this; + } + + public Block setSumBrightness() { + this.sumBrightness = true; + return this; + } + + public Block setMiningLevel(int level) { + this.miningLevel = level; + return this; + } + + public Block setAxeHarvestable() { + this.axeHarvest = true; + return this; + } + + public Block setShovelHarvestable() { + this.shovelHarvest = true; + return this; + } + + public Block setShearsEfficiency(int efficiency) { + this.shearsEfficiency = efficiency; + return this; + } + + public Block setRadiation(float value) { + this.radiation = value; + if(value > 0.0f) + this.ticked = true; + return this; + } + + public boolean isFullBlock() { + return this.fullBlock; + } + + public int getLightOpacity() { + return this.lightOpacity; + } + + public boolean isTranslucent() { + return this.translucent; + } + + public int getLightValue() { + return this.lightValue; + } + + public boolean getSumBrightness() { + return this.sumBrightness; + } + + public final Material getMaterial() { + return this.material; + } + + public ImmutableList getValidStates() { + return this.states; + } + + public final State getBaseState() { + return this.states.get(0); + } + + public Collection getPropertyMap() { + return this.properties; + } + + public State getStateFromMeta(int meta) { + return this.getState(); + } + + public int getMetaFromState(State state) { + if(state != null && !state.getPropertyNames().isEmpty()) { + throw new IllegalArgumentException("Don\'t know how to convert " + state + " back into data..."); + } + else { + return 0; + } + } + + public State getActualState(State state, IWorldAccess worldIn, BlockPos pos) { + return state; + } + + public boolean isBlockNormalCube() { + return this.material.blocksMovement() && this.isFullCube(); + } + + public boolean isNormalCube() { + return this.material.isOpaque() && this.isFullCube() && !this.canProvidePower(); + } + + public boolean isVisuallyOpaque() { + return this.material.blocksMovement() && this.isFullCube(); + } + + public boolean isFullCube() { + return true; + } + + public boolean isPassable(IBlockAccess worldIn, BlockPos pos) { + return !this.material.blocksMovement(); + } + + public int getRenderType() { + return 3; + } + + public boolean isXrayVisible() { + return false; + } + + public boolean isReplaceable(World worldIn, BlockPos pos) { + return false; + } + + public float getBlockHardness(World worldIn, BlockPos pos) { + return this.blockHardness; + } + + public final float getRawHardness() { + return this.blockHardness; + } + + public final float getRawResistance() { + return this.blockResistance; + } + + public boolean getTickRandomly() { + return this.ticked; + } + + public boolean hasTileEntity() { + return this.hasTile; + } + + protected final void setBlockBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) { + this.minX = (double)minX; + this.minY = (double)minY; + this.minZ = (double)minZ; + this.maxX = (double)maxX; + this.maxY = (double)maxY; + this.maxZ = (double)maxZ; + } + + public int getMixedBrightnessForBlock(IWorldAccess worldIn, BlockPos pos) { + Block block = worldIn.getState(pos).getBlock(); + int i = worldIn.getCombinedLight(pos, block.getLightValue()); + + if(i == 0 && block instanceof BlockSlab) { + pos = pos.down(); + block = worldIn.getState(pos).getBlock(); + return worldIn.getCombinedLight(pos, block.getLightValue()); + } + else { + return i; + } + } + + public boolean shouldSideBeRendered(IWorldAccess worldIn, BlockPos pos, Facing side) { + return side == Facing.DOWN && this.minY > 0.0D ? true + : (side == Facing.UP && this.maxY < 1.0D ? true + : (side == Facing.NORTH && this.minZ > 0.0D ? true + : (side == Facing.SOUTH && this.maxZ < 1.0D ? true + : (side == Facing.WEST && this.minX > 0.0D ? true + : (side == Facing.EAST && this.maxX < 1.0D ? true + : !worldIn.getState(pos).getBlock().isOpaqueCube()))))); + } + + public BoundingBox getSelectedBoundingBox(World worldIn, BlockPos pos) { + return new BoundingBox((double)pos.getX() + this.minX, (double)pos.getY() + this.minY, (double)pos.getZ() + this.minZ, + (double)pos.getX() + this.maxX, (double)pos.getY() + this.maxY, (double)pos.getZ() + this.maxZ); + } + + public void addCollisionBoxesToList(World worldIn, BlockPos pos, State state, BoundingBox mask, List list, Entity collidingEntity) { + BoundingBox axisalignedbb = this.getCollisionBoundingBox(worldIn, pos, state); + + if(axisalignedbb != null && mask.intersectsWith(axisalignedbb)) { + list.add(axisalignedbb); + } + } + + public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) { + return new BoundingBox((double)pos.getX() + this.minX, (double)pos.getY() + this.minY, (double)pos.getZ() + this.minZ, + (double)pos.getX() + this.maxX, (double)pos.getY() + this.maxY, (double)pos.getZ() + this.maxZ); + } + + public boolean isOpaqueCube() { + return true; + } + + public boolean canCollideCheck(State state, boolean liquid) { + return this.isCollidable(); + } + + public boolean isCollidable() { + return true; + } + + public void randomTick(AWorldServer worldIn, BlockPos pos, State state, Random random) { + this.updateTick(worldIn, pos, state, random); + if(this.radiation > 0.0f) // && /* worldIn.getTime() % 5L == 0L && */ random.chance(Config.randomTick / 3)) + this.affectEntities(worldIn, pos, state, this.radiation * 8.0f * 0.25f); + } + + private void affectEntities(AWorldServer worldIn, BlockPos pos, State state, float rad) { + float r = ExtMath.clampf(rad * 2.0f, 0.0f, 25.0f); + BoundingBox box = this.getCollisionBoundingBox(worldIn, pos, state); + if(box == null) + box = new BoundingBox(pos, pos.add(1, 1, 1)); + for(EntityLiving entity : worldIn.getEntitiesWithinAABB(EntityLiving.class, box.expand(r, r, r))) { + float effect = rad * 2.0f * (r - ExtMath.sqrtf((float)entity.getDistanceSq(pos))) / r; + if(effect > 0.0f) + entity.addRadiation(effect); + } + } + + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { + } + + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { + } + + public void onBlockDestroyedByPlayer(World worldIn, BlockPos pos, State state) { + } + + public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) { + } + + public int tickRate(World worldIn, BlockPos pos) { + return 10; + } + + public void onBlockAdded(AWorldServer world, BlockPos pos, State state) { + } + + public void onBlockRemoved(AWorldServer world, BlockPos pos, State state) { + } + + public int quantityDropped(Random random) { + return 1; + } + + public Item getItemDropped(State state, Random rand, int fortune) { + return ItemRegistry.getItemFromBlock(this); + } + + public float getPlayerRelativeBlockHardness(EntityNPC playerIn, World worldIn, BlockPos pos) { + float f = this.getBlockHardness(worldIn, pos); + return f < 0.0F ? 0.0F + : (!playerIn.canHarvestBlock(this) ? playerIn.getToolDigEfficiency(this) / f / 100.0F + : playerIn.getToolDigEfficiency(this) / f / 30.0F); + } + + public final void dropBlockAsItem(World worldIn, BlockPos pos, State state, int forture) { + this.dropBlockAsItemWithChance(worldIn, pos, state, 1.0F, forture); + } + + public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) { + if(!worldIn.client) { + int i = this.quantityDroppedWithBonus(fortune, worldIn.rand); + + for(int j = 0; j < i; ++j) { + if(worldIn.rand.floatv() <= chance) { + Item item = this.getItemDropped(state, worldIn.rand, fortune); + + if(item != null) { + spawnAsEntity(worldIn, pos, new ItemStack(item, 1, this.damageDropped(state))); + } + } + } + } + } + + public static void spawnAsEntity(World worldIn, BlockPos pos, ItemStack stack) { + if(!worldIn.client && Vars.blockDrop) { + float f = 0.5F; + double d0 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; + double d1 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; + double d2 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; + EntityItem entityitem = new EntityItem(worldIn, (double)pos.getX() + d0, (double)pos.getY() + d1, (double)pos.getZ() + d2, stack); + entityitem.setDefaultPickupDelay(); + worldIn.spawnEntityInWorld(entityitem); + } + } + + protected void dropXpOnBlockBreak(World worldIn, BlockPos pos, int amount) { + if(!worldIn.client && Vars.blockXP) { + while(amount > 0) { + int i = EntityXp.getXPSplit(amount); + amount -= i; + worldIn.spawnEntityInWorld(new EntityXp(worldIn, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, i)); + } + } + } + + public int damageDropped(State state) { + return 0; + } + + public float getExplosionResistance(Entity exploder) { + return this.blockResistance / 5.0F; + } + + public HitPosition collisionRayTrace(World worldIn, BlockPos pos, Vec3 start, Vec3 end) { + this.setBlockBoundsBasedOnState(worldIn, pos); + start = start.addVector((double)(-pos.getX()), (double)(-pos.getY()), (double)(-pos.getZ())); + end = end.addVector((double)(-pos.getX()), (double)(-pos.getY()), (double)(-pos.getZ())); + Vec3 vec3 = start.getIntermediateWithXValue(end, this.minX); + Vec3 vec31 = start.getIntermediateWithXValue(end, this.maxX); + Vec3 vec32 = start.getIntermediateWithYValue(end, this.minY); + Vec3 vec33 = start.getIntermediateWithYValue(end, this.maxY); + Vec3 vec34 = start.getIntermediateWithZValue(end, this.minZ); + Vec3 vec35 = start.getIntermediateWithZValue(end, this.maxZ); + + if(!this.isVecInsideYZBounds(vec3)) { + vec3 = null; + } + + if(!this.isVecInsideYZBounds(vec31)) { + vec31 = null; + } + + if(!this.isVecInsideXZBounds(vec32)) { + vec32 = null; + } + + if(!this.isVecInsideXZBounds(vec33)) { + vec33 = null; + } + + if(!this.isVecInsideXYBounds(vec34)) { + vec34 = null; + } + + if(!this.isVecInsideXYBounds(vec35)) { + vec35 = null; + } + + Vec3 vec36 = null; + + if(vec3 != null && (vec36 == null || start.squareDistanceTo(vec3) < start.squareDistanceTo(vec36))) { + vec36 = vec3; + } + + if(vec31 != null && (vec36 == null || start.squareDistanceTo(vec31) < start.squareDistanceTo(vec36))) { + vec36 = vec31; + } + + if(vec32 != null && (vec36 == null || start.squareDistanceTo(vec32) < start.squareDistanceTo(vec36))) { + vec36 = vec32; + } + + if(vec33 != null && (vec36 == null || start.squareDistanceTo(vec33) < start.squareDistanceTo(vec36))) { + vec36 = vec33; + } + + if(vec34 != null && (vec36 == null || start.squareDistanceTo(vec34) < start.squareDistanceTo(vec36))) { + vec36 = vec34; + } + + if(vec35 != null && (vec36 == null || start.squareDistanceTo(vec35) < start.squareDistanceTo(vec36))) { + vec36 = vec35; + } + + if(vec36 == null) { + return null; + } + else { + Facing enumfacing = null; + + if(vec36 == vec3) { + enumfacing = Facing.WEST; + } + + if(vec36 == vec31) { + enumfacing = Facing.EAST; + } + + if(vec36 == vec32) { + enumfacing = Facing.DOWN; + } + + if(vec36 == vec33) { + enumfacing = Facing.UP; + } + + if(vec36 == vec34) { + enumfacing = Facing.NORTH; + } + + if(vec36 == vec35) { + enumfacing = Facing.SOUTH; + } + + return new HitPosition(ObjectType.BLOCK, vec36.addVector((double)pos.getX(), (double)pos.getY(), (double)pos.getZ()), enumfacing, pos); + } + } + + private boolean isVecInsideYZBounds(Vec3 point) { + return point == null ? false + : point.yCoord >= this.minY && point.yCoord <= this.maxY && point.zCoord >= this.minZ && point.zCoord <= this.maxZ; + } + + private boolean isVecInsideXZBounds(Vec3 point) { + return point == null ? false + : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.zCoord >= this.minZ && point.zCoord <= this.maxZ; + } + + private boolean isVecInsideXYBounds(Vec3 point) { + return point == null ? false + : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.yCoord >= this.minY && point.yCoord <= this.maxY; + } + + public void onBlockDestroyedByExplosion(World worldIn, BlockPos pos, Explosion explosionIn, State prevState) { + } + + public BlockLayer getBlockLayer() { + return BlockLayer.SOLID; + } + + public boolean canReplace(World worldIn, BlockPos pos, Facing side, ItemStack stack) { + return this.canPlaceBlockOnSide(worldIn, pos, side); + } + + public boolean canPlaceBlockOnSide(World worldIn, BlockPos pos, Facing side) { + return this.canPlaceBlockAt(worldIn, pos); + } + + public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { + return worldIn.getState(pos).getBlock().getMaterial().isReplaceable(); + } + + public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { + return false; + } + + public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, Entity entityIn) { + } + + public State onBlockPlaced(World worldIn, BlockPos pos, Facing facing, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) { + return this.getStateFromMeta(meta); + } + + public void onBlockClicked(World worldIn, BlockPos pos, EntityNPC playerIn) { + } + + public Vec3 modifyAcceleration(World worldIn, BlockPos pos, Entity entityIn, Vec3 motion) { + return motion; + } + + public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos) { + } + + public final double getBlockBoundsMinX() { + return this.minX; + } + + public final double getBlockBoundsMaxX() { + return this.maxX; + } + + public final double getBlockBoundsMinY() { + return this.minY; + } + + public final double getBlockBoundsMaxY() { + return this.maxY; + } + + public final double getBlockBoundsMinZ() { + return this.minZ; + } + + public final double getBlockBoundsMaxZ() { + return this.maxZ; + } + + public int getRenderColor(State state) { + return 16777215; + } + + public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass) { + return 16777215; + } + + public final int colorMultiplier(IWorldAccess worldIn, BlockPos pos) { + return this.colorMultiplier(worldIn, pos, 0); + } + + public int getWeakPower(IWorldAccess worldIn, BlockPos pos, State state, Facing side) { + return 0; + } + + public boolean canProvidePower() { + return false; + } + + public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, State state, Entity entityIn) { + } + + public int getStrongPower(IWorldAccess worldIn, BlockPos pos, State state, Facing side) { + return 0; + } + + public void setBlockBoundsForItemRender() { + } + + public void harvestBlock(World worldIn, EntityNPC player, BlockPos pos, State state, TileEntity te) { + if(this.canSilkHarvest() && EnchantmentHelper.getSilkTouchModifier(player)) { + ItemStack itemstack = this.createStackedBlock(state); + + if(itemstack != null) { + spawnAsEntity(worldIn, pos, itemstack); + } + } + else { + int i = EnchantmentHelper.getFortuneModifier(player); + this.dropBlockAsItem(worldIn, pos, state, i); + } + } + + public boolean canSilkHarvest() { + return this.isFullCube() && !this.hasTile; + } + + public ItemStack createStackedBlock(State state) { + int i = 0; + Item item = ItemRegistry.getItemFromBlock(this); + + if(item != null && item.getHasSubtypes()) { + i = this.getMetaFromState(state); + } + + return new ItemStack(item, 1, i); + } + + public int quantityDroppedWithBonus(int fortune, Random random) { + return this.quantityDropped(random); + } + + public void onBlockPlacedBy(World worldIn, BlockPos pos, State state, EntityLiving placer, ItemStack stack) { + } + + public boolean canSpawnInBlock() { + return !this.material.isSolid() && !this.material.isLiquid(); + } + + public final String getDisplay() { + return this.display; + } + + public boolean onBlockEventReceived(World worldIn, BlockPos pos, State state, int eventID, int eventParam) { + return false; + } + + public int getMobilityFlag() { + return this.material.getMobility(); + } + + public float getAmbientOcclusionLightValue() { + return this.isBlockNormalCube() ? 0.2F : 1.0F; + } + + public void onFallenUpon(World worldIn, BlockPos pos, Entity entityIn, float fallDistance) { + entityIn.fall(fallDistance, 1.0F); + } + + public void onLanded(World worldIn, Entity entityIn) { + entityIn.motionY = 0.0D; + } + + public Item getItem(World worldIn, BlockPos pos) { + return ItemRegistry.getItemFromBlock(this); + } + + public int getDamageValue(World worldIn, BlockPos pos) { + return this.damageDropped(worldIn.getState(pos)); + } + + public void getSubBlocks(Item itemIn, CheatTab tab, List list) { + list.add(new ItemStack(itemIn, 1, 0)); + } + + public CheatTab getTab() { + return this.tab; + } + + public void onBlockHarvested(World worldIn, BlockPos pos, State state, EntityNPC player) { + } + + public void fillWithRain(World worldIn, BlockPos pos) { + } + + public boolean isPickStrict() { + return false; + } + + public boolean requiresUpdates() { + return true; + } + + public boolean canDropFromExplosion(Explosion explosionIn) { + return true; + } + + public boolean isAssociatedBlock(Block other) { + return this == other; + } + + public static boolean isEqualTo(Block blockIn, Block other) { + return blockIn != null && other != null ? (blockIn == other ? true : blockIn.isAssociatedBlock(other)) : false; + } + + public boolean hasComparatorInputOverride() { + return false; + } + + public int getComparatorInputOverride(World worldIn, BlockPos pos) { + return 0; + } + + public State getStateForEntityRender(State state) { + return state; + } + + protected IProperty[] getProperties() { + return new IProperty[0]; + } + + protected final void setDefaultState(State state) { + this.defaultState = state; + } + + public final State getState() { + return this.defaultState; + } + + public int getMiningLevel() { + return this.miningLevel; + } + + public boolean canAxeHarvest() { + return this.axeHarvest; + } + + public boolean canShovelHarvest() { + return this.shovelHarvest; + } + + public int getShearsEfficiency() { + return this.shearsEfficiency; + } + + public boolean isMagnetic() { + return false; + } + + public Transforms getTransform() { + return Transforms.BLOCK; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(name).add().all(); + } + + public IProperty[] getIgnoredProperties() { + return null; + } + + public void getAnimatedTextures(Map map) { + } + + public boolean canKeepFire() { + return false; + } + + public boolean canExtinguish() { + return false; + } + + public void onDestroyedByFire(World world, BlockPos pos, State state) { + } + + public boolean onShot(World world, BlockPos pos, State state, Entity projectile) { + return this.material.blocksMovement(); + } +} diff --git a/common/src/main/java/common/block/BlockAir.java b/common/src/main/java/common/block/BlockAir.java new file mode 100755 index 0000000..588e87e --- /dev/null +++ b/common/src/main/java/common/block/BlockAir.java @@ -0,0 +1,35 @@ +package common.block; + +import common.util.BlockPos; +import common.util.BoundingBox; +import common.world.State; +import common.world.World; + +public final class BlockAir extends Block { + public BlockAir() { + super(Material.NONE); + } + + public int getRenderType() { + return -1; + } + + public BoundingBox getCollisionBoundingBox(World world, BlockPos pos, State state) { + return null; + } + + public boolean isOpaqueCube() { + return false; + } + + public boolean canCollideCheck(State state, boolean liquid) { + return false; + } + + public void dropBlockAsItemWithChance(World world, BlockPos pos, State state, float chance, int fortune) { + } + + public boolean isReplaceable(World world, BlockPos pos) { + return true; + } +} diff --git a/common/src/main/java/common/block/BlockColored.java b/common/src/main/java/common/block/BlockColored.java new file mode 100755 index 0000000..6ff3755 --- /dev/null +++ b/common/src/main/java/common/block/BlockColored.java @@ -0,0 +1,49 @@ +package common.block; + +import java.util.List; + +import common.color.DyeColor; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.world.State; + +public class BlockColored extends Block { + public static final PropertyEnum COLOR = PropertyEnum.create("color", DyeColor.class); + + public BlockColored(Material material) { + super(material); + this.setDefaultState(this.getBaseState().withProperty(COLOR, DyeColor.WHITE)); + this.setTab(CheatTab.BLOCKS); + } + + public int damageDropped(State state) { + return state.getValue(COLOR).getMetadata(); + } + + public void getSubBlocks(Item item, CheatTab tab, List list) { + for(DyeColor color : DyeColor.values()) { + list.add(new ItemStack(item, 1, color.getMetadata())); + } + } + + public State getStateFromMeta(int meta) { + return this.getState().withProperty(COLOR, DyeColor.byMetadata(meta)); + } + + public int getMetaFromState(State state) { + return state.getValue(COLOR).getMetadata(); + } + + protected IProperty[] getProperties() { + return new IProperty[] {COLOR}; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(state.getValue(COLOR).getName() + "_" + name).add().all(); + } +} diff --git a/common/src/main/java/common/block/BlockContainer.java b/common/src/main/java/common/block/BlockContainer.java new file mode 100755 index 0000000..561a8a8 --- /dev/null +++ b/common/src/main/java/common/block/BlockContainer.java @@ -0,0 +1,39 @@ +package common.block; + +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; + +public abstract class BlockContainer extends Block implements ITileEntityProvider { + public BlockContainer(Material material) { + super(material); + this.hasTile = true; + } + + protected boolean isInvalidNeighbor(World world, BlockPos pos, Facing face) { + return world.getState(pos.offset(face)).getBlock().getMaterial() == Material.BLOCKING; + } + + protected boolean hasInvalidNeighbor(World world, BlockPos pos) { + return this.isInvalidNeighbor(world, pos, Facing.NORTH) || this.isInvalidNeighbor(world, pos, Facing.SOUTH) + || this.isInvalidNeighbor(world, pos, Facing.WEST) || this.isInvalidNeighbor(world, pos, Facing.EAST); + } + + public int getRenderType() { + return -1; + } + + public void onBlockRemoved(AWorldServer world, BlockPos pos, State state) { + super.onBlockRemoved(world, pos, state); + world.removeTileEntity(pos); + } + + public boolean onBlockEventReceived(World world, BlockPos pos, State state, int id, int param) { + super.onBlockEventReceived(world, pos, state, id, param); + TileEntity tile = world.getTileEntity(pos); + return tile == null ? false : tile.receiveClientEvent(id, param); + } +} diff --git a/common/src/main/java/common/block/BlockDirectional.java b/common/src/main/java/common/block/BlockDirectional.java new file mode 100755 index 0000000..0cb7a7a --- /dev/null +++ b/common/src/main/java/common/block/BlockDirectional.java @@ -0,0 +1,12 @@ +package common.block; + +import common.properties.PropertyDirection; +import common.util.Facing; + +public abstract class BlockDirectional extends Block { + public static final PropertyDirection FACING = PropertyDirection.create("facing", Facing.Plane.HORIZONTAL); + + public BlockDirectional(Material material) { + super(material); + } +} diff --git a/common/src/main/java/common/block/BlockFalling.java b/common/src/main/java/common/block/BlockFalling.java new file mode 100755 index 0000000..7c793f9 --- /dev/null +++ b/common/src/main/java/common/block/BlockFalling.java @@ -0,0 +1,72 @@ +package common.block; + +import common.block.natural.BlockFire; +import common.entity.item.EntityFalling; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; + +public class BlockFalling extends Block { + public static boolean fallInstantly; + + public static boolean canFallInto(World world, BlockPos pos) { + Block block = world.getState(pos).getBlock(); + return block instanceof BlockFire || block == Blocks.air || block.getMaterial().isLiquid(); + } + + public BlockFalling(Material material) { + super(material); + } + + public void onBlockAdded(AWorldServer world, BlockPos pos, State state) { + world.scheduleUpdate(pos, this, this.tickRate(world, pos)); + } + + public void onNeighborBlockChange(World world, BlockPos pos, State state, Block neighbor) { + world.scheduleUpdate(pos, this, this.tickRate(world, pos)); + } + + public void updateTick(AWorldServer world, BlockPos pos, State state, Random rand) { + if(Vars.blockGravity) + this.checkFallable(world, pos); + } + + private void checkFallable(World world, BlockPos pos) { + if(canFallInto(world, pos.down()) && pos.getY() >= 0) { + int range = 32; + if(!fallInstantly && world.isAreaLoaded(pos.add(-range, -range, -range), pos.add(range, range, range))) { + if(!world.client) { + EntityFalling entity = new EntityFalling(world, (double)pos.getX() + 0.5D, (double)pos.getY(), + (double)pos.getZ() + 0.5D, world.getState(pos)); + this.onStartFalling(entity); + world.spawnEntityInWorld(entity); + } + } + else { + world.setBlockToAir(pos); + BlockPos loc; + int limit = 512; + for(loc = pos.down(); canFallInto(world, loc) && loc.getY() > -World.MAX_SIZE_Y; loc = loc.down()) { + if(--limit <= 0) + return; + } + if(loc.getY() > -World.MAX_SIZE_Y) + world.setState(loc.up(), this.getState()); + } + } + } + + public int tickRate(World world, BlockPos pos) { + return 2; + } + + protected void onStartFalling(EntityFalling entity) { + } + + public void onEndFalling(World world, BlockPos pos) { + } +} diff --git a/common/src/main/java/common/block/BlockRotatedPillar.java b/common/src/main/java/common/block/BlockRotatedPillar.java new file mode 100755 index 0000000..5071e8a --- /dev/null +++ b/common/src/main/java/common/block/BlockRotatedPillar.java @@ -0,0 +1,32 @@ +package common.block; + +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.PropertyEnum; +import common.util.Facing; +import common.world.State; + +public abstract class BlockRotatedPillar extends Block { + public static final PropertyEnum AXIS = PropertyEnum.create("axis", Facing.Axis.class); + + public BlockRotatedPillar(Material material) { + super(material); + } + + public Model getModel(ModelProvider provider, String name, State state) { + switch(state.getValue(AXIS)) { + case X: + return provider.getModel(name + "_side").add().d().rot(180).u() + .n(name + "_top").rot(180).s(name + "_top").w().rot(270) + .e().rot(90).rotate(ModelRotation.X0_Y90); + case Y: + default: + return provider.getModel(name + "_side").add().nswe().du(name + "_top"); + case Z: + return provider.getModel(name + "_side").add().d().rot(180).u() + .n(name + "_top").rot(180).s(name + "_top").w().rot(270) + .e().rot(90); + } + } +} diff --git a/common/src/main/java/common/block/BlockTranslucent.java b/common/src/main/java/common/block/BlockTranslucent.java new file mode 100755 index 0000000..e74012f --- /dev/null +++ b/common/src/main/java/common/block/BlockTranslucent.java @@ -0,0 +1,27 @@ +package common.block; + +import common.model.BlockLayer; +import common.util.BlockPos; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; + +public class BlockTranslucent extends Block { + public BlockTranslucent(Material material) { + super(material); + } + + public final boolean isOpaqueCube() { + return false; + } + + public final BlockLayer getBlockLayer() { + return BlockLayer.TRANSLUCENT; + } + + public boolean shouldSideBeRendered(IWorldAccess world, BlockPos pos, Facing side) { + State state = world.getState(pos); + Block block = state.getBlock(); + return block != this && super.shouldSideBeRendered(world, pos, side); + } +} diff --git a/common/src/main/java/common/block/BlockTreasure.java b/common/src/main/java/common/block/BlockTreasure.java new file mode 100755 index 0000000..b5548e0 --- /dev/null +++ b/common/src/main/java/common/block/BlockTreasure.java @@ -0,0 +1,11 @@ +package common.block; + +public class BlockTreasure extends Block { + public BlockTreasure(Material material) { + super(material); + } + + public boolean isXrayVisible() { + return true; + } +} diff --git a/common/src/main/java/common/block/ITileEntityProvider.java b/common/src/main/java/common/block/ITileEntityProvider.java new file mode 100755 index 0000000..fe4ab9f --- /dev/null +++ b/common/src/main/java/common/block/ITileEntityProvider.java @@ -0,0 +1,8 @@ +package common.block; + +import common.tileentity.TileEntity; +import common.world.World; + +public interface ITileEntityProvider { + TileEntity createNewTileEntity(World world); +} diff --git a/common/src/main/java/common/block/Material.java b/common/src/main/java/common/block/Material.java new file mode 100755 index 0000000..5abbdb0 --- /dev/null +++ b/common/src/main/java/common/block/Material.java @@ -0,0 +1,192 @@ +package common.block; + +public enum Material { + NONE {{ + this.setNonSolid().setReplaceable(); + }}, + LOOSE {{ + ; + }}, + WOOD {{ + this.setBurning(); + }}, + SOLID {{ + this.setRequiresTool(); + }}, + DIGGABLE {{ // can harvest with shovel + this.setRequiresTool(); + }}, + TRANSLUCENT {{ + this.setTranslucent(); + }}, + BURNABLE {{ + this.setBurning(); + }}, + SOFT {{ // can break faster with sword, can't connect to fences+walls + this.setNoPushMobility(); + }}, + PISTON {{ + this.setImmovableMobility(); + }}, + HEAVY {{ + this.setRequiresTool().setImmovableMobility(); + }}, + PLANT {{ // can break faster with sword + this.setNonSolid().setNoPushMobility(); + }}, + SMALL {{ // can be placed more easily + this.setNonSolid().setNoPushMobility(); + }}, + FLEECE {{ + this.setNonSolid().setBurning(); + }}, + EXPLOSIVE {{ + this.setBurning().setTranslucent(); + }}, + BLOCKING {{ // can't be placed next to signs and banners + this.setTranslucent().setNoPushMobility(); + }}, + PORTAL {{ // not floodable by liquids + this.setNonSolid().setImmovableMobility(); + }}, + WATER {{ + this.setLiquid(false).setReplaceable().setNoPushMobility(); + }}, + COLD {{ + this.setLiquid(false).setReplaceable().setNoPushMobility(); + }}, + LAVA {{ + this.setLiquid(true).setReplaceable().setNoPushMobility(); + }}, + HOT {{ + this.setLiquid(true).setReplaceable().setNoPushMobility(); + }}, + LEAVES {{ // can break faster with sword, precipitation block, special treatment in some worldgen + this.setBurning().setTranslucent().setNoPushMobility(); + }}, + BUSH {{ // can break faster with sword, can be replaced by small tree leaves + this.setNonSolid().setBurning().setNoPushMobility().setReplaceable(); + }}, + FIRE {{ + this.setNonSolid().setReplaceable().setNoPushMobility(); + }}, + POWDER {{ // can harvest with shovel, precipitation block + this.setNonSolid().setReplaceable().setRequiresTool().setNoPushMobility(); + }}, + FLUFF {{ // can harvest with shears + this.setPassable().setRequiresTool().setNoPushMobility(); + }}; + + private boolean solid = true; + private boolean lightOpaque = true; + private boolean unpassable = true; + private boolean opaque = true; + private boolean liquid; + private boolean cold; + private boolean hot; + private boolean burnable; + private boolean replaceable; + private boolean requiresTool; + // 0 - normal; 1 - can't push other blocks; 2 - can't be pushed + private int mobility; + + protected Material setTranslucent() { + this.opaque = false; + return this; + } + + protected Material setNonSolid() { + this.solid = false; + this.lightOpaque = false; + this.unpassable = false; + this.opaque = false; + return this; + } + + protected Material setPassable() { + this.unpassable = false; + this.opaque = false; + return this; + } + + protected Material setLiquid(boolean hot) { + this.solid = false; + this.unpassable = false; + this.opaque = false; + this.liquid = true; + if(hot) + this.hot = true; + else + this.cold = true; + return this; + } + + protected Material setRequiresTool() { + this.requiresTool = true; + return this; + } + + protected Material setBurning() { + this.burnable = true; + return this; + } + + protected Material setReplaceable() { + this.replaceable = true; + return this; + } + + protected Material setNoPushMobility() { + this.mobility = 1; + return this; + } + + protected Material setImmovableMobility() { + this.mobility = 2; + return this; + } + + public boolean isLiquid() { + return this.liquid; + } + + public boolean isColdLiquid() { + return this.cold; + } + + public boolean isHotLiquid() { + return this.hot; + } + + public boolean isSolid() { + return this.solid; + } + + public boolean blocksLight() { + return this.lightOpaque; + } + + public boolean blocksMovement() { + return this.unpassable; + } + + public boolean getCanBurn() { + return this.burnable; + } + + public boolean isReplaceable() { + return this.replaceable; + } + + public boolean isOpaque() { + return this.opaque; + } + + public boolean isToolRequired() { + return this.requiresTool; + } + + public int getMobility() { + return this.mobility; + } +} diff --git a/java/src/game/audio/SoundType.java b/common/src/main/java/common/block/SoundType.java similarity index 91% rename from java/src/game/audio/SoundType.java rename to common/src/main/java/common/block/SoundType.java index 74c6519..4b1e988 100755 --- a/java/src/game/audio/SoundType.java +++ b/common/src/main/java/common/block/SoundType.java @@ -1,6 +1,6 @@ -package game.audio; +package common.block; -import game.init.SoundEvent; +import common.init.SoundEvent; public enum SoundType { STONE(SoundEvent.STONE), diff --git a/java/src/game/block/BlockBed.java b/common/src/main/java/common/block/artificial/BlockBed.java similarity index 85% rename from java/src/game/block/BlockBed.java rename to common/src/main/java/common/block/artificial/BlockBed.java index bfb2ac0..371619d 100755 --- a/java/src/game/block/BlockBed.java +++ b/common/src/main/java/common/block/artificial/BlockBed.java @@ -1,27 +1,30 @@ -package game.block; +package common.block.artificial; -import game.color.DyeColor; -import game.color.TextColor; -import game.entity.npc.EntityNPC; -import game.init.ItemRegistry; -import game.item.Item; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyEnum; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldPos; +import common.block.Block; +import common.block.BlockDirectional; +import common.block.Material; +import common.color.DyeColor; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.init.ItemRegistry; +import common.item.Item; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.util.Identifyable; +import common.util.WorldPos; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockBed extends BlockDirectional { - public static enum EnumPartType implements IStringSerializable { + public static enum EnumPartType implements Identifyable { HEAD("head"), FOOT("foot"); private final String name; @@ -47,7 +50,7 @@ public class BlockBed extends BlockDirectional { private final DyeColor color; public BlockBed(DyeColor color) { - super(Material.cloth); + super(Material.BURNABLE); this.color = color; this.setDefaultState(this.getBaseState().withProperty(PART, BlockBed.EnumPartType.FOOT)); this.setBedBounds(); @@ -189,15 +192,15 @@ public class BlockBed extends BlockDirectional { return new IProperty[] {FACING, PART}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { if(state.getValue(PART) == EnumPartType.HEAD) - return new ModelBlock(this.color + "_bed_head_top").add(0, 0, 0, 16, 9, 16) + return provider.getModel(this.color + "_bed_head_top").add(0, 0, 0, 16, 9, 16) .u().rot(90).noCull().s(this.color + "_bed_head_end").noCull() .w(this.color + "_bed_head_side").uv(0, 7, 16, 16).noCull().e(this.color + "_bed_head_side").uv(16, 7, 0, 16).noCull() .add(0, 3, 0, 16, 3, 16) .d("oak_planks").noCull().rotate(ModelRotation.getNorthRot(state.getValue(FACING).getOpposite())); else - return new ModelBlock(this.color + "_bed_foot_top").add(0, 0, 0, 16, 9, 16) + return provider.getModel(this.color + "_bed_foot_top").add(0, 0, 0, 16, 9, 16) .u().rot(90).noCull().n(this.color + "_bed_foot_end").noCull() .w(this.color + "_bed_foot_side").uv(0, 7, 16, 16).noCull().e(this.color + "_bed_foot_side").uv(16, 7, 0, 16).noCull() .add(0, 3, 0, 16, 3, 16) diff --git a/common/src/main/java/common/block/artificial/BlockBookshelf.java b/common/src/main/java/common/block/artificial/BlockBookshelf.java new file mode 100755 index 0000000..756f574 --- /dev/null +++ b/common/src/main/java/common/block/artificial/BlockBookshelf.java @@ -0,0 +1,40 @@ +package common.block.artificial; + +import common.block.Block; +import common.block.Material; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.rng.Random; +import common.world.State; + +public class BlockBookshelf extends Block +{ + public BlockBookshelf() + { + super(Material.WOOD); + this.setTab(CheatTab.DECORATION); + } + + /** + * Returns the quantity of items to drop on block destruction. + */ + public int quantityDropped(Random random) + { + return 3; + } + + /** + * Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(State state, Random rand, int fortune) + { + return Items.book; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("bookshelf").add().nswe().du("oak_planks"); + } +} diff --git a/java/src/game/block/BlockCake.java b/common/src/main/java/common/block/artificial/BlockCake.java similarity index 81% rename from java/src/game/block/BlockCake.java rename to common/src/main/java/common/block/artificial/BlockCake.java index c71cee1..425c641 100755 --- a/java/src/game/block/BlockCake.java +++ b/common/src/main/java/common/block/artificial/BlockCake.java @@ -1,24 +1,26 @@ -package game.block; +package common.block.artificial; -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.item.Item; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.item.Item; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockCake extends Block { - private static final ModelBlock cake_slice3 = new ModelBlock("cake_side") + private static final Model cake_slice3 = ModelProvider.getModelProvider().getModel("cake_side") .add(7, 0, 1, 15, 8, 15) .d("cake_bottom").uv(7, 1, 15, 15) .u("cake_top").uv(7, 1, 15, 15).noCull() @@ -27,7 +29,7 @@ public class BlockCake extends Block .w("cake_inner").uv(1, 8, 15, 16).noCull() .e().uv(1, 8, 15, 16).noCull() ; - private static final ModelBlock cake_slice1 = new ModelBlock("cake_side") + private static final Model cake_slice1 = ModelProvider.getModelProvider().getModel("cake_side") .add(3, 0, 1, 15, 8, 15) .d("cake_bottom").uv(3, 1, 15, 15) .u("cake_top").uv(3, 1, 15, 15).noCull() @@ -36,7 +38,7 @@ public class BlockCake extends Block .w("cake_inner").uv(1, 8, 15, 16).noCull() .e().uv(1, 8, 15, 16).noCull() ; - private static final ModelBlock cake_slice2 = new ModelBlock("cake_side") + private static final Model cake_slice2 = ModelProvider.getModelProvider().getModel("cake_side") .add(5, 0, 1, 15, 8, 15) .d("cake_bottom").uv(5, 1, 15, 15) .u("cake_top").uv(5, 1, 15, 15).noCull() @@ -45,7 +47,7 @@ public class BlockCake extends Block .w("cake_inner").uv(1, 8, 15, 16).noCull() .e().uv(1, 8, 15, 16).noCull() ; - private static final ModelBlock cake_slice5 = new ModelBlock("cake_side") + private static final Model cake_slice5 = ModelProvider.getModelProvider().getModel("cake_side") .add(11, 0, 1, 15, 8, 15) .d("cake_bottom").uv(11, 1, 15, 15) .u("cake_top").uv(11, 1, 15, 15).noCull() @@ -54,7 +56,7 @@ public class BlockCake extends Block .w("cake_inner").uv(1, 8, 15, 16).noCull() .e().uv(1, 8, 15, 16).noCull() ; - private static final ModelBlock cake_slice4 = new ModelBlock("cake_side") + private static final Model cake_slice4 = ModelProvider.getModelProvider().getModel("cake_side") .add(9, 0, 1, 15, 8, 15) .d("cake_bottom").uv(9, 1, 15, 15) .u("cake_top").uv(9, 1, 15, 15).noCull() @@ -63,7 +65,7 @@ public class BlockCake extends Block .w("cake_inner").uv(1, 8, 15, 16).noCull() .e().uv(1, 8, 15, 16).noCull() ; - private static final ModelBlock cake_uneaten = new ModelBlock("cake_side") + private static final Model cake_uneaten = ModelProvider.getModelProvider().getModel("cake_side") .add(1, 0, 1, 15, 8, 15) .d("cake_bottom").uv(1, 1, 15, 15) .u("cake_top").uv(1, 1, 15, 15).noCull() @@ -72,7 +74,7 @@ public class BlockCake extends Block .w().uv(1, 8, 15, 16).noCull() .e().uv(1, 8, 15, 16).noCull() ; - private static final ModelBlock cake_slice6 = new ModelBlock("cake_side") + private static final Model cake_slice6 = ModelProvider.getModelProvider().getModel("cake_side") .add(13, 0, 1, 15, 8, 15) .d("cake_bottom").uv(13, 1, 15, 15) .u("cake_top").uv(13, 1, 15, 15).noCull() @@ -81,14 +83,14 @@ public class BlockCake extends Block .w("cake_inner").uv(1, 8, 15, 16).noCull() .e().uv(1, 8, 15, 16).noCull() ; - private static final ModelBlock[] cake_slices = - new ModelBlock[] {cake_uneaten, cake_slice1, cake_slice2, cake_slice3, cake_slice4, cake_slice5, cake_slice6}; + private static final Model[] cake_slices = + new Model[] {cake_uneaten, cake_slice1, cake_slice2, cake_slice3, cake_slice4, cake_slice5, cake_slice6}; public static final PropertyInteger BITES = PropertyInteger.create("bites", 0, 6); public BlockCake() { - super(Material.cake); + super(Material.SOFT); this.setDefaultState(this.getBaseState().withProperty(BITES, Integer.valueOf(0))); // this.setTickRandomly(true); } @@ -241,7 +243,7 @@ public class BlockCake extends Block return true; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { return cake_slices[state.getValue(BITES)]; } } diff --git a/java/src/game/block/BlockCarpet.java b/common/src/main/java/common/block/artificial/BlockCarpet.java similarity index 82% rename from java/src/game/block/BlockCarpet.java rename to common/src/main/java/common/block/artificial/BlockCarpet.java index a5a7c00..6deb687 100755 --- a/java/src/game/block/BlockCarpet.java +++ b/common/src/main/java/common/block/artificial/BlockCarpet.java @@ -1,21 +1,23 @@ -package game.block; +package common.block.artificial; import java.util.List; -import game.color.DyeColor; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.color.DyeColor; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.util.BlockPos; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockCarpet extends Block { @@ -23,11 +25,11 @@ public class BlockCarpet extends Block public BlockCarpet() { - super(Material.carpet); + super(Material.FLEECE); this.setDefaultState(this.getBaseState().withProperty(COLOR, DyeColor.WHITE)); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F); // this.setTickRandomly(true); - this.setTab(CheatTab.tabDeco); + this.setTab(CheatTab.DECORATION); this.setBlockBoundsFromMeta(0); } @@ -154,7 +156,7 @@ public class BlockCarpet extends Block return Transforms.LAYER; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock(state.getValue(COLOR).getName() + "_wool").add(0, 0, 0, 16, 1, 16).nswe().uv(0, 15, 16, 16).d().u().noCull(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(state.getValue(COLOR).getName() + "_wool").add(0, 0, 0, 16, 1, 16).nswe().uv(0, 15, 16, 16).d().u().noCull(); } } diff --git a/java/src/game/block/BlockCompressedPowered.java b/common/src/main/java/common/block/artificial/BlockCompressedPowered.java similarity index 71% rename from java/src/game/block/BlockCompressedPowered.java rename to common/src/main/java/common/block/artificial/BlockCompressedPowered.java index 39d2736..bd2af8d 100755 --- a/java/src/game/block/BlockCompressedPowered.java +++ b/common/src/main/java/common/block/artificial/BlockCompressedPowered.java @@ -1,10 +1,11 @@ -package game.block; +package common.block.artificial; -import game.material.Material; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; +import common.block.Block; +import common.block.Material; +import common.util.BlockPos; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; public class BlockCompressedPowered extends Block { diff --git a/java/src/game/block/BlockDoor.java b/common/src/main/java/common/block/artificial/BlockDoor.java similarity index 92% rename from java/src/game/block/BlockDoor.java rename to common/src/main/java/common/block/artificial/BlockDoor.java index 64f33c7..eb445ea 100755 --- a/java/src/game/block/BlockDoor.java +++ b/common/src/main/java/common/block/artificial/BlockDoor.java @@ -1,32 +1,33 @@ -package game.block; +package common.block.artificial; import java.util.List; -import game.collect.Lists; - -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Items; -import game.item.Item; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyBool; -import game.properties.PropertyDirection; -import game.properties.PropertyEnum; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.HitPosition; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.Vec3; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.collect.Lists; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.item.Item; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyDirection; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.util.HitPosition; +import common.util.Identifyable; +import common.util.Vec3; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockDoor extends Block { @@ -162,7 +163,7 @@ public class BlockDoor extends Block public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { - if (this.material == Material.iron) + if (this.material == Material.SOLID) { return true; } @@ -291,7 +292,7 @@ public class BlockDoor extends Block public boolean canPlaceBlockAt(World worldIn, BlockPos pos) { - return pos.getY() >= 511 ? false : worldIn.isBlockSolid(pos.down()) && super.canPlaceBlockAt(worldIn, pos) && super.canPlaceBlockAt(worldIn, pos.up()); + return pos.getY() >= World.MAX_SIZE_Y - 1 ? false : worldIn.isBlockSolid(pos.down()) && super.canPlaceBlockAt(worldIn, pos) && super.canPlaceBlockAt(worldIn, pos.up()); } public int getMobilityFlag() @@ -454,12 +455,12 @@ public class BlockDoor extends Block return ModelRotation.getEastRot(Facing.getHorizontal(rot.getHorizontalIndex() + offset), false); } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { String bottom = name + "_bottom"; String top = name + "_top"; if(state.getValue(HALF) == EnumDoorHalf.LOWER) { if(state.getValue(HINGE) == EnumHingePosition.LEFT == state.getValue(OPEN)) - return new ModelBlock(bottom).noOcclude() + return provider.getModel(bottom) .add(0, 0, 0, 3, 16, 16) .d().uv(13, 0, 16, 16) .n().uv(3, 0, 0, 16) @@ -468,7 +469,7 @@ public class BlockDoor extends Block .e().uv(0, 0, 16, 16).noCull() .rotate(getRotation(state.getValue(FACING), state.getValue(OPEN) ? 1 : 0)); else - return new ModelBlock(bottom).noOcclude() + return provider.getModel(bottom) .add(0, 0, 0, 3, 16, 16) .d().uv(13, 0, 16, 16) .n().uv(3, 0, 0, 16) @@ -479,7 +480,7 @@ public class BlockDoor extends Block } else { if(state.getValue(HINGE) == EnumHingePosition.LEFT == state.getValue(OPEN)) - return new ModelBlock(top).noOcclude() + return provider.getModel(top) .add(0, 0, 0, 3, 16, 16) .u(bottom).uv(13, 0, 16, 16) .n().uv(3, 0, 0, 16) @@ -488,7 +489,7 @@ public class BlockDoor extends Block .e().uv(0, 0, 16, 16).noCull() .rotate(getRotation(state.getValue(FACING), state.getValue(OPEN) ? 1 : 0)); else - return new ModelBlock(top).noOcclude() + return provider.getModel(top) .add(0, 0, 0, 3, 16, 16) .u(bottom).uv(13, 0, 16, 16) .n().uv(3, 0, 0, 16) @@ -503,7 +504,7 @@ public class BlockDoor extends Block return new IProperty[] {POWERED}; } - public static enum EnumDoorHalf implements IStringSerializable + public static enum EnumDoorHalf implements Identifyable { UPPER, LOWER; @@ -519,7 +520,7 @@ public class BlockDoor extends Block } } - public static enum EnumHingePosition implements IStringSerializable + public static enum EnumHingePosition implements Identifyable { LEFT, RIGHT; diff --git a/java/src/game/block/BlockDragonEgg.java b/common/src/main/java/common/block/artificial/BlockDragonEgg.java similarity index 85% rename from java/src/game/block/BlockDragonEgg.java rename to common/src/main/java/common/block/artificial/BlockDragonEgg.java index 057e2b6..cef344c 100755 --- a/java/src/game/block/BlockDragonEgg.java +++ b/common/src/main/java/common/block/artificial/BlockDragonEgg.java @@ -1,22 +1,26 @@ -package game.block; +package common.block.artificial; -import game.entity.item.EntityFalling; -import game.entity.npc.EntityNPC; -import game.init.Config; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockFalling; +import common.block.Material; +import common.entity.item.EntityFalling; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ParticleType; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockDragonEgg extends Block { - private static final ModelBlock dragon_egg = new ModelBlock("dragon_egg").noOcclude() + private static final Model dragon_egg = ModelProvider.getModelProvider().getModel("dragon_egg") .add(6, 15, 6, 10, 16, 10) .d().uv(6, 6, 10, 10).noCull() .u().uv(6, 6, 10, 10).noCull() @@ -77,11 +81,11 @@ public class BlockDragonEgg extends Block public BlockDragonEgg() { - super(Material.dragonEgg); + super(Material.SOFT); this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 1.0F, 0.9375F); } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn, pos)); } @@ -94,9 +98,9 @@ public class BlockDragonEgg extends Block worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn, pos)); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Config.blockGravity) + if(Vars.blockGravity) this.checkFall(worldIn, pos); } @@ -145,7 +149,7 @@ public class BlockDragonEgg extends Block { BlockPos blockpos = pos.add(worldIn.rand.zrange(16) - worldIn.rand.zrange(16), worldIn.rand.zrange(8) - worldIn.rand.zrange(8), worldIn.rand.zrange(16) - worldIn.rand.zrange(16)); - if (worldIn.getState(blockpos).getBlock().material == Material.air) + if (worldIn.getState(blockpos).getBlock() == Blocks.air) { if (worldIn.client) { @@ -164,7 +168,7 @@ public class BlockDragonEgg extends Block else { worldIn.setBlockToAir(pos); - if(!Config.blockGravity) { + if(!Vars.blockGravity) { BlockPos blockpos2; for(blockpos2 = blockpos; BlockFalling.canFallInto(worldIn, blockpos2) && blockpos2.getY() > 0; blockpos2 = blockpos2.down()) { } @@ -211,7 +215,7 @@ public class BlockDragonEgg extends Block // return null; // } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { return dragon_egg; } } diff --git a/java/src/game/block/BlockFence.java b/common/src/main/java/common/block/artificial/BlockFence.java similarity index 89% rename from java/src/game/block/BlockFence.java rename to common/src/main/java/common/block/artificial/BlockFence.java index 8b8530a..dfd3cad 100755 --- a/java/src/game/block/BlockFence.java +++ b/common/src/main/java/common/block/artificial/BlockFence.java @@ -1,26 +1,27 @@ -package game.block; +package common.block.artificial; import java.util.List; -import game.collect.Lists; - -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.item.CheatTab; -import game.item.ItemLead; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.collect.Lists; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.item.CheatTab; +import common.item.ItemLead; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.Transforms; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockFence extends Block { @@ -43,7 +44,7 @@ public class BlockFence extends Block { super(p_i46395_1_); this.setDefaultState(this.getBaseState().withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false))); - this.setTab(p_i46395_1_ == Material.wood ? CheatTab.tabWood : CheatTab.tabBlocks); + this.setTab(p_i46395_1_ == Material.WOOD ? CheatTab.WOOD : CheatTab.BLOCKS); this.texture = texture; FENCES.add(this); } @@ -165,7 +166,7 @@ public class BlockFence extends Block public boolean canConnectTo(IBlockAccess worldIn, BlockPos pos) { Block block = worldIn.getState(pos).getBlock(); - return ((!(block instanceof BlockFence) || block.material != this.material) && !(block instanceof BlockFenceGate) ? (block.material.isOpaque() && block.isFullCube() ? block.material != Material.gourd : false) : true); + return ((!(block instanceof BlockFence) || block.getMaterial() != this.material) && !(block instanceof BlockFenceGate) ? (block.getMaterial().isOpaque() && block.isFullCube() ? block.getMaterial() != Material.SOFT : false) : true); } public boolean shouldSideBeRendered(IWorldAccess worldIn, BlockPos pos, Facing side) @@ -208,14 +209,14 @@ public class BlockFence extends Block return this.texture; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { boolean n = state.getValue(NORTH); boolean s = state.getValue(SOUTH); boolean w = state.getValue(WEST); boolean e = state.getValue(EAST); int sides = (n ? 1 : 0) + (s ? 1 : 0) + (w ? 1 : 0) + (e ? 1 : 0); if(sides == 0) - return new ModelBlock(this.texture) + return provider.getModel(this.texture) .add(6, 0, 6, 10, 16, 10) .d().uv(6, 6, 10, 10) .u().uv(6, 6, 10, 10) @@ -224,7 +225,7 @@ public class BlockFence extends Block .w().uv(6, 0, 10, 16).noCull() .e().uv(6, 0, 10, 16).noCull(); else if(sides == 4) - return new ModelBlock(this.texture).uvLock() + return provider.getModel(this.texture).uvLock() .add(6, 0, 6, 10, 16, 10) .d().uv(6, 6, 10, 10) .u().uv(6, 6, 10, 10) @@ -261,7 +262,7 @@ public class BlockFence extends Block .w().uv(7, 7, 9, 10) .e().uv(7, 7, 9, 10); else if(sides == 1) - return new ModelBlock(this.texture).uvLock() + return provider.getModel(this.texture).uvLock() .add(6, 0, 6, 10, 16, 10) .d().uv(6, 6, 10, 10) .u().uv(6, 6, 10, 10) @@ -283,7 +284,7 @@ public class BlockFence extends Block .e().uv(0, 7, 9, 10).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return new ModelBlock(this.texture).uvLock() + return provider.getModel(this.texture).uvLock() .add(6, 0, 6, 10, 16, 10) .d().uv(6, 6, 10, 10) .u().uv(6, 6, 10, 10) @@ -318,7 +319,7 @@ public class BlockFence extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2) - return new ModelBlock(this.texture).uvLock() + return provider.getModel(this.texture).uvLock() .add(6, 0, 6, 10, 16, 10) .d().uv(6, 6, 10, 10) .u().uv(6, 6, 10, 10) @@ -342,7 +343,7 @@ public class BlockFence extends Block .e().uv(0, 7, 16, 10).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else - return new ModelBlock(this.texture).uvLock() + return provider.getModel(this.texture).uvLock() .add(6, 0, 6, 10, 16, 10) .d().uv(6, 6, 10, 10) .u().uv(6, 6, 10, 10) diff --git a/java/src/game/block/BlockFenceGate.java b/common/src/main/java/common/block/artificial/BlockFenceGate.java similarity index 91% rename from java/src/game/block/BlockFenceGate.java rename to common/src/main/java/common/block/artificial/BlockFenceGate.java index ffc78cb..887479f 100755 --- a/java/src/game/block/BlockFenceGate.java +++ b/common/src/main/java/common/block/artificial/BlockFenceGate.java @@ -1,23 +1,26 @@ -package game.block; +package common.block.artificial; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.WoodType; -import game.item.CheatTab; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.BlockDirectional; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.WoodType; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.Transforms; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockFenceGate extends BlockDirectional { @@ -29,9 +32,9 @@ public class BlockFenceGate extends BlockDirectional public BlockFenceGate(WoodType p_i46394_1_) { - super(Material.wood); // , p_i46394_1_.getMapColor()); + super(Material.WOOD); // , p_i46394_1_.getMapColor()); this.setDefaultState(this.getBaseState().withProperty(OPEN, Boolean.valueOf(false)).withProperty(POWERED, Boolean.valueOf(false)).withProperty(IN_WALL, Boolean.valueOf(false))); - this.setTab(CheatTab.tabWood); + this.setTab(CheatTab.WOOD); this.texture = p_i46394_1_.getName() + "_planks"; } @@ -206,8 +209,8 @@ public class BlockFenceGate extends BlockDirectional return Transforms.GATE; } - public ModelBlock getModel(String name, State state) { - return (state.getValue(IN_WALL) ? (state.getValue(OPEN) ? new ModelBlock(this.texture).noOcclude().uvLock() + public Model getModel(ModelProvider provider, String name, State state) { + return (state.getValue(IN_WALL) ? (state.getValue(OPEN) ? provider.getModel(this.texture).uvLock() .add(0, 2, 7, 2, 13, 9) .d().uv(0, 7, 2, 9).noCull() .u().uv(0, 7, 2, 9).noCull() @@ -255,7 +258,7 @@ public class BlockFenceGate extends BlockDirectional .d().uv(14, 9, 16, 13).noCull() .u().uv(14, 9, 16, 13).noCull() .w().uv(13, 1, 15, 4).noCull() - .e().uv(13, 1, 15, 4).noCull() : new ModelBlock(this.texture).noOcclude().uvLock() + .e().uv(13, 1, 15, 4).noCull() : provider.getModel(this.texture).uvLock() .add(0, 2, 7, 2, 13, 9) .d().uv(0, 7, 2, 9).noCull() .u().uv(0, 7, 2, 9).noCull() @@ -303,7 +306,7 @@ public class BlockFenceGate extends BlockDirectional .d().uv(10, 7, 14, 9).noCull() .u().uv(10, 7, 14, 9).noCull() .n().uv(10, 1, 14, 4).noCull() - .s().uv(10, 1, 14, 4).noCull()) : (state.getValue(OPEN) ? new ModelBlock(this.texture).uvLock() + .s().uv(10, 1, 14, 4).noCull()) : (state.getValue(OPEN) ? provider.getModel(this.texture).uvLock() .add(0, 5, 7, 2, 16, 9) .d().uv(0, 7, 2, 9).noCull() .u().uv(0, 7, 2, 9).noCull() @@ -351,7 +354,7 @@ public class BlockFenceGate extends BlockDirectional .d().uv(14, 9, 16, 13).noCull() .u().uv(14, 9, 16, 13).noCull() .w().uv(13, 1, 15, 4).noCull() - .e().uv(13, 1, 15, 4).noCull() : new ModelBlock(this.texture).uvLock() + .e().uv(13, 1, 15, 4).noCull() : provider.getModel(this.texture).uvLock() .add(0, 5, 7, 2, 16, 9) .d().uv(0, 7, 2, 9).noCull() .u().uv(0, 7, 2, 9).noCull() diff --git a/java/src/game/block/BlockFloorPortal.java b/common/src/main/java/common/block/artificial/BlockFloorPortal.java similarity index 83% rename from java/src/game/block/BlockFloorPortal.java rename to common/src/main/java/common/block/artificial/BlockFloorPortal.java index 4eb4c3f..c9b3c33 100755 --- a/java/src/game/block/BlockFloorPortal.java +++ b/common/src/main/java/common/block/artificial/BlockFloorPortal.java @@ -1,28 +1,29 @@ -package game.block; +package common.block.artificial; import java.util.List; import java.util.Map; import java.util.Set; -import game.collect.Sets; - -import game.entity.Entity; -import game.item.Item; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldClient; +import common.block.Block; +import common.block.Material; +import common.collect.Sets; +import common.entity.Entity; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ParticleType; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; public class BlockFloorPortal extends Block { - private static final ModelBlock floor_portal = new ModelBlock("floor_portal") + private static final Model floor_portal = ModelProvider.getModelProvider().getModel("floor_portal") .add(0, 11, 0, 16, 12, 16).du().uv(0, 0, 16, 16).noCull().nswe().uv(0, 0, 16, 1); public BlockFloorPortal(Material materialIn) @@ -90,7 +91,7 @@ public class BlockFloorPortal extends Block entityIn.setFlatPortal(); } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { double d0 = (double)((float)pos.getX() + rand.floatv()); double d1 = (double)((float)pos.getY() + 0.8F); @@ -146,7 +147,7 @@ public class BlockFloorPortal extends Block return true; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { return floor_portal; } diff --git a/java/src/game/block/BlockFlowerPot.java b/common/src/main/java/common/block/artificial/BlockFlowerPot.java similarity index 91% rename from java/src/game/block/BlockFlowerPot.java rename to common/src/main/java/common/block/artificial/BlockFlowerPot.java index 46dfb09..7c3436b 100755 --- a/java/src/game/block/BlockFlowerPot.java +++ b/common/src/main/java/common/block/artificial/BlockFlowerPot.java @@ -1,27 +1,30 @@ -package game.block; +package common.block.artificial; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.ItemRegistry; -import game.init.Items; -import game.item.Item; -import game.item.ItemBlock; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockFlower; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; +import common.item.Item; +import common.item.ItemBlock; +import common.item.ItemStack; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockFlowerPot extends Block // Container { - private static final ModelBlock flower_pot_cactus = new ModelBlock("flower_pot").noOcclude() + private static final Model flower_pot_cactus = ModelProvider.getModelProvider().getModel("flower_pot") .add(5, 0, 5, 6, 6, 11) .d().uv(5, 5, 6, 11) .u().uv(5, 5, 6, 11).noCull() @@ -66,7 +69,7 @@ public class BlockFlowerPot extends Block // Container .w("cactus_side").uv(6, 0, 10, 4).noCull() .e("cactus_side").uv(6, 0, 10, 4).noCull() ; - private static final ModelBlock flower_pot = new ModelBlock("flower_pot").noOcclude() + private static final Model flower_pot = ModelProvider.getModelProvider().getModel("flower_pot") .add(5, 0, 5, 6, 6, 11) .d().uv(5, 5, 6, 11) .u().uv(5, 5, 6, 11).noCull() @@ -100,7 +103,7 @@ public class BlockFlowerPot extends Block // Container public BlockFlowerPot() { - super(Material.circuits); + super(Material.SMALL); this.setDefaultState(this.getBaseState().withProperty(CONTENTS, 0)); // .withProperty(LEGACY_DATA, Integer.valueOf(0))); this.setBlockBoundsForItemRender(); } @@ -188,7 +191,7 @@ public class BlockFlowerPot extends Block // Container // worldIn.markBlockForUpdate(pos); // playerIn.triggerAchievement(StatRegistry.flowerPottedStat); - if (/* !playerIn.creative && */ --itemstack.stackSize <= 0) + if (/* !playerIn.creative && */ --itemstack.size <= 0) { playerIn.inventory.setInventorySlotContents(playerIn.inventory.currentItem, (ItemStack)null); } @@ -241,7 +244,7 @@ public class BlockFlowerPot extends Block // Container } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { int type = state.getValue(CONTENTS); if(type > 0) @@ -344,7 +347,7 @@ public class BlockFlowerPot extends Block // Container return BlockLayer.CUTOUT; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { switch(state.getValue(CONTENTS)) { case 0: return flower_pot; @@ -354,7 +357,7 @@ public class BlockFlowerPot extends Block // Container // return flower_pot_fern; default: String plant = BlockFlower.EnumFlowerType.getType(BlockFlower.EnumFlowerColor.BASE, state.getValue(CONTENTS) - 2).getName().toLowerCase(); - return new ModelBlock("flower_pot").noOcclude() + return provider.getModel("flower_pot") .add(5, 0, 5, 6, 6, 11) .d().uv(5, 5, 6, 11) .u().uv(5, 5, 6, 11).noCull() diff --git a/common/src/main/java/common/block/artificial/BlockGlass.java b/common/src/main/java/common/block/artificial/BlockGlass.java new file mode 100755 index 0000000..e331570 --- /dev/null +++ b/common/src/main/java/common/block/artificial/BlockGlass.java @@ -0,0 +1,51 @@ +package common.block.artificial; + +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.item.CheatTab; +import common.model.BlockLayer; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; + +public class BlockGlass extends Block { + public BlockGlass() { + super(Material.TRANSLUCENT); + this.setTab(CheatTab.BLOCKS); + } + + public int quantityDropped(Random rand) { + return 0; + } + + public BlockLayer getBlockLayer() { + return BlockLayer.CUTOUT; + } + + public boolean isOpaqueCube() { + return false; + } + + public boolean isFullCube() { + return false; + } + + public boolean canSilkHarvest() { + return true; + } + + public boolean shouldSideBeRendered(IWorldAccess world, BlockPos pos, Facing side) { + State state = world.getState(pos); + Block block = state.getBlock(); + return world.getState(pos.offset(side.getOpposite())) != state || (block != this && super.shouldSideBeRendered(world, pos, side)); + } + + public boolean onShot(World world, BlockPos pos, State state, Entity projectile) { + world.destroyBlock(pos, true); + return false; + } +} diff --git a/java/src/game/block/BlockHay.java b/common/src/main/java/common/block/artificial/BlockHay.java similarity index 79% rename from java/src/game/block/BlockHay.java rename to common/src/main/java/common/block/artificial/BlockHay.java index 6aad1cc..eefc04f 100755 --- a/java/src/game/block/BlockHay.java +++ b/common/src/main/java/common/block/artificial/BlockHay.java @@ -1,23 +1,24 @@ -package game.block; +package common.block.artificial; -import game.entity.types.EntityLiving; -import game.init.ItemRegistry; -import game.item.CheatTab; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.BlockRotatedPillar; +import common.block.Material; +import common.entity.types.EntityLiving; +import common.init.ItemRegistry; +import common.item.CheatTab; +import common.item.ItemStack; +import common.properties.IProperty; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; public class BlockHay extends BlockRotatedPillar { public BlockHay() { - super(Material.grass); + super(Material.LOOSE); this.setDefaultState(this.getBaseState().withProperty(AXIS, Facing.Axis.Y)); - this.setTab(CheatTab.tabBlocks); + this.setTab(CheatTab.BLOCKS); } /** diff --git a/java/src/game/block/BlockLadder.java b/common/src/main/java/common/block/artificial/BlockLadder.java similarity index 85% rename from java/src/game/block/BlockLadder.java rename to common/src/main/java/common/block/artificial/BlockLadder.java index b29c387..20c8ac2 100755 --- a/java/src/game/block/BlockLadder.java +++ b/common/src/main/java/common/block/artificial/BlockLadder.java @@ -1,19 +1,22 @@ -package game.block; +package common.block.artificial; -import game.entity.types.EntityLiving; -import game.item.CheatTab; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.BlockDirectional; +import common.block.Material; +import common.entity.types.EntityLiving; +import common.item.CheatTab; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockLadder extends Block { @@ -21,9 +24,9 @@ public class BlockLadder extends Block public BlockLadder() { - super(Material.circuits); + super(Material.SMALL); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); - this.setTab(CheatTab.tabWood); + this.setTab(CheatTab.WOOD); } public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) @@ -163,8 +166,8 @@ public class BlockLadder extends Block return new IProperty[] {FACING}; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("ladder").noOcclude() + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("ladder") .add(0, 0, 15.2f, 16, 16, 15.2f).noShade() .n().uv(0, 0, 16, 16).noCull() .s().uv(0, 0, 16, 16).noCull() diff --git a/java/src/game/block/BlockPane.java b/common/src/main/java/common/block/artificial/BlockPane.java similarity index 91% rename from java/src/game/block/BlockPane.java rename to common/src/main/java/common/block/artificial/BlockPane.java index d911c82..2125ba3 100755 --- a/java/src/game/block/BlockPane.java +++ b/common/src/main/java/common/block/artificial/BlockPane.java @@ -1,24 +1,26 @@ -package game.block; +package common.block.artificial; import java.util.List; -import game.entity.Entity; -import game.init.Blocks; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.init.Blocks; +import common.item.CheatTab; +import common.item.Item; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockPane extends Block { @@ -33,7 +35,7 @@ public class BlockPane extends Block super(materialIn); this.setDefaultState(this.getBaseState().withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false))); this.canDrop = canDrop; - this.setTab(CheatTab.tabBlocks); + this.setTab(CheatTab.BLOCKS); } /** @@ -205,8 +207,14 @@ public class BlockPane extends Block } public boolean isMagnetic() { - return this.material == Material.iron; + return this.material == Material.SOLID; } + + public boolean onShot(World world, BlockPos pos, State state, Entity projectile) { + if(this.material != Material.SOLID) + world.destroyBlock(pos, true); + return this.material == Material.SOLID; + } protected String getPaneBase(State state) { return "glass"; @@ -216,7 +224,7 @@ public class BlockPane extends Block return "glass_pane"; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { boolean n = state.getValue(NORTH); boolean s = state.getValue(SOUTH); boolean w = state.getValue(WEST); @@ -224,7 +232,7 @@ public class BlockPane extends Block int sides = (n ? 1 : 0) + (s ? 1 : 0) + (w ? 1 : 0) + (e ? 1 : 0); if(this.canDrop) { if(sides == 0 || sides == 4) - return new ModelBlock(name).noOcclude() + return provider.getModel(name) .add(8, 0, 0, 8, 16, 16) .w().uv(0, 0, 16, 16).noCull() .e().uv(0, 0, 16, 16).noCull() @@ -247,7 +255,7 @@ public class BlockPane extends Block .d().uv(9, 0, 7, 7).rot(90).noCull() .u().uv(7, 0, 9, 7).rot(90).noCull(); else if(sides == 1) - return new ModelBlock(name).noOcclude() + return provider.getModel(name) .add(8, 0, 0, 8, 16, 8) .w().uv(8, 0, 16, 16).noCull() .e().uv(8, 0, 16, 16).noCull() @@ -259,7 +267,7 @@ public class BlockPane extends Block .u().uv(7, 0, 9, 9).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return new ModelBlock(name).noOcclude() + return provider.getModel(name) .add(8, 0, 0, 8, 16, 8) .w().uv(0, 0, 8, 16).noCull() .e().uv(8, 0, 16, 16).noCull() @@ -279,7 +287,7 @@ public class BlockPane extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2) - return new ModelBlock(name).noOcclude() + return provider.getModel(name) .add(8, 0, 0, 8, 16, 16) .w().uv(0, 0, 16, 16).noCull() .e().uv(0, 0, 16, 16).noCull() @@ -291,7 +299,7 @@ public class BlockPane extends Block .u().uv(9, 0, 7, 16).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else - return new ModelBlock(name).noOcclude() + return provider.getModel(name) .add(8, 0, 0, 8, 16, 16) .w().uv(0, 0, 16, 16).noCull() .e().uv(0, 0, 16, 16).noCull() @@ -315,7 +323,7 @@ public class BlockPane extends Block String pane = this.getPaneBase(state); String edge = this.getPaneEdge(state); if(sides == 0 || sides == 4) - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 0, 9, 16, 16).noShade() .d(edge).uv(7, 0, 9, 16).noCull() .u(edge).uv(7, 0, 9, 16).noCull() @@ -331,7 +339,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16) .e(edge).uv(7, 0, 9, 16); else if(sides == 1 && (n || e)) - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 0, 9, 16, 9).noShade() .d(edge).uv(7, 0, 9, 9).noCull() .u(edge).uv(7, 0, 9, 9).noCull() @@ -341,7 +349,7 @@ public class BlockPane extends Block .e().uv(7, 0, 16, 16).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(sides == 1) - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 7, 9, 16, 16).noShade() .d(edge).uv(7, 7, 9, 16).noCull() .u(edge).uv(7, 7, 9, 16).noCull() @@ -351,7 +359,7 @@ public class BlockPane extends Block .e().uv(0, 0, 9, 16).noCull() .rotate(s ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(e && n && !s && !w) - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 0, 9, 16, 9).noShade() .d(edge).uv(7, 0, 9, 9).noCull() .u(edge).uv(7, 0, 9, 9).noCull() @@ -367,7 +375,7 @@ public class BlockPane extends Block .w().uv(7, 0, 9, 16).noCull() .e(edge).uv(7, 0, 9, 16); else if(e && !n && s && !w) - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 7, 9, 16, 16).noShade() .d(edge).uv(7, 7, 9, 16).noCull() .u(edge).uv(7, 7, 9, 16).noCull() @@ -383,7 +391,7 @@ public class BlockPane extends Block .w().uv(7, 0, 9, 16).noCull() .e(edge).uv(7, 0, 9, 16); else if(!e && !n && s && w) - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 7, 9, 16, 16).noShade() .d(edge).uv(7, 7, 9, 16).noCull() .u(edge).uv(7, 7, 9, 16).noCull() @@ -399,7 +407,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16) .e().uv(7, 0, 9, 16).noCull(); else if(!e && n && !s && w) - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 0, 9, 16, 9).noShade() .d(edge).uv(7, 0, 9, 9).noCull() .u(edge).uv(7, 0, 9, 9).noCull() @@ -415,7 +423,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16) .e().uv(7, 0, 9, 16).noCull(); else if((!e && n && s && !w) || (e && !n && !s && w)) - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 0, 9, 16, 16).noShade() .d(edge).uv(7, 0, 9, 16).noCull() .u(edge).uv(7, 0, 9, 16).noCull() @@ -425,7 +433,7 @@ public class BlockPane extends Block .e().uv(0, 0, 16, 16).noCull() .rotate(s ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(!w) - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 0, 9, 16, 16).noShade() .d(edge).uv(7, 0, 9, 16).noCull() .u(edge).uv(7, 0, 9, 16).noCull() @@ -441,7 +449,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16).noCull() .e(edge).uv(7, 0, 9, 16); else if(!n) - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 9, 9, 16, 16).noShade() .d(edge).uv(7, 9, 9, 16).noCull() .u(edge).uv(7, 9, 9, 16).noCull() @@ -457,7 +465,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16) .e(edge).uv(7, 0, 9, 16); else if(!e) - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 0, 9, 16, 16).noShade() .d(edge).uv(7, 0, 9, 16).noCull() .u(edge).uv(7, 0, 9, 16).noCull() @@ -473,7 +481,7 @@ public class BlockPane extends Block .w(edge).uv(7, 0, 9, 16).cull(Facing.EAST) .e(edge).uv(7, 0, 9, 16).noCull(); else - return new ModelBlock(pane).noOcclude() + return provider.getModel(pane) .add(7, 0, 0, 9, 16, 7).noShade() .d(edge).uv(7, 0, 9, 7).noCull() .u(edge).uv(7, 0, 9, 7).noCull() diff --git a/java/src/game/block/BlockPortal.java b/common/src/main/java/common/block/artificial/BlockPortal.java similarity index 91% rename from java/src/game/block/BlockPortal.java rename to common/src/main/java/common/block/artificial/BlockPortal.java index e715a8a..a140f4b 100755 --- a/java/src/game/block/BlockPortal.java +++ b/common/src/main/java/common/block/artificial/BlockPortal.java @@ -1,28 +1,31 @@ -package game.block; +package common.block.artificial; import java.util.Map; -import game.entity.Entity; -import game.init.Blocks; -import game.item.Item; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyEnum; -import game.properties.PropertyInteger; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.Facing.Axis; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldClient; +import common.block.Block; +import common.block.Material; +import common.block.natural.BlockFire; +import common.entity.Entity; +import common.init.Blocks; +import common.item.Item; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ParticleType; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.util.Facing.Axis; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; -public class BlockPortal extends BlockBreakable +public class BlockPortal extends Block { public static final PropertyEnum AXIS = PropertyEnum.create("axis", Facing.Axis.class, Facing.Axis.X, Facing.Axis.Z); public static final PropertyInteger DIM = PropertyInteger.create("dim", 0, 7); @@ -31,12 +34,12 @@ public class BlockPortal extends BlockBreakable public BlockPortal() { - super(Material.portal, false); + super(Material.PORTAL); this.setDefaultState(this.getBaseState().withProperty(AXIS, Facing.Axis.X).withProperty(DIM, 0)); // this.setTickRandomly(); } -// public void updateTick(WorldServer worldIn, BlockPos pos, IBlockState state, Random rand) +// public void updateTick(IWorldServer worldIn, BlockPos pos, IBlockState state, Random rand) // { //// super.updateTick(worldIn, pos, state, rand); // @@ -96,6 +99,14 @@ public class BlockPortal extends BlockBreakable return false; } + public boolean isOpaqueCube() { + return false; + } + + public BlockLayer getBlockLayer() { + return BlockLayer.TRANSLUCENT; + } + public boolean tryIgnitePortal(World worldIn, BlockPos pos, int dim) { BlockPortal.Size size = new BlockPortal.Size(worldIn, pos, Facing.Axis.X, dim); @@ -191,11 +202,6 @@ public class BlockPortal extends BlockBreakable return 0; } - public BlockLayer getBlockLayer() - { - return BlockLayer.TRANSLUCENT; - } - /** * Called When an Entity Collided with the Block */ @@ -207,7 +213,7 @@ public class BlockPortal extends BlockBreakable } } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { // if (rand.chance(100)) // { @@ -276,11 +282,11 @@ public class BlockPortal extends BlockBreakable return new IProperty[] {AXIS, DIM}; } - public ModelBlock getModel(String name, State state) { - return state.getValue(AXIS) == Facing.Axis.X ? new ModelBlock(name) + public Model getModel(ModelProvider provider, String name, State state) { + return state.getValue(AXIS) == Facing.Axis.X ? provider.getModel(name) .add(0, 0, 6, 16, 16, 10) .n().uv(0, 0, 16, 16).noCull().tint() - .s().uv(0, 0, 16, 16).noCull().tint() : new ModelBlock(name) + .s().uv(0, 0, 16, 16).noCull().tint() : provider.getModel(name) .add(6, 0, 0, 10, 16, 16) .w().uv(0, 0, 16, 16).noCull().tint() .e().uv(0, 0, 16, 16).noCull().tint(); @@ -322,7 +328,7 @@ public class BlockPortal extends BlockBreakable // { // BlockWorldState blockworldstate = blockpattern$patternhelper.translateOffset(i, j, 1); // -// if (blockworldstate.getBlockState() != null && blockworldstate.getBlockState().getBlock().getMaterial() != Material.air) +// if (blockworldstate.getBlockState() != null && blockworldstate.getBlockState().getBlock() != Blocks.air) // { // ++aint[enumfacing$axisdirection.ordinal()]; // } @@ -492,7 +498,7 @@ public class BlockPortal extends BlockBreakable protected boolean func_150857_a(Block p_150857_1_) { - return p_150857_1_.material == Material.air || p_150857_1_ == Blocks.fire || p_150857_1_ == Blocks.portal; + return p_150857_1_ == Blocks.air || p_150857_1_ instanceof BlockFire || p_150857_1_ == Blocks.portal; } public boolean func_150860_b() diff --git a/java/src/game/block/BlockPortalFrame.java b/common/src/main/java/common/block/artificial/BlockPortalFrame.java similarity index 82% rename from java/src/game/block/BlockPortalFrame.java rename to common/src/main/java/common/block/artificial/BlockPortalFrame.java index 6ec55a2..0c5a300 100755 --- a/java/src/game/block/BlockPortalFrame.java +++ b/common/src/main/java/common/block/artificial/BlockPortalFrame.java @@ -1,28 +1,30 @@ -package game.block; +package common.block.artificial; import java.util.List; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.ItemRegistry; -import game.init.Items; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyDirection; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyDirection; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.State; +import common.world.World; public class BlockPortalFrame extends Block { @@ -31,7 +33,7 @@ public class BlockPortalFrame extends Block public BlockPortalFrame() { - super(Material.rock); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(ORB, Boolean.valueOf(false))); } @@ -151,8 +153,8 @@ public class BlockPortalFrame extends Block return true; } - public ModelBlock getModel(String name, State state) { - return (state.getValue(ORB) ? new ModelBlock("portal_frame_side") + public Model getModel(ModelProvider provider, String name, State state) { + return (state.getValue(ORB) ? provider.getModel("portal_frame_side") .add(0, 0, 0, 16, 13, 16) .d("portal_frame_bottom").uv(0, 0, 16, 16).noCull() .u("portal_frame_top").uv(0, 0, 16, 16).noCull() @@ -166,7 +168,7 @@ public class BlockPortalFrame extends Block .n("portal_frame_orb").uv(4, 0, 12, 3).noCull() .s("portal_frame_orb").uv(4, 0, 12, 3).noCull() .w("portal_frame_orb").uv(4, 0, 12, 3).noCull() - .e("portal_frame_orb").uv(4, 0, 12, 3).noCull() : new ModelBlock("portal_frame_side") + .e("portal_frame_orb").uv(4, 0, 12, 3).noCull() : provider.getModel("portal_frame_side") .add(0, 0, 0, 16, 13, 16) .d("portal_frame_bottom").uv(0, 0, 16, 16).noCull() .u("portal_frame_top").uv(0, 0, 16, 16).noCull() diff --git a/java/src/game/block/BlockQuartz.java b/common/src/main/java/common/block/artificial/BlockQuartz.java similarity index 78% rename from java/src/game/block/BlockQuartz.java rename to common/src/main/java/common/block/artificial/BlockQuartz.java index ce2bc47..5e78fc2 100755 --- a/java/src/game/block/BlockQuartz.java +++ b/common/src/main/java/common/block/artificial/BlockQuartz.java @@ -1,22 +1,24 @@ -package game.block; +package common.block.artificial; import java.util.List; -import game.entity.types.EntityLiving; -import game.init.ItemRegistry; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.types.EntityLiving; +import common.init.ItemRegistry; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.util.BlockPos; +import common.util.Facing; +import common.util.Identifyable; +import common.world.State; +import common.world.World; public class BlockQuartz extends Block { @@ -26,9 +28,9 @@ public class BlockQuartz extends Block public BlockQuartz(String prefix) { - super(Material.rock); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(VARIANT, BlockQuartz.EnumType.DEFAULT)); - this.setTab(CheatTab.tabBlocks); + this.setTab(CheatTab.BLOCKS); this.prefix = prefix; } @@ -114,23 +116,23 @@ public class BlockQuartz extends Block return new IProperty[] {VARIANT}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { switch(state.getValue(VARIANT)) { case DEFAULT: default: - return new ModelBlock(this.prefix + "quartz_block_side").add().nswe().d(this.prefix + "quartz_block_bottom").u(this.prefix + "quartz_top"); + return provider.getModel(this.prefix + "quartz_block_side").add().nswe().d(this.prefix + "quartz_block_bottom").u(this.prefix + "quartz_top"); case CHISELED: - return new ModelBlock(this.prefix + "quartz_block_chiseled").add().nswe().du(this.prefix + "quartz_block_chiseled_top"); + return provider.getModel(this.prefix + "quartz_block_chiseled").add().nswe().du(this.prefix + "quartz_block_chiseled_top"); case LINES_X: - return new ModelBlock(this.prefix + "quartz_block_lines").add().nswe().du(this.prefix + "quartz_block_lines_top").rotate(ModelRotation.X90_Y90); + return provider.getModel(this.prefix + "quartz_block_lines").add().nswe().du(this.prefix + "quartz_block_lines_top").rotate(ModelRotation.X90_Y90); case LINES_Y: - return new ModelBlock(this.prefix + "quartz_block_lines").add().nswe().du(this.prefix + "quartz_block_lines_top"); + return provider.getModel(this.prefix + "quartz_block_lines").add().nswe().du(this.prefix + "quartz_block_lines_top"); case LINES_Z: - return new ModelBlock(this.prefix + "quartz_block_lines").add().nswe().du(this.prefix + "quartz_block_lines_top").rotate(ModelRotation.X90_Y0); + return provider.getModel(this.prefix + "quartz_block_lines").add().nswe().du(this.prefix + "quartz_block_lines_top").rotate(ModelRotation.X90_Y0); } } - public static enum EnumType implements IStringSerializable + public static enum EnumType implements Identifyable { DEFAULT(0, "default", "default", null), CHISELED(1, "chiseled", "chiseled", null), diff --git a/common/src/main/java/common/block/artificial/BlockSkull.java b/common/src/main/java/common/block/artificial/BlockSkull.java new file mode 100755 index 0000000..f5f0c26 --- /dev/null +++ b/common/src/main/java/common/block/artificial/BlockSkull.java @@ -0,0 +1,75 @@ +package common.block.artificial; + +import common.block.BlockDirectional; +import common.block.Material; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; + +public class BlockSkull extends BlockDirectional { + public BlockSkull() { + super(Material.SMALL); + this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); + this.setBlockBounds(0.25F, 0.0F, 0.25F, 0.75F, 0.5F, 0.75F); + } + + public boolean canPlaceBlockAt(World world, BlockPos pos) { + return world.getState(pos).getBlock().getMaterial().isReplaceable() && world.isBlockSolid(pos.down()); + } + + public State onBlockPlaced(World world, BlockPos pos, Facing face, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) { + return this.getState().withProperty(FACING, placer.getHorizontalFacing().getOpposite()); + } + + public State getStateFromMeta(int meta) { + return this.getState().withProperty(FACING, Facing.getHorizontal(meta)); + } + + public int getMetaFromState(State state) { + return state.getValue(FACING).getHorizontalIndex(); + } + + protected IProperty[] getProperties() { + return new IProperty[] {FACING}; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("skull_top").add(4, 0, 4, 12, 8, 12) + .d("skull_bottom").u().n("skull_front").s("skull_back").w("skull_right").e("skull_left").rotate(ModelRotation.getNorthRot(state.getValue(FACING))); + } + + public boolean isOpaqueCube() { + return false; + } + + public boolean isFullCube() { + return false; + } + + public Item getItemDropped(State state, Random rand, int fortune) { + return Items.skull; + } + + public Item getItem(World worldIn, BlockPos pos) { + return Items.skull; + } + + public boolean isXrayVisible() { + return true; + } + + public boolean onShot(World world, BlockPos pos, State state, Entity projectile) { + world.destroyBlock(pos, true); + return true; + } +} diff --git a/java/src/game/block/BlockSlab.java b/common/src/main/java/common/block/artificial/BlockSlab.java similarity index 73% rename from java/src/game/block/BlockSlab.java rename to common/src/main/java/common/block/artificial/BlockSlab.java index caebe48..223745c 100755 --- a/java/src/game/block/BlockSlab.java +++ b/common/src/main/java/common/block/artificial/BlockSlab.java @@ -1,26 +1,27 @@ -package game.block; +package common.block.artificial; import java.util.List; -import game.collect.Lists; - -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyDirection; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.Facing.Axis; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.collect.Lists; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyDirection; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.util.Facing.Axis; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockSlab extends Block { @@ -43,7 +44,7 @@ public class BlockSlab extends Block super(materialIn); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.DOWN).withProperty(DOUBLE, false) .withProperty(SEAMLESS, false)); - this.setTab(materialIn == Material.wood ? CheatTab.tabWood : CheatTab.tabBlocks); + this.setTab(materialIn == Material.WOOD ? CheatTab.WOOD : CheatTab.BLOCKS); // this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.5F); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.5F, 1.0F); @@ -251,52 +252,52 @@ public class BlockSlab extends Block // // public abstract Object getVariant(ItemStack stack); - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { if(state.getValue(DOUBLE)) { - return new ModelBlock(state.getValue(SEAMLESS) ? this.textureTop : this.textureSide) + return provider.getModel(state.getValue(SEAMLESS) ? this.textureTop : this.textureSide) .add().nswe().d(state.getValue(SEAMLESS) ? this.textureTop : this.textureBottom).u(this.textureTop); } else { if(state.getValue(FACING).getAxis() != Axis.Y) - return new ModelBlock(this.textureSide).vslab(state.getValue(FACING), this.textureBottom, this.textureTop); + return provider.getModel(this.textureSide).vslab(state.getValue(FACING), this.textureBottom, this.textureTop); else - return new ModelBlock(this.textureSide).slab(state.getValue(FACING) == Facing.UP, this.textureBottom, + return provider.getModel(this.textureSide).slab(state.getValue(FACING) == Facing.UP, this.textureBottom, this.textureTop); } } /* - public ModelBlock getModel(String name, IBlockState state) { + public Model getModel(String name, IBlockState state) { if(state.getValue(VARIANT) == EnumType.STONE) - return state.getValue(SEAMLESS) ? new ModelBlock("double_stone_top").add().all() : - new ModelBlock("stone_slab_side").add().nswe().du("double_stone_top"); + return state.getValue(SEAMLESS) ? provider.getModel("double_stone_top").add().all() : + provider.getModel("stone_slab_side").add().nswe().du("double_stone_top"); else if(state.getValue(VARIANT) == EnumType.QUARTZ) - return new ModelBlock("quartz_block_side").add().nswe().d("quartz_block_bottom").u("quartz_top"); + return provider.getModel("quartz_block_side").add().nswe().d("quartz_block_bottom").u("quartz_top"); else if(state.getValue(VARIANT) == EnumType.SAND) - return new ModelBlock("sandstone_normal").add().nswe().d("sandstone_bottom").u("sandstone_all"); + return provider.getModel("sandstone_normal").add().nswe().d("sandstone_bottom").u("sandstone_all"); else - return new ModelBlock(getTexture(state.getValue(VARIANT))).add().all(); + return provider.getModel(getTexture(state.getValue(VARIANT))).add().all(); } - public ModelBlock getModel(String name, IBlockState state) { + public Model getModel(String name, IBlockState state) { if(state.getValue(VARIANT) == EnumType.STONE) - return new ModelBlock("stone_slab_side").slab(state.getValue(HALF) == EnumBlockHalf.TOP, "double_stone_top"); + return provider.getModel("stone_slab_side").slab(state.getValue(HALF) == EnumBlockHalf.TOP, "double_stone_top"); else if(state.getValue(VARIANT) == EnumType.QUARTZ) - return new ModelBlock("quartz_block_side").slab(state.getValue(HALF) == EnumBlockHalf.TOP, "quartz_block_bottom", + return provider.getModel("quartz_block_side").slab(state.getValue(HALF) == EnumBlockHalf.TOP, "quartz_block_bottom", "quartz_top"); else if(state.getValue(VARIANT) == EnumType.SAND) - return new ModelBlock("sandstone_normal").slab(state.getValue(HALF) == EnumBlockHalf.TOP, "sandstone_bottom", + return provider.getModel("sandstone_normal").slab(state.getValue(HALF) == EnumBlockHalf.TOP, "sandstone_bottom", "sandstone_all"); else - return new ModelBlock(getTexture(state.getValue(VARIANT))).slab(state.getValue(HALF) == EnumBlockHalf.TOP); + return provider.getModel(getTexture(state.getValue(VARIANT))).slab(state.getValue(HALF) == EnumBlockHalf.TOP); } - public ModelBlock getModel(String name, IBlockState state) { - return new ModelBlock(state.getValue(VARIANT).getName() + "_planks").slab(state.getValue(HALF) == EnumBlockHalf.TOP); + public Model getModel(String name, IBlockState state) { + return provider.getModel(state.getValue(VARIANT).getName() + "_planks").slab(state.getValue(HALF) == EnumBlockHalf.TOP); } - public ModelBlock getModel(String name, IBlockState state) { - return new ModelBlock(state.getValue(VARIANT).getName() + "_planks").add().all(); + public Model getModel(String name, IBlockState state) { + return provider.getModel(state.getValue(VARIANT).getName() + "_planks").add().all(); } protected static String getTexture(BlockStoneSlab.EnumType type) { @@ -321,14 +322,14 @@ public class BlockSlab extends Block } } - public ModelBlock getModel(String name, IBlockState state) { + public Model getModel(String name, IBlockState state) { if(state.getValue(VARIANT) == EnumType.STONE) - return new ModelBlock("stone_slab_side").vslab(state.getValue(FACING), "double_stone_top"); + return provider.getModel("stone_slab_side").vslab(state.getValue(FACING), "double_stone_top"); else if(state.getValue(VARIANT) == EnumType.SAND) - return new ModelBlock("sandstone_normal").vslab(state.getValue(FACING), "sandstone_bottom", + return provider.getModel("sandstone_normal").vslab(state.getValue(FACING), "sandstone_bottom", "sandstone_all"); else - return new ModelBlock(getTexture(state.getValue(VARIANT))).vslab(state.getValue(FACING)); + return provider.getModel(getTexture(state.getValue(VARIANT))).vslab(state.getValue(FACING)); } private static String getTexture(BlockVertStoneSlab2.EnumType type) { @@ -342,20 +343,20 @@ public class BlockSlab extends Block } } - public ModelBlock getModel(String name, IBlockState state) { + public Model getModel(String name, IBlockState state) { if(state.getValue(VARIANT) == EnumType.QUARTZ) - return new ModelBlock("quartz_block_side").vslab(state.getValue(FACING), "quartz_block_bottom", + return provider.getModel("quartz_block_side").vslab(state.getValue(FACING), "quartz_block_bottom", "quartz_top"); else - return new ModelBlock(getTexture(state.getValue(VARIANT))).vslab(state.getValue(FACING)); + return provider.getModel(getTexture(state.getValue(VARIANT))).vslab(state.getValue(FACING)); } - public ModelBlock getModel(String name, IBlockState state) { - return new ModelBlock(state.getValue(VARIANT).getName() + "_planks").vslab(state.getValue(FACING)); + public Model getModel(String name, IBlockState state) { + return provider.getModel(state.getValue(VARIANT).getName() + "_planks").vslab(state.getValue(FACING)); } - public ModelBlock getModel(String name, IBlockState state) { - return new ModelBlock(state.getValue(VARIANT).getName() + "_planks").vslab(state.getValue(FACING)); + public Model getModel(String name, IBlockState state) { + return provider.getModel(state.getValue(VARIANT).getName() + "_planks").vslab(state.getValue(FACING)); } */ } diff --git a/common/src/main/java/common/block/artificial/BlockStainedGlass.java b/common/src/main/java/common/block/artificial/BlockStainedGlass.java new file mode 100755 index 0000000..8ca8637 --- /dev/null +++ b/common/src/main/java/common/block/artificial/BlockStainedGlass.java @@ -0,0 +1,52 @@ +package common.block.artificial; + +import java.util.List; + +import common.color.DyeColor; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.world.State; + +public class BlockStainedGlass extends BlockGlass { + public static final PropertyEnum COLOR = PropertyEnum.create("color", DyeColor.class); + + public BlockStainedGlass() { + this.setDefaultState(this.getBaseState().withProperty(COLOR, DyeColor.WHITE)); + } + + public int damageDropped(State state) { + return state.getValue(COLOR).getMetadata(); + } + + public void getSubBlocks(Item item, CheatTab tab, List list) { + for(DyeColor color : DyeColor.values()) { + list.add(new ItemStack(item, 1, color.getMetadata())); + } + } + + public BlockLayer getBlockLayer() { + return BlockLayer.TRANSLUCENT; + } + + public State getStateFromMeta(int meta) { + return this.getState().withProperty(COLOR, DyeColor.byMetadata(meta)); + } + + public int getMetaFromState(State state) { + return state.getValue(COLOR).getMetadata(); + } + + protected IProperty[] getProperties() { + return new IProperty[] {COLOR}; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(state.getValue(COLOR).getName() + "_glass").add().all(); + } +} diff --git a/java/src/game/block/BlockStainedGlassPane.java b/common/src/main/java/common/block/artificial/BlockStainedGlassPane.java similarity index 81% rename from java/src/game/block/BlockStainedGlassPane.java rename to common/src/main/java/common/block/artificial/BlockStainedGlassPane.java index 7642973..9c29581 100755 --- a/java/src/game/block/BlockStainedGlassPane.java +++ b/common/src/main/java/common/block/artificial/BlockStainedGlassPane.java @@ -1,16 +1,16 @@ -package game.block; +package common.block.artificial; import java.util.List; -import game.color.DyeColor; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyEnum; -import game.renderer.BlockLayer; -import game.world.State; +import common.block.Material; +import common.color.DyeColor; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.BlockLayer; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.world.State; public class BlockStainedGlassPane extends BlockPane { @@ -18,9 +18,9 @@ public class BlockStainedGlassPane extends BlockPane public BlockStainedGlassPane() { - super(Material.glass, false); + super(Material.TRANSLUCENT, false); this.setDefaultState(this.getBaseState().withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)).withProperty(COLOR, DyeColor.WHITE)); - this.setTab(CheatTab.tabBlocks); + this.setTab(CheatTab.BLOCKS); } /** @@ -77,7 +77,7 @@ public class BlockStainedGlassPane extends BlockPane return new IProperty[] {NORTH, EAST, WEST, SOUTH, COLOR}; } -// public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) +// public void onBlockAdded(IWorldServer worldIn, BlockPos pos, State state) // { // if (!worldIn.client) // { @@ -85,7 +85,7 @@ public class BlockStainedGlassPane extends BlockPane // } // } // -// public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) +// public void onBlockRemoved(IWorldServer worldIn, BlockPos pos, State state) // { // if (!worldIn.client) // { diff --git a/java/src/game/block/BlockStairs.java b/common/src/main/java/common/block/artificial/BlockStairs.java similarity index 93% rename from java/src/game/block/BlockStairs.java rename to common/src/main/java/common/block/artificial/BlockStairs.java index 6b035eb..337f715 100755 --- a/java/src/game/block/BlockStairs.java +++ b/common/src/main/java/common/block/artificial/BlockStairs.java @@ -1,35 +1,37 @@ -package game.block; +package common.block.artificial; import java.util.Arrays; import java.util.List; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.item.CheatTab; -import game.material.Material; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyDirection; -import game.properties.PropertyEnum; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Explosion; -import game.world.Facing; -import game.world.HitPosition; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.Vec3; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.item.CheatTab; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.util.HitPosition; +import common.util.Identifyable; +import common.util.Vec3; +import common.world.Explosion; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockStairs extends Block { @@ -51,15 +53,15 @@ public class BlockStairs extends Block public BlockStairs(State modelState, String down, String up) { - super(modelState.getBlock().material); + super(modelState.getBlock().getMaterial()); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(HALF, BlockStairs.EnumHalf.BOTTOM).withProperty(SHAPE, BlockStairs.EnumShape.STRAIGHT)); this.modelBlock = modelState.getBlock(); this.modelState = modelState; - this.setHardness(this.modelBlock.blockHardness); - this.setResistance(this.modelBlock.blockResistance / 3.0F); + this.setHardness(this.modelBlock.getRawHardness()); + this.setResistance(this.modelBlock.getRawResistance() / 3.0F); this.setStepSound(this.modelBlock.sound); this.setLightOpacity(255); - this.setTab(modelState.getBlock().material == Material.wood ? CheatTab.tabWood : CheatTab.tabBlocks); + this.setTab(modelState.getBlock().getMaterial() == Material.WOOD ? CheatTab.WOOD : CheatTab.BLOCKS); this.downTex = down; this.upTex = up; } @@ -560,7 +562,7 @@ public class BlockStairs extends Block this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { this.modelBlock.randomDisplayTick(worldIn, pos, state, rand); } @@ -622,9 +624,9 @@ public class BlockStairs extends Block return this.modelBlock.isCollidable(); } - public boolean canCollideCheck(State state, boolean hitIfLiquid) + public boolean canCollideCheck(State state, boolean liquid) { - return this.modelBlock.canCollideCheck(state, hitIfLiquid); + return this.modelBlock.canCollideCheck(state, liquid); } public boolean canPlaceBlockAt(World worldIn, BlockPos pos) @@ -632,13 +634,13 @@ public class BlockStairs extends Block return this.modelBlock.canPlaceBlockAt(worldIn, pos); } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { this.onNeighborBlockChange(worldIn, pos, this.modelState, Blocks.air); this.modelBlock.onBlockAdded(worldIn, pos, this.modelState); } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { this.modelBlock.onBlockRemoved(worldIn, pos, this.modelState); } @@ -651,7 +653,7 @@ public class BlockStairs extends Block this.modelBlock.onEntityCollidedWithBlock(worldIn, pos, entityIn); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { this.modelBlock.updateTick(worldIn, pos, state, rand); } @@ -812,10 +814,10 @@ public class BlockStairs extends Block return Transforms.STAIRS; } - public ModelBlock getModel(String name, State state) { - String primary = this.modelBlock.getModel(BlockRegistry.REGISTRY.getNameForObject(this.modelBlock).toString(), this.modelState) + public Model getModel(ModelProvider provider, String name, State state) { + String primary = this.modelBlock.getModel(provider, BlockRegistry.getNameFromBlock(this.modelBlock).toString(), this.modelState) .getPrimary(); - return new ModelBlock(primary) + return provider.getModel(primary) .stairs(state.getValue(HALF) == EnumHalf.TOP, state.getValue(SHAPE) == EnumShape.INNER_RIGHT || state.getValue(SHAPE) == EnumShape.INNER_LEFT, state.getValue(SHAPE) == EnumShape.OUTER_RIGHT || state.getValue(SHAPE) == EnumShape.OUTER_LEFT, state.getValue(SHAPE) == EnumShape.INNER_LEFT || @@ -828,7 +830,7 @@ public class BlockStairs extends Block ); } - public static enum EnumHalf implements IStringSerializable + public static enum EnumHalf implements Identifyable { TOP("top"), BOTTOM("bottom"); @@ -851,7 +853,7 @@ public class BlockStairs extends Block } } - public static enum EnumShape implements IStringSerializable + public static enum EnumShape implements Identifyable { STRAIGHT("straight"), INNER_LEFT("inner_left"), diff --git a/java/src/game/block/BlockStoneBrick.java b/common/src/main/java/common/block/artificial/BlockStoneBrick.java similarity index 84% rename from java/src/game/block/BlockStoneBrick.java rename to common/src/main/java/common/block/artificial/BlockStoneBrick.java index 3b0389d..f0a7508 100755 --- a/java/src/game/block/BlockStoneBrick.java +++ b/common/src/main/java/common/block/artificial/BlockStoneBrick.java @@ -1,16 +1,18 @@ -package game.block; +package common.block.artificial; import java.util.List; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.world.State; +import common.block.Block; +import common.block.Material; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.util.Identifyable; +import common.world.State; public class BlockStoneBrick extends Block { @@ -22,9 +24,9 @@ public class BlockStoneBrick extends Block public BlockStoneBrick() { - super(Material.rock); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(VARIANT, BlockStoneBrick.EnumType.DEFAULT)); - this.setTab(CheatTab.tabBlocks); + this.setTab(CheatTab.BLOCKS); } /** @@ -68,11 +70,11 @@ public class BlockStoneBrick extends Block return new IProperty[] {VARIANT}; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("stonebrick_" + state.getValue(VARIANT).getTexture()).add().all(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("stonebrick_" + state.getValue(VARIANT).getTexture()).add().all(); } - public static enum EnumType implements IStringSerializable + public static enum EnumType implements Identifyable { DEFAULT("default", 0, "stonebrick", "Steinziegel"), MOSSY("mossy", 1, "mossy_stonebrick", "Bemooste Steinziegel"), diff --git a/java/src/game/block/BlockTrapDoor.java b/common/src/main/java/common/block/artificial/BlockTrapDoor.java similarity index 85% rename from java/src/game/block/BlockTrapDoor.java rename to common/src/main/java/common/block/artificial/BlockTrapDoor.java index edc6932..3f970d6 100755 --- a/java/src/game/block/BlockTrapDoor.java +++ b/common/src/main/java/common/block/artificial/BlockTrapDoor.java @@ -1,28 +1,30 @@ -package game.block; +package common.block.artificial; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.item.CheatTab; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyBool; -import game.properties.PropertyDirection; -import game.properties.PropertyEnum; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.HitPosition; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.Vec3; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.item.CheatTab; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.Transforms; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyDirection; +import common.properties.PropertyEnum; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.util.HitPosition; +import common.util.Identifyable; +import common.util.Vec3; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockTrapDoor extends Block { @@ -37,7 +39,7 @@ public class BlockTrapDoor extends Block float f = 0.5F; float f1 = 1.0F; this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - this.setTab(materialIn == Material.wood ? CheatTab.tabWood : CheatTab.tabTech); + this.setTab(materialIn == Material.WOOD ? CheatTab.WOOD : CheatTab.TECHNOLOGY); } /** @@ -129,7 +131,7 @@ public class BlockTrapDoor extends Block public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { - if (this.material == Material.iron) + if (this.material == Material.SOLID) { return true; } @@ -248,7 +250,7 @@ public class BlockTrapDoor extends Block private static boolean isValidSupportBlock(Block blockIn) { - return blockIn.material.isOpaque() && blockIn.isFullCube() || blockIn == Blocks.glass || blockIn == Blocks.stained_glass || blockIn == Blocks.glowstone || blockIn instanceof BlockSlab || blockIn instanceof BlockStairs; + return blockIn.getMaterial().isOpaque() && blockIn.isFullCube() || blockIn == Blocks.glass || blockIn == Blocks.stained_glass || blockIn == Blocks.glowstone || blockIn instanceof BlockSlab || blockIn instanceof BlockStairs; } public BlockLayer getBlockLayer() @@ -291,17 +293,17 @@ public class BlockTrapDoor extends Block } public boolean isMagnetic() { - return this.material == Material.iron; + return this.material == Material.SOLID; } public Transforms getTransform() { return Transforms.FLAT; } - public ModelBlock getModel(String name, State state) { - ModelBlock model; + public Model getModel(ModelProvider provider, String name, State state) { + Model model; if(state.getValue(OPEN)) { - model = new ModelBlock(name) + model = provider.getModel(name) .add(0, 0, 13, 16, 16, 16) .d().uv(0, 13, 16, 16) .u().uv(0, 16, 16, 13) @@ -311,7 +313,7 @@ public class BlockTrapDoor extends Block .e().uv(13, 0, 16, 16); } else if(state.getValue(HALF) == DoorHalf.TOP) { - model = new ModelBlock(name) + model = provider.getModel(name) .add(0, 13, 0, 16, 16, 16) .d().uv(0, 0, 16, 16).noCull() .u().uv(0, 0, 16, 16) @@ -321,7 +323,7 @@ public class BlockTrapDoor extends Block .e().uv(0, 16, 16, 13); } else { - model = new ModelBlock(name) + model = provider.getModel(name) .add(0, 0, 0, 16, 3, 16) .d().uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -333,7 +335,7 @@ public class BlockTrapDoor extends Block return model.rotate(ModelRotation.getNorthRot(state.getValue(FACING))); } - public static enum DoorHalf implements IStringSerializable + public static enum DoorHalf implements Identifyable { TOP("top"), BOTTOM("bottom"); diff --git a/java/src/game/block/BlockWall.java b/common/src/main/java/common/block/artificial/BlockWall.java similarity index 86% rename from java/src/game/block/BlockWall.java rename to common/src/main/java/common/block/artificial/BlockWall.java index 38383f3..703eed4 100755 --- a/java/src/game/block/BlockWall.java +++ b/common/src/main/java/common/block/artificial/BlockWall.java @@ -1,24 +1,27 @@ -package game.block; +package common.block.artificial; import java.util.List; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyBool; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyEnum; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.util.Identifyable; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockWall extends Block { @@ -31,12 +34,12 @@ public class BlockWall extends Block public BlockWall(Block modelBlock) { - super(modelBlock.material); + super(modelBlock.getMaterial()); this.setDefaultState(this.getBaseState().withProperty(UP, Boolean.valueOf(false)).withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)).withProperty(VARIANT, BlockWall.EnumType.NORMAL)); - this.setHardness(modelBlock.blockHardness); - this.setResistance(modelBlock.blockResistance / 3.0F); + this.setHardness(modelBlock.getRawHardness()); + this.setResistance(modelBlock.getRawResistance() / 3.0F); this.setStepSound(modelBlock.sound); - this.setTab(CheatTab.tabBlocks); + this.setTab(CheatTab.BLOCKS); } // /** @@ -123,7 +126,7 @@ public class BlockWall extends Block public boolean canConnectTo(IBlockAccess worldIn, BlockPos pos) { Block block = worldIn.getState(pos).getBlock(); - return (block != this && !(block instanceof BlockFenceGate) ? (block.material.isOpaque() && block.isFullCube() ? block.material != Material.gourd : false) : true); + return (block != this && !(block instanceof BlockFenceGate) ? (block.getMaterial().isOpaque() && block.isFullCube() ? block.getMaterial() != Material.SOFT : false) : true); } /** @@ -173,7 +176,7 @@ public class BlockWall extends Block */ public State getActualState(State state, IWorldAccess worldIn, BlockPos pos) { - return state.withProperty(UP, Boolean.valueOf(worldIn.getState(pos.up()).getBlock().getMaterial() != Material.air)).withProperty(NORTH, Boolean.valueOf(this.canConnectTo(worldIn, pos.north()))).withProperty(EAST, Boolean.valueOf(this.canConnectTo(worldIn, pos.east()))).withProperty(SOUTH, Boolean.valueOf(this.canConnectTo(worldIn, pos.south()))).withProperty(WEST, Boolean.valueOf(this.canConnectTo(worldIn, pos.west()))); + return state.withProperty(UP, Boolean.valueOf(worldIn.getState(pos.up()).getBlock() != Blocks.air)).withProperty(NORTH, Boolean.valueOf(this.canConnectTo(worldIn, pos.north()))).withProperty(EAST, Boolean.valueOf(this.canConnectTo(worldIn, pos.east()))).withProperty(SOUTH, Boolean.valueOf(this.canConnectTo(worldIn, pos.south()))).withProperty(WEST, Boolean.valueOf(this.canConnectTo(worldIn, pos.west()))); } protected IProperty[] getProperties() @@ -181,7 +184,7 @@ public class BlockWall extends Block return new IProperty[] {UP, NORTH, EAST, WEST, SOUTH, VARIANT}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { String wall = state.getValue(VARIANT).getName(); boolean n = state.getValue(NORTH); boolean s = state.getValue(SOUTH); @@ -189,7 +192,7 @@ public class BlockWall extends Block boolean e = state.getValue(EAST); int sides = (n ? 1 : 0) + (s ? 1 : 0) + (w ? 1 : 0) + (e ? 1 : 0); if(sides == 0) - return new ModelBlock(wall) + return provider.getModel(wall) .add(4, 0, 4, 12, 16, 12) .d().uv(4, 4, 12, 12) .u().uv(4, 4, 12, 12) @@ -198,7 +201,7 @@ public class BlockWall extends Block .w().uv(4, 0, 12, 16).noCull() .e().uv(4, 0, 12, 16).noCull(); else if(sides == 4) - return new ModelBlock(wall) + return provider.getModel(wall) .add(4, 0, 4, 12, 16, 12) .d().uv(4, 4, 12, 12) .u().uv(4, 4, 12, 12) @@ -231,7 +234,7 @@ public class BlockWall extends Block .s().uv(0, 3, 4, 16).noCull() .w().uv(5, 3, 11, 16); else if(sides == 1) - return new ModelBlock(wall).uvLock() + return provider.getModel(wall).uvLock() .add(4, 0, 4, 12, 16, 12) .d().uv(4, 4, 12, 12) .u().uv(4, 4, 12, 12) @@ -247,7 +250,7 @@ public class BlockWall extends Block .e().uv(0, 3, 4, 16).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return new ModelBlock(wall).uvLock() + return provider.getModel(wall).uvLock() .add(4, 0, 4, 12, 16, 12) .d().uv(4, 4, 12, 12) .u().uv(4, 4, 12, 12) @@ -270,7 +273,7 @@ public class BlockWall extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && state.getValue(UP)) - return new ModelBlock(wall).uvLock() + return provider.getModel(wall).uvLock() .add(4, 0, 4, 12, 16, 12) .d().uv(4, 4, 12, 12) .u().uv(4, 4, 12, 12) @@ -287,7 +290,7 @@ public class BlockWall extends Block .e().uv(0, 3, 16, 16).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(sides == 2) - return new ModelBlock(wall).uvLock() + return provider.getModel(wall).uvLock() .add(5, 0, 0, 11, 13, 16) .d().uv(5, 0, 11, 16) .u().uv(5, 0, 11, 16).noCull() @@ -297,7 +300,7 @@ public class BlockWall extends Block .e().uv(0, 3, 16, 16).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else - return new ModelBlock(wall).uvLock() + return provider.getModel(wall).uvLock() .add(4, 0, 4, 12, 16, 12) .d().uv(4, 4, 12, 12) .u().uv(4, 4, 12, 12) @@ -326,7 +329,7 @@ public class BlockWall extends Block .rotate(!w ? ModelRotation.X0_Y0 : (!e ? ModelRotation.X0_Y180 : (!s ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); } - public static enum EnumType implements IStringSerializable + public static enum EnumType implements Identifyable { NORMAL(0, "cobblestone", "Bruchsteinmauer"), MOSSY(1, "mossy_cobblestone", "Bemooste Bruchsteinmauer"); diff --git a/java/src/game/block/BlockBaseFlower.java b/common/src/main/java/common/block/foliage/BlockBaseFlower.java similarity index 84% rename from java/src/game/block/BlockBaseFlower.java rename to common/src/main/java/common/block/foliage/BlockBaseFlower.java index 205a707..413ec6e 100755 --- a/java/src/game/block/BlockBaseFlower.java +++ b/common/src/main/java/common/block/foliage/BlockBaseFlower.java @@ -1,4 +1,4 @@ -package game.block; +package common.block.foliage; public class BlockBaseFlower extends BlockFlower { diff --git a/java/src/game/block/BlockBlackenedSoil.java b/common/src/main/java/common/block/foliage/BlockBlackenedSoil.java similarity index 56% rename from java/src/game/block/BlockBlackenedSoil.java rename to common/src/main/java/common/block/foliage/BlockBlackenedSoil.java index 7b3026a..e185c74 100644 --- a/java/src/game/block/BlockBlackenedSoil.java +++ b/common/src/main/java/common/block/foliage/BlockBlackenedSoil.java @@ -1,33 +1,36 @@ -package game.block; +package common.block.foliage; -import game.init.Blocks; -import game.init.Config; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.biome.Biome; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.item.CheatTab; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.AWorldServer; public class BlockBlackenedSoil extends Block { public BlockBlackenedSoil() { - super(Material.grass); + super(Material.LOOSE); this.setTickRandomly(); - this.setTab(CheatTab.tabNature); + this.setTab(CheatTab.NATURE); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { if (worldIn.getLightFromNeighbors(pos.up()) < 2 && worldIn.getState(pos.up()).getBlock().getLightOpacity() > 6) { - if(Config.darkSoilDecay) + if(Vars.darkSoilDecay) worldIn.setState(pos, Blocks.blackened_dirt.getState()); } - else if (Config.darkSoilSpread && worldIn.getLightFromNeighbors(pos.up()) >= 1) + else if (Vars.darkSoilSpread && worldIn.getLightFromNeighbors(pos.up()) >= 1) { for (int i = 0; i < 4; i++) { @@ -38,6 +41,7 @@ public class BlockBlackenedSoil extends Block if ((iblockstate.getBlock() == Blocks.dirt || iblockstate.getBlock() == Blocks.grass || iblockstate.getBlock() == Blocks.blackened_dirt) && worldIn.getLightFromNeighbors(blockpos.up()) >= 2 && block.getLightOpacity() <= 6) { worldIn.setState(blockpos, Blocks.blackened_soil.getState()); + worldIn.setBiome(blockpos, Biome.BLACKENED); } } } @@ -48,7 +52,7 @@ public class BlockBlackenedSoil extends Block return Blocks.blackened_dirt.getItemDropped(Blocks.blackened_dirt.getState(), rand, fortune); } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("blackened_dirt").add().d().u("blackened_soil_top").nswe("blackened_soil_side"); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("blackened_dirt").add().d().u("blackened_soil_top").nswe("blackened_soil_side"); } } diff --git a/java/src/game/block/BlockBlueShroom.java b/common/src/main/java/common/block/foliage/BlockBlueShroom.java similarity index 75% rename from java/src/game/block/BlockBlueShroom.java rename to common/src/main/java/common/block/foliage/BlockBlueShroom.java index ff95349..816e2cc 100755 --- a/java/src/game/block/BlockBlueShroom.java +++ b/common/src/main/java/common/block/foliage/BlockBlueShroom.java @@ -1,13 +1,15 @@ -package game.block; +package common.block.foliage; -import game.init.Blocks; -import game.init.Config; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.init.Blocks; +import common.model.Model; +import common.model.ModelProvider; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockBlueShroom extends BlockBush { @@ -18,9 +20,9 @@ public class BlockBlueShroom extends BlockBush this.setTickRandomly(); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Config.blueShroomGrowth > 0 && rand.chance(Config.blueShroomGrowth)) + if (Vars.blueShroomGrowth > 0 && rand.chance(Vars.blueShroomGrowth)) { int i = 5; int j = 4; @@ -69,7 +71,7 @@ public class BlockBlueShroom extends BlockBush public boolean canBlockStay(World worldIn, BlockPos pos, State state) { - if (pos.getY() >= 0 && pos.getY() < 512) + if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) { State iblockstate = worldIn.getState(pos.down()); return (iblockstate.getBlock() == Blocks.tian_soil || iblockstate.getBlock() == Blocks.obsidian) ? true : (worldIn.getLight(pos) < 13 && this.canPlaceBlockOn(iblockstate.getBlock())); @@ -80,7 +82,7 @@ public class BlockBlueShroom extends BlockBush } } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("blue_mushroom").cross(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("blue_mushroom").cross(); } } diff --git a/java/src/game/block/BlockBush.java b/common/src/main/java/common/block/foliage/BlockBush.java similarity index 79% rename from java/src/game/block/BlockBush.java rename to common/src/main/java/common/block/foliage/BlockBush.java index a24495d..acc0c1b 100755 --- a/java/src/game/block/BlockBush.java +++ b/common/src/main/java/common/block/foliage/BlockBush.java @@ -1,21 +1,22 @@ -package game.block; +package common.block.foliage; -import game.init.Blocks; -import game.item.CheatTab; -import game.material.Material; -import game.renderer.BlockLayer; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.item.CheatTab; +import common.model.BlockLayer; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockBush extends Block { public BlockBush() { - this(Material.plants); + this(Material.PLANT); } public BlockBush(Material p_i46452_1_) @@ -24,7 +25,7 @@ public class BlockBush extends Block this.setTickRandomly(); float f = 0.2F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f * 3.0F, 0.5F + f); - this.setTab(CheatTab.tabPlants); + this.setTab(CheatTab.PLANTS); } public boolean canPlaceBlockAt(World worldIn, BlockPos pos) @@ -49,7 +50,7 @@ public class BlockBush extends Block this.checkAndDropBlock(worldIn, pos, state); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { this.checkAndDropBlock(worldIn, pos, state); } diff --git a/java/src/game/block/BlockCactus.java b/common/src/main/java/common/block/foliage/BlockCactus.java similarity index 79% rename from java/src/game/block/BlockCactus.java rename to common/src/main/java/common/block/foliage/BlockCactus.java index 1ab1259..204599a 100755 --- a/java/src/game/block/BlockCactus.java +++ b/common/src/main/java/common/block/foliage/BlockCactus.java @@ -1,26 +1,28 @@ -package game.block; +package common.block.foliage; -import game.entity.DamageSource; -import game.entity.Entity; -import game.init.Blocks; -import game.init.Config; -import game.item.CheatTab; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.entity.DamageSource; +import common.entity.Entity; +import common.init.Blocks; +import common.item.CheatTab; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.vars.Vars; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockCactus extends Block { - private static final ModelBlock cactus = new ModelBlock("cactus_side").noOcclude() + private static final Model cactus = ModelProvider.getModelProvider().getModel("cactus_side") .add(0, 0, 0, 16, 16, 16) .d("cactus_bottom").uv(0, 0, 16, 16) .u("cactus_top").uv(0, 0, 16, 16) @@ -36,17 +38,17 @@ public class BlockCactus extends Block public BlockCactus() { - super(Material.cactus); + super(Material.BLOCKING); this.setDefaultState(this.getBaseState().withProperty(AGE, Integer.valueOf(0))); this.setTickRandomly(); - this.setTab(CheatTab.tabPlants); + this.setTab(CheatTab.PLANTS); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { BlockPos blockpos = pos.up(); - if (Config.cactusHeight > 0 && worldIn.isAirBlock(blockpos)) + if (Vars.cactusHeight > 0 && worldIn.isAirBlock(blockpos)) { int i; @@ -55,7 +57,7 @@ public class BlockCactus extends Block ; } - if (i < Config.cactusHeight) + if (i < Vars.cactusHeight) { int j = ((Integer)state.getValue(AGE)).intValue(); @@ -134,7 +136,7 @@ public class BlockCactus extends Block */ public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, State state, Entity entityIn) { - if(worldIn.client || Config.cactusDamage) + if(worldIn.client || Vars.cactusDamage) entityIn.attackEntityFrom(DamageSource.cactus, 1); } @@ -164,7 +166,7 @@ public class BlockCactus extends Block return new IProperty[] {AGE}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { return cactus; } diff --git a/common/src/main/java/common/block/foliage/BlockCarrot.java b/common/src/main/java/common/block/foliage/BlockCarrot.java new file mode 100755 index 0000000..e35b94b --- /dev/null +++ b/common/src/main/java/common/block/foliage/BlockCarrot.java @@ -0,0 +1,25 @@ +package common.block.foliage; + +import common.init.Items; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.world.State; + +public class BlockCarrot extends BlockCrops +{ + protected Item getSeed() + { + return Items.carrot; + } + + protected Item getCrop() + { + return Items.carrot; + } + + public Model getModel(ModelProvider provider, String name, State state) { + int age = state.getValue(AGE); + return crop(provider, name + "_" + (age == 6 ? 2 : (age / 2))); + } +} diff --git a/java/src/game/block/BlockCocoa.java b/common/src/main/java/common/block/foliage/BlockCocoa.java similarity index 85% rename from java/src/game/block/BlockCocoa.java rename to common/src/main/java/common/block/foliage/BlockCocoa.java index d24cbe3..3f8e27c 100755 --- a/java/src/game/block/BlockCocoa.java +++ b/common/src/main/java/common/block/foliage/BlockCocoa.java @@ -1,26 +1,29 @@ -package game.block; +package common.block.foliage; -import game.color.DyeColor; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.init.Items; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockDirectional; +import common.block.Material; +import common.color.DyeColor; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.Items; +import common.item.Item; +import common.item.ItemStack; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockCocoa extends BlockDirectional implements IGrowable { @@ -28,18 +31,18 @@ public class BlockCocoa extends BlockDirectional implements IGrowable public BlockCocoa() { - super(Material.plants); + super(Material.PLANT); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(AGE, Integer.valueOf(0))); this.setTickRandomly(); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { if (!this.canBlockStay(worldIn, pos, state)) { this.dropBlock(worldIn, pos, state); } - else if (Config.cocoaGrowth > 0 && worldIn.rand.chance(Config.cocoaGrowth)) + else if (Vars.cocoaGrowth > 0 && worldIn.rand.chance(Vars.cocoaGrowth)) { int i = ((Integer)state.getValue(AGE)).intValue(); @@ -196,7 +199,7 @@ public class BlockCocoa extends BlockDirectional implements IGrowable return true; } - public void grow(WorldServer worldIn, Random rand, BlockPos pos, State state) + public void grow(AWorldServer worldIn, Random rand, BlockPos pos, State state) { worldIn.setState(pos, state.withProperty(AGE, Integer.valueOf(((Integer)state.getValue(AGE)).intValue() + 1)), 2); } @@ -230,11 +233,11 @@ public class BlockCocoa extends BlockDirectional implements IGrowable return new IProperty[] {FACING, AGE}; } - public ModelBlock getModel(String name, State state) { - ModelBlock model; + public Model getModel(ModelProvider provider, String name, State state) { + Model model; switch(state.getValue(AGE)) { case 0: - model = new ModelBlock("cocoa_0").noOcclude() + model = provider.getModel("cocoa_0") .add(6, 7, 11, 10, 12, 15) .d().uv(0, 0, 4, 4).noCull() .u().uv(0, 0, 4, 4).noCull() @@ -247,7 +250,7 @@ public class BlockCocoa extends BlockDirectional implements IGrowable .e().uv(16, 0, 12, 4).noCull(); break; case 1: - model = new ModelBlock("cocoa_1").noOcclude() + model = provider.getModel("cocoa_1") .add(5, 5, 9, 11, 12, 15) .d().uv(0, 0, 6, 6).noCull() .u().uv(0, 0, 6, 6).noCull() @@ -261,7 +264,7 @@ public class BlockCocoa extends BlockDirectional implements IGrowable break; case 2: default: - model = new ModelBlock("cocoa_2").noOcclude() + model = provider.getModel("cocoa_2") .add(4, 3, 7, 12, 12, 15) .d().uv(0, 0, 7, 7).noCull() .u().uv(0, 0, 7, 7).noCull() diff --git a/java/src/game/block/BlockCrops.java b/common/src/main/java/common/block/foliage/BlockCrops.java similarity index 84% rename from java/src/game/block/BlockCrops.java rename to common/src/main/java/common/block/foliage/BlockCrops.java index 9b5d17a..db1806e 100755 --- a/java/src/game/block/BlockCrops.java +++ b/common/src/main/java/common/block/foliage/BlockCrops.java @@ -1,20 +1,22 @@ -package game.block; +package common.block.foliage; -import game.audio.SoundType; -import game.init.Blocks; -import game.init.Config; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.SoundType; +import common.init.Blocks; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockCrops extends BlockBush implements IGrowable { @@ -40,11 +42,11 @@ public class BlockCrops extends BlockBush implements IGrowable return ground == Blocks.farmland; } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { super.updateTick(worldIn, pos, state, rand); - if (Config.cropGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9) + if (Vars.cropGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9) { int i = ((Integer)state.getValue(AGE)).intValue(); @@ -52,7 +54,7 @@ public class BlockCrops extends BlockBush implements IGrowable { float f = getGrowthChance(this, worldIn, pos); - if (rand.chance((int)((float)(Config.cropGrowth - 1) / f) + 1)) + if (rand.chance((int)((float)(Vars.cropGrowth - 1) / f) + 1)) { worldIn.setState(pos, state.withProperty(AGE, Integer.valueOf(i + 1)), 2); } @@ -194,7 +196,7 @@ public class BlockCrops extends BlockBush implements IGrowable return true; } - public void grow(WorldServer worldIn, Random rand, BlockPos pos, State state) + public void grow(AWorldServer worldIn, Random rand, BlockPos pos, State state) { this.grow(worldIn, pos, state); } @@ -220,12 +222,12 @@ public class BlockCrops extends BlockBush implements IGrowable return new IProperty[] {AGE}; } - public ModelBlock getModel(String name, State state) { - return crop(name + "_" + state.getValue(AGE)); + public Model getModel(ModelProvider provider, String name, State state) { + return crop(provider, name + "_" + state.getValue(AGE)); } - public static ModelBlock crop(String crop) { - return new ModelBlock(crop).noOcclude() + public static Model crop(ModelProvider provider, String crop) { + return provider.getModel(crop) .add(4, -1, 0, 4, 15, 16).noShade() .w().uv(0, 0, 16, 16).noCull() .e().uv(0, 0, 16, 16).noCull() diff --git a/java/src/game/block/BlockDeadBush.java b/common/src/main/java/common/block/foliage/BlockDeadBush.java similarity index 72% rename from java/src/game/block/BlockDeadBush.java rename to common/src/main/java/common/block/foliage/BlockDeadBush.java index 1cfc441..9e24f13 100755 --- a/java/src/game/block/BlockDeadBush.java +++ b/common/src/main/java/common/block/foliage/BlockDeadBush.java @@ -1,24 +1,26 @@ -package game.block; +package common.block.foliage; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Items; -import game.item.Item; -import game.item.ItemShears; -import game.item.ItemStack; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.item.Item; +import common.item.ItemShears; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.world.State; +import common.world.World; public class BlockDeadBush extends BlockBush { public BlockDeadBush() { - super(Material.vine); + super(Material.BUSH); float f = 0.4F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.8F, 0.5F + f); } @@ -68,7 +70,7 @@ public class BlockDeadBush extends BlockBush } } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("deadbush").cross(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("deadbush").cross(); } } diff --git a/java/src/game/block/BlockDoublePlant.java b/common/src/main/java/common/block/foliage/BlockDoublePlant.java similarity index 90% rename from java/src/game/block/BlockDoublePlant.java rename to common/src/main/java/common/block/foliage/BlockDoublePlant.java index a54fe1f..34ef424 100755 --- a/java/src/game/block/BlockDoublePlant.java +++ b/common/src/main/java/common/block/foliage/BlockDoublePlant.java @@ -1,33 +1,36 @@ -package game.block; +package common.block.foliage; import java.util.List; -import game.audio.SoundType; -import game.color.Colorizer; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.init.ItemRegistry; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemShears; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.Facing; -import game.world.Facing.Axis; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockDirectional; +import common.block.Material; +import common.block.SoundType; +import common.color.Colorizer; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemShears; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.Facing; +import common.util.Identifyable; +import common.util.Facing.Axis; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockDoublePlant extends BlockBush implements IGrowable { @@ -37,7 +40,7 @@ public class BlockDoublePlant extends BlockBush implements IGrowable public BlockDoublePlant() { - super(Material.vine); + super(Material.BUSH); this.setDefaultState(this.getBaseState().withProperty(VARIANT, BlockDoublePlant.EnumPlantType.SUNFLOWER).withProperty(HALF, BlockDoublePlant.EnumBlockHalf.LOWER).withProperty(FACING, Facing.NORTH)); this.setHardness(0.0F); this.setStepSound(SoundType.GRASS); @@ -45,9 +48,9 @@ public class BlockDoublePlant extends BlockBush implements IGrowable // this.setTickRandomly(); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Config.plantDry && worldIn.getTemperatureC(pos) >= 50.0f) + if(Vars.plantDry && worldIn.getTemperatureC(pos) >= 50.0f) { boolean upper = state.getValue(HALF) == EnumBlockHalf.UPPER; if(!upper) @@ -295,7 +298,7 @@ public class BlockDoublePlant extends BlockBush implements IGrowable return true; } - public void grow(WorldServer worldIn, Random rand, BlockPos pos, State state) + public void grow(AWorldServer worldIn, Random rand, BlockPos pos, State state) { spawnAsEntity(worldIn, pos, new ItemStack(this, 1, this.getVariant(worldIn, pos).getMeta())); } @@ -345,9 +348,9 @@ public class BlockDoublePlant extends BlockBush implements IGrowable // return EnumOffsetType.XZ; // } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { if(state.getValue(VARIANT) == EnumPlantType.SUNFLOWER && state.getValue(HALF) == EnumBlockHalf.UPPER) - return new ModelBlock("sunflower_front").noOcclude() + return provider.getModel("sunflower_front") .add(0.8f, 0f, 8f, 15.2f, 8f, 8f).noShade().rotate(8, 8, 8, Axis.Y, 45, true).ns("sunflower_top") .uv(0, 8, 16, 16).noCull() .add(8f, 0f, 0.8f, 8f, 8f, 15.2f).noShade().rotate(8, 8, 8, Axis.Y, 45, true).we("sunflower_top") @@ -355,10 +358,10 @@ public class BlockDoublePlant extends BlockBush implements IGrowable .add(9.6f, -1f, 1f, 9.6f, 15f, 15f).noShade().rotate(8, 8, 8, Axis.Z, 22.5f, true).w("sunflower_back") .uv(0, 0, 16, 16).noCull().e().uv(0, 0, 16, 16).noCull(); else if(state.getValue(VARIANT) == EnumPlantType.FERN || state.getValue(VARIANT) == EnumPlantType.GRASS) - return new ModelBlock(state.getValue(VARIANT).getName() + "_" + (state.getValue(HALF) == EnumBlockHalf.UPPER + return provider.getModel(state.getValue(VARIANT).getName() + "_" + (state.getValue(HALF) == EnumBlockHalf.UPPER ? "top" : "bottom")).crossTint(); else - return new ModelBlock(state.getValue(VARIANT).getName() + "_" + (state.getValue(HALF) == EnumBlockHalf.UPPER + return provider.getModel(state.getValue(VARIANT).getName() + "_" + (state.getValue(HALF) == EnumBlockHalf.UPPER ? "top" : "bottom")).cross(); } @@ -366,7 +369,7 @@ public class BlockDoublePlant extends BlockBush implements IGrowable return new IProperty[] {FACING}; } - public static enum EnumBlockHalf implements IStringSerializable + public static enum EnumBlockHalf implements Identifyable { UPPER, LOWER; @@ -382,7 +385,7 @@ public class BlockDoublePlant extends BlockBush implements IGrowable } } - public static enum EnumPlantType implements IStringSerializable + public static enum EnumPlantType implements Identifyable { SUNFLOWER(0, "sunflower", "Sonnenblume"), SYRINGA(1, "syringa", "Flieder"), diff --git a/java/src/game/block/BlockDryLeaves.java b/common/src/main/java/common/block/foliage/BlockDryLeaves.java similarity index 81% rename from java/src/game/block/BlockDryLeaves.java rename to common/src/main/java/common/block/foliage/BlockDryLeaves.java index 532086e..a227249 100755 --- a/java/src/game/block/BlockDryLeaves.java +++ b/common/src/main/java/common/block/foliage/BlockDryLeaves.java @@ -1,12 +1,12 @@ -package game.block; +package common.block.foliage; -import game.audio.SoundType; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.rng.Random; -import game.world.State; +import common.block.Material; +import common.block.SoundType; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.rng.Random; +import common.world.State; public class BlockDryLeaves extends BlockLeavesBase { @@ -14,8 +14,8 @@ public class BlockDryLeaves extends BlockLeavesBase public BlockDryLeaves() { - super(Material.gourd); - this.setTab(CheatTab.tabPlants); + super(Material.SOFT); + this.setTab(CheatTab.PLANTS); this.setHardness(0.2F); this.setLightOpacity(1); this.setStepSound(SoundType.GRASS); diff --git a/java/src/game/block/BlockFarmland.java b/common/src/main/java/common/block/foliage/BlockFarmland.java similarity index 76% rename from java/src/game/block/BlockFarmland.java rename to common/src/main/java/common/block/foliage/BlockFarmland.java index a3c476c..d4ccd0e 100755 --- a/java/src/game/block/BlockFarmland.java +++ b/common/src/main/java/common/block/foliage/BlockFarmland.java @@ -1,23 +1,26 @@ -package game.block; +package common.block.foliage; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.init.ItemRegistry; -import game.item.Item; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.natural.BlockDirt; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockFarmland extends Block { @@ -25,7 +28,7 @@ public class BlockFarmland extends Block public BlockFarmland() { - super(Material.ground); + super(Material.LOOSE); this.setDefaultState(this.getBaseState().withProperty(MOISTURE, Integer.valueOf(0))); this.setTickRandomly(); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.9375F, 1.0F); @@ -50,24 +53,24 @@ public class BlockFarmland extends Block return false; } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { int i = ((Integer)state.getValue(MOISTURE)).intValue(); if (!this.hasWater(worldIn, pos) && !worldIn.isRainingAt(pos.up(), true)) { - if(Config.cropDrying) { + if(Vars.cropDrying) { if (i > 0) { worldIn.setState(pos, state.withProperty(MOISTURE, Integer.valueOf(i - 1)), 2); } - else if (Config.cropDecay && !this.hasCrops(worldIn, pos)) + else if (Vars.cropDecay && !this.hasCrops(worldIn, pos)) { worldIn.setState(pos, Blocks.dirt.getState()); } } } - else if (Config.cropSoaking && i < 7) + else if (Vars.cropSoaking && i < 7) { worldIn.setState(pos, state.withProperty(MOISTURE, Integer.valueOf(7)), 2); } @@ -80,9 +83,9 @@ public class BlockFarmland extends Block { if (entityIn instanceof EntityLiving) { - if (!worldIn.client && Config.cropTrampling && worldIn.rand.floatv() < fallDistance - 0.5F) + if (!worldIn.client && Vars.cropTrampling && worldIn.rand.floatv() < fallDistance - 0.5F) { - if (Config.mobGrief) + if (Vars.mobGrief) worldIn.setState(pos, Blocks.dirt.getState()); } @@ -100,7 +103,7 @@ public class BlockFarmland extends Block { for (BlockPos.MutableBlockPos blockpos$mutableblockpos : BlockPos.getAllInBoxMutable(pos.add(-4, 0, -4), pos.add(4, 1, 4))) { - if (worldIn.getState(blockpos$mutableblockpos).getBlock().getMaterial() == Material.water) + if (worldIn.getState(blockpos$mutableblockpos).getBlock().getMaterial() == Material.WATER) { return true; } @@ -175,7 +178,7 @@ public class BlockFarmland extends Block return new IProperty[] {MOISTURE}; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("dirt").add(0, 0, 0, 16, 15, 16).dnswe().u("farmland_" + state.getValue(MOISTURE)).noCull(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("dirt").add(0, 0, 0, 16, 15, 16).dnswe().u("farmland_" + state.getValue(MOISTURE)).noCull(); } } diff --git a/java/src/game/block/BlockFlower.java b/common/src/main/java/common/block/foliage/BlockFlower.java similarity index 88% rename from java/src/game/block/BlockFlower.java rename to common/src/main/java/common/block/foliage/BlockFlower.java index 7479965..dabe90f 100755 --- a/java/src/game/block/BlockFlower.java +++ b/common/src/main/java/common/block/foliage/BlockFlower.java @@ -1,25 +1,25 @@ -package game.block; +package common.block.foliage; import java.util.Collection; import java.util.List; - import java.util.function.Predicate; -import game.collect.Filter; -import game.collect.Lists; -import game.init.Blocks; -import game.init.Config; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.collect.Filter; +import common.collect.Lists; +import common.init.Blocks; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Identifyable; +import common.vars.Vars; +import common.world.State; +import common.world.AWorldServer; public abstract class BlockFlower extends BlockBush { @@ -31,9 +31,9 @@ public abstract class BlockFlower extends BlockBush // this.setTickRandomly(); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Config.flowerDry && worldIn.getTemperatureC(pos) >= 50.0f) + if(Vars.flowerDry && worldIn.getTemperatureC(pos) >= 50.0f) { worldIn.setState(pos, worldIn.rand.chance(3) ? Blocks.air.getState() : Blocks.tallgrass.getState().withProperty(BlockTallGrass.TYPE, BlockTallGrass.EnumType.DEAD_BUSH)); @@ -119,11 +119,11 @@ public abstract class BlockFlower extends BlockBush } } - public ModelBlock getModel(String name, State state) { - return new ModelBlock(state.getValue(this.type).getName()).cross(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(state.getValue(this.type).getName()).cross(); } - public static enum EnumFlowerType implements IStringSerializable + public static enum EnumFlowerType implements Identifyable { DANDELION(BlockFlower.EnumFlowerColor.BASE, 0, "dandelion", "Löwenzahn"), ROSE(BlockFlower.EnumFlowerColor.BASE, 1, "rose", "Rose"), diff --git a/java/src/game/block/BlockGrass.java b/common/src/main/java/common/block/foliage/BlockGrass.java similarity index 52% rename from java/src/game/block/BlockGrass.java rename to common/src/main/java/common/block/foliage/BlockGrass.java index f360442..9780435 100755 --- a/java/src/game/block/BlockGrass.java +++ b/common/src/main/java/common/block/foliage/BlockGrass.java @@ -1,21 +1,25 @@ -package game.block; +package common.block.foliage; -import game.color.Colorizer; -import game.init.Blocks; -import game.init.Config; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.biome.IBiome; +import common.block.Block; +import common.block.Material; +import common.block.natural.BlockDirt; +import common.color.Colorizer; +import common.init.Blocks; +import common.item.CheatTab; +import common.item.Item; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockGrass extends Block implements IGrowable { @@ -23,10 +27,10 @@ public class BlockGrass extends Block implements IGrowable public BlockGrass() { - super(Material.grass); + super(Material.LOOSE); this.setDefaultState(this.getBaseState().withProperty(SNOWY, Boolean.valueOf(false))); this.setTickRandomly(); - this.setTab(CheatTab.tabNature); + this.setTab(CheatTab.NATURE); } /** @@ -55,18 +59,18 @@ public class BlockGrass extends Block implements IGrowable return Colorizer.getGrassColor(worldIn, pos); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { // if (!worldIn.client) // { if (worldIn.getLightFromNeighbors(pos.up()) < 4 && worldIn.getState(pos.up()).getBlock().getLightOpacity() > 2) { - if(Config.grassDecay) + if(Vars.grassDecay) worldIn.setState(pos, Blocks.dirt.getState()); } else if(worldIn.getTemperatureC(pos) < 50.0f) { - if (Config.grassSpread && worldIn.getLightFromNeighbors(pos.up()) >= 9) + if (Vars.grassSpread && worldIn.getLightFromNeighbors(pos.up()) >= 9) { for (int i = 0; i < 4; ++i) { @@ -82,7 +86,7 @@ public class BlockGrass extends Block implements IGrowable } } else { - if(Config.grassDry) + if(Vars.grassDry) worldIn.setState(pos, worldIn.rand.chance(20) ? Blocks.dirt.getState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.COARSE_DIRT) : Blocks.dirt.getState()); } @@ -110,56 +114,9 @@ public class BlockGrass extends Block implements IGrowable return true; } - public void grow(WorldServer worldIn, Random rand, BlockPos pos, State state) + public void grow(AWorldServer worldIn, Random rand, BlockPos pos, State state) { - BlockPos blockpos = pos.up(); - - for (int i = 0; i < 128; ++i) - { - BlockPos blockpos1 = blockpos; - int j = 0; - - while (true) - { - if (j >= i / 16) - { - if (worldIn.getState(blockpos1).getBlock().material == Material.air) - { - if (rand.chance(8)) - { - BlockFlower.EnumFlowerType blockflower$enumflowertype = worldIn.getBiomeGenForCoords(blockpos1).pickRandomFlower(rand, blockpos1); - BlockFlower blockflower = blockflower$enumflowertype.getBlockType().getBlock(); - State iblockstate = blockflower.getState().withProperty(blockflower.getTypeProperty(), blockflower$enumflowertype); - - if (blockflower.canBlockStay(worldIn, blockpos1, iblockstate)) - { - worldIn.setState(blockpos1, iblockstate, 3); - } - } - else - { - State iblockstate1 = Blocks.tallgrass.getState().withProperty(BlockTallGrass.TYPE, BlockTallGrass.EnumType.GRASS); - - if (Blocks.tallgrass.canBlockStay(worldIn, blockpos1, iblockstate1)) - { - worldIn.setState(blockpos1, iblockstate1, 3); - } - } - } - - break; - } - - blockpos1 = blockpos1.add(rand.zrange(3) - 1, (rand.zrange(3) - 1) * rand.zrange(3) / 2, rand.zrange(3) - 1); - - if (worldIn.getState(blockpos1.down()).getBlock() != Blocks.grass || worldIn.getState(blockpos1).getBlock().isNormalCube()) - { - break; - } - - ++j; - } - } + IBiome.getBiome(worldIn.getBiomeGenForCoords(pos)).growGrass(worldIn, pos, state, rand); } public BlockLayer getBlockLayer() @@ -180,11 +137,11 @@ public class BlockGrass extends Block implements IGrowable return new IProperty[] {SNOWY}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { if(state.getValue(SNOWY)) - return new ModelBlock("grass_side_snowed").add().nswe().d("dirt").u("grass_top"); + return provider.getModel("grass_side_snowed").add().nswe().d("dirt").u("grass_top"); else - return new ModelBlock("dirt").add().d().u("grass_top").tint().nswe("grass_side") + return provider.getModel("dirt").add().d().u("grass_top").tint().nswe("grass_side") .add().nswe("grass_side_overlay").tint(); } } diff --git a/java/src/game/block/BlockHugeMushroom.java b/common/src/main/java/common/block/foliage/BlockHugeMushroom.java similarity index 70% rename from java/src/game/block/BlockHugeMushroom.java rename to common/src/main/java/common/block/foliage/BlockHugeMushroom.java index 6926cf6..873240b 100755 --- a/java/src/game/block/BlockHugeMushroom.java +++ b/common/src/main/java/common/block/foliage/BlockHugeMushroom.java @@ -1,18 +1,20 @@ -package game.block; +package common.block.foliage; -import game.entity.types.EntityLiving; -import game.init.ItemRegistry; -import game.item.Item; -import game.material.Material; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.types.EntityLiving; +import common.init.ItemRegistry; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.util.Identifyable; +import common.world.State; +import common.world.World; public class BlockHugeMushroom extends Block { @@ -98,48 +100,48 @@ public class BlockHugeMushroom extends Block return new IProperty[] {VARIANT}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { switch(state.getValue(VARIANT)) { case ALL_INSIDE: - return new ModelBlock(name + "_inside").add().all(); + return provider.getModel(name + "_inside").add().all(); case ALL_OUTSIDE: default: - return new ModelBlock(name + "_cap").add().all(); + return provider.getModel(name + "_cap").add().all(); case ALL_STEM: - return new ModelBlock(name + "_stem").add().all(); + return provider.getModel(name + "_stem").add().all(); case STEM: - return new ModelBlock(name + "_stem").add().nswe().du(name + "_inside"); + return provider.getModel(name + "_stem").add().nswe().du(name + "_inside"); case CENTER: - return new ModelBlock(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_inside") + return provider.getModel(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_inside") .w(name + "_inside").e(name + "_inside"); case EAST: - return new ModelBlock(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_inside") + return provider.getModel(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_inside") .w(name + "_inside").e(name + "_cap"); case NORTH_EAST: - return new ModelBlock(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_cap").s(name + "_inside") + return provider.getModel(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_cap").s(name + "_inside") .w(name + "_inside").e(name + "_cap"); case NORTH: - return new ModelBlock(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_cap").s(name + "_inside") + return provider.getModel(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_cap").s(name + "_inside") .w(name + "_inside").e(name + "_inside"); case NORTH_WEST: - return new ModelBlock(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_cap").s(name + "_inside") + return provider.getModel(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_cap").s(name + "_inside") .w(name + "_cap").e(name + "_inside"); case SOUTH_EAST: - return new ModelBlock(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_cap") + return provider.getModel(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_cap") .w(name + "_inside").e(name + "_cap"); case SOUTH: - return new ModelBlock(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_cap") + return provider.getModel(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_cap") .w(name + "_inside").e(name + "_inside"); case SOUTH_WEST: - return new ModelBlock(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_cap") + return provider.getModel(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_cap") .w(name + "_cap").e(name + "_inside"); case WEST: - return new ModelBlock(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_inside") + return provider.getModel(name + "_inside").add().d(name + "_inside").u(name + "_cap").n(name + "_inside").s(name + "_inside") .w(name + "_cap").e(name + "_inside"); } } - public static enum EnumType implements IStringSerializable + public static enum EnumType implements Identifyable { NORTH_WEST(1, "north_west"), NORTH(2, "north"), diff --git a/java/src/game/block/BlockLeaves.java b/common/src/main/java/common/block/foliage/BlockLeaves.java similarity index 86% rename from java/src/game/block/BlockLeaves.java rename to common/src/main/java/common/block/foliage/BlockLeaves.java index 96a20bf..1d08150 100755 --- a/java/src/game/block/BlockLeaves.java +++ b/common/src/main/java/common/block/foliage/BlockLeaves.java @@ -1,34 +1,35 @@ -package game.block; +package common.block.foliage; import java.util.List; -import game.collect.Lists; - -import game.audio.SoundType; -import game.color.Colorizer; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Config; -import game.init.ItemRegistry; -import game.init.WoodType; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemShears; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.SoundType; +import common.collect.Lists; +import common.color.Colorizer; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.WoodType; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemShears; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ParticleType; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockLeaves extends BlockLeavesBase { @@ -42,11 +43,11 @@ public class BlockLeaves extends BlockLeavesBase public BlockLeaves(WoodType type) { - super(Material.leaves); + super(Material.LEAVES); this.type = type; this.setDefaultState(this.getBaseState().withProperty(TYPE, LeavesType.SPRING).withProperty(DECAY, Boolean.valueOf(true))); this.setTickRandomly(); - this.setTab(CheatTab.tabPlants); + this.setTab(CheatTab.PLANTS); this.setHardness(0.2F); this.setLightOpacity(1); this.setStepSound(SoundType.GRASS); @@ -68,7 +69,7 @@ public class BlockLeaves extends BlockLeavesBase // return BiomeColorHelper.getFoliageColorAtPos(worldIn, pos); // } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { int i = 1; int j = i + 1; @@ -87,7 +88,7 @@ public class BlockLeaves extends BlockLeavesBase BlockPos blockpos = pos.add(j1, k1, l1); State iblockstate = worldIn.getState(blockpos); - if (iblockstate.getBlock().getMaterial() == Material.leaves && !((Boolean)iblockstate.getValue(DECAY)).booleanValue()) + if (iblockstate.getBlock().getMaterial() == Material.LEAVES && !((Boolean)iblockstate.getValue(DECAY)).booleanValue()) { worldIn.setState(blockpos, iblockstate.withProperty(DECAY, Boolean.valueOf(true)), 4); } @@ -97,17 +98,17 @@ public class BlockLeaves extends BlockLeavesBase } } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Config.seasonLeaves && state.getValue(TYPE) != worldIn.getLeavesGen(pos)) { + if(Vars.seasonLeaves && state.getValue(TYPE) != worldIn.getLeavesGen(pos)) { worldIn.setState(pos, state.withProperty(TYPE, worldIn.getLeavesGen(pos)), 2); } - if(Config.leafDry && worldIn.getTemperatureC(pos) >= 50.0f) { + if(Vars.leafDry && worldIn.getTemperatureC(pos) >= 50.0f) { worldIn.setState(pos, worldIn.rand.chance(40) ? Blocks.air.getState() : Blocks.dry_leaves.getState()); } // if (!worldIn.client) // { - else if (Config.leavesDecay && ((Boolean)state.getValue(DECAY)).booleanValue()) + else if (Vars.leavesDecay && ((Boolean)state.getValue(DECAY)).booleanValue()) { int i = 4; int j = i + 1; @@ -137,7 +138,7 @@ public class BlockLeaves extends BlockLeavesBase if (!(block instanceof BlockLog)) { - if (block.getMaterial() == Material.leaves) + if (block.getMaterial() == Material.LEAVES) { this.surroundings[(i2 + l1) * k1 + (j2 + l1) * j1 + k2 + l1] = -2; } @@ -214,7 +215,7 @@ public class BlockLeaves extends BlockLeavesBase // } } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { if (worldIn.isRainingAt(pos.up(), true) && !worldIn.isBlockSolid(pos.down()) && rand.chance(15)) // == 1 { @@ -349,9 +350,9 @@ public class BlockLeaves extends BlockLeavesBase } } - public ModelBlock getModel(String name, State state) { - return state.getValue(TYPE).isTinted() ? new ModelBlock(name + "_" + state.getValue(TYPE).getName()).add().all().tint() : - new ModelBlock(name + "_" + state.getValue(TYPE).getName()).add().all(); + public Model getModel(ModelProvider provider, String name, State state) { + return state.getValue(TYPE).isTinted() ? provider.getModel(name + "_" + state.getValue(TYPE).getName()).add().all().tint() : + provider.getModel(name + "_" + state.getValue(TYPE).getName()).add().all(); } public IProperty[] getIgnoredProperties() { diff --git a/java/src/game/block/BlockLeavesBase.java b/common/src/main/java/common/block/foliage/BlockLeavesBase.java similarity index 89% rename from java/src/game/block/BlockLeavesBase.java rename to common/src/main/java/common/block/foliage/BlockLeavesBase.java index 6dfe938..1bf0fd0 100755 --- a/java/src/game/block/BlockLeavesBase.java +++ b/common/src/main/java/common/block/foliage/BlockLeavesBase.java @@ -1,7 +1,8 @@ -package game.block; +package common.block.foliage; -import game.material.Material; -import game.renderer.BlockLayer; +import common.block.Block; +import common.block.Material; +import common.model.BlockLayer; public class BlockLeavesBase extends Block { diff --git a/java/src/game/block/BlockLilyPad.java b/common/src/main/java/common/block/foliage/BlockLilyPad.java similarity index 76% rename from java/src/game/block/BlockLilyPad.java rename to common/src/main/java/common/block/foliage/BlockLilyPad.java index d7d04d9..1102480 100755 --- a/java/src/game/block/BlockLilyPad.java +++ b/common/src/main/java/common/block/foliage/BlockLilyPad.java @@ -1,21 +1,26 @@ -package game.block; +package common.block.foliage; import java.util.List; -import game.entity.Entity; -import game.entity.item.EntityBoat; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.item.CheatTab; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.BlockDirectional; +import common.block.liquid.BlockLiquid; +import common.block.liquid.BlockStaticLiquid; +import common.entity.Entity; +import common.entity.item.EntityBoat; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockLilyPad extends BlockBush { @@ -25,7 +30,7 @@ public class BlockLilyPad extends BlockBush float f1 = 0.015625F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); this.setDefaultState(this.getBaseState().withProperty(BlockDirectional.FACING, Facing.NORTH)); - this.setTab(CheatTab.tabPlants); + this.setTab(CheatTab.PLANTS); } public void addCollisionBoxesToList(World worldIn, BlockPos pos, State state, BoundingBox mask, List list, Entity collidingEntity) @@ -63,7 +68,7 @@ public class BlockLilyPad extends BlockBush public boolean canBlockStay(World worldIn, BlockPos pos, State state) { - if (pos.getY() >= 0 && pos.getY() < 512) + if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) { State iblockstate = worldIn.getState(pos.down()); return (iblockstate.getBlock().getMaterial().isColdLiquid() && ((Integer)iblockstate.getValue(BlockLiquid.LEVEL)).intValue() == 0) @@ -100,8 +105,8 @@ public class BlockLilyPad extends BlockBush return this.getState().withProperty(BlockDirectional.FACING, placer.getHorizontalFacing().getOpposite()); } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("waterlily").noOcclude() + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("waterlily") .add(0, 0.25f, 0, 16, 0.25f, 16) .d().uv(16, 16, 0, 0).tint().noCull() .u().uv(16, 0, 0, 16).tint().noCull() diff --git a/java/src/game/block/BlockLog.java b/common/src/main/java/common/block/foliage/BlockLog.java similarity index 77% rename from java/src/game/block/BlockLog.java rename to common/src/main/java/common/block/foliage/BlockLog.java index 8a1ee73..8c9fbab 100755 --- a/java/src/game/block/BlockLog.java +++ b/common/src/main/java/common/block/foliage/BlockLog.java @@ -1,19 +1,21 @@ -package game.block; +package common.block.foliage; -import game.audio.SoundType; -import game.entity.types.EntityLiving; -import game.item.CheatTab; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.BlockRotatedPillar; +import common.block.Material; +import common.block.SoundType; +import common.entity.types.EntityLiving; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.util.BlockPos; +import common.util.Facing; +import common.util.Identifyable; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockLog extends BlockRotatedPillar { @@ -21,14 +23,14 @@ public class BlockLog extends BlockRotatedPillar public BlockLog() { - super(Material.wood); + super(Material.WOOD); this.setDefaultState(this.getBaseState().withProperty(LOG_AXIS, BlockLog.EnumAxis.Y)); - this.setTab(CheatTab.tabWood); + this.setTab(CheatTab.WOOD); this.setHardness(2.0F); this.setStepSound(SoundType.WOOD); } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { int i = 4; int j = i + 1; @@ -39,7 +41,7 @@ public class BlockLog extends BlockRotatedPillar { State iblockstate = worldIn.getState(blockpos); - if (iblockstate.getBlock().getMaterial() == Material.leaves && !((Boolean)iblockstate.getValue(BlockLeaves.DECAY)).booleanValue()) + if (iblockstate.getBlock().getMaterial() == Material.LEAVES && !((Boolean)iblockstate.getValue(BlockLeaves.DECAY)).booleanValue()) { worldIn.setState(blockpos, iblockstate.withProperty(BlockLeaves.DECAY, Boolean.valueOf(true)), 4); } @@ -56,21 +58,21 @@ public class BlockLog extends BlockRotatedPillar return super.onBlockPlaced(worldIn, pos, facing, hitX, hitY, hitZ, meta, placer).withProperty(LOG_AXIS, BlockLog.EnumAxis.fromFacingAxis(facing.getAxis())); } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { switch(state.getValue(LOG_AXIS)) { case X: - return new ModelBlock(name + "_bark").add().d().rot(180).u() + return provider.getModel(name + "_bark").add().d().rot(180).u() .n(name + "_top").rot(180).s(name + "_top").w().rot(270) .e().rot(90).rotate(ModelRotation.X0_Y90); case Y: default: - return new ModelBlock(name + "_bark").add().nswe().du(name + "_top"); + return provider.getModel(name + "_bark").add().nswe().du(name + "_top"); case Z: - return new ModelBlock(name + "_bark").add().d().rot(180).u() + return provider.getModel(name + "_bark").add().d().rot(180).u() .n(name + "_top").rot(180).s(name + "_top").w().rot(270) .e().rot(90); case NONE: - return new ModelBlock(name + "_bark").add().all(); + return provider.getModel(name + "_bark").add().all(); } } @@ -131,7 +133,7 @@ public class BlockLog extends BlockRotatedPillar return new IProperty[] {LOG_AXIS}; } - public static enum EnumAxis implements IStringSerializable + public static enum EnumAxis implements Identifyable { X("x", Facing.Axis.X), Y("y", Facing.Axis.Y), diff --git a/java/src/game/block/BlockMelon.java b/common/src/main/java/common/block/foliage/BlockMelon.java similarity index 58% rename from java/src/game/block/BlockMelon.java rename to common/src/main/java/common/block/foliage/BlockMelon.java index 1095cba..ea81ba1 100755 --- a/java/src/game/block/BlockMelon.java +++ b/common/src/main/java/common/block/foliage/BlockMelon.java @@ -1,19 +1,21 @@ -package game.block; +package common.block.foliage; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.State; +import common.block.Block; +import common.block.Material; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.rng.Random; +import common.world.State; public class BlockMelon extends Block { public BlockMelon() { - super(Material.gourd); - this.setTab(CheatTab.tabPlants); + super(Material.SOFT); + this.setTab(CheatTab.PLANTS); } /** @@ -40,7 +42,7 @@ public class BlockMelon extends Block return Math.min(9, this.quantityDropped(random) + random.zrange(1 + fortune)); } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("melon_side").add().nswe().du("melon_top"); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("melon_side").add().nswe().du("melon_top"); } } diff --git a/java/src/game/block/BlockMushroom.java b/common/src/main/java/common/block/foliage/BlockMushroom.java similarity index 62% rename from java/src/game/block/BlockMushroom.java rename to common/src/main/java/common/block/foliage/BlockMushroom.java index ab19610..24a8fb4 100755 --- a/java/src/game/block/BlockMushroom.java +++ b/common/src/main/java/common/block/foliage/BlockMushroom.java @@ -1,15 +1,17 @@ -package game.block; +package common.block.foliage; -import game.init.Blocks; -import game.init.Config; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.World; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; -import game.worldgen.foliage.WorldGenBigMushroom; +import common.biome.IBiome; +import common.block.Block; +import common.block.natural.BlockDirt; +import common.init.Blocks; +import common.model.Model; +import common.model.ModelProvider; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockMushroom extends BlockBush implements IGrowable { @@ -20,9 +22,9 @@ public class BlockMushroom extends BlockBush implements IGrowable this.setTickRandomly(); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Config.shroomGrowth > 0 && rand.chance(Config.shroomGrowth)) + if (Vars.shroomGrowth > 0 && rand.chance(Vars.shroomGrowth)) { int i = 5; int j = 4; @@ -74,7 +76,7 @@ public class BlockMushroom extends BlockBush implements IGrowable public boolean canBlockStay(World worldIn, BlockPos pos, State state) { - if (pos.getY() >= 0 && pos.getY() < 512) + if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) { State iblockstate = worldIn.getState(pos.down()); return iblockstate.getBlock() == Blocks.mycelium ? true : (iblockstate.getBlock() == Blocks.dirt && iblockstate.getValue(BlockDirt.VARIANT) == BlockDirt.DirtType.PODZOL ? true : worldIn.getLight(pos) < 13 && this.canPlaceBlockOn(iblockstate.getBlock())); @@ -85,31 +87,6 @@ public class BlockMushroom extends BlockBush implements IGrowable } } - public boolean generateBigMushroom(WorldServer worldIn, BlockPos pos, State state, Random rand) - { - worldIn.setBlockToAir(pos); - FeatureGenerator worldgenerator = null; - - if (this == Blocks.brown_mushroom) - { - worldgenerator = new WorldGenBigMushroom(Blocks.brown_mushroom_block); - } - else if (this == Blocks.red_mushroom) - { - worldgenerator = new WorldGenBigMushroom(Blocks.red_mushroom_block); - } - - if (worldgenerator != null && worldgenerator.generate(worldIn, rand, pos)) - { - return true; - } - else - { - worldIn.setState(pos, state, 3); - return false; - } - } - /** * Whether this IGrowable can grow */ @@ -123,12 +100,12 @@ public class BlockMushroom extends BlockBush implements IGrowable return (double)rand.floatv() < 0.4D; } - public void grow(WorldServer worldIn, Random rand, BlockPos pos, State state) + public void grow(AWorldServer worldIn, Random rand, BlockPos pos, State state) { - this.generateBigMushroom(worldIn, pos, state, rand); + IBiome.getBiome(worldIn.getBiomeGenForCoords(pos)).generateBigMushroom(worldIn, pos, state, rand); } - public ModelBlock getModel(String name, State state) { - return new ModelBlock(name).cross(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(name).cross(); } } diff --git a/java/src/game/block/BlockMycelium.java b/common/src/main/java/common/block/foliage/BlockMycelium.java similarity index 70% rename from java/src/game/block/BlockMycelium.java rename to common/src/main/java/common/block/foliage/BlockMycelium.java index 9ee62fb..65e5ce3 100755 --- a/java/src/game/block/BlockMycelium.java +++ b/common/src/main/java/common/block/foliage/BlockMycelium.java @@ -1,20 +1,23 @@ -package game.block; +package common.block.foliage; -import game.init.Blocks; -import game.init.Config; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.BlockPos; -import game.world.IWorldAccess; -import game.world.State; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.natural.BlockDirt; +import common.init.Blocks; +import common.item.CheatTab; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ParticleType; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.AWorldServer; public class BlockMycelium extends Block { @@ -22,10 +25,10 @@ public class BlockMycelium extends Block public BlockMycelium() { - super(Material.grass); + super(Material.LOOSE); this.setDefaultState(this.getBaseState().withProperty(SNOWY, Boolean.valueOf(false))); this.setTickRandomly(); - this.setTab(CheatTab.tabNature); + this.setTab(CheatTab.NATURE); } /** @@ -38,16 +41,16 @@ public class BlockMycelium extends Block return state.withProperty(SNOWY, Boolean.valueOf(block == Blocks.snow || block == Blocks.snow_layer)); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { // if (!worldIn.client) // { if (worldIn.getLightFromNeighbors(pos.up()) < 4 && worldIn.getState(pos.up()).getBlock().getLightOpacity() > 2) { - if(Config.mycelDecay) + if(Vars.mycelDecay) worldIn.setState(pos, Blocks.dirt.getState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.DIRT)); } - else if(Config.mycelSpread) + else if(Vars.mycelSpread) { if (worldIn.getLightFromNeighbors(pos.up()) >= 9) { @@ -67,7 +70,7 @@ public class BlockMycelium extends Block // } } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { super.randomDisplayTick(worldIn, pos, state, rand); @@ -98,10 +101,10 @@ public class BlockMycelium extends Block return new IProperty[] {SNOWY}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { if(state.getValue(SNOWY)) - return new ModelBlock("grass_side_snowed").add().nswe().d("dirt").u("grass_top"); + return provider.getModel("grass_side_snowed").add().nswe().d("dirt").u("grass_top"); else - return new ModelBlock("mycelium_side").add().nswe().d("dirt").u("mycelium_top"); + return provider.getModel("mycelium_side").add().nswe().d("dirt").u("mycelium_top"); } } diff --git a/java/src/game/block/BlockPotato.java b/common/src/main/java/common/block/foliage/BlockPotato.java similarity index 65% rename from java/src/game/block/BlockPotato.java rename to common/src/main/java/common/block/foliage/BlockPotato.java index 8795566..2083b27 100755 --- a/java/src/game/block/BlockPotato.java +++ b/common/src/main/java/common/block/foliage/BlockPotato.java @@ -1,12 +1,13 @@ -package game.block; +package common.block.foliage; -import game.init.Items; -import game.item.Item; -import game.item.ItemStack; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.init.Items; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.util.BlockPos; +import common.world.State; +import common.world.World; public class BlockPotato extends BlockCrops { @@ -36,8 +37,8 @@ public class BlockPotato extends BlockCrops } } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { int age = state.getValue(AGE); - return crop(name + "_" + (age == 6 ? 2 : (age / 2))); + return crop(provider, name + "_" + (age == 6 ? 2 : (age / 2))); } } diff --git a/common/src/main/java/common/block/foliage/BlockPumpkin.java b/common/src/main/java/common/block/foliage/BlockPumpkin.java new file mode 100755 index 0000000..9b70bad --- /dev/null +++ b/common/src/main/java/common/block/foliage/BlockPumpkin.java @@ -0,0 +1,47 @@ +package common.block.foliage; + +import common.block.BlockDirectional; +import common.block.Material; +import common.entity.types.EntityLiving; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; + +public class BlockPumpkin extends BlockDirectional { + public BlockPumpkin() { + super(Material.SOFT); + this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); + this.setTab(CheatTab.PLANTS); + } + + public boolean canPlaceBlockAt(World world, BlockPos pos) { + return world.getState(pos).getBlock().getMaterial().isReplaceable() && world.isBlockSolid(pos.down()); + } + + public State onBlockPlaced(World world, BlockPos pos, Facing face, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) { + return this.getState().withProperty(FACING, placer.getHorizontalFacing().getOpposite()); + } + + public State getStateFromMeta(int meta) { + return this.getState().withProperty(FACING, Facing.getHorizontal(meta)); + } + + public int getMetaFromState(State state) { + return state.getValue(FACING).getHorizontalIndex(); + } + + protected IProperty[] getProperties() { + return new IProperty[] {FACING}; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("pumpkin_side").add().du("pumpkin_top").n("pumpkin_face_" + (this.getLightValue() == 0 ? "off" : "on")).s().we() + .rotate(ModelRotation.getNorthRot(state.getValue(FACING))); + } +} diff --git a/java/src/game/block/BlockReed.java b/common/src/main/java/common/block/foliage/BlockReed.java similarity index 79% rename from java/src/game/block/BlockReed.java rename to common/src/main/java/common/block/foliage/BlockReed.java index 6cae792..e581de9 100755 --- a/java/src/game/block/BlockReed.java +++ b/common/src/main/java/common/block/foliage/BlockReed.java @@ -1,22 +1,24 @@ -package game.block; +package common.block.foliage; -import game.init.Blocks; -import game.init.Config; -import game.init.Items; -import game.item.Item; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.init.Items; +import common.item.Item; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockReed extends Block { @@ -24,23 +26,23 @@ public class BlockReed extends Block public BlockReed() { - super(Material.plants); + super(Material.PLANT); this.setDefaultState(this.getBaseState().withProperty(AGE, Integer.valueOf(0))); float f = 0.375F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 1.0F, 0.5F + f); this.setTickRandomly(); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Config.reedDry && worldIn.getTemperatureC(pos) >= 50.0f) + if(Vars.reedDry && worldIn.getTemperatureC(pos) >= 50.0f) { worldIn.destroyBlock(pos, true); return; } if (worldIn.getState(pos.down()).getBlock() == Blocks.reeds || this.checkForDrop(worldIn, pos, state)) { - if (Config.reedHeight > 0 && worldIn.isAirBlock(pos.up())) + if (Vars.reedHeight > 0 && worldIn.isAirBlock(pos.up())) { int i; @@ -49,7 +51,7 @@ public class BlockReed extends Block ; } - if (i < Config.reedHeight) + if (i < Vars.reedHeight) { int j = ((Integer)state.getValue(AGE)).intValue(); @@ -83,7 +85,7 @@ public class BlockReed extends Block { for (Facing enumfacing : Facing.Plane.HORIZONTAL) { - if (worldIn.getState(pos.offset(enumfacing).down()).getBlock().getMaterial() == Material.water) + if (worldIn.getState(pos.offset(enumfacing).down()).getBlock().getMaterial() == Material.WATER) { return true; } @@ -182,8 +184,8 @@ public class BlockReed extends Block return new IProperty[] {AGE}; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("reeds").crossTint(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("reeds").crossTint(); } public IProperty[] getIgnoredProperties() { diff --git a/common/src/main/java/common/block/foliage/BlockSapling.java b/common/src/main/java/common/block/foliage/BlockSapling.java new file mode 100755 index 0000000..df3ca7d --- /dev/null +++ b/common/src/main/java/common/block/foliage/BlockSapling.java @@ -0,0 +1,147 @@ +package common.block.foliage; + +import java.util.List; + +import common.biome.IBiome; +import common.collect.Lists; +import common.init.Blocks; +import common.init.WoodType; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; + +public class BlockSapling extends BlockBush implements IGrowable +{ +// public static final PropertyEnum TYPE = PropertyEnum.create("type", BlockPlanks.EnumType.class); + public static final PropertyInteger STAGE = PropertyInteger.create("stage", 0, 1); + public static final List SAPLINGS = Lists.newArrayList(); + + private final WoodType type; + + public BlockSapling(WoodType type) + { + this.setDefaultState(this.getBaseState() /* .withProperty(TYPE, BlockPlanks.EnumType.OAK) */ .withProperty(STAGE, Integer.valueOf(0))); + float f = 0.4F; + this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f * 2.0F, 0.5F + f); + this.setTab(CheatTab.PLANTS); + this.type = type; + SAPLINGS.add(this); + } + +// /** +// * Gets the localized name of this block. Used for the statistics page. +// */ +// public String getLocalizedName() +// { +// return I18n.translate(this.getUnlocalizedName() + "." + BlockPlanks.EnumType.OAK.getUnlocalizedName() + ".name"); +// } + + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) + { + if(Vars.saplingDry && worldIn.getTemperatureC(pos) >= 50.0f) + { + worldIn.setState(pos, worldIn.rand.chance(25) ? Blocks.air.getState() : + Blocks.tallgrass.getState().withProperty(BlockTallGrass.TYPE, BlockTallGrass.EnumType.DEAD_BUSH)); + return; + } +// if (!worldIn.client) +// { + super.updateTick(worldIn, pos, state, rand); + + if (Vars.treeGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9 && rand.chance(Vars.treeGrowth)) + { + this.grow(worldIn, pos, state, rand); + } +// } + } + + public void grow(AWorldServer worldIn, BlockPos pos, State state, Random rand) + { + if (((Integer)state.getValue(STAGE)).intValue() == 0) + { + worldIn.setState(pos, state.cycleProperty(STAGE), 4); + } + else + { + IBiome.getBiome(worldIn.getBiomeGenForCoords(pos)).generateTree(worldIn, pos, state, rand); + } + } + +// /** +// * Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It +// * returns the metadata of the dropped item based on the old metadata of the block. +// */ +// public int damageDropped(IBlockState state) +// { +// return ((BlockPlanks.EnumType)state.getValue(TYPE)).getMetadata(); +// } + +// /** +// * returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks) +// */ +// public void getSubBlocks(Item itemIn, CreativeTab tab, List list) +// { +// for (BlockPlanks.EnumType blockplanks$enumtype : BlockPlanks.EnumType.values()) +// { +// list.add(new ItemStack(itemIn, 1, blockplanks$enumtype.getMetadata())); +// } +// } + + /** + * Whether this IGrowable can grow + */ + public boolean canGrow(World worldIn, BlockPos pos, State state, boolean isClient) + { + return true; + } + + public boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, State state) + { + return (double)worldIn.rand.floatv() < 0.45D; + } + + public void grow(AWorldServer worldIn, Random rand, BlockPos pos, State state) + { + this.grow(worldIn, pos, state, rand); + } + + /** + * Convert the given metadata into a BlockState for this Block + */ + public State getStateFromMeta(int meta) + { + return this.getState() /* .withProperty(TYPE, BlockPlanks.EnumType.byMetadata(meta & 7)) */ .withProperty(STAGE, meta & 1); + } + + /** + * Convert the BlockState into the correct metadata value + */ + public int getMetaFromState(State state) + { +// int i = 0; +// i = i | ((BlockPlanks.EnumType)state.getValue(TYPE)).getMetadata(); +// i = i | ((Integer)state.getValue(STAGE)).intValue() << 3; + return state.getValue(STAGE); + } + + protected IProperty[] getProperties() + { + return new IProperty[] {STAGE}; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(name).cross(); + } + + public WoodType getWoodType() { + return this.type; + } +} diff --git a/java/src/game/block/BlockStem.java b/common/src/main/java/common/block/foliage/BlockStem.java similarity index 86% rename from java/src/game/block/BlockStem.java rename to common/src/main/java/common/block/foliage/BlockStem.java index f8b3364..e647e19 100755 --- a/java/src/game/block/BlockStem.java +++ b/common/src/main/java/common/block/foliage/BlockStem.java @@ -1,26 +1,27 @@ -package game.block; +package common.block.foliage; import java.util.function.Predicate; -import game.init.Blocks; -import game.init.Config; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.init.Blocks; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockStem extends BlockBush implements IGrowable { @@ -72,15 +73,15 @@ public class BlockStem extends BlockBush implements IGrowable return ground == Blocks.farmland; } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { super.updateTick(worldIn, pos, state, rand); - if (Config.stemGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9) + if (Vars.stemGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9) { float f = BlockCrops.getGrowthChance(this, worldIn, pos); - if (rand.chance((int)((float)(Config.stemGrowth - 1) / f) + 1)) + if (rand.chance((int)((float)(Vars.stemGrowth - 1) / f) + 1)) { int i = ((Integer)state.getValue(AGE)).intValue(); @@ -102,7 +103,7 @@ public class BlockStem extends BlockBush implements IGrowable pos = pos.offset(Facing.Plane.HORIZONTAL.random(rand)); Block block = worldIn.getState(pos.down()).getBlock(); - if (worldIn.getState(pos).getBlock().material == Material.air && (block == Blocks.farmland || block == Blocks.dirt || block == Blocks.grass)) + if (worldIn.getState(pos).getBlock() == Blocks.air && (block == Blocks.farmland || block == Blocks.dirt || block == Blocks.grass)) { worldIn.setState(pos, this.crop.getState()); } @@ -212,7 +213,7 @@ public class BlockStem extends BlockBush implements IGrowable return true; } - public void grow(WorldServer worldIn, Random rand, BlockPos pos, State state) + public void grow(AWorldServer worldIn, Random rand, BlockPos pos, State state) { this.growStem(worldIn, pos, state); } @@ -238,13 +239,13 @@ public class BlockStem extends BlockBush implements IGrowable return new IProperty[] {AGE, FACING}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { String stem = name; String upperstem = name + "_connected"; if(state.getValue(FACING) == Facing.UP) { switch(state.getValue(AGE)) { case 0: - return new ModelBlock(stem).noOcclude() + return provider.getModel(stem) .add(0, -1, 8, 16, 1, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 2).tint().noCull() .s().uv(16, 0, 0, 2).tint().noCull() @@ -252,7 +253,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 2).tint().noCull() .e().uv(16, 0, 0, 2).tint().noCull(); case 1: - return new ModelBlock(stem).noOcclude() + return provider.getModel(stem) .add(0, -1, 8, 16, 3, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 4).tint().noCull() .s().uv(16, 0, 0, 4).tint().noCull() @@ -260,7 +261,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 4).tint().noCull() .e().uv(16, 0, 0, 4).tint().noCull(); case 2: - return new ModelBlock(stem).noOcclude() + return provider.getModel(stem) .add(0, -1, 8, 16, 5, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 6).tint().noCull() .s().uv(16, 0, 0, 6).tint().noCull() @@ -268,7 +269,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 6).tint().noCull() .e().uv(16, 0, 0, 6).tint().noCull(); case 3: - return new ModelBlock(stem).noOcclude() + return provider.getModel(stem) .add(0, -1, 8, 16, 7, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 8).tint().noCull() .s().uv(16, 0, 0, 8).tint().noCull() @@ -276,7 +277,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 8).tint().noCull() .e().uv(16, 0, 0, 8).tint().noCull(); case 4: - return new ModelBlock(stem).noOcclude() + return provider.getModel(stem) .add(0, -1, 8, 16, 9, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 10).tint().noCull() .s().uv(16, 0, 0, 10).tint().noCull() @@ -284,7 +285,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 10).tint().noCull() .e().uv(16, 0, 0, 10).tint().noCull(); case 5: - return new ModelBlock(stem).noOcclude() + return provider.getModel(stem) .add(0, -1, 8, 16, 11, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 12).tint().noCull() .s().uv(16, 0, 0, 12).tint().noCull() @@ -292,7 +293,7 @@ public class BlockStem extends BlockBush implements IGrowable .w().uv(0, 0, 16, 12).tint().noCull() .e().uv(16, 0, 0, 12).tint().noCull(); case 6: - return new ModelBlock(stem).noOcclude() + return provider.getModel(stem) .add(0, -1, 8, 16, 13, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 14).tint().noCull() .s().uv(16, 0, 0, 14).tint().noCull() @@ -301,7 +302,7 @@ public class BlockStem extends BlockBush implements IGrowable .e().uv(16, 0, 0, 14).tint().noCull(); case 7: default: - return new ModelBlock(stem).noOcclude() + return provider.getModel(stem) .add(0, -1, 8, 16, 15, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 16).tint().noCull() .s().uv(16, 0, 0, 16).tint().noCull() @@ -311,7 +312,7 @@ public class BlockStem extends BlockBush implements IGrowable } } else { - return new ModelBlock(stem).noOcclude() + return provider.getModel(stem) .add(0, -1, 8, 16, 7, 8).rotate(8, 8, 8, Facing.Axis.Y, 45, true) .n().uv(0, 0, 16, 8).tint().noCull() .s().uv(16, 0, 0, 8).tint().noCull() diff --git a/java/src/game/block/BlockTallGrass.java b/common/src/main/java/common/block/foliage/BlockTallGrass.java similarity index 82% rename from java/src/game/block/BlockTallGrass.java rename to common/src/main/java/common/block/foliage/BlockTallGrass.java index 0ac4605..be708d5 100755 --- a/java/src/game/block/BlockTallGrass.java +++ b/common/src/main/java/common/block/foliage/BlockTallGrass.java @@ -1,28 +1,29 @@ -package game.block; +package common.block.foliage; import java.util.List; -import game.color.Colorizer; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Config; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemShears; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Material; +import common.color.Colorizer; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemShears; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.Identifyable; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockTallGrass extends BlockBush implements IGrowable { @@ -30,16 +31,16 @@ public class BlockTallGrass extends BlockBush implements IGrowable public BlockTallGrass() { - super(Material.vine); + super(Material.BUSH); this.setDefaultState(this.getBaseState().withProperty(TYPE, BlockTallGrass.EnumType.DEAD_BUSH)); float f = 0.4F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, 0.8F, 0.5F + f); // this.setTickRandomly(); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Config.tallgrassDry && worldIn.getTemperatureC(pos) >= 50.0f && state.getValue(TYPE) != EnumType.DEAD_BUSH) + if(Vars.tallgrassDry && worldIn.getTemperatureC(pos) >= 50.0f && state.getValue(TYPE) != EnumType.DEAD_BUSH) { worldIn.setState(pos, state.getValue(TYPE) == EnumType.GRASS || worldIn.rand.chance(20) ? Blocks.air.getState() : this.getState().withProperty(TYPE, EnumType.DEAD_BUSH)); @@ -146,7 +147,7 @@ public class BlockTallGrass extends BlockBush implements IGrowable return true; } - public void grow(WorldServer worldIn, Random rand, BlockPos pos, State state) + public void grow(AWorldServer worldIn, Random rand, BlockPos pos, State state) { BlockDoublePlant.EnumPlantType blockdoubleplant$enumplanttype = BlockDoublePlant.EnumPlantType.GRASS; @@ -187,14 +188,14 @@ public class BlockTallGrass extends BlockBush implements IGrowable // return EnumOffsetType.XYZ; // } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { if(state.getValue(TYPE) != EnumType.DEAD_BUSH) - return new ModelBlock(state.getValue(TYPE).getName()).crossTint(); + return provider.getModel(state.getValue(TYPE).getName()).crossTint(); else - return new ModelBlock("deadbush").cross(); + return provider.getModel("deadbush").cross(); } - public static enum EnumType implements IStringSerializable + public static enum EnumType implements Identifyable { DEAD_BUSH(0, "dead_bush"), GRASS(1, "tall_grass"), diff --git a/java/src/game/block/BlockTianSoil.java b/common/src/main/java/common/block/foliage/BlockTianSoil.java similarity index 54% rename from java/src/game/block/BlockTianSoil.java rename to common/src/main/java/common/block/foliage/BlockTianSoil.java index fbfea0f..bf7aa44 100755 --- a/java/src/game/block/BlockTianSoil.java +++ b/common/src/main/java/common/block/foliage/BlockTianSoil.java @@ -1,16 +1,18 @@ -package game.block; +package common.block.foliage; -import game.init.Blocks; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.IWorldAccess; -import game.world.State; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.item.CheatTab; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.rng.Random; +import common.util.BlockPos; +import common.world.IWorldAccess; +import common.world.State; public class BlockTianSoil extends Block { @@ -18,9 +20,9 @@ public class BlockTianSoil extends Block public BlockTianSoil() { - super(Material.rock); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(SNOWY, Boolean.valueOf(false))); - this.setTab(CheatTab.tabNature); + this.setTab(CheatTab.NATURE); } public State getActualState(State state, IWorldAccess worldIn, BlockPos pos) @@ -44,10 +46,10 @@ public class BlockTianSoil extends Block return new IProperty[] {SNOWY}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { if(state.getValue(SNOWY)) - return new ModelBlock("tian_soil_side_snowed").add().nswe().d("tian").u("grass_top"); + return provider.getModel("tian_soil_side_snowed").add().nswe().d("tian").u("grass_top"); else - return new ModelBlock("tian_soil_side").add().nswe().d("tian").u("tian_soil_top"); + return provider.getModel("tian_soil_side").add().nswe().d("tian").u("tian_soil_top"); } } diff --git a/java/src/game/block/BlockVine.java b/common/src/main/java/common/block/foliage/BlockVine.java similarity index 92% rename from java/src/game/block/BlockVine.java rename to common/src/main/java/common/block/foliage/BlockVine.java index 779cd88..5e0b4e7 100755 --- a/java/src/game/block/BlockVine.java +++ b/common/src/main/java/common/block/foliage/BlockVine.java @@ -1,29 +1,31 @@ -package game.block; +package common.block.foliage; -import game.color.Colorizer; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemShears; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.color.Colorizer; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemShears; +import common.item.ItemStack; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockVine extends Block { @@ -36,10 +38,10 @@ public class BlockVine extends Block public BlockVine() { - super(Material.vine); + super(Material.BUSH); this.setDefaultState(this.getBaseState().withProperty(UP, Boolean.valueOf(false)).withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false))); this.setTickRandomly(); - this.setTab(CheatTab.tabPlants); + this.setTab(CheatTab.PLANTS); } /** @@ -176,7 +178,7 @@ public class BlockVine extends Block private boolean canPlaceOn(Block blockIn) { - return blockIn.isFullCube() && blockIn.material.blocksMovement(); + return blockIn.isFullCube() && blockIn.getMaterial().blocksMovement(); } private boolean recheckGrownSides(World worldIn, BlockPos pos, State state) @@ -240,16 +242,16 @@ public class BlockVine extends Block } } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Config.vineDry && worldIn.getTemperatureC(pos) >= 50.0f) + if(Vars.vineDry && worldIn.getTemperatureC(pos) >= 50.0f) { worldIn.setBlockToAir(pos); return; } // if (!worldIn.client) // { - if (Config.vineGrowth > 0 && worldIn.rand.chance(Config.vineGrowth)) + if (Vars.vineGrowth > 0 && worldIn.rand.chance(Vars.vineGrowth)) { int i = 4; int j = 5; @@ -279,7 +281,7 @@ public class BlockVine extends Block Facing enumfacing1 = Facing.random(rand); BlockPos blockpos1 = pos.up(); - if (enumfacing1 == Facing.UP && pos.getY() < 511 && worldIn.isAirBlock(blockpos1)) + if (enumfacing1 == Facing.UP && pos.getY() < World.MAX_SIZE_Y - 1 && worldIn.isAirBlock(blockpos1)) { if (!flag) { @@ -306,7 +308,7 @@ public class BlockVine extends Block BlockPos blockpos3 = pos.offset(enumfacing1); Block block1 = worldIn.getState(blockpos3).getBlock(); - if (block1.material == Material.air) + if (block1 == Blocks.air) { Facing enumfacing2 = enumfacing1.rotateY(); Facing enumfacing4 = enumfacing1.rotateYCCW(); @@ -336,7 +338,7 @@ public class BlockVine extends Block worldIn.setState(blockpos3, this.getState(), 2); } } - else if (block1.material.isOpaque() && block1.isFullCube()) + else if (block1.getMaterial().isOpaque() && block1.isFullCube()) { worldIn.setState(pos, state.withProperty(getPropertyFor(enumfacing1), Boolean.valueOf(true)), 2); } @@ -350,7 +352,7 @@ public class BlockVine extends Block State iblockstate = worldIn.getState(blockpos2); Block block = iblockstate.getBlock(); - if (block.material == Material.air) + if (block == Blocks.air) { State iblockstate1 = state; @@ -518,8 +520,8 @@ public class BlockVine extends Block return i; } - public ModelBlock getModel(String name, State state) { - ModelBlock model = new ModelBlock("vine").noOcclude(); + public Model getModel(ModelProvider provider, String name, State state) { + Model model = provider.getModel("vine"); if(state.getValue(UP)) model.add(0, 15.2f, 0, 16, 15.2f, 16).noShade() .d().uv(0, 0, 16, 16).tint().noCull() diff --git a/java/src/game/block/BlockWart.java b/common/src/main/java/common/block/foliage/BlockWart.java similarity index 75% rename from java/src/game/block/BlockWart.java rename to common/src/main/java/common/block/foliage/BlockWart.java index ee31c6a..30771d8 100755 --- a/java/src/game/block/BlockWart.java +++ b/common/src/main/java/common/block/foliage/BlockWart.java @@ -1,20 +1,22 @@ -package game.block; +package common.block.foliage; -import game.init.Blocks; -import game.init.Config; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockWart extends BlockBush { @@ -22,7 +24,7 @@ public class BlockWart extends BlockBush public BlockWart() { - super(Material.plants); + super(Material.PLANT); this.setDefaultState(this.getBaseState().withProperty(AGE, Integer.valueOf(0))); this.setTickRandomly(); float f = 0.5F; @@ -43,12 +45,12 @@ public class BlockWart extends BlockBush return this.canPlaceBlockOn(worldIn.getState(pos.down()).getBlock()); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(Config.wartGrowth > 0) { + if(Vars.wartGrowth > 0) { int i = ((Integer)state.getValue(AGE)).intValue(); - if (i < 3 && rand.chance(Config.wartGrowth)) + if (i < 3 && rand.chance(Vars.wartGrowth)) { state = state.withProperty(AGE, Integer.valueOf(i + 1)); worldIn.setState(pos, state, 2); @@ -126,8 +128,8 @@ public class BlockWart extends BlockBush return new IProperty[] {AGE}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { int age = state.getValue(AGE); - return BlockCrops.crop(name + "_" + (age >= 2 ? age - 1 : age)); + return BlockCrops.crop(provider, name + "_" + (age >= 2 ? age - 1 : age)); } } diff --git a/common/src/main/java/common/block/foliage/IGrowable.java b/common/src/main/java/common/block/foliage/IGrowable.java new file mode 100755 index 0000000..87ca9b8 --- /dev/null +++ b/common/src/main/java/common/block/foliage/IGrowable.java @@ -0,0 +1,16 @@ +package common.block.foliage; + +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; + +public interface IGrowable +{ + boolean canGrow(World worldIn, BlockPos pos, State state, boolean isClient); + + boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, State state); + + void grow(AWorldServer worldIn, Random rand, BlockPos pos, State state); +} diff --git a/java/src/game/block/LeavesType.java b/common/src/main/java/common/block/foliage/LeavesType.java similarity index 87% rename from java/src/game/block/LeavesType.java rename to common/src/main/java/common/block/foliage/LeavesType.java index 22bc1cb..0a918bf 100755 --- a/java/src/game/block/LeavesType.java +++ b/common/src/main/java/common/block/foliage/LeavesType.java @@ -1,8 +1,8 @@ -package game.block; +package common.block.foliage; -import game.properties.IStringSerializable; +import common.util.Identifyable; -public enum LeavesType implements IStringSerializable { +public enum LeavesType implements Identifyable { SPRING(0, "spring", true, "Frühling"), SUMMER(1, "summer", true, "Sommer"), AUTUMN(2, "autumn", false, "Herbst"), diff --git a/java/src/game/block/BlockDynamicLiquid.java b/common/src/main/java/common/block/liquid/BlockDynamicLiquid.java similarity index 84% rename from java/src/game/block/BlockDynamicLiquid.java rename to common/src/main/java/common/block/liquid/BlockDynamicLiquid.java index 98c362f..98a4d51 100755 --- a/java/src/game/block/BlockDynamicLiquid.java +++ b/common/src/main/java/common/block/liquid/BlockDynamicLiquid.java @@ -1,17 +1,19 @@ -package game.block; +package common.block.liquid; import java.util.EnumSet; import java.util.Set; -import game.init.Blocks; -import game.init.Config; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.artificial.BlockDoor; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.vars.Vars; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockDynamicLiquid extends BlockLiquid { @@ -29,9 +31,9 @@ public class BlockDynamicLiquid extends BlockLiquid worldIn.setState(pos, getStaticBlock(this).getState().withProperty(LEVEL, currentState.getValue(LEVEL)), 2); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if(!Config.liquidPhysics) + if(!Vars.liquidPhysics) return; int i = ((Integer)state.getValue(LEVEL)).intValue(); int j = 1; @@ -74,10 +76,10 @@ public class BlockDynamicLiquid extends BlockLiquid } } - if (this.adjacentSourceBlocks >= 2 && ((Config.mergeWater && this.material == Material.water) - || (Config.mergeLava && this.material == Material.lava) - || (this.infinite && Config.mergeInfinite && this.material != Material.water && this.material != Material.lava) - || (!this.infinite && Config.mergeFinite && this.material != Material.water && this.material != Material.lava))) + if (this.adjacentSourceBlocks >= 2 && ((Vars.mergeWater && this.material == Material.WATER) + || (Vars.mergeLava && this.material == Material.LAVA) + || (this.infinite && Vars.mergeInfinite && this.material != Material.WATER && this.material != Material.LAVA) + || (!this.infinite && Vars.mergeFinite && this.material != Material.WATER && this.material != Material.LAVA))) { State iblockstate1 = worldIn.getState(pos.down()); @@ -126,7 +128,7 @@ public class BlockDynamicLiquid extends BlockLiquid if (this.canFlowInto(worldIn, pos.down(), iblockstate)) { - if (this.material == Material.lava && worldIn.getState(pos.down()).getBlock().getMaterial().isColdLiquid()) + if (this.material == Material.LAVA && worldIn.getState(pos.down()).getBlock().getMaterial().isColdLiquid()) { worldIn.setState(pos.down(), Blocks.stone.getState()); this.triggerMixEffects(worldIn, pos.down()); @@ -170,7 +172,7 @@ public class BlockDynamicLiquid extends BlockLiquid { if (state.getBlock() != Blocks.air) { - if (this.material == Material.lava) + if (this.material == Material.LAVA) { this.triggerMixEffects(worldIn, pos); } @@ -260,7 +262,7 @@ public class BlockDynamicLiquid extends BlockLiquid private boolean isBlocked(World worldIn, BlockPos pos, State state) { Block block = worldIn.getState(pos).getBlock(); - return !(block instanceof BlockDoor) && block != Blocks.sign && block != Blocks.ladder && block != Blocks.reeds ? (block.material == Material.portal ? true : block.material.blocksMovement()) : true; + return !(block instanceof BlockDoor) && block != Blocks.sign && block != Blocks.ladder && block != Blocks.reeds ? (block.getMaterial() == Material.PORTAL ? true : block.getMaterial().blocksMovement()) : true; } protected int checkAdjacentBlock(World worldIn, BlockPos pos, int currentMinLevel) @@ -290,10 +292,10 @@ public class BlockDynamicLiquid extends BlockLiquid private boolean canFlowInto(World worldIn, BlockPos pos, State state) { Material material = state.getBlock().getMaterial(); - return material != this.material && material != Material.lava && !this.isBlocked(worldIn, pos, state); + return (this.material == Material.LAVA || !(state.getBlock() instanceof BlockLiquid) || (state.getBlock() instanceof BlockStaticLiquid ? BlockLiquid.getFlowingBlock((BlockStaticLiquid)state.getBlock()) : state.getBlock()) == this) && material != this.material && material != Material.LAVA && !this.isBlocked(worldIn, pos, state); } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { if (!this.checkForMixing(worldIn, pos, state)) { diff --git a/java/src/game/block/BlockLiquid.java b/common/src/main/java/common/block/liquid/BlockLiquid.java similarity index 85% rename from java/src/game/block/BlockLiquid.java rename to common/src/main/java/common/block/liquid/BlockLiquid.java index 6a2b1e7..4643b57 100755 --- a/java/src/game/block/BlockLiquid.java +++ b/common/src/main/java/common/block/liquid/BlockLiquid.java @@ -1,29 +1,30 @@ -package game.block; +package common.block.liquid; -import game.color.Colorizer; -import game.entity.Entity; -import game.init.Blocks; -import game.init.Config; -import game.init.FluidRegistry; -import game.init.SoundEvent; -import game.item.Item; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.BlockLayer; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.Vec3; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.color.Colorizer; +import common.entity.Entity; +import common.init.Blocks; +import common.init.FluidRegistry; +import common.init.SoundEvent; +import common.item.Item; +import common.model.BlockLayer; +import common.model.ParticleType; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Facing; +import common.util.Vec3; +import common.vars.Vars; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public abstract class BlockLiquid extends Block { @@ -50,7 +51,7 @@ public abstract class BlockLiquid extends Block public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass) { - return this.material == Material.water ? Colorizer.getWaterColor(worldIn, pos) : 16777215; + return this.material == Material.WATER ? Colorizer.getWaterColor(worldIn, pos) : 16777215; } /** @@ -90,18 +91,15 @@ public abstract class BlockLiquid extends Block return false; } - public boolean canCollideCheck(State state, boolean hitIfLiquid) + public boolean canCollideCheck(State state, boolean liquid) { - return hitIfLiquid && ((Integer)state.getValue(LEVEL)).intValue() == 0; + return liquid && ((Integer)state.getValue(LEVEL)).intValue() == 0; } - /** - * Whether this Block is solid on the given Side - */ public boolean isBlockSolid(IBlockAccess worldIn, BlockPos pos, Facing side) { - Material material = worldIn.getState(pos).getBlock().getMaterial(); - return material == this.material ? false : (side == Facing.UP ? true : (material == Material.ice ? false : super.isBlockSolid(worldIn, pos, side))); + Block block = worldIn.getState(pos).getBlock(); + return block.getMaterial() == this.material ? false : (side == Facing.UP ? true : (block != Blocks.ice && worldIn.getState(pos).getBlock().getMaterial().isSolid())); } public boolean shouldSideBeRendered(IWorldAccess worldIn, BlockPos pos, Facing side) @@ -234,13 +232,13 @@ public abstract class BlockLiquid extends Block return this.opaque ? BlockLayer.SOLID : BlockLayer.TRANSLUCENT; } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { double d0 = (double)pos.getX(); double d1 = (double)pos.getY(); double d2 = (double)pos.getZ(); - if (this.material == Material.water) + if (this.material == Material.WATER) { int i = ((Integer)state.getValue(LEVEL)).intValue(); @@ -257,7 +255,7 @@ public abstract class BlockLiquid extends Block } } - if (this.material == Material.lava && worldIn.getState(pos.up()).getBlock().getMaterial() == Material.air && !worldIn.getState(pos.up()).getBlock().isOpaqueCube()) + if (this.material == Material.LAVA && worldIn.getState(pos.up()).getBlock() == Blocks.air && !worldIn.getState(pos.up()).getBlock().isOpaqueCube()) { if (rand.chance(100)) { @@ -284,7 +282,7 @@ public abstract class BlockLiquid extends Block double d5 = d1 - 1.05D; double d7 = d2 + (double)rand.floatv(); - if (this.material == Material.water) + if (this.material == Material.WATER) { worldIn.spawnParticle(ParticleType.DRIP_WATER, d3, d5, d7, 0.0D, 0.0D, 0.0D); } @@ -302,7 +300,7 @@ public abstract class BlockLiquid extends Block return vec3.xCoord == 0.0D && vec3.zCoord == 0.0D ? -1000.0D : ExtMath.atan2(vec3.zCoord, vec3.xCoord) - (Math.PI / 2D); } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { this.checkForMixing(worldIn, pos, state); } @@ -317,9 +315,9 @@ public abstract class BlockLiquid extends Block public boolean checkForMixing(World worldIn, BlockPos pos, State state) { - if(worldIn.client || !Config.liquidPhysics) + if(worldIn.client || !Vars.liquidPhysics) return true; - if (this.material == Material.lava) + if (this.material == Material.LAVA) { boolean flag = false; @@ -396,11 +394,11 @@ public abstract class BlockLiquid extends Block public static BlockDynamicLiquid getFlowingBlock(BlockStaticLiquid block) { - if (block.getMaterial() == Material.water) + if (block.getMaterial() == Material.WATER) { return Blocks.flowing_water; } - else if (block.getMaterial() == Material.lava) + else if (block.getMaterial() == Material.LAVA) { return Blocks.flowing_lava; } @@ -412,11 +410,11 @@ public abstract class BlockLiquid extends Block public static BlockStaticLiquid getStaticBlock(BlockDynamicLiquid block) { - if (block.getMaterial() == Material.water) + if (block.getMaterial() == Material.WATER) { return Blocks.water; } - else if (block.getMaterial() == Material.lava) + else if (block.getMaterial() == Material.LAVA) { return Blocks.lava; } diff --git a/java/src/game/block/BlockStaticLiquid.java b/common/src/main/java/common/block/liquid/BlockStaticLiquid.java similarity index 80% rename from java/src/game/block/BlockStaticLiquid.java rename to common/src/main/java/common/block/liquid/BlockStaticLiquid.java index c34411c..85946e7 100755 --- a/java/src/game/block/BlockStaticLiquid.java +++ b/common/src/main/java/common/block/liquid/BlockStaticLiquid.java @@ -1,20 +1,21 @@ -package game.block; +package common.block.liquid; -import game.init.Blocks; -import game.init.Config; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.vars.Vars; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockStaticLiquid extends BlockLiquid { public BlockStaticLiquid(Material materialIn, boolean opaque, int rate) { - super(materialIn, materialIn == Material.lava, opaque, rate); + super(materialIn, materialIn == Material.LAVA, opaque, rate); // this.setTickRandomly(false); // // if (materialIn == Material.lava) @@ -41,11 +42,11 @@ public class BlockStaticLiquid extends BlockLiquid worldIn.scheduleUpdate(pos, blockdynamicliquid, this.tickRate(worldIn, pos)); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Config.lavaFire && this.material == Material.lava) + if (Vars.lavaFire && this.material == Material.LAVA) { - if (Config.fire) + if (Vars.fire) { int i = rand.zrange(3); @@ -58,7 +59,7 @@ public class BlockStaticLiquid extends BlockLiquid blockpos = blockpos.add(rand.zrange(3) - 1, 1, rand.zrange(3) - 1); Block block = worldIn.getState(blockpos).getBlock(); - if (block.material == Material.air) + if (block == Blocks.air) { if (this.isSurroundingBlockFlammable(worldIn, blockpos)) { @@ -66,7 +67,7 @@ public class BlockStaticLiquid extends BlockLiquid return; } } - else if (block.material.blocksMovement()) + else if (block.getMaterial().blocksMovement()) { return; } diff --git a/common/src/main/java/common/block/natural/BlockBedrock.java b/common/src/main/java/common/block/natural/BlockBedrock.java new file mode 100755 index 0000000..a1c0a9b --- /dev/null +++ b/common/src/main/java/common/block/natural/BlockBedrock.java @@ -0,0 +1,23 @@ +package common.block.natural; + +import common.block.Block; +import common.block.Material; +import common.model.ParticleType; +import common.rng.Random; +import common.util.BlockPos; +import common.world.AWorldClient; +import common.world.State; + +public class BlockBedrock extends Block { + public BlockBedrock() { + super(Material.SOLID); + } + + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) + { + if(/* worldIn.canShowVoidParticles() && */ pos.getY() <= 5 && rand.chance(8)) { + worldIn.spawnParticle(ParticleType.SUSPENDED_DEPTH, (double)pos.getX() + rand.floatv(), (double)(pos.getY()+1) + (rand.floatv() * 0.5f), + (double)pos.getZ() + rand.floatv(), 0.0D, 0.0D, 0.0D); + } + } +} diff --git a/java/src/game/block/BlockBlackenedDirt.java b/common/src/main/java/common/block/natural/BlockBlackenedDirt.java similarity index 66% rename from java/src/game/block/BlockBlackenedDirt.java rename to common/src/main/java/common/block/natural/BlockBlackenedDirt.java index 9021411..c6e0fa0 100644 --- a/java/src/game/block/BlockBlackenedDirt.java +++ b/common/src/main/java/common/block/natural/BlockBlackenedDirt.java @@ -1,26 +1,28 @@ -package game.block; +package common.block.natural; -import game.init.Blocks; -import game.init.Config; -import game.item.CheatTab; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.biome.Biome; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.item.CheatTab; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.AWorldServer; public class BlockBlackenedDirt extends Block { public BlockBlackenedDirt() { - super(Material.ground); + super(Material.LOOSE); this.setTickRandomly(); - this.setTab(CheatTab.tabNature); + this.setTab(CheatTab.NATURE); } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Config.darkDirtSpread) + if (Vars.darkDirtSpread) { for (int i = 0; i < 4; i++) { @@ -35,6 +37,7 @@ public class BlockBlackenedDirt extends Block else if (iblockstate.getBlock() == Blocks.grass && worldIn.getLightFromNeighbors(blockpos.up()) >= 2 && block.getLightOpacity() <= 6) { worldIn.setState(blockpos, Blocks.blackened_soil.getState()); + worldIn.setBiome(blockpos, Biome.BLACKENED); } else if (iblockstate.getBlock() == Blocks.stone && rand.chance(25)) { diff --git a/common/src/main/java/common/block/natural/BlockBlackenedStone.java b/common/src/main/java/common/block/natural/BlockBlackenedStone.java new file mode 100644 index 0000000..bf35ab6 --- /dev/null +++ b/common/src/main/java/common/block/natural/BlockBlackenedStone.java @@ -0,0 +1,21 @@ +package common.block.natural; + +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.item.CheatTab; +import common.item.Item; +import common.rng.Random; +import common.world.State; + +public class BlockBlackenedStone extends Block { + public BlockBlackenedStone() { + super(Material.SOLID); + this.setTab(CheatTab.NATURE); + } + + public Item getItemDropped(State state, Random rand, int fortune) { + return ItemRegistry.getItemFromBlock(Blocks.blackened_cobble); + } +} diff --git a/java/src/game/block/BlockClay.java b/common/src/main/java/common/block/natural/BlockClay.java similarity index 59% rename from java/src/game/block/BlockClay.java rename to common/src/main/java/common/block/natural/BlockClay.java index 0637152..9f15600 100755 --- a/java/src/game/block/BlockClay.java +++ b/common/src/main/java/common/block/natural/BlockClay.java @@ -1,18 +1,19 @@ -package game.block; +package common.block.natural; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.rng.Random; -import game.world.State; +import common.block.Block; +import common.block.Material; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.rng.Random; +import common.world.State; public class BlockClay extends Block { public BlockClay() { - super(Material.clay); - this.setTab(CheatTab.tabNature); + super(Material.LOOSE); + this.setTab(CheatTab.NATURE); } /** diff --git a/java/src/game/block/BlockDirt.java b/common/src/main/java/common/block/natural/BlockDirt.java similarity index 81% rename from java/src/game/block/BlockDirt.java rename to common/src/main/java/common/block/natural/BlockDirt.java index f77e481..f93a03c 100755 --- a/java/src/game/block/BlockDirt.java +++ b/common/src/main/java/common/block/natural/BlockDirt.java @@ -1,21 +1,23 @@ -package game.block; +package common.block.natural; import java.util.List; -import game.init.Blocks; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyBool; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyEnum; +import common.util.BlockPos; +import common.util.Identifyable; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockDirt extends Block { @@ -24,9 +26,9 @@ public class BlockDirt extends Block public BlockDirt() { - super(Material.ground); + super(Material.LOOSE); this.setDefaultState(this.getBaseState().withProperty(VARIANT, BlockDirt.DirtType.DIRT).withProperty(SNOWY, Boolean.valueOf(false))); - this.setTab(CheatTab.tabNature); + this.setTab(CheatTab.NATURE); } // /** @@ -108,20 +110,20 @@ public class BlockDirt extends Block return blockdirt$dirttype.getMetadata(); } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { switch(state.getValue(VARIANT)) { case DIRT: default: - return new ModelBlock("dirt").add().all(); + return provider.getModel("dirt").add().all(); case COARSE_DIRT: - return new ModelBlock("coarse_dirt").add().all(); + return provider.getModel("coarse_dirt").add().all(); case PODZOL: - return state.getValue(SNOWY) ? new ModelBlock("grass_side_snowed").add().nswe().d("dirt").u("grass_top") : - new ModelBlock("dirt_podzol_side").add().nswe().d("dirt").u("dirt_podzol_top"); + return state.getValue(SNOWY) ? provider.getModel("grass_side_snowed").add().nswe().d("dirt").u("grass_top") : + provider.getModel("dirt_podzol_side").add().nswe().d("dirt").u("dirt_podzol_top"); } } - public static enum DirtType implements IStringSerializable + public static enum DirtType implements Identifyable { DIRT(0, "dirt", "Erde"), COARSE_DIRT(1, "coarse_dirt", "Grobe Erde"), diff --git a/java/src/game/block/BlockFire.java b/common/src/main/java/common/block/natural/BlockFire.java similarity index 70% rename from java/src/game/block/BlockFire.java rename to common/src/main/java/common/block/natural/BlockFire.java index f517e84..40002fa 100755 --- a/java/src/game/block/BlockFire.java +++ b/common/src/main/java/common/block/natural/BlockFire.java @@ -1,32 +1,31 @@ -package game.block; +package common.block.natural; import java.util.Map; -import game.collect.Maps; - -import game.init.Blocks; -import game.init.Config; -import game.init.SoundEvent; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyInteger; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.renderer.ticked.TextureFlamesFX1; -import game.renderer.ticked.TextureFlamesFX2; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.init.FlammabilityRegistry; +import common.init.SoundEvent; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.ParticleType; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.vars.Vars; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockFire extends Block { @@ -38,8 +37,6 @@ public class BlockFire extends Block public static final PropertyBool SOUTH = PropertyBool.create("south"); public static final PropertyBool WEST = PropertyBool.create("west"); public static final PropertyInteger UPPER = PropertyInteger.create("upper", 0, 2); - private final Map encouragements = Maps.newIdentityHashMap(); - private final Map flammabilities = Maps.newIdentityHashMap(); /** * Get the actual Block state of this Block at the given position. This applies properties not visible in the @@ -51,7 +48,7 @@ public class BlockFire extends Block int j = pos.getY(); int k = pos.getZ(); - if (!World.isSolidSurface(worldIn.getState(pos.down())) && !Blocks.fire.canCatchFire(worldIn, pos.down())) + if (!World.isSolidSurface(worldIn.getState(pos.down())) && !this.canCatchFire(worldIn, pos.down())) { boolean flag = (i + j + k & 1) == 1; boolean flag1 = (i / 2 + j / 2 + k / 2 & 1) == 1; @@ -72,17 +69,11 @@ public class BlockFire extends Block public BlockFire() { - super(Material.fire); + super(Material.FIRE); this.setDefaultState(this.getBaseState().withProperty(AGE, Integer.valueOf(0)).withProperty(FLIP, Boolean.valueOf(false)).withProperty(ALT, Boolean.valueOf(false)).withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false)).withProperty(UPPER, Integer.valueOf(0))); this.setTickRandomly(); } - public void setFireInfo(Block blockIn, int encouragement, int flammability) - { - this.encouragements.put(blockIn, Integer.valueOf(encouragement)); - this.flammabilities.put(blockIn, Integer.valueOf(flammability)); - } - public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) { return null; @@ -117,9 +108,9 @@ public class BlockFire extends Block return 30; } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Config.fire) + if (Vars.fire) { if (!this.canPlaceBlockAt(worldIn, pos)) { @@ -134,7 +125,7 @@ public class BlockFire extends Block // flag = true; // } - if (!flag && worldIn.isRaining() && this.canDie(worldIn, pos)) + if (!flag && this.canDie(worldIn, pos)) { worldIn.setBlockToAir(pos); } @@ -214,7 +205,7 @@ public class BlockFire extends Block l1 /= 2; } - if (l1 > 0 && rand.zrange(j1) <= l1 && (!worldIn.isRaining() || !this.canDie(worldIn, blockpos))) + if (l1 > 0 && rand.zrange(j1) <= l1 && !this.canDie(worldIn, blockpos)) { int i2 = i + rand.zrange(5) / 4; @@ -234,9 +225,9 @@ public class BlockFire extends Block } } - protected boolean canDie(World worldIn, BlockPos pos) + protected boolean canDie(World world, BlockPos pos) { - return worldIn.isRainingAt(pos, true) || worldIn.isRainingAt(pos.west(), true) || worldIn.isRainingAt(pos.east(), true) || worldIn.isRainingAt(pos.north(), true) || worldIn.isRainingAt(pos.south(), true); + return world.isRaining() && (world.isRainingAt(pos, true) || world.isRainingAt(pos.west(), true) || world.isRainingAt(pos.east(), true) || world.isRainingAt(pos.north(), true) || world.isRainingAt(pos.south(), true)); } public boolean requiresUpdates() @@ -244,43 +235,31 @@ public class BlockFire extends Block return false; } - private int getFlammability(Block blockIn) + protected void catchOnFire(World world, BlockPos pos, int chance, Random rand, int age) { - Integer integer = (Integer)this.flammabilities.get(blockIn); - return integer == null ? 0 : integer.intValue(); - } + int i = FlammabilityRegistry.getFlammability(world.getState(pos).getBlock()); - private int getEncouragement(Block blockIn) - { - Integer integer = (Integer)this.encouragements.get(blockIn); - return integer == null ? 0 : integer.intValue(); - } - - private void catchOnFire(World worldIn, BlockPos pos, int chance, Random random, int age) - { - int i = this.getFlammability(worldIn.getState(pos).getBlock()); - - if (random.zrange(chance) < i) + if (rand.zrange(chance) < i) { - State iblockstate = worldIn.getState(pos); + State iblockstate = world.getState(pos); - if (random.zrange(age + 10) < 5 && !worldIn.isRainingAt(pos, true)) + if (rand.zrange(age + 10) < 5 && !world.isRainingAt(pos, true)) { - int j = age + random.zrange(5) / 4; + int j = age + rand.zrange(5) / 4; if (j > 15) { j = 15; } - worldIn.setState(pos, this.getState().withProperty(AGE, Integer.valueOf(j)), 3); + world.setState(pos, this.getState().withProperty(AGE, Integer.valueOf(j)), 3); } else { - worldIn.setBlockToAir(pos); + world.setBlockToAir(pos); } - iblockstate.getBlock().onDestroyedByFire(worldIn, pos, iblockstate); + iblockstate.getBlock().onDestroyedByFire(world, pos, iblockstate); // if (iblockstate.getBlock() == Blocks.tnt) // { // Blocks.tnt.onBlockDestroyedByPlayer(worldIn, pos, iblockstate.withProperty(BlockTNT.EXPLODE, Boolean.valueOf(true))); @@ -313,7 +292,7 @@ public class BlockFire extends Block for (Facing enumfacing : Facing.values()) { - i = Math.max(this.getEncouragement(worldIn.getState(pos.offset(enumfacing)).getBlock()), i); + i = Math.max(FlammabilityRegistry.getEncouragement(worldIn.getState(pos.offset(enumfacing)).getBlock()), i); } return i; @@ -333,7 +312,7 @@ public class BlockFire extends Block */ public boolean canCatchFire(IBlockAccess worldIn, BlockPos pos) { - return this.getEncouragement(worldIn.getState(pos).getBlock()) > 0; + return FlammabilityRegistry.getEncouragement(worldIn.getState(pos).getBlock()) > 0; } public boolean canPlaceBlockAt(World worldIn, BlockPos pos) @@ -352,7 +331,7 @@ public class BlockFire extends Block } } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { if ( // (worldIn.dimension.getDimensionId() < -1 || worldIn.dimension.getDimensionId() > 0) || !Blocks.portal.tryIgnitePortal(worldIn, pos, worldIn.rand.zrange(8))) @@ -368,16 +347,16 @@ public class BlockFire extends Block } } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { if (rand.chance(24)) { worldIn.playSound((double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), SoundEvent.FIRE, 1.0F + rand.floatv()); } - if (!worldIn.isBlockSolid(pos.down()) && !Blocks.fire.canCatchFire(worldIn, pos.down())) + if (!worldIn.isBlockSolid(pos.down()) && !this.canCatchFire(worldIn, pos.down())) { - if (Blocks.fire.canCatchFire(worldIn, pos.west())) + if (this.canCatchFire(worldIn, pos.west())) { for (int j = 0; j < 2; ++j) { @@ -388,7 +367,7 @@ public class BlockFire extends Block } } - if (Blocks.fire.canCatchFire(worldIn, pos.east())) + if (this.canCatchFire(worldIn, pos.east())) { for (int k = 0; k < 2; ++k) { @@ -399,7 +378,7 @@ public class BlockFire extends Block } } - if (Blocks.fire.canCatchFire(worldIn, pos.north())) + if (this.canCatchFire(worldIn, pos.north())) { for (int l = 0; l < 2; ++l) { @@ -410,7 +389,7 @@ public class BlockFire extends Block } } - if (Blocks.fire.canCatchFire(worldIn, pos.south())) + if (this.canCatchFire(worldIn, pos.south())) { for (int i1 = 0; i1 < 2; ++i1) { @@ -421,7 +400,7 @@ public class BlockFire extends Block } } - if (Blocks.fire.canCatchFire(worldIn, pos.up())) + if (this.canCatchFire(worldIn, pos.up())) { for (int j1 = 0; j1 < 2; ++j1) { @@ -478,488 +457,487 @@ public class BlockFire extends Block return new IProperty[] {AGE, NORTH, EAST, SOUTH, WEST, UPPER, FLIP, ALT}; } - private static ModelBlock fire_nsu2_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nsu2_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull() + .d().uv(0, 0, 16, 16).rot(180).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull(); + .d().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_nu1(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nu1(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull() + .d().uv(0, 0, 16, 16).rot(270).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull(); + .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); } - private static ModelBlock fire_nseu2_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nseu2_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull() + .w().uv(16, 0, 0, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull() + .d().uv(0, 0, 16, 16).rot(180).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull(); + .d().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_neu1_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_neu1_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull() + .w().uv(16, 0, 0, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull() + .d().uv(0, 0, 16, 16).rot(270).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull(); + .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); } - private static ModelBlock fire_nsu2(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nsu2(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull() + .d().uv(0, 0, 16, 16).rot(180).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull(); + .d().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_nu2_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nu2_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull() + .d().uv(0, 0, 16, 16).rot(180).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull(); + .d().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_neu2_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_neu2_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull() + .w().uv(16, 0, 0, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull() + .d().uv(0, 0, 16, 16).rot(180).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull(); + .d().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_nsewu2_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nsewu2_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull() + .w().uv(16, 0, 0, 16).noCull().tint() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull() + .w().uv(16, 0, 0, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull() + .d().uv(0, 0, 16, 16).rot(180).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull(); + .d().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_nsewu2(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nsewu2(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull().tint() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull() + .d().uv(0, 0, 16, 16).rot(180).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull(); + .d().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_nsew(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nsew(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull().tint() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull(); + .w().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_floor(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_floor(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 0, 8.8f, 16, 22.4f, 8.8f).noShade().rotate(8, 8, 8, Facing.Axis.X, -22.5f, true) - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 0, 7.2f, 16, 22.4f, 7.2f).noShade().rotate(8, 8, 8, Facing.Axis.X, 22.5f, true) - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(8.8f, 0, 0, 8.8f, 22.4f, 16).noShade().rotate(8, 8, 8, Facing.Axis.Z, -22.5f, true) - .w().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull().tint() .add(7.2f, 0, 0, 7.2f, 22.4f, 16).noShade().rotate(8, 8, 8, Facing.Axis.Z, 22.5f, true) - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(0, 0, 15.99f, 16, 22.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 0, 0.01f, 16, 22.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0.01f, 0, 0, 0.01f, 22.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 0, 0, 15.99f, 22.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull(); + .e().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_u1(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_u1(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull() + .d().uv(0, 0, 16, 16).rot(270).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull(); + .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); } - private static ModelBlock fire_n_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_n_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull(); + .n().uv(16, 0, 0, 16).noCull().tint(); } - private static ModelBlock fire_ne(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_ne(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull(); + .w().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_nsew_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nsew_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull() + .w().uv(16, 0, 0, 16).noCull().tint() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull(); + .w().uv(16, 0, 0, 16).noCull().tint(); } - private static ModelBlock fire_nse(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nse(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull(); + .w().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_nse_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nse_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull(); + .w().uv(16, 0, 0, 16).noCull().tint(); } - private static ModelBlock fire_nsu1_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nsu1_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull() + .d().uv(0, 0, 16, 16).rot(270).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull(); + .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); } - private static ModelBlock fire_n(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_n(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull(); + .n().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_ns(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_ns(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull(); + .n().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_neu1(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_neu1(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull() + .d().uv(0, 0, 16, 16).rot(270).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull(); + .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); } - private static ModelBlock fire_u2(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_u2(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull() + .d().uv(0, 0, 16, 16).rot(180).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull(); + .d().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_nseu2(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nseu2(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull() + .d().uv(0, 0, 16, 16).rot(180).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull(); + .d().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_neu2(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_neu2(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull() + .d().uv(0, 0, 16, 16).rot(180).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull(); + .d().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_nu2(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nu2(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 16, Facing.Axis.X, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(180).noCull() + .d().uv(0, 0, 16, 16).rot(180).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(8, 16, 0, Facing.Axis.X, 22.5f, true) - .d().uv(0, 0, 16, 16).noCull(); + .d().uv(0, 0, 16, 16).noCull().tint(); } - private static ModelBlock fire_nseu1(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nseu1(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull() + .d().uv(0, 0, 16, 16).rot(270).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull(); + .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); } - private static ModelBlock fire_ns_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_ns_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull(); + .n().uv(16, 0, 0, 16).noCull().tint(); } - private static ModelBlock fire_nsewu1(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nsewu1(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull().tint() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull().tint() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull() + .d().uv(0, 0, 16, 16).rot(270).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull(); + .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); } - private static ModelBlock fire_nsu1(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nsu1(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull() + .d().uv(0, 0, 16, 16).rot(270).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull(); + .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); } - private static ModelBlock fire_nsewu1_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nsewu1_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull() + .w().uv(16, 0, 0, 16).noCull().tint() .add(0.01f, 1, 0, 0.01f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 0.01f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull() + .w().uv(16, 0, 0, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull() + .d().uv(0, 0, 16, 16).rot(270).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull(); + .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); } - private static ModelBlock fire_ne_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_ne_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull(); + .w().uv(16, 0, 0, 16).noCull().tint(); } - private static ModelBlock fire_nseu1_flip(String fire) { - return new ModelBlock(fire).noOcclude() + private static Model fire_nseu1_flip(String fire) { + return ModelProvider.getModelProvider().getModel(fire) .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 0.01f, 16, 23.4f, 0.01f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .s().uv(16, 0, 0, 16).noCull() + .s().uv(16, 0, 0, 16).noCull().tint() .add(0, 1, 15.99f, 16, 23.4f, 15.99f).noShade() - .n().uv(16, 0, 0, 16).noCull() + .n().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .e().uv(16, 0, 0, 16).noCull() + .e().uv(16, 0, 0, 16).noCull().tint() .add(15.99f, 1, 0, 15.99f, 23.4f, 16).noShade() - .w().uv(16, 0, 0, 16).noCull() + .w().uv(16, 0, 0, 16).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(16, 16, 8, Facing.Axis.Z, 22.5f, true) - .d().uv(0, 0, 16, 16).rot(270).noCull() + .d().uv(0, 0, 16, 16).rot(270).noCull().tint() .add(0, 16, 0, 16, 16, 16).noShade().rotate(0, 16, 8, Facing.Axis.Z, -22.5f, true) - .d().uv(0, 0, 16, 16).rot(90).noCull(); + .d().uv(0, 0, 16, 16).rot(90).noCull().tint(); } - private static ModelBlock getFireModel(boolean alt, boolean flip, int upper, boolean n, boolean s, boolean w, boolean e) { - String tex = alt ? "fire_layer_1" : "fire_layer_0"; + protected static Model getFireModel(String tex, boolean flip, int upper, boolean n, boolean s, boolean w, boolean e) { if(!e && !flip && !n && !s && upper == 0 && !w) return fire_floor(tex); else if(!e && !flip && !n && s && upper == 0 && !w) @@ -1156,8 +1134,8 @@ public class BlockFire extends Block return fire_floor(tex); } - public ModelBlock getModel(String name, State state) { - return getFireModel(state.getValue(ALT), state.getValue(FLIP), state.getValue(UPPER), + public Model getModel(ModelProvider provider, String name, State state) { + return getFireModel(state.getValue(ALT) ? "fire_layer_1" : "fire_layer_0", state.getValue(FLIP), state.getValue(UPPER), state.getValue(NORTH), state.getValue(SOUTH), state.getValue(WEST), state.getValue(EAST)); } @@ -1166,7 +1144,11 @@ public class BlockFire extends Block } public void getAnimatedTextures(Map map) { - map.put("blocks/fire_layer_0", TextureFlamesFX1.class); - map.put("blocks/fire_layer_1", TextureFlamesFX2.class); + map.put("blocks/fire_layer_0", "fire1"); + map.put("blocks/fire_layer_1", "fire2"); + } + + public boolean canExtinguish() { + return true; } } diff --git a/java/src/game/block/BlockGlowstone.java b/common/src/main/java/common/block/natural/BlockGlowstone.java similarity index 65% rename from java/src/game/block/BlockGlowstone.java rename to common/src/main/java/common/block/natural/BlockGlowstone.java index 99cbce4..77a18c2 100755 --- a/java/src/game/block/BlockGlowstone.java +++ b/common/src/main/java/common/block/natural/BlockGlowstone.java @@ -1,19 +1,23 @@ -package game.block; +package common.block.natural; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.rng.Random; -import game.util.ExtMath; -import game.world.State; +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.State; +import common.world.World; public class BlockGlowstone extends Block { public BlockGlowstone(Material materialIn) { super(materialIn); - this.setTab(CheatTab.tabNature); + this.setTab(CheatTab.NATURE); } /** @@ -39,6 +43,11 @@ public class BlockGlowstone extends Block { return Items.glowstone_dust; } + + public boolean onShot(World world, BlockPos pos, State state, Entity projectile) { + world.destroyBlock(pos, true); + return false; + } // /** // * Get the MapColor for this Block and the given BlockState diff --git a/java/src/game/block/BlockGravel.java b/common/src/main/java/common/block/natural/BlockGravel.java similarity index 55% rename from java/src/game/block/BlockGravel.java rename to common/src/main/java/common/block/natural/BlockGravel.java index 8684acb..de0466d 100755 --- a/java/src/game/block/BlockGravel.java +++ b/common/src/main/java/common/block/natural/BlockGravel.java @@ -1,17 +1,25 @@ -package game.block; +package common.block.natural; -import game.init.Config; -import game.init.ItemRegistry; -import game.init.Items; -import game.item.Item; -import game.rng.Random; -import game.world.State; +import common.block.BlockFalling; +import common.block.Material; +import common.init.ItemRegistry; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.rng.Random; +import common.vars.Vars; +import common.world.State; public class BlockGravel extends BlockFalling { + public BlockGravel() { + super(Material.LOOSE); + this.setTab(CheatTab.NATURE); + } + public Item getItemDropped(State state, Random rand, int fortune) { - int chance = Config.flintChance; + int chance = Vars.flintChance; if(chance <= 0) return ItemRegistry.getItemFromBlock(this); fortune *= 3; diff --git a/java/src/game/block/BlockHardenedClay.java b/common/src/main/java/common/block/natural/BlockHardenedClay.java similarity index 59% rename from java/src/game/block/BlockHardenedClay.java rename to common/src/main/java/common/block/natural/BlockHardenedClay.java index 4f3cbdb..93e8b74 100755 --- a/java/src/game/block/BlockHardenedClay.java +++ b/common/src/main/java/common/block/natural/BlockHardenedClay.java @@ -1,14 +1,15 @@ -package game.block; +package common.block.natural; -import game.item.CheatTab; -import game.material.Material; +import common.block.Block; +import common.block.Material; +import common.item.CheatTab; public class BlockHardenedClay extends Block { public BlockHardenedClay() { - super(Material.rock); - this.setTab(CheatTab.tabNature); + super(Material.SOLID); + this.setTab(CheatTab.NATURE); } // /** diff --git a/java/src/game/block/BlockHellRock.java b/common/src/main/java/common/block/natural/BlockHellRock.java similarity index 64% rename from java/src/game/block/BlockHellRock.java rename to common/src/main/java/common/block/natural/BlockHellRock.java index 664aad4..63c6b72 100755 --- a/java/src/game/block/BlockHellRock.java +++ b/common/src/main/java/common/block/natural/BlockHellRock.java @@ -1,14 +1,15 @@ -package game.block; +package common.block.natural; -import game.item.CheatTab; -import game.material.Material; +import common.block.Block; +import common.block.Material; +import common.item.CheatTab; public class BlockHellRock extends Block { public BlockHellRock() { - super(Material.rock); - this.setTab(CheatTab.tabNature); + super(Material.SOLID); + this.setTab(CheatTab.NATURE); } // /** diff --git a/common/src/main/java/common/block/natural/BlockIce.java b/common/src/main/java/common/block/natural/BlockIce.java new file mode 100755 index 0000000..725f6fe --- /dev/null +++ b/common/src/main/java/common/block/natural/BlockIce.java @@ -0,0 +1,65 @@ +package common.block.natural; + +import common.block.BlockTranslucent; +import common.block.Material; +import common.enchantment.EnchantmentHelper; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.item.CheatTab; +import common.item.ItemStack; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.LightType; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; + +public class BlockIce extends BlockTranslucent { + public BlockIce() { + super(Material.TRANSLUCENT); + this.slipperiness = 0.98F; + this.setTickRandomly(); + this.setTab(CheatTab.NATURE); + } + + public void harvestBlock(World world, EntityNPC player, BlockPos pos, State state, TileEntity tile) { + if(this.canSilkHarvest() && EnchantmentHelper.getSilkTouchModifier(player)) { + ItemStack stack = this.createStackedBlock(state); + if(stack != null) + spawnAsEntity(world, pos, stack); + } + else { + if(world.doesWaterVaporize(pos)) { + world.setBlockToAir(pos); + return; + } + int fortune = EnchantmentHelper.getFortuneModifier(player); + this.dropBlockAsItem(world, pos, state, fortune); + Material material = world.getState(pos.down()).getBlock().getMaterial(); + if(material.blocksMovement() || material.isLiquid()) + world.setState(pos, Blocks.flowing_water.getState()); + } + } + + public int quantityDropped(Random rand) { + return 0; + } + + public void updateTick(AWorldServer world, BlockPos pos, State state, Random rand) { + if(Vars.iceMelt && (world.getLightFor(LightType.BLOCK, pos) > 11 - this.getLightOpacity() || !world.canFreezeAt(pos))) { + if(world.doesWaterVaporize(pos)) { + world.setBlockToAir(pos); + } + else { + this.dropBlockAsItem(world, pos, world.getState(pos), 0); + world.setState(pos, Blocks.water.getState()); + } + } + } + + public int getMobilityFlag() { + return 0; + } +} diff --git a/java/src/game/block/BlockObsidian.java b/common/src/main/java/common/block/natural/BlockObsidian.java similarity index 61% rename from java/src/game/block/BlockObsidian.java rename to common/src/main/java/common/block/natural/BlockObsidian.java index 86aab37..97cdf05 100755 --- a/java/src/game/block/BlockObsidian.java +++ b/common/src/main/java/common/block/natural/BlockObsidian.java @@ -1,19 +1,20 @@ -package game.block; +package common.block.natural; -import game.init.Blocks; -import game.init.ItemRegistry; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.rng.Random; -import game.world.State; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.item.CheatTab; +import common.item.Item; +import common.rng.Random; +import common.world.State; public class BlockObsidian extends Block { public BlockObsidian() { - super(Material.rock); - this.setTab(CheatTab.tabNature); + super(Material.SOLID); + this.setTab(CheatTab.NATURE); } /** diff --git a/java/src/game/block/BlockOre.java b/common/src/main/java/common/block/natural/BlockOre.java similarity index 86% rename from java/src/game/block/BlockOre.java rename to common/src/main/java/common/block/natural/BlockOre.java index ebec758..bcf4df1 100755 --- a/java/src/game/block/BlockOre.java +++ b/common/src/main/java/common/block/natural/BlockOre.java @@ -1,15 +1,16 @@ -package game.block; +package common.block.natural; -import game.init.Config; -import game.init.ItemRegistry; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.init.ItemRegistry; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.World; public class BlockOre extends Block { @@ -21,8 +22,8 @@ public class BlockOre extends Block public BlockOre() { - super(Material.rock); - this.setTab(CheatTab.tabGems); + super(Material.SOLID); + this.setTab(CheatTab.GEMS); } public void setDropItem(ItemStack item, int chance, int minXp) { @@ -59,7 +60,7 @@ public class BlockOre extends Block public int quantityDropped(Random random) { - return this.dropItem == null ? 1 : (this.dropItem.stackSize + (this.dropChance > 0 ? random.zrange(this.dropChance + 1) : 0)); + return this.dropItem == null ? 1 : (this.dropItem.size + (this.dropChance > 0 ? random.zrange(this.dropChance + 1) : 0)); // this == Blocks.lapis_ore ? 4 + random.nextInt(5) : 1; } @@ -85,7 +86,7 @@ public class BlockOre extends Block public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) { - if(!worldIn.client && this.smeltItem != null && Config.cleanCut) { + if(!worldIn.client && this.smeltItem != null && Vars.cleanCut) { if (worldIn.rand.floatv() <= chance) { spawnAsEntity(worldIn, pos, this.smeltItem.copy()); diff --git a/java/src/game/block/BlockPackedIce.java b/common/src/main/java/common/block/natural/BlockPackedIce.java similarity index 57% rename from java/src/game/block/BlockPackedIce.java rename to common/src/main/java/common/block/natural/BlockPackedIce.java index ca2270c..59ddc47 100755 --- a/java/src/game/block/BlockPackedIce.java +++ b/common/src/main/java/common/block/natural/BlockPackedIce.java @@ -1,16 +1,17 @@ -package game.block; +package common.block.natural; -import game.item.CheatTab; -import game.material.Material; -import game.rng.Random; +import common.block.Block; +import common.block.Material; +import common.item.CheatTab; +import common.rng.Random; public class BlockPackedIce extends Block { public BlockPackedIce() { - super(Material.packedIce); + super(Material.LOOSE); this.slipperiness = 0.98F; - this.setTab(CheatTab.tabNature); + this.setTab(CheatTab.NATURE); } /** diff --git a/java/src/game/block/BlockRedstoneOre.java b/common/src/main/java/common/block/natural/BlockRedstoneOre.java similarity index 83% rename from java/src/game/block/BlockRedstoneOre.java rename to common/src/main/java/common/block/natural/BlockRedstoneOre.java index b590557..f42bba2 100755 --- a/java/src/game/block/BlockRedstoneOre.java +++ b/common/src/main/java/common/block/natural/BlockRedstoneOre.java @@ -1,22 +1,24 @@ -package game.block; +package common.block.natural; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.ItemRegistry; -import game.init.Items; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ParticleType; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockRedstoneOre extends Block { @@ -24,7 +26,7 @@ public class BlockRedstoneOre extends Block public BlockRedstoneOre(boolean isOn) { - super(Material.rock); + super(Material.SOLID); if (isOn) { @@ -73,7 +75,7 @@ public class BlockRedstoneOre extends Block } } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { if (this == Blocks.lit_redstone_ore) { @@ -119,7 +121,7 @@ public class BlockRedstoneOre extends Block } } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { if (this.isOn) { @@ -189,7 +191,7 @@ public class BlockRedstoneOre extends Block return true; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("redstone_ore").add().all(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("redstone_ore").add().all(); } } diff --git a/java/src/game/block/BlockRock.java b/common/src/main/java/common/block/natural/BlockRock.java similarity index 57% rename from java/src/game/block/BlockRock.java rename to common/src/main/java/common/block/natural/BlockRock.java index a457ece..92b0352 100755 --- a/java/src/game/block/BlockRock.java +++ b/common/src/main/java/common/block/natural/BlockRock.java @@ -1,23 +1,25 @@ -package game.block; +package common.block.natural; import java.util.List; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.renderer.blockmodel.ModelBlock; -import game.world.State; +import common.block.Block; +import common.block.Material; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.world.State; public class BlockRock extends Block { public static final PropertyBool SMOOTH = PropertyBool.create("smooth"); public BlockRock() { - super(Material.rock); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(SMOOTH, false)); - this.setTab(CheatTab.tabNature); + this.setTab(CheatTab.NATURE); } public int damageDropped(State state) { @@ -41,7 +43,7 @@ public class BlockRock extends Block { return new IProperty[] {SMOOTH}; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock(state.getValue(SMOOTH) ? "smooth_rock" : "rock").add().all(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(state.getValue(SMOOTH) ? "smooth_rock" : "rock").add().all(); } } diff --git a/java/src/game/block/BlockSand.java b/common/src/main/java/common/block/natural/BlockSand.java similarity index 82% rename from java/src/game/block/BlockSand.java rename to common/src/main/java/common/block/natural/BlockSand.java index 2739809..ae5d6cb 100755 --- a/java/src/game/block/BlockSand.java +++ b/common/src/main/java/common/block/natural/BlockSand.java @@ -1,15 +1,18 @@ -package game.block; +package common.block.natural; import java.util.List; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.world.State; +import common.block.BlockFalling; +import common.block.Material; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.util.Identifyable; +import common.world.State; public class BlockSand extends BlockFalling { @@ -17,7 +20,9 @@ public class BlockSand extends BlockFalling public BlockSand() { + super(Material.LOOSE); this.setDefaultState(this.getBaseState().withProperty(VARIANT, BlockSand.EnumType.SAND)); + this.setTab(CheatTab.NATURE); } /** @@ -69,11 +74,11 @@ public class BlockSand extends BlockFalling return new IProperty[] {VARIANT}; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock(state.getValue(VARIANT).getName()).add().all(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(state.getValue(VARIANT).getName()).add().all(); } - public static enum EnumType implements IStringSerializable + public static enum EnumType implements Identifyable { SAND(0, "sand", "Sand"), RED_SAND(1, "red_sand", "Roter Sand"); diff --git a/java/src/game/block/BlockSandStone.java b/common/src/main/java/common/block/natural/BlockSandStone.java similarity index 79% rename from java/src/game/block/BlockSandStone.java rename to common/src/main/java/common/block/natural/BlockSandStone.java index 5bbba58..ca1bcac 100755 --- a/java/src/game/block/BlockSandStone.java +++ b/common/src/main/java/common/block/natural/BlockSandStone.java @@ -1,16 +1,18 @@ -package game.block; +package common.block.natural; import java.util.List; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.world.State; +import common.block.Block; +import common.block.Material; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.util.Identifyable; +import common.world.State; public class BlockSandStone extends Block { @@ -18,9 +20,9 @@ public class BlockSandStone extends Block public BlockSandStone() { - super(Material.rock); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(TYPE, BlockSandStone.EnumType.DEFAULT)); - this.setTab(CheatTab.tabNature); + this.setTab(CheatTab.NATURE); } /** @@ -72,19 +74,19 @@ public class BlockSandStone extends Block return new IProperty[] {TYPE}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { switch(state.getValue(TYPE)) { case DEFAULT: default: - return new ModelBlock("sandstone_normal").add().nswe().d("sandstone_bottom").u("sandstone_all"); + return provider.getModel("sandstone_normal").add().nswe().d("sandstone_bottom").u("sandstone_all"); case CHISELED: - return new ModelBlock("sandstone_carved").add().nswe().d("sandstone_bottom").u("sandstone_all"); + return provider.getModel("sandstone_carved").add().nswe().d("sandstone_bottom").u("sandstone_all"); case SMOOTH: - return new ModelBlock("sandstone_smooth").add().nswe().d("sandstone_bottom").u("sandstone_all"); + return provider.getModel("sandstone_smooth").add().nswe().d("sandstone_bottom").u("sandstone_all"); } } - public static enum EnumType implements IStringSerializable + public static enum EnumType implements Identifyable { DEFAULT(0, "sandstone", "Sandstein"), CHISELED(1, "chiseled_sandstone", "Gemeißelter Sandstein"), diff --git a/common/src/main/java/common/block/natural/BlockSlime.java b/common/src/main/java/common/block/natural/BlockSlime.java new file mode 100755 index 0000000..1d1f6f6 --- /dev/null +++ b/common/src/main/java/common/block/natural/BlockSlime.java @@ -0,0 +1,63 @@ +package common.block.natural; + +import common.block.BlockTranslucent; +import common.block.Material; +import common.entity.Entity; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.util.BlockPos; +import common.world.State; +import common.world.World; + +public class BlockSlime extends BlockTranslucent { + private static final Model slime = ModelProvider.getModelProvider().getModel("slime") + .add(0, 0, 0, 16, 16, 16) + .d().uv(0, 0, 16, 16).noCull() + .u().uv(0, 0, 16, 16).noCull() + .n().uv(0, 0, 16, 16).noCull() + .s().uv(0, 0, 16, 16).noCull() + .w().uv(0, 0, 16, 16).noCull() + .e().uv(0, 0, 16, 16).noCull() + .add(3, 3, 3, 13, 13, 13) + .d().uv(3, 3, 13, 13).noCull() + .u().uv(3, 3, 13, 13).noCull() + .n().uv(3, 3, 13, 13).noCull() + .s().uv(3, 3, 13, 13).noCull() + .w().uv(3, 3, 13, 13).noCull() + .e().uv(3, 3, 13, 13).noCull() + ; + + public BlockSlime() { + super(Material.LOOSE); + this.setTab(CheatTab.TECHNOLOGY); + this.slipperiness = 0.8F; + } + + public void onFallenUpon(World world, BlockPos pos, Entity entity, float distance) { + if(entity.isSneaking()) + super.onFallenUpon(world, pos, entity, distance); + else + entity.fall(distance, 0.0F); + } + + public void onLanded(World world, Entity entity) { + if(entity.isSneaking()) + super.onLanded(world, entity); + else if(entity.motionY < 0.0D) + entity.motionY = -entity.motionY; + } + + public void onEntityCollidedWithBlock(World world, BlockPos pos, Entity entity) { + if(Math.abs(entity.motionY) < 0.1D && !entity.isSneaking()) { + double friction = 0.4D + Math.abs(entity.motionY) * 0.2D; + entity.motionX *= friction; + entity.motionZ *= friction; + } + super.onEntityCollidedWithBlock(world, pos, entity); + } + + public Model getModel(ModelProvider provider, String name, State state) { + return slime; + } +} diff --git a/java/src/game/block/BlockSnow.java b/common/src/main/java/common/block/natural/BlockSnow.java similarity index 76% rename from java/src/game/block/BlockSnow.java rename to common/src/main/java/common/block/natural/BlockSnow.java index bff067b..4a41240 100755 --- a/java/src/game/block/BlockSnow.java +++ b/common/src/main/java/common/block/natural/BlockSnow.java @@ -1,28 +1,30 @@ -package game.block; +package common.block.natural; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Config; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.LightType; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.vars.Vars; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.LightType; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockSnow extends Block { @@ -30,11 +32,11 @@ public class BlockSnow extends Block public BlockSnow() { - super(Material.snow); + super(Material.POWDER); this.setDefaultState(this.getBaseState().withProperty(LAYERS, Integer.valueOf(1))); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); this.setTickRandomly(); - this.setTab(CheatTab.tabDeco); + this.setTab(CheatTab.DECORATION); this.setBlockBoundsForItemRender(); } @@ -86,7 +88,7 @@ public class BlockSnow extends Block { State iblockstate = worldIn.getState(pos.down()); Block block = iblockstate.getBlock(); - return block != Blocks.ice && block != Blocks.packed_ice ? (block.getMaterial() == Material.leaves ? true : (block == this && ((Integer)iblockstate.getValue(LAYERS)).intValue() >= 7 ? true : block.isOpaqueCube() && block.material.blocksMovement())) : false; + return block != Blocks.ice && block != Blocks.packed_ice ? (block.getMaterial() == Material.LEAVES ? true : (block == this && ((Integer)iblockstate.getValue(LAYERS)).intValue() >= 7 ? true : block.isOpaqueCube() && block.getMaterial().blocksMovement())) : false; } /** @@ -134,9 +136,9 @@ public class BlockSnow extends Block return 0; } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { - if (Config.snowMelt && ((worldIn.getLightFor(LightType.BLOCK, pos) > 11) || !worldIn.canFreezeAt(pos))) + if (Vars.snowMelt && (worldIn.getLightFor(LightType.BLOCK, pos) > 11 || !worldIn.canFreezeAt(pos))) { this.dropBlockAsItem(worldIn, pos, worldIn.getState(pos), 0); worldIn.setBlockToAir(pos); @@ -181,9 +183,9 @@ public class BlockSnow extends Block return Transforms.LAYER; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { int height = state.getValue(LAYERS) * 2; - return height == 16 ? new ModelBlock("snow").add().all() : - new ModelBlock("snow").add(0, 0, 0, 16, height, 16).u().noCull().d().nswe().uv(0, 16 - height, 16, 16); + return height == 16 ? provider.getModel("snow").add().all() : + provider.getModel("snow").add(0, 0, 0, 16, height, 16).u().noCull().d().nswe().uv(0, 16 - height, 16, 16); } } diff --git a/common/src/main/java/common/block/natural/BlockSnowBlock.java b/common/src/main/java/common/block/natural/BlockSnowBlock.java new file mode 100755 index 0000000..0e9dd52 --- /dev/null +++ b/common/src/main/java/common/block/natural/BlockSnowBlock.java @@ -0,0 +1,36 @@ +package common.block.natural; + +import common.block.Block; +import common.block.Material; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.rng.Random; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.LightType; +import common.world.State; +import common.world.AWorldServer; + +public class BlockSnowBlock extends Block { + public BlockSnowBlock() { + super(Material.DIGGABLE); + this.setTickRandomly(); + this.setTab(CheatTab.NATURE); + } + + public Item getItemDropped(State state, Random rand, int fortune) { + return Items.snowball; + } + + public int quantityDropped(Random rand) { + return rand.range(2, 4); + } + + public void updateTick(AWorldServer world, BlockPos pos, State state, Random rand) { + if(Vars.snowFullMelt && (world.getLightFor(LightType.BLOCK, pos) > 11 || !world.canFreezeAt(pos))) { + this.dropBlockAsItem(world, pos, world.getState(pos), 0); + world.setBlockToAir(pos); + } + } +} diff --git a/common/src/main/java/common/block/natural/BlockSoulFire.java b/common/src/main/java/common/block/natural/BlockSoulFire.java new file mode 100644 index 0000000..9cacaeb --- /dev/null +++ b/common/src/main/java/common/block/natural/BlockSoulFire.java @@ -0,0 +1,18 @@ +package common.block.natural; + +import common.rng.Random; +import common.util.BlockPos; +import common.world.World; + +public class BlockSoulFire extends BlockTintedFire { + public BlockSoulFire() { + super(0x4010ff); + } + + protected void catchOnFire(World world, BlockPos pos, int chance, Random rand, int age) { + } + + protected boolean canDie(World world, BlockPos pos) { + return super.canDie(world, pos) || world.rand.chance(20); + } +} diff --git a/java/src/game/block/BlockSoulSand.java b/common/src/main/java/common/block/natural/BlockSoulSand.java similarity index 66% rename from java/src/game/block/BlockSoulSand.java rename to common/src/main/java/common/block/natural/BlockSoulSand.java index 70641d0..e521c5f 100755 --- a/java/src/game/block/BlockSoulSand.java +++ b/common/src/main/java/common/block/natural/BlockSoulSand.java @@ -1,19 +1,20 @@ -package game.block; +package common.block.natural; -import game.entity.Entity; -import game.item.CheatTab; -import game.material.Material; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.item.CheatTab; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.world.State; +import common.world.World; public class BlockSoulSand extends Block { public BlockSoulSand() { - super(Material.sand); - this.setTab(CheatTab.tabNature); + super(Material.LOOSE); + this.setTab(CheatTab.NATURE); } public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) diff --git a/common/src/main/java/common/block/natural/BlockStone.java b/common/src/main/java/common/block/natural/BlockStone.java new file mode 100755 index 0000000..7bb352a --- /dev/null +++ b/common/src/main/java/common/block/natural/BlockStone.java @@ -0,0 +1,21 @@ +package common.block.natural; + +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.item.CheatTab; +import common.item.Item; +import common.rng.Random; +import common.world.State; + +public class BlockStone extends Block { + public BlockStone() { + super(Material.SOLID); + this.setTab(CheatTab.NATURE); + } + + public Item getItemDropped(State state, Random rand, int fortune) { + return ItemRegistry.getItemFromBlock(Blocks.cobblestone); + } +} diff --git a/common/src/main/java/common/block/natural/BlockTintedFire.java b/common/src/main/java/common/block/natural/BlockTintedFire.java new file mode 100644 index 0000000..70e64c6 --- /dev/null +++ b/common/src/main/java/common/block/natural/BlockTintedFire.java @@ -0,0 +1,35 @@ +package common.block.natural; + +import java.util.Map; + +import common.model.Model; +import common.model.ModelProvider; +import common.util.BlockPos; +import common.world.IWorldAccess; +import common.world.State; + +public class BlockTintedFire extends BlockFire { + private final int tint; + + public BlockTintedFire(int tint) { + this.tint = tint; + } + + public int getRenderColor(State state) { + return this.tint; + } + + public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass) { + return this.tint; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return getFireModel(state.getValue(ALT) ? "flame_layer_1" : "flame_layer_0", state.getValue(FLIP), state.getValue(UPPER), + state.getValue(NORTH), state.getValue(SOUTH), state.getValue(WEST), state.getValue(EAST)); + } + + public void getAnimatedTextures(Map map) { + map.put("blocks/flame_layer_0", "flame1"); + map.put("blocks/flame_layer_1", "flame2"); + } +} diff --git a/java/src/game/block/BlockWeb.java b/common/src/main/java/common/block/natural/BlockWeb.java similarity index 61% rename from java/src/game/block/BlockWeb.java rename to common/src/main/java/common/block/natural/BlockWeb.java index e7cf5c4..4dbaf5d 100755 --- a/java/src/game/block/BlockWeb.java +++ b/common/src/main/java/common/block/natural/BlockWeb.java @@ -1,24 +1,26 @@ -package game.block; +package common.block.natural; -import game.entity.Entity; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.init.Items; +import common.item.CheatTab; +import common.item.Item; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.world.State; +import common.world.World; public class BlockWeb extends Block { public BlockWeb() { - super(Material.web); - this.setTab(CheatTab.tabDeco); + super(Material.FLUFF); + this.setTab(CheatTab.DECORATION); } /** @@ -65,7 +67,7 @@ public class BlockWeb extends Block return BlockLayer.CUTOUT; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("web").cross(); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("web").cross(); } } diff --git a/java/src/game/block/BlockAnvil.java b/common/src/main/java/common/block/tech/BlockAnvil.java similarity index 84% rename from java/src/game/block/BlockAnvil.java rename to common/src/main/java/common/block/tech/BlockAnvil.java index ef79ee3..8a00352 100755 --- a/java/src/game/block/BlockAnvil.java +++ b/common/src/main/java/common/block/tech/BlockAnvil.java @@ -1,29 +1,31 @@ -package game.block; +package common.block.tech; import java.util.List; -import game.entity.item.EntityFalling; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.inventory.Container; -import game.inventory.ContainerRepair; -import game.inventory.InventoryPlayer; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.tileentity.IInteractionObject; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.BlockFalling; +import common.block.Material; +import common.entity.item.EntityFalling; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.inventory.Container; +import common.inventory.ContainerRepair; +import common.inventory.InventoryPlayer; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.Transforms; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.properties.PropertyInteger; +import common.tileentity.IInteractionObject; +import common.util.BlockPos; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockAnvil extends BlockFalling { @@ -32,10 +34,10 @@ public class BlockAnvil extends BlockFalling public BlockAnvil() { - super(Material.anvil); + super(Material.HEAVY); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(DAMAGE, Integer.valueOf(0))); this.setLightOpacity(0); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); } public boolean isFullCube() @@ -155,8 +157,8 @@ public class BlockAnvil extends BlockFalling return Transforms.ANVIL; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("anvil_base") + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("anvil_base") .add(2, 0, 2, 14, 4, 14).d().uv(2, 2, 14, 14).rot(180).u().uv(2, 2, 14, 14).rot(180).noCull() .ns().uv(2, 12, 14, 16).noCull().w().uv(0, 2, 4, 14).rot(90).noCull().e().uv(4, 2, 0, 14).rot(270).noCull() .add(4, 4, 3, 12, 5, 13).du().uv(4, 3, 12, 13).rot(180).noCull() diff --git a/java/src/game/block/BlockBasePressurePlate.java b/common/src/main/java/common/block/tech/BlockBasePressurePlate.java similarity index 86% rename from java/src/game/block/BlockBasePressurePlate.java rename to common/src/main/java/common/block/tech/BlockBasePressurePlate.java index 38057fd..a920fbe 100755 --- a/java/src/game/block/BlockBasePressurePlate.java +++ b/common/src/main/java/common/block/tech/BlockBasePressurePlate.java @@ -1,26 +1,29 @@ -package game.block; +package common.block.tech; -import game.entity.Entity; -import game.init.SoundEvent; -import game.item.CheatTab; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.artificial.BlockFence; +import common.entity.Entity; +import common.init.SoundEvent; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public abstract class BlockBasePressurePlate extends Block { public BlockBasePressurePlate(Material p_i46401_1_) { super(p_i46401_1_); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); // this.setTickRandomly(true); } @@ -108,11 +111,11 @@ public abstract class BlockBasePressurePlate extends Block /** * Called randomly when setTickRandomly is set to true (used by e.g. crops to grow, etc.) */ - public void randomTick(WorldServer worldIn, BlockPos pos, State state, Random random) + public void randomTick(AWorldServer worldIn, BlockPos pos, State state, Random random) { } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { // if (!worldIn.client) // { @@ -182,7 +185,7 @@ public abstract class BlockBasePressurePlate extends Block return new BoundingBox((double)((float)pos.getX() + 0.125F), (double)pos.getY(), (double)((float)pos.getZ() + 0.125F), (double)((float)(pos.getX() + 1) - 0.125F), (double)pos.getY() + 0.25D, (double)((float)(pos.getZ() + 1) - 0.125F)); } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { if (this.getRedstoneStrength(state) > 0) { @@ -235,9 +238,9 @@ public abstract class BlockBasePressurePlate extends Block return 1; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { if(this.getRedstoneStrength(state) > 0) - return new ModelBlock(this.getTexture()) + return provider.getModel(this.getTexture()) .add(1, 0, 1, 15, 0.5f, 15) .d().uv(1, 1, 15, 15) .u().uv(1, 1, 15, 15).noCull() @@ -246,7 +249,7 @@ public abstract class BlockBasePressurePlate extends Block .w().uv(1, 15.5f, 15, 16).noCull() .e().uv(1, 15.5f, 15, 16).noCull(); else - return new ModelBlock(this.getTexture()) + return provider.getModel(this.getTexture()) .add(1, 0, 1, 15, 1, 15) .d().uv(1, 1, 15, 15) .u().uv(1, 1, 15, 15).noCull() diff --git a/java/src/game/block/BlockBeacon.java b/common/src/main/java/common/block/tech/BlockBeacon.java similarity index 81% rename from java/src/game/block/BlockBeacon.java rename to common/src/main/java/common/block/tech/BlockBeacon.java index 000cd97..83986bc 100755 --- a/java/src/game/block/BlockBeacon.java +++ b/common/src/main/java/common/block/tech/BlockBeacon.java @@ -1,20 +1,23 @@ -package game.block; +package common.block.tech; -import game.entity.npc.EntityNPC; -import game.item.CheatTab; -import game.material.Material; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityBeacon; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.BlockContainer; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.item.CheatTab; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityBeacon; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; public class BlockBeacon extends BlockContainer { - private static final ModelBlock beacon = new ModelBlock("glass").noOcclude() + private static final Model beacon = ModelProvider.getModelProvider().getModel("glass") .add(0, 0, 0, 16, 16, 16) .d().uv(0, 0, 16, 16).noCull() .u().uv(0, 0, 16, 16).noCull() @@ -40,15 +43,15 @@ public class BlockBeacon extends BlockContainer public BlockBeacon() { - super(Material.glass); + super(Material.TRANSLUCENT); this.setHardness(3.0F); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); } /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return new TileEntityBeacon(); } @@ -131,7 +134,7 @@ public class BlockBeacon extends BlockContainer return BlockLayer.CUTOUT; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { return beacon; } } diff --git a/java/src/game/block/BlockBrewingStand.java b/common/src/main/java/common/block/tech/BlockBrewingStand.java similarity index 89% rename from java/src/game/block/BlockBrewingStand.java rename to common/src/main/java/common/block/tech/BlockBrewingStand.java index 7fafe33..bcde12f 100755 --- a/java/src/game/block/BlockBrewingStand.java +++ b/common/src/main/java/common/block/tech/BlockBrewingStand.java @@ -1,35 +1,37 @@ -package game.block; +package common.block.tech; import java.util.List; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.inventory.Container; -import game.inventory.InventoryHelper; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityBrewingStand; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.BlockContainer; +import common.block.Material; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.inventory.Container; +import common.inventory.InventoryHelper; +import common.item.Item; +import common.item.ItemStack; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ParticleType; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityBrewingStand; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockBrewingStand extends BlockContainer { - private static final ModelBlock brewing_stand_bottles_2 = new ModelBlock("brewing_stand") + private static final Model brewing_stand_bottles_2 = ModelProvider.getModelProvider().getModel("brewing_stand") .add(7, 0, 7, 9, 14, 9) .d().uv(7, 7, 9, 9).noCull() .u().uv(7, 7, 9, 9).noCull() @@ -68,7 +70,7 @@ public class BlockBrewingStand extends BlockContainer .n().uv(8, 0, 0, 16).noCull() .s().uv(0, 0, 8, 16).noCull() ; - private static final ModelBlock brewing_stand_bottles_123 = new ModelBlock("brewing_stand") + private static final Model brewing_stand_bottles_123 = ModelProvider.getModelProvider().getModel("brewing_stand") .add(7, 0, 7, 9, 14, 9) .d().uv(7, 7, 9, 9).noCull() .u().uv(7, 7, 9, 9).noCull() @@ -107,7 +109,7 @@ public class BlockBrewingStand extends BlockContainer .n().uv(8, 0, 0, 16).noCull() .s().uv(0, 0, 8, 16).noCull() ; - private static final ModelBlock brewing_stand_empty = new ModelBlock("brewing_stand") + private static final Model brewing_stand_empty = ModelProvider.getModelProvider().getModel("brewing_stand") .add(7, 0, 7, 9, 14, 9) .d().uv(7, 7, 9, 9).noCull() .u().uv(7, 7, 9, 9).noCull() @@ -146,7 +148,7 @@ public class BlockBrewingStand extends BlockContainer .n().uv(8, 0, 16, 16).noCull() .s().uv(16, 0, 8, 16).noCull() ; - private static final ModelBlock brewing_stand_bottles_3 = new ModelBlock("brewing_stand") + private static final Model brewing_stand_bottles_3 = ModelProvider.getModelProvider().getModel("brewing_stand") .add(7, 0, 7, 9, 14, 9) .d().uv(7, 7, 9, 9).noCull() .u().uv(7, 7, 9, 9).noCull() @@ -185,7 +187,7 @@ public class BlockBrewingStand extends BlockContainer .n().uv(8, 0, 16, 16).noCull() .s().uv(16, 0, 8, 16).noCull() ; - private static final ModelBlock brewing_stand_bottles_13 = new ModelBlock("brewing_stand") + private static final Model brewing_stand_bottles_13 = ModelProvider.getModelProvider().getModel("brewing_stand") .add(7, 0, 7, 9, 14, 9) .d().uv(7, 7, 9, 9).noCull() .u().uv(7, 7, 9, 9).noCull() @@ -224,7 +226,7 @@ public class BlockBrewingStand extends BlockContainer .n().uv(8, 0, 16, 16).noCull() .s().uv(16, 0, 8, 16).noCull() ; - private static final ModelBlock brewing_stand_bottles_12 = new ModelBlock("brewing_stand") + private static final Model brewing_stand_bottles_12 = ModelProvider.getModelProvider().getModel("brewing_stand") .add(7, 0, 7, 9, 14, 9) .d().uv(7, 7, 9, 9).noCull() .u().uv(7, 7, 9, 9).noCull() @@ -263,7 +265,7 @@ public class BlockBrewingStand extends BlockContainer .n().uv(8, 0, 0, 16).noCull() .s().uv(0, 0, 8, 16).noCull() ; - private static final ModelBlock brewing_stand_bottles_23 = new ModelBlock("brewing_stand") + private static final Model brewing_stand_bottles_23 = ModelProvider.getModelProvider().getModel("brewing_stand") .add(7, 0, 7, 9, 14, 9) .d().uv(7, 7, 9, 9).noCull() .u().uv(7, 7, 9, 9).noCull() @@ -302,7 +304,7 @@ public class BlockBrewingStand extends BlockContainer .n().uv(8, 0, 0, 16).noCull() .s().uv(0, 0, 8, 16).noCull() ; - private static final ModelBlock brewing_stand_bottles_1 = new ModelBlock("brewing_stand") + private static final Model brewing_stand_bottles_1 = ModelProvider.getModelProvider().getModel("brewing_stand") .add(7, 0, 7, 9, 14, 9) .d().uv(7, 7, 9, 9).noCull() .u().uv(7, 7, 9, 9).noCull() @@ -341,7 +343,7 @@ public class BlockBrewingStand extends BlockContainer .n().uv(8, 0, 16, 16).noCull() .s().uv(16, 0, 8, 16).noCull() ; - private static final ModelBlock[] brewing_stand_bottles = new ModelBlock[] { + private static final Model[] brewing_stand_bottles = new Model[] { brewing_stand_empty, brewing_stand_bottles_1, brewing_stand_bottles_2, brewing_stand_bottles_12, brewing_stand_bottles_3, brewing_stand_bottles_13, brewing_stand_bottles_23, brewing_stand_bottles_123 }; @@ -350,7 +352,7 @@ public class BlockBrewingStand extends BlockContainer public BlockBrewingStand() { - super(Material.iron); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(HAS_BOTTLE[0], Boolean.valueOf(false)).withProperty(HAS_BOTTLE[1], Boolean.valueOf(false)).withProperty(HAS_BOTTLE[2], Boolean.valueOf(false))); } @@ -381,7 +383,7 @@ public class BlockBrewingStand extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return new TileEntityBrewingStand(); } @@ -446,7 +448,7 @@ public class BlockBrewingStand extends BlockContainer } } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { double d0 = (double)((float)pos.getX() + 0.4F + rand.floatv() * 0.2F); double d1 = (double)((float)pos.getY() + 0.7F + rand.floatv() * 0.3F); @@ -454,7 +456,7 @@ public class BlockBrewingStand extends BlockContainer worldIn.spawnParticle(ParticleType.SMOKE_NORMAL, d0, d1, d2, 0.0D, 0.0D, 0.0D); } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { TileEntity tileentity = worldIn.getTileEntity(pos); @@ -536,7 +538,7 @@ public class BlockBrewingStand extends BlockContainer return true; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { return brewing_stand_bottles[(state.getValue(HAS_BOTTLE[0]) ? 1 : 0) | (state.getValue(HAS_BOTTLE[1]) ? 2 : 0) | (state.getValue(HAS_BOTTLE[2]) ? 4 : 0)]; } diff --git a/java/src/game/block/BlockButton.java b/common/src/main/java/common/block/tech/BlockButton.java similarity index 90% rename from java/src/game/block/BlockButton.java rename to common/src/main/java/common/block/tech/BlockButton.java index f98c869..956d0fe 100755 --- a/java/src/game/block/BlockButton.java +++ b/common/src/main/java/common/block/tech/BlockButton.java @@ -1,30 +1,31 @@ -package game.block; +package common.block.tech; import java.util.List; -import game.collect.Lists; - -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityArrow; -import game.entity.types.EntityLiving; -import game.init.SoundEvent; -import game.item.CheatTab; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyDirection; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.collect.Lists; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityArrow; +import common.entity.types.EntityLiving; +import common.init.SoundEvent; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.Transforms; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyDirection; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockButton extends Block { @@ -38,10 +39,10 @@ public class BlockButton extends Block public BlockButton(boolean arrows, int onTime, String texture) { - super(Material.circuits); + super(Material.SMALL); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(POWERED, Boolean.valueOf(false))); // this.setTickRandomly(true); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); this.checkArrows = arrows; this.onTime = onTime; this.texture = texture; @@ -195,7 +196,7 @@ public class BlockButton extends Block } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { if (((Boolean)state.getValue(POWERED)).booleanValue()) { @@ -226,11 +227,11 @@ public class BlockButton extends Block /** * Called randomly when setTickRandomly is set to true (used by e.g. crops to grow, etc.) */ - public void randomTick(WorldServer worldIn, BlockPos pos, State state, Random random) + public void randomTick(AWorldServer worldIn, BlockPos pos, State state, Random random) { } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { // if (!worldIn.client) // { @@ -428,9 +429,9 @@ public class BlockButton extends Block return this.texture; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { boolean pressed = state.getValue(POWERED); - return new ModelBlock(this.texture).add(5, 0, 6, 11, pressed ? 1 : 2, 10) + return provider.getModel(this.texture).add(5, 0, 6, 11, pressed ? 1 : 2, 10) .d().uv(5, 6, 11, 10).u().uv(5, 10, 11, 6).noCull() .ns().uv(5, pressed ? 15 : 14, 11, 16).noCull().we().uv(6, pressed ? 15 : 14, 10, 16).noCull() .rotate(getRotation(state.getValue(FACING))); diff --git a/java/src/game/block/BlockCauldron.java b/common/src/main/java/common/block/tech/BlockCauldron.java similarity index 92% rename from java/src/game/block/BlockCauldron.java rename to common/src/main/java/common/block/tech/BlockCauldron.java index aa8d2c6..087c865 100755 --- a/java/src/game/block/BlockCauldron.java +++ b/common/src/main/java/common/block/tech/BlockCauldron.java @@ -1,33 +1,35 @@ -package game.block; +package common.block.tech; import java.util.List; -import game.entity.Entity; -import game.entity.item.EntityItem; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.FluidRegistry; -import game.init.Items; -import game.item.Item; -import game.item.ItemArmor; -import game.item.ItemBanner; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.tileentity.TileEntityBanner; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.entity.item.EntityItem; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.FluidRegistry; +import common.init.Items; +import common.item.Item; +import common.item.ItemArmor; +import common.item.ItemBanner; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.tileentity.TileEntityBanner; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Facing; +import common.world.State; +import common.world.World; public class BlockCauldron extends Block { - private static final ModelBlock cauldron_empty = new ModelBlock("cauldron_side").noOcclude() + private static final Model cauldron_empty = ModelProvider.getModelProvider().getModel("cauldron_side") .add(0, 3, 0, 2, 16, 16) .d("cauldron_inner").uv(0, 0, 2, 16) .u("cauldron_top").uv(0, 0, 2, 16) @@ -120,7 +122,7 @@ public class BlockCauldron extends Block .w().uv(14, 13, 12, 16).noCull() .e().uv(14, 13, 12, 16).noCull() ; - private static final ModelBlock cauldron_level1 = new ModelBlock("cauldron_side").noOcclude() + private static final Model cauldron_level1 = ModelProvider.getModelProvider().getModel("cauldron_side") .add(0, 3, 0, 2, 16, 16) .d("cauldron_inner").uv(0, 0, 2, 16) .u("cauldron_top").uv(0, 0, 2, 16) @@ -215,7 +217,7 @@ public class BlockCauldron extends Block .add(2, 9, 2, 14, 9, 14) .u("water_still").uv(2, 2, 14, 14).noCull() ; - private static final ModelBlock cauldron_level2 = new ModelBlock("cauldron_side").noOcclude() + private static final Model cauldron_level2 = ModelProvider.getModelProvider().getModel("cauldron_side") .add(0, 3, 0, 2, 16, 16) .d("cauldron_inner").uv(0, 0, 2, 16) .u("cauldron_top").uv(0, 0, 2, 16) @@ -310,7 +312,7 @@ public class BlockCauldron extends Block .add(2, 12, 2, 14, 12, 14) .u("water_still").uv(2, 2, 14, 14).noCull() ; - private static final ModelBlock cauldron_level3 = new ModelBlock("cauldron_side").noOcclude() + private static final Model cauldron_level3 = ModelProvider.getModelProvider().getModel("cauldron_side") .add(0, 3, 0, 2, 16, 16) .d("cauldron_inner").uv(0, 0, 2, 16) .u("cauldron_top").uv(0, 0, 2, 16) @@ -405,14 +407,14 @@ public class BlockCauldron extends Block .add(2, 15, 2, 14, 15, 14) .u("water_still").uv(2, 2, 14, 14).noCull() ; - private static final ModelBlock[] cauldron_levels = - new ModelBlock[] {cauldron_empty, cauldron_level1, cauldron_level2, cauldron_level3}; + private static final Model[] cauldron_levels = + new Model[] {cauldron_empty, cauldron_level1, cauldron_level2, cauldron_level3}; public static final PropertyInteger LEVEL = PropertyInteger.create("level", 0, 3); public BlockCauldron() { - super(Material.iron); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(LEVEL, Integer.valueOf(0))); } @@ -523,9 +525,9 @@ public class BlockCauldron extends Block } // playerIn.triggerAchievement(StatRegistry.cauldronUsedStat); - --itemstack.stackSize; + --itemstack.size; - if (itemstack.stackSize <= 0) + if (itemstack.size <= 0) { playerIn.inventory.setInventorySlotContents(playerIn.inventory.currentItem, (ItemStack)null); } @@ -554,10 +556,10 @@ public class BlockCauldron extends Block if (i > 0 && item instanceof ItemBanner && TileEntityBanner.getPatterns(itemstack) > 0) { ItemStack itemstack1 = itemstack.copy(); - itemstack1.stackSize = 1; + itemstack1.size = 1; TileEntityBanner.removeBannerData(itemstack1); - if (itemstack.stackSize <= 1) // && !playerIn.creative) + if (itemstack.size <= 1) // && !playerIn.creative) { playerIn.inventory.setInventorySlotContents(playerIn.inventory.currentItem, itemstack1); } @@ -576,7 +578,7 @@ public class BlockCauldron extends Block // if (!playerIn.creative) // { - --itemstack.stackSize; + --itemstack.size; // } } @@ -666,7 +668,7 @@ public class BlockCauldron extends Block return true; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { return cauldron_levels[state.getValue(LEVEL)]; } } diff --git a/java/src/game/block/BlockChest.java b/common/src/main/java/common/block/tech/BlockChest.java similarity index 90% rename from java/src/game/block/BlockChest.java rename to common/src/main/java/common/block/tech/BlockChest.java index bcb3356..75d977d 100755 --- a/java/src/game/block/BlockChest.java +++ b/common/src/main/java/common/block/tech/BlockChest.java @@ -1,35 +1,37 @@ -package game.block; +package common.block.tech; -import game.color.TextColor; -import game.entity.Entity; -import game.entity.animal.EntityOcelot; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Config; -import game.init.Items; -import game.init.SoundEvent; -import game.inventory.Container; -import game.inventory.IInventory; -import game.inventory.InventoryHelper; -import game.inventory.InventoryLargeChest; -import game.item.CheatTab; -import game.item.ItemStack; -import game.material.Material; -import game.packet.S29PacketSoundEffect; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.tileentity.ILockableContainer; -import game.tileentity.LockCode; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityChest; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockContainer; +import common.block.Material; +import common.color.TextColor; +import common.entity.Entity; +import common.entity.animal.EntityOcelot; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.init.SoundEvent; +import common.inventory.Container; +import common.inventory.IInventory; +import common.inventory.InventoryHelper; +import common.inventory.InventoryLargeChest; +import common.item.CheatTab; +import common.item.ItemStack; +import common.packet.SPacketSoundEffect; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.tileentity.ILockableContainer; +import common.tileentity.Passcode; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityChest; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Facing; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockChest extends BlockContainer { @@ -40,10 +42,10 @@ public class BlockChest extends BlockContainer public BlockChest(int type) { - super(Material.wood); + super(Material.WOOD); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); this.chestType = type; - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); } @@ -92,7 +94,7 @@ public class BlockChest extends BlockContainer } } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { this.checkForSurroundingChests(worldIn, pos, state); @@ -416,7 +418,7 @@ public class BlockChest extends BlockContainer } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { TileEntity tileentity = worldIn.getTileEntity(pos); @@ -441,22 +443,22 @@ public class BlockChest extends BlockContainer if (ilockablecontainer != null) { - ItemStack stack = Config.locking ? playerIn.getHeldItem() : null; + ItemStack stack = Vars.locking ? playerIn.getHeldItem() : null; if(stack != null && stack.getItem() == Items.key) { if(ilockablecontainer.isLocked()) { - if(stack.hasDisplayName() && stack.getDisplayName().equals(ilockablecontainer.getLockCode().getLock())) { - ilockablecontainer.setLockCode(LockCode.EMPTY_CODE); + if(stack.hasDisplayName() && stack.getDisplayName().equals(ilockablecontainer.getLockCode().code())) { + ilockablecontainer.setLockCode(Passcode.EMPTY_CODE); // playerIn.triggerAchievement(StatRegistry.chestUnlockedStat); playerIn.connection.addHotbar(TextColor.BLUE + "%s wurde entriegelt", ilockablecontainer.getCommandName()); - playerIn.connection.sendPacket(new S29PacketSoundEffect(SoundEvent.DOOR, playerIn.posX, playerIn.posY, playerIn.posZ, 1.0F)); + playerIn.connection.sendPacket(new SPacketSoundEffect(SoundEvent.DOOR, playerIn.posX, playerIn.posY, playerIn.posZ, 1.0F)); return true; } } else if(stack.hasDisplayName()) { - ilockablecontainer.setLockCode(new LockCode(stack.getDisplayName())); + ilockablecontainer.setLockCode(new Passcode(stack.getDisplayName())); // playerIn.triggerAchievement(StatRegistry.chestLockedStat); playerIn.connection.addHotbar(TextColor.ORANGE + "%s wurde verriegelt", ilockablecontainer.getCommandName()); - playerIn.connection.sendPacket(new S29PacketSoundEffect(SoundEvent.DOOR, playerIn.posX, playerIn.posY, playerIn.posZ, 1.0F)); + playerIn.connection.sendPacket(new SPacketSoundEffect(SoundEvent.DOOR, playerIn.posX, playerIn.posY, playerIn.posZ, 1.0F)); return true; } } @@ -530,7 +532,7 @@ public class BlockChest extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return new TileEntityChest(); } diff --git a/common/src/main/java/common/block/tech/BlockCore.java b/common/src/main/java/common/block/tech/BlockCore.java new file mode 100755 index 0000000..131e2e7 --- /dev/null +++ b/common/src/main/java/common/block/tech/BlockCore.java @@ -0,0 +1,28 @@ +package common.block.tech; + +import common.block.Block; +import common.block.Material; +import common.item.CheatTab; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.AWorldServer; + +public class BlockCore extends Block { + public BlockCore() { + super(Material.SOLID); + this.setTab(CheatTab.TECHNOLOGY); + } + + public void onBlockRemoved(AWorldServer world, BlockPos pos, State state) + { + if(Vars.loaders) + world.removeLoader(pos); + } + + public void onBlockAdded(AWorldServer world, BlockPos pos, State state) + { + if(Vars.loaders) + world.addLoader(pos); + } +} diff --git a/java/src/game/block/BlockDaylightDetector.java b/common/src/main/java/common/block/tech/BlockDaylightDetector.java similarity index 78% rename from java/src/game/block/BlockDaylightDetector.java rename to common/src/main/java/common/block/tech/BlockDaylightDetector.java index ca7d156..f35f530 100755 --- a/java/src/game/block/BlockDaylightDetector.java +++ b/common/src/main/java/common/block/tech/BlockDaylightDetector.java @@ -1,30 +1,32 @@ -package game.block; +package common.block.tech; import java.util.List; -import game.audio.SoundType; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.ItemRegistry; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityDaylightDetector; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.LightType; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.BlockContainer; +import common.block.Material; +import common.block.SoundType; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityDaylightDetector; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.LightType; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockDaylightDetector extends BlockContainer { @@ -33,11 +35,11 @@ public class BlockDaylightDetector extends BlockContainer public BlockDaylightDetector(boolean inverted) { - super(Material.wood); + super(Material.WOOD); this.inverted = inverted; this.setDefaultState(this.getBaseState().withProperty(POWER, Integer.valueOf(0))); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.375F, 1.0F); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); this.setHardness(0.2F); this.setStepSound(SoundType.WOOD); // this.setDisplay("daylightDetector"); @@ -53,7 +55,7 @@ public class BlockDaylightDetector extends BlockContainer return ((Integer)state.getValue(POWER)).intValue(); } - public void updatePower(WorldServer worldIn, BlockPos pos) + public void updatePower(AWorldServer worldIn, BlockPos pos) { if (!worldIn.dimension.hasNoLight()) { @@ -90,12 +92,12 @@ public class BlockDaylightDetector extends BlockContainer if (this.inverted) { worldIn.setState(pos, Blocks.daylight_detector.getState().withProperty(POWER, state.getValue(POWER)), 4); - Blocks.daylight_detector.updatePower((WorldServer)worldIn, pos); + Blocks.daylight_detector.updatePower((AWorldServer)worldIn, pos); } else { worldIn.setState(pos, Blocks.daylight_detector_inverted.getState().withProperty(POWER, state.getValue(POWER)), 4); - Blocks.daylight_detector_inverted.updatePower((WorldServer)worldIn, pos); + Blocks.daylight_detector_inverted.updatePower((AWorldServer)worldIn, pos); } return true; @@ -152,7 +154,7 @@ public class BlockDaylightDetector extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return new TileEntityDaylightDetector(); } @@ -193,8 +195,8 @@ public class BlockDaylightDetector extends BlockContainer return Transforms.FLAT; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock(this.inverted ? "daylight_detector_inverted_top" : "daylight_detector_top") + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel(this.inverted ? "daylight_detector_inverted_top" : "daylight_detector_top") .add(0, 0, 0, 16, 6, 16) .d("daylight_detector_side").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() diff --git a/java/src/game/block/BlockDispenser.java b/common/src/main/java/common/block/tech/BlockDispenser.java similarity index 82% rename from java/src/game/block/BlockDispenser.java rename to common/src/main/java/common/block/tech/BlockDispenser.java index 2cce3ee..4421fbb 100755 --- a/java/src/game/block/BlockDispenser.java +++ b/common/src/main/java/common/block/tech/BlockDispenser.java @@ -1,33 +1,37 @@ -package game.block; +package common.block.tech; -import game.dispenser.BehaviorDefaultDispenseItem; -import game.dispenser.IBehaviorDispenseItem; -import game.dispenser.IBlockSource; -import game.dispenser.IPosition; -import game.dispenser.PositionImpl; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.DispenserRegistry; -import game.init.RegistryDefaulted; -import game.inventory.Container; -import game.inventory.InventoryHelper; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyDirection; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityDispenser; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockContainer; +import common.block.Material; +import common.dispenser.BehaviorDefaultDispenseItem; +import common.dispenser.IBehaviorDispenseItem; +import common.dispenser.IBlockSource; +import common.dispenser.IPosition; +import common.dispenser.DispenserPos; +import common.dispenser.DispenserSource; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.DispenserRegistry; +import common.inventory.Container; +import common.inventory.InventoryHelper; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyDirection; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityDispenser; +import common.util.BlockPos; +import common.util.Facing; +import common.util.RegistryDefaulted; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockDispenser extends BlockContainer { @@ -38,9 +42,9 @@ public class BlockDispenser extends BlockContainer public BlockDispenser() { - super(Material.rock); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(TRIGGERED, Boolean.valueOf(false))); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); } /** @@ -51,7 +55,7 @@ public class BlockDispenser extends BlockContainer return 4; } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { super.onBlockAdded(worldIn, pos, state); this.setDefaultDirection(worldIn, pos, state); @@ -122,7 +126,7 @@ public class BlockDispenser extends BlockContainer protected void dispense(World worldIn, BlockPos pos) { - BlockSourceImpl blocksourceimpl = new BlockSourceImpl(worldIn, pos); + DispenserSource blocksourceimpl = new DispenserSource(worldIn, pos); TileEntityDispenser tileentitydispenser = (TileEntityDispenser)blocksourceimpl.getBlockTileEntity(); if (tileentitydispenser != null) @@ -141,7 +145,7 @@ public class BlockDispenser extends BlockContainer if (ibehaviordispenseitem != IBehaviorDispenseItem.itemDispenseBehaviorProvider) { ItemStack itemstack1 = ibehaviordispenseitem.dispense(blocksourceimpl, itemstack); - tileentitydispenser.setInventorySlotContents(i, itemstack1.stackSize <= 0 ? null : itemstack1); + tileentitydispenser.setInventorySlotContents(i, itemstack1.size <= 0 ? null : itemstack1); } } } @@ -171,7 +175,7 @@ public class BlockDispenser extends BlockContainer } } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { // if (!worldIn.client) // { @@ -182,7 +186,7 @@ public class BlockDispenser extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return new TileEntityDispenser(); } @@ -214,7 +218,7 @@ public class BlockDispenser extends BlockContainer } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { TileEntity tileentity = worldIn.getTileEntity(pos); @@ -236,7 +240,7 @@ public class BlockDispenser extends BlockContainer double d0 = coords.getX() + 0.7D * (double)enumfacing.getFrontOffsetX(); double d1 = coords.getY() + 0.7D * (double)enumfacing.getFrontOffsetY(); double d2 = coords.getZ() + 0.7D * (double)enumfacing.getFrontOffsetZ(); - return new PositionImpl(d0, d1, d2); + return new DispenserPos(d0, d1, d2); } /** @@ -306,12 +310,12 @@ public class BlockDispenser extends BlockContainer return true; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { if(state.getValue(FACING) == Facing.DOWN || state.getValue(FACING) == Facing.UP) - return new ModelBlock("furnace_top").add().dnswe().u(name + "_front_vertical") + return provider.getModel("furnace_top").add().dnswe().u(name + "_front_vertical") .rotate(state.getValue(FACING) == Facing.DOWN ? ModelRotation.X180_Y0 : ModelRotation.X0_Y0); else - return new ModelBlock(name + "_front_horizontal").add().du("furnace_top").n() + return provider.getModel(name + "_front_horizontal").add().du("furnace_top").n() .s("furnace_side").we("furnace_side").rotate(ModelRotation.getNorthRot(state.getValue(FACING))); } diff --git a/java/src/game/block/BlockDropper.java b/common/src/main/java/common/block/tech/BlockDropper.java similarity index 76% rename from java/src/game/block/BlockDropper.java rename to common/src/main/java/common/block/tech/BlockDropper.java index 668378a..8d2f890 100755 --- a/java/src/game/block/BlockDropper.java +++ b/common/src/main/java/common/block/tech/BlockDropper.java @@ -1,16 +1,17 @@ -package game.block; +package common.block.tech; -import game.dispenser.BehaviorDefaultDispenseItem; -import game.dispenser.IBehaviorDispenseItem; -import game.inventory.IInventory; -import game.item.ItemStack; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityDispenser; -import game.tileentity.TileEntityDropper; -import game.tileentity.TileEntityHopper; -import game.world.BlockPos; -import game.world.Facing; -import game.world.World; +import common.dispenser.BehaviorDefaultDispenseItem; +import common.dispenser.DispenserSource; +import common.dispenser.IBehaviorDispenseItem; +import common.inventory.IInventory; +import common.item.ItemStack; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityDispenser; +import common.tileentity.TileEntityDropper; +import common.tileentity.TileEntityHopper; +import common.util.BlockPos; +import common.util.Facing; +import common.world.World; public class BlockDropper extends BlockDispenser { @@ -24,14 +25,14 @@ public class BlockDropper extends BlockDispenser /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return new TileEntityDropper(); } protected void dispense(World worldIn, BlockPos pos) { - BlockSourceImpl blocksourceimpl = new BlockSourceImpl(worldIn, pos); + DispenserSource blocksourceimpl = new DispenserSource(worldIn, pos); TileEntityDispenser tileentitydispenser = (TileEntityDispenser)blocksourceimpl.getBlockTileEntity(); if (tileentitydispenser != null) @@ -57,7 +58,7 @@ public class BlockDropper extends BlockDispenser { itemstack1 = this.dropBehavior.dispense(blocksourceimpl, itemstack); - if (itemstack1 != null && itemstack1.stackSize <= 0) + if (itemstack1 != null && itemstack1.size <= 0) { itemstack1 = null; } @@ -70,7 +71,7 @@ public class BlockDropper extends BlockDispenser { itemstack1 = itemstack.copy(); - if (--itemstack1.stackSize <= 0) + if (--itemstack1.size <= 0) { itemstack1 = null; } diff --git a/java/src/game/block/BlockEnchantmentTable.java b/common/src/main/java/common/block/tech/BlockEnchantmentTable.java similarity index 76% rename from java/src/game/block/BlockEnchantmentTable.java rename to common/src/main/java/common/block/tech/BlockEnchantmentTable.java index 161c254..d242f81 100755 --- a/java/src/game/block/BlockEnchantmentTable.java +++ b/common/src/main/java/common/block/tech/BlockEnchantmentTable.java @@ -1,25 +1,27 @@ -package game.block; +package common.block.tech; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.item.CheatTab; -import game.item.ItemStack; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityEnchantmentTable; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldClient; +import common.block.BlockContainer; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.item.CheatTab; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ParticleType; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityEnchantmentTable; +import common.util.BlockPos; +import common.util.Facing; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; public class BlockEnchantmentTable extends BlockContainer { - private static final ModelBlock enchanting_table_base = new ModelBlock("enchanting_table_bottom") + private static final Model enchanting_table_base = ModelProvider.getModelProvider().getModel("enchanting_table_bottom") .add(0, 0, 0, 16, 12, 16) .d().uv(0, 0, 16, 16) .u("enchanting_table_top").uv(0, 0, 16, 16).noCull() @@ -31,10 +33,10 @@ public class BlockEnchantmentTable extends BlockContainer public BlockEnchantmentTable() { - super(Material.rock); + super(Material.SOLID); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.75F, 1.0F); this.setLightOpacity(0); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); } public boolean isFullCube() @@ -42,7 +44,7 @@ public class BlockEnchantmentTable extends BlockContainer return false; } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { super.randomDisplayTick(worldIn, pos, state, rand); @@ -95,7 +97,7 @@ public class BlockEnchantmentTable extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return new TileEntityEnchantmentTable(); } @@ -137,7 +139,7 @@ public class BlockEnchantmentTable extends BlockContainer } } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { return enchanting_table_base; } } diff --git a/java/src/game/block/BlockFurnace.java b/common/src/main/java/common/block/tech/BlockFurnace.java similarity index 85% rename from java/src/game/block/BlockFurnace.java rename to common/src/main/java/common/block/tech/BlockFurnace.java index 5dfdb9b..4a3d9fa 100755 --- a/java/src/game/block/BlockFurnace.java +++ b/common/src/main/java/common/block/tech/BlockFurnace.java @@ -1,28 +1,31 @@ -package game.block; +package common.block.tech; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.ItemRegistry; -import game.inventory.Container; -import game.inventory.InventoryHelper; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityFurnace; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockContainer; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.inventory.Container; +import common.inventory.InventoryHelper; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.ParticleType; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityFurnace; +import common.util.BlockPos; +import common.util.Facing; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockFurnace extends BlockContainer { @@ -32,7 +35,7 @@ public class BlockFurnace extends BlockContainer public BlockFurnace(boolean isBurning) { - super(Material.rock); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); this.isBurning = isBurning; } @@ -45,7 +48,7 @@ public class BlockFurnace extends BlockContainer return ItemRegistry.getItemFromBlock(Blocks.furnace); } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { this.setDefaultFacing(worldIn, pos, state); } @@ -82,7 +85,7 @@ public class BlockFurnace extends BlockContainer } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { if (this.isBurning) { @@ -166,7 +169,7 @@ public class BlockFurnace extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return new TileEntityFurnace(); } @@ -198,7 +201,7 @@ public class BlockFurnace extends BlockContainer } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { if (!keepInventory) { @@ -273,8 +276,8 @@ public class BlockFurnace extends BlockContainer return new IProperty[] {FACING}; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("furnace_side").add().du("furnace_top").n("furnace_front_" + (this.isBurning ? "on" : "off")) + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("furnace_side").add().du("furnace_top").n("furnace_front_" + (this.isBurning ? "on" : "off")) .s().we().rotate(ModelRotation.getNorthRot(state.getValue(FACING))); } } diff --git a/java/src/game/block/BlockHopper.java b/common/src/main/java/common/block/tech/BlockHopper.java similarity index 88% rename from java/src/game/block/BlockHopper.java rename to common/src/main/java/common/block/tech/BlockHopper.java index 6b3c0f7..524a799 100755 --- a/java/src/game/block/BlockHopper.java +++ b/common/src/main/java/common/block/tech/BlockHopper.java @@ -1,36 +1,38 @@ -package game.block; +package common.block.tech; import java.util.List; - import java.util.function.Predicate; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.inventory.Container; -import game.inventory.InventoryHelper; -import game.item.CheatTab; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyDirection; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityHopper; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockContainer; +import common.block.Material; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.inventory.Container; +import common.inventory.InventoryHelper; +import common.item.CheatTab; +import common.item.ItemStack; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyDirection; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityHopper; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockHopper extends BlockContainer { - private static final ModelBlock hopper_down = new ModelBlock("hopper_outside").noOcclude() + private static final Model hopper_down = ModelProvider.getModelProvider().getModel("hopper_outside") .add(0, 10, 0, 16, 11, 16) .d().uv(0, 0, 16, 16).noCull() .u("hopper_inside").uv(0, 0, 16, 16).noCull() @@ -93,9 +95,9 @@ public class BlockHopper extends BlockContainer public BlockHopper() { - super(Material.iron); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.DOWN).withProperty(ENABLED, Boolean.valueOf(true))); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); } @@ -142,7 +144,7 @@ public class BlockHopper extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return new TileEntityHopper(); } @@ -165,7 +167,7 @@ public class BlockHopper extends BlockContainer } } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { this.updateState(worldIn, pos, state); } @@ -208,7 +210,7 @@ public class BlockHopper extends BlockContainer } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { TileEntity tileentity = worldIn.getTileEntity(pos); @@ -309,8 +311,8 @@ public class BlockHopper extends BlockContainer return true; } - public ModelBlock getModel(String name, State state) { - return state.getValue(FACING) == Facing.DOWN ? hopper_down : new ModelBlock("hopper_outside").noOcclude() + public Model getModel(ModelProvider provider, String name, State state) { + return state.getValue(FACING) == Facing.DOWN ? hopper_down : provider.getModel("hopper_outside") .add(0, 10, 0, 16, 11, 16) .d().uv(0, 0, 16, 16).noCull() .u("hopper_inside").uv(0, 0, 16, 16).noCull() diff --git a/common/src/main/java/common/block/tech/BlockJukebox.java b/common/src/main/java/common/block/tech/BlockJukebox.java new file mode 100755 index 0000000..cfe625d --- /dev/null +++ b/common/src/main/java/common/block/tech/BlockJukebox.java @@ -0,0 +1,30 @@ +package common.block.tech; + +import common.block.Block; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.init.SoundEvent; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; + +public class BlockJukebox extends Block { + public BlockJukebox() { + super(Material.WOOD); + this.setTab(CheatTab.TECHNOLOGY); + } + + public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { + if(!worldIn.client) + worldIn.playSound(worldIn.rand.pick(SoundEvent.values()), pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, 1.0f); + return true; + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("jukebox_side").add().dnswe().u("jukebox_top"); + } +} diff --git a/java/src/game/block/BlockLever.java b/common/src/main/java/common/block/tech/BlockLever.java similarity index 92% rename from java/src/game/block/BlockLever.java rename to common/src/main/java/common/block/tech/BlockLever.java index 369457c..6e5e276 100755 --- a/java/src/game/block/BlockLever.java +++ b/common/src/main/java/common/block/tech/BlockLever.java @@ -1,23 +1,25 @@ -package game.block; +package common.block.tech; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.SoundEvent; -import game.item.CheatTab; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyBool; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.SoundEvent; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyEnum; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.util.Identifyable; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockLever extends Block { @@ -26,9 +28,9 @@ public class BlockLever extends Block public BlockLever() { - super(Material.circuits); + super(Material.SMALL); this.setDefaultState(this.getBaseState().withProperty(FACING, BlockLever.EnumOrientation.NORTH).withProperty(POWERED, Boolean.valueOf(false))); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); } public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) @@ -214,7 +216,7 @@ public class BlockLever extends Block } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { if (((Boolean)state.getValue(POWERED)).booleanValue()) { @@ -295,8 +297,8 @@ public class BlockLever extends Block } } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("cobblestone").noOcclude() + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("cobblestone") .add(5, 0, 4, 11, 3, 12) .d().uv(5, 4, 11, 12).noCull() .u().uv(5, 4, 11, 12).noCull() @@ -314,7 +316,7 @@ public class BlockLever extends Block .rotate(getRotation(state.getValue(FACING))); } - public static enum EnumOrientation implements IStringSerializable + public static enum EnumOrientation implements Identifyable { DOWN_X(0, "down_x", Facing.DOWN), EAST(1, "east", Facing.EAST), diff --git a/java/src/game/block/BlockMachine.java b/common/src/main/java/common/block/tech/BlockMachine.java similarity index 68% rename from java/src/game/block/BlockMachine.java rename to common/src/main/java/common/block/tech/BlockMachine.java index 55d7719..efdf9c3 100755 --- a/java/src/game/block/BlockMachine.java +++ b/common/src/main/java/common/block/tech/BlockMachine.java @@ -1,31 +1,34 @@ -package game.block; +package common.block.tech; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.inventory.Container; -import game.inventory.InventoryHelper; -import game.item.CheatTab; -import game.material.Material; -import game.properties.IProperty; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityMachine; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockDirectional; +import common.block.ITileEntityProvider; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.inventory.Container; +import common.inventory.InventoryHelper; +import common.item.CheatTab; +import common.properties.IProperty; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityDevice; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public abstract class BlockMachine extends BlockDirectional implements ITileEntityProvider { public BlockMachine() { - super(Material.iron); + super(Material.SOLID); this.hasTile = true; this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); } - public abstract TileEntity createNewTileEntity(World worldIn, int meta); + public abstract TileEntity createNewTileEntity(World worldIn); - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) { + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { this.updateState(worldIn, pos, state); } @@ -34,8 +37,8 @@ public abstract class BlockMachine extends BlockDirectional implements ITileEnti if(worldIn.client) return true; TileEntity tileentity = worldIn.getTileEntity(pos); - if(tileentity instanceof TileEntityMachine) { - playerIn.displayGUIChest((TileEntityMachine)tileentity); + if(tileentity instanceof TileEntityDevice) { + playerIn.displayGUIChest((TileEntityDevice)tileentity); // playerIn.triggerAchievement(StatList.hopperStat); } return true; @@ -54,10 +57,10 @@ public abstract class BlockMachine extends BlockDirectional implements ITileEnti // } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) { + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { TileEntity tileentity = worldIn.getTileEntity(pos); - if(tileentity instanceof TileEntityMachine) { - InventoryHelper.dropInventoryItems(worldIn, pos, (TileEntityMachine)tileentity); + if(tileentity instanceof TileEntityDevice) { + InventoryHelper.dropInventoryItems(worldIn, pos, (TileEntityDevice)tileentity); worldIn.updateComparatorOutputLevel(pos, this); } super.onBlockRemoved(worldIn, pos, state); diff --git a/common/src/main/java/common/block/tech/BlockMobSpawner.java b/common/src/main/java/common/block/tech/BlockMobSpawner.java new file mode 100755 index 0000000..12399c6 --- /dev/null +++ b/common/src/main/java/common/block/tech/BlockMobSpawner.java @@ -0,0 +1,11 @@ +package common.block.tech; + +import common.tileentity.TileEntity; +import common.tileentity.TileEntityMobSpawner; +import common.world.World; + +public class BlockMobSpawner extends BlockMachine { + public TileEntity createNewTileEntity(World world) { + return new TileEntityMobSpawner(); + } +} diff --git a/common/src/main/java/common/block/tech/BlockNote.java b/common/src/main/java/common/block/tech/BlockNote.java new file mode 100755 index 0000000..f9ce07c --- /dev/null +++ b/common/src/main/java/common/block/tech/BlockNote.java @@ -0,0 +1,47 @@ +package common.block.tech; + +import common.block.Block; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.SoundEvent; +import common.item.CheatTab; +import common.model.ParticleType; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; + +public class BlockNote extends Block { + public BlockNote() { + super(Material.WOOD); + this.setTab(CheatTab.TECHNOLOGY); + } + + public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) { + if(worldIn.isBlockPowered(pos)) + worldIn.addBlockEvent(pos, Blocks.noteblock, 0, 0); + } + + public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { + if(!worldIn.client) + worldIn.addBlockEvent(pos, Blocks.noteblock, 0, 0); + return true; + } + + public void onBlockClicked(World worldIn, BlockPos pos, EntityNPC playerIn) { + if(!worldIn.client) + worldIn.addBlockEvent(pos, Blocks.noteblock, 0, 0); + } + + public boolean onBlockEventReceived(World worldIn, BlockPos pos, State state, int eventID, int eventParam) { + worldIn.playSound(SoundEvent.NOTE, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, 3.0F); + worldIn.spawnParticle(ParticleType.NOTE, (double)pos.getX() + 0.5D, (double)pos.getY() + 1.2D, (double)pos.getZ() + 0.5D, + (double)eventParam / 24.0D, 0.0D, 0.0D); + return true; + } + + public boolean isMagnetic() { + return true; + } +} diff --git a/java/src/game/block/BlockNuke.java b/common/src/main/java/common/block/tech/BlockNuke.java similarity index 64% rename from java/src/game/block/BlockNuke.java rename to common/src/main/java/common/block/tech/BlockNuke.java index ce5e470..1413eed 100755 --- a/java/src/game/block/BlockNuke.java +++ b/common/src/main/java/common/block/tech/BlockNuke.java @@ -1,26 +1,28 @@ -package game.block; +package common.block.tech; -import game.entity.item.EntityNuke; -import game.init.Blocks; -import game.init.SoundEvent; -import game.item.CheatTab; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.Explosion; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.entity.item.EntityNuke; +import common.init.Blocks; +import common.init.SoundEvent; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.util.BlockPos; +import common.world.Explosion; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockNuke extends Block { public BlockNuke() { - super(Material.tnt); - this.setTab(CheatTab.tabTech); + super(Material.EXPLOSIVE); + this.setTab(CheatTab.TECHNOLOGY); } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { super.onBlockAdded(worldIn, pos, state); @@ -68,7 +70,7 @@ public class BlockNuke extends Block return true; } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("nuke_side").add().nswe().d("nuke_bottom").u("nuke_top"); + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("nuke_side").add().nswe().d("nuke_bottom").u("nuke_top"); } } diff --git a/java/src/game/block/BlockPistonBase.java b/common/src/main/java/common/block/tech/BlockPistonBase.java similarity index 91% rename from java/src/game/block/BlockPistonBase.java rename to common/src/main/java/common/block/tech/BlockPistonBase.java index 04c6fd6..cc6a061 100755 --- a/java/src/game/block/BlockPistonBase.java +++ b/common/src/main/java/common/block/tech/BlockPistonBase.java @@ -1,33 +1,35 @@ -package game.block; +package common.block.tech; import java.util.List; -import game.collect.Lists; - -import game.audio.SoundType; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.init.SoundEvent; -import game.item.CheatTab; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyDirection; -import game.renderer.blockmodel.ModelBlock; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityPiston; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.ITileEntityProvider; +import common.block.Material; +import common.block.SoundType; +import common.collect.Lists; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.SoundEvent; +import common.item.CheatTab; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyDirection; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityPiston; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Facing; +import common.vars.Vars; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockPistonBase extends Block { @@ -99,7 +101,7 @@ public class BlockPistonBase extends Block { Block block = this.world.getState(origin).getBlock(); - if (block.getMaterial() == Material.air) + if (block == Blocks.air) { return true; } @@ -119,7 +121,7 @@ public class BlockPistonBase extends Block { int i = 1; - if (i + this.toMove.size() > Config.pistonLimit) + if (i + this.toMove.size() > Vars.pistonLimit) { return false; } @@ -130,14 +132,14 @@ public class BlockPistonBase extends Block BlockPos blockpos = origin.offset(this.moveDirection.getOpposite(), i); block = this.world.getState(blockpos).getBlock(); - if (block.getMaterial() == Material.air || !BlockPistonBase.canPush(block, this.world, blockpos, this.moveDirection, false) || blockpos.equals(this.pistonPos)) + if (block == Blocks.air || !BlockPistonBase.canPush(block, this.world, blockpos, this.moveDirection, false) || blockpos.equals(this.pistonPos)) { break; } ++i; - if (i + this.toMove.size() > Config.pistonLimit) + if (i + this.toMove.size() > Vars.pistonLimit) { return false; } @@ -177,7 +179,7 @@ public class BlockPistonBase extends Block block = this.world.getState(blockpos1).getBlock(); - if (block.getMaterial() == Material.air) + if (block == Blocks.air) { return true; } @@ -193,7 +195,7 @@ public class BlockPistonBase extends Block return true; } - if (this.toMove.size() >= Config.pistonLimit) + if (this.toMove.size() >= Vars.pistonLimit) { return false; } @@ -252,12 +254,12 @@ public class BlockPistonBase extends Block public BlockPistonBase(boolean isSticky) { - super(Material.piston); + super(Material.PISTON); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(EXTENDED, Boolean.valueOf(false))); this.isSticky = isSticky; this.setStepSound(SoundType.STONE); this.setHardness(0.5F); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); } /** @@ -292,7 +294,7 @@ public class BlockPistonBase extends Block } } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { if (!worldIn.client && worldIn.getTileEntity(pos) == null) { @@ -425,7 +427,7 @@ public class BlockPistonBase extends Block } } - if (!flag1 && block.getMaterial() != Material.air && canPush(block, worldIn, blockpos, enumfacing.getOpposite(), false) && (block.getMobilityFlag() == 0 || block == Blocks.piston || block == Blocks.sticky_piston)) + if (!flag1 && block != Blocks.air && canPush(block, worldIn, blockpos, enumfacing.getOpposite(), false) && (block.getMobilityFlag() == 0 || block == Blocks.piston || block == Blocks.sticky_piston)) { this.doMove(worldIn, pos, enumfacing, false); } @@ -549,9 +551,9 @@ public class BlockPistonBase extends Block { return false; } - else if (pos.getY() >= 0 && (direction != Facing.DOWN || pos.getY() != 0)) + else if (pos.getY() >= -World.MAX_SIZE_Y && (direction != Facing.DOWN || pos.getY() != -World.MAX_SIZE_Y)) { - if (pos.getY() <= World.HEIGHT - 1 && (direction != Facing.UP || pos.getY() != World.HEIGHT - 1)) + if (pos.getY() <= World.MAX_SIZE_Y - 1 && (direction != Facing.UP || pos.getY() != World.MAX_SIZE_Y - 1)) { if (blockIn != Blocks.piston && blockIn != Blocks.sticky_piston) { @@ -706,15 +708,15 @@ public class BlockPistonBase extends Block return new IProperty[] {FACING, EXTENDED}; } - public ModelBlock getModel(String name, State state) { - return (state.getValue(EXTENDED) ? new ModelBlock("piston_side") + public Model getModel(ModelProvider provider, String name, State state) { + return (state.getValue(EXTENDED) ? provider.getModel("piston_side") .add(0, 0, 4, 16, 16, 16) .d().uv(0, 4, 16, 16).rot(180) .u().uv(0, 4, 16, 16) .n("piston_inner").uv(0, 0, 16, 16).noCull() .s("piston_bottom").uv(0, 0, 16, 16) .w().uv(0, 4, 16, 16).rot(270) - .e().uv(0, 4, 16, 16).rot(90) : new ModelBlock("piston_side") + .e().uv(0, 4, 16, 16).rot(90) : provider.getModel("piston_side") .add(0, 0, 0, 16, 16, 16) .d().uv(0, 0, 16, 16).rot(180) .u().uv(0, 0, 16, 16) diff --git a/java/src/game/block/BlockPistonHead.java b/common/src/main/java/common/block/tech/BlockPistonHead.java similarity index 87% rename from java/src/game/block/BlockPistonHead.java rename to common/src/main/java/common/block/tech/BlockPistonHead.java index a77af50..21aa5e2 100755 --- a/java/src/game/block/BlockPistonHead.java +++ b/common/src/main/java/common/block/tech/BlockPistonHead.java @@ -1,28 +1,30 @@ -package game.block; +package common.block.tech; import java.util.List; -import game.audio.SoundType; -import game.entity.Entity; -import game.init.Blocks; -import game.init.ItemRegistry; -import game.item.Item; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyBool; -import game.properties.PropertyDirection; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.SoundType; +import common.entity.Entity; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyDirection; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.util.Identifyable; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockPistonHead extends Block { @@ -32,7 +34,7 @@ public class BlockPistonHead extends Block public BlockPistonHead() { - super(Material.piston); + super(Material.PISTON); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(TYPE, BlockPistonHead.EnumPistonType.DEFAULT).withProperty(SHORT, Boolean.valueOf(false))); this.setStepSound(SoundType.STONE); this.setHardness(0.5F); @@ -59,7 +61,7 @@ public class BlockPistonHead extends Block // super.onBlockHarvested(worldIn, pos, state, player); // } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { super.onBlockRemoved(worldIn, pos, state); Facing enumfacing = ((Facing)state.getValue(FACING)).getOpposite(); @@ -258,9 +260,9 @@ public class BlockPistonHead extends Block return new IProperty[] {FACING, TYPE, SHORT}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { String side = "piston_side"; - return (state.getValue(SHORT) ? new ModelBlock(state.getValue(TYPE) == EnumPistonType.STICKY ? "piston_top_sticky" : "piston_top") + return (state.getValue(SHORT) ? provider.getModel(state.getValue(TYPE) == EnumPistonType.STICKY ? "piston_top_sticky" : "piston_top") .add(0, 0, 0, 16, 16, 4) .d(side).uv(0, 0, 16, 4).rot(180) .u(side).uv(0, 0, 16, 4) @@ -273,7 +275,7 @@ public class BlockPistonHead extends Block .u(side).uv(4, 0, 16, 4).rot(270).noCull() .w(side).uv(16, 4, 4, 0).noCull() .e(side).uv(4, 0, 16, 4).noCull() - : new ModelBlock(state.getValue(TYPE) == EnumPistonType.STICKY ? "piston_top_sticky" : "piston_top") + : provider.getModel(state.getValue(TYPE) == EnumPistonType.STICKY ? "piston_top_sticky" : "piston_top") .add(0, 0, 0, 16, 16, 4) .d(side).uv(0, 0, 16, 4).rot(180) .u(side).uv(0, 0, 16, 4) @@ -295,7 +297,7 @@ public class BlockPistonHead extends Block ? state.getValue(FACING).getOpposite() : state.getValue(FACING))); } - public static enum EnumPistonType implements IStringSerializable + public static enum EnumPistonType implements Identifyable { DEFAULT("normal"), STICKY("sticky"); diff --git a/java/src/game/block/BlockPistonMoving.java b/common/src/main/java/common/block/tech/BlockPistonMoving.java similarity index 90% rename from java/src/game/block/BlockPistonMoving.java rename to common/src/main/java/common/block/tech/BlockPistonMoving.java index 89fea3b..666061d 100755 --- a/java/src/game/block/BlockPistonMoving.java +++ b/common/src/main/java/common/block/tech/BlockPistonMoving.java @@ -1,24 +1,26 @@ -package game.block; +package common.block.tech; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.item.Item; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.properties.PropertyEnum; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityPiston; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.HitPosition; -import game.world.IWorldAccess; -import game.world.State; -import game.world.Vec3; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockContainer; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.item.Item; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityPiston; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.util.HitPosition; +import common.util.Vec3; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockPistonMoving extends BlockContainer { @@ -27,7 +29,7 @@ public class BlockPistonMoving extends BlockContainer public BlockPistonMoving() { - super(Material.piston); + super(Material.PISTON); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(TYPE, BlockPistonHead.EnumPistonType.DEFAULT)); this.setHardness(-1.0F); } @@ -35,7 +37,7 @@ public class BlockPistonMoving extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return null; } @@ -45,7 +47,7 @@ public class BlockPistonMoving extends BlockContainer return new TileEntityPiston(state, facing, extending, renderHead); } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { TileEntity tileentity = worldIn.getTileEntity(pos); @@ -186,7 +188,7 @@ public class BlockPistonMoving extends BlockContainer State iblockstate = tileentitypiston.getPistonState(); Block block = iblockstate.getBlock(); - if (block == this || block.getMaterial() == Material.air) + if (block == this || block == Blocks.air) { return; } @@ -217,7 +219,7 @@ public class BlockPistonMoving extends BlockContainer public BoundingBox getBoundingBox(World worldIn, BlockPos pos, State extendingBlock, float progress, Facing direction) { - if (extendingBlock.getBlock() != this && extendingBlock.getBlock().getMaterial() != Material.air) + if (extendingBlock.getBlock() != this && extendingBlock.getBlock() != Blocks.air) { BoundingBox axisalignedbb = extendingBlock.getBlock().getCollisionBoundingBox(worldIn, pos, extendingBlock); diff --git a/java/src/game/block/BlockPressurePlate.java b/common/src/main/java/common/block/tech/BlockPressurePlate.java similarity index 88% rename from java/src/game/block/BlockPressurePlate.java rename to common/src/main/java/common/block/tech/BlockPressurePlate.java index 64bafb7..b17b4b0 100755 --- a/java/src/game/block/BlockPressurePlate.java +++ b/common/src/main/java/common/block/tech/BlockPressurePlate.java @@ -1,16 +1,16 @@ -package game.block; +package common.block.tech; import java.util.List; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.State; -import game.world.World; +import common.block.Material; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.world.State; +import common.world.World; public class BlockPressurePlate extends BlockBasePressurePlate { diff --git a/java/src/game/block/BlockPressurePlateWeighted.java b/common/src/main/java/common/block/tech/BlockPressurePlateWeighted.java similarity index 88% rename from java/src/game/block/BlockPressurePlateWeighted.java rename to common/src/main/java/common/block/tech/BlockPressurePlateWeighted.java index ddce333..eeac2ec 100755 --- a/java/src/game/block/BlockPressurePlateWeighted.java +++ b/common/src/main/java/common/block/tech/BlockPressurePlateWeighted.java @@ -1,13 +1,13 @@ -package game.block; +package common.block.tech; -import game.entity.Entity; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.Material; +import common.entity.Entity; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.State; +import common.world.World; public class BlockPressurePlateWeighted extends BlockBasePressurePlate { diff --git a/java/src/game/block/BlockRail.java b/common/src/main/java/common/block/tech/BlockRail.java similarity index 86% rename from java/src/game/block/BlockRail.java rename to common/src/main/java/common/block/tech/BlockRail.java index 92bab17..de178aa 100755 --- a/java/src/game/block/BlockRail.java +++ b/common/src/main/java/common/block/tech/BlockRail.java @@ -1,10 +1,11 @@ -package game.block; +package common.block.tech; -import game.properties.IProperty; -import game.properties.PropertyEnum; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.util.BlockPos; +import common.world.State; +import common.world.World; public class BlockRail extends BlockRailBase { diff --git a/java/src/game/block/BlockRailBase.java b/common/src/main/java/common/block/tech/BlockRailBase.java similarity index 95% rename from java/src/game/block/BlockRailBase.java rename to common/src/main/java/common/block/tech/BlockRailBase.java index 44c9cee..df3e43c 100755 --- a/java/src/game/block/BlockRailBase.java +++ b/common/src/main/java/common/block/tech/BlockRailBase.java @@ -1,26 +1,27 @@ -package game.block; +package common.block.tech; import java.util.List; -import game.collect.Lists; - -import game.init.Blocks; -import game.item.CheatTab; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.HitPosition; -import game.world.IWorldAccess; -import game.world.State; -import game.world.Vec3; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.collect.Lists; +import common.init.Blocks; +import common.item.CheatTab; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.util.HitPosition; +import common.util.Identifyable; +import common.util.Vec3; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public abstract class BlockRailBase extends Block { @@ -39,10 +40,10 @@ public abstract class BlockRailBase extends Block public BlockRailBase(boolean isPowered) { - super(Material.circuits); + super(Material.SMALL); this.isPowered = isPowered; this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); } public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) @@ -92,7 +93,7 @@ public abstract class BlockRailBase extends Block return worldIn.isBlockSolid(pos.down()); } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { if (!worldIn.client) { @@ -168,7 +169,7 @@ public abstract class BlockRailBase extends Block return BlockLayer.CUTOUT; } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { super.onBlockRemoved(worldIn, pos, state); @@ -188,13 +189,13 @@ public abstract class BlockRailBase extends Block return true; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { EnumRailDirection dir = state.getValue(this.getShapeProperty()); switch(dir) { case NORTH_SOUTH: case EAST_WEST: default: - return new ModelBlock(name).noOcclude() + return provider.getModel(name) .add(0, 1, 0, 16, 1, 16) .d().uv(0, 16, 16, 0).noCull() .u().uv(0, 0, 16, 16).noCull() @@ -203,7 +204,7 @@ public abstract class BlockRailBase extends Block case NORTH_WEST: case SOUTH_EAST: case SOUTH_WEST: - return new ModelBlock(name + "_turned").noOcclude() + return provider.getModel(name + "_turned") .add(0, 1, 0, 16, 1, 16) .d().uv(0, 16, 16, 0).noCull() .u().uv(0, 0, 16, 16).noCull() @@ -211,14 +212,14 @@ public abstract class BlockRailBase extends Block ModelRotation.X0_Y180 : (dir == EnumRailDirection.NORTH_EAST ? ModelRotation.X0_Y270 : ModelRotation.X0_Y0))); case ASCENDING_NORTH: case ASCENDING_EAST: - return new ModelBlock(name).noOcclude() + return provider.getModel(name) .add(0, 9, 0, 16, 9, 16).rotate(8, 9, 8, Facing.Axis.X, 45, true) .d().uv(0, 16, 16, 0).noCull() .u().uv(0, 0, 16, 16).noCull() .rotate(dir == EnumRailDirection.ASCENDING_EAST ? ModelRotation.X0_Y90 : ModelRotation.X0_Y0); case ASCENDING_SOUTH: case ASCENDING_WEST: - return new ModelBlock(name).noOcclude() + return provider.getModel(name) .add(0, 9, 0, 16, 9, 16).rotate(8, 9, 8, Facing.Axis.X, -45, true) .d().uv(0, 16, 16, 0).noCull() .u().uv(0, 0, 16, 16).noCull() @@ -228,7 +229,7 @@ public abstract class BlockRailBase extends Block public abstract IProperty getShapeProperty(); - public static enum EnumRailDirection implements IStringSerializable + public static enum EnumRailDirection implements Identifyable { NORTH_SOUTH(0, "north_south", Facing.SOUTH), EAST_WEST(1, "east_west", Facing.EAST), diff --git a/java/src/game/block/BlockRailDetector.java b/common/src/main/java/common/block/tech/BlockRailDetector.java similarity index 86% rename from java/src/game/block/BlockRailDetector.java rename to common/src/main/java/common/block/tech/BlockRailDetector.java index 976b079..330cc6c 100755 --- a/java/src/game/block/BlockRailDetector.java +++ b/common/src/main/java/common/block/tech/BlockRailDetector.java @@ -1,25 +1,25 @@ -package game.block; +package common.block.tech; import java.util.List; - import java.util.function.Predicate; -import game.entity.Entity; -import game.entity.item.EntityCart; -import game.inventory.Container; -import game.inventory.IInventory; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.entity.Entity; +import common.entity.item.EntityCart; +import common.inventory.Container; +import common.inventory.IInventory; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockRailDetector extends BlockRailBase { @@ -72,11 +72,11 @@ public class BlockRailDetector extends BlockRailBase /** * Called randomly when setTickRandomly is set to true (used by e.g. crops to grow, etc.) */ - public void randomTick(WorldServer worldIn, BlockPos pos, State state, Random random) + public void randomTick(AWorldServer worldIn, BlockPos pos, State state, Random random) { } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { if (/* !worldIn.client && */ ((Boolean)state.getValue(POWERED)).booleanValue()) { @@ -129,7 +129,7 @@ public class BlockRailDetector extends BlockRailBase worldIn.updateComparatorOutputLevel(pos, this); } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { super.onBlockAdded(worldIn, pos, state); this.updatePoweredState(worldIn, pos, state); @@ -212,7 +212,7 @@ public class BlockRailDetector extends BlockRailBase return new IProperty[] {SHAPE, POWERED}; } - public ModelBlock getModel(String name, State state) { - return super.getModel(name + (state.getValue(POWERED) ? "_powered" : ""), state); + public Model getModel(ModelProvider provider, String name, State state) { + return super.getModel(provider, name + (state.getValue(POWERED) ? "_powered" : ""), state); } } diff --git a/java/src/game/block/BlockRailPowered.java b/common/src/main/java/common/block/tech/BlockRailPowered.java similarity index 93% rename from java/src/game/block/BlockRailPowered.java rename to common/src/main/java/common/block/tech/BlockRailPowered.java index 7782ed8..727800b 100755 --- a/java/src/game/block/BlockRailPowered.java +++ b/common/src/main/java/common/block/tech/BlockRailPowered.java @@ -1,14 +1,16 @@ -package game.block; +package common.block.tech; import java.util.function.Predicate; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyEnum; +import common.util.BlockPos; +import common.world.State; +import common.world.World; public class BlockRailPowered extends BlockRailBase { @@ -198,7 +200,7 @@ public class BlockRailPowered extends BlockRailBase return new IProperty[] {SHAPE, POWERED}; } - public ModelBlock getModel(String name, State state) { - return super.getModel(name + (state.getValue(POWERED) ? "_powered" : ""), state); + public Model getModel(ModelProvider provider, String name, State state) { + return super.getModel(provider, name + (state.getValue(POWERED) ? "_powered" : ""), state); } } diff --git a/java/src/game/block/BlockRedstoneComparator.java b/common/src/main/java/common/block/tech/BlockRedstoneComparator.java similarity index 89% rename from java/src/game/block/BlockRedstoneComparator.java rename to common/src/main/java/common/block/tech/BlockRedstoneComparator.java index 1e79399..635d9f4 100755 --- a/java/src/game/block/BlockRedstoneComparator.java +++ b/common/src/main/java/common/block/tech/BlockRedstoneComparator.java @@ -1,26 +1,29 @@ -package game.block; +package common.block.tech; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Items; -import game.init.SoundEvent; -import game.item.Item; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyBool; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityComparator; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.ITileEntityProvider; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.Items; +import common.init.SoundEvent; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyEnum; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityComparator; +import common.util.BlockPos; +import common.util.Facing; +import common.util.Identifyable; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITileEntityProvider { @@ -131,7 +134,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile { i = block.getComparatorInputOverride(worldIn, blockpos); } -// else if (block.getMaterial() == Material.air) +// else if (block == Blocks.air) // { // EntityFrame entityitemframe = this.findItemFrame(worldIn, enumfacing, blockpos); // @@ -175,7 +178,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile protected void updateState(World worldIn, BlockPos pos, State state) { - if (worldIn.client || !((WorldServer)worldIn).isBlockTickPending(pos, this)) + if (worldIn.client || !((AWorldServer)worldIn).isBlockTickPending(pos, this)) { int i = this.calculateOutput(worldIn, pos, state); TileEntity tileentity = worldIn.getTileEntity(pos); @@ -186,12 +189,12 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile if (this.isFacingTowardsRepeater(worldIn, pos, state)) { if(!worldIn.client) - ((WorldServer)worldIn).updateBlockTick(pos, this, 2, -1); + ((AWorldServer)worldIn).updateBlockTick(pos, this, 2, -1); } else { if(!worldIn.client) - ((WorldServer)worldIn).updateBlockTick(pos, this, 2, 0); + ((AWorldServer)worldIn).updateBlockTick(pos, this, 2, 0); } } } @@ -228,7 +231,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile } } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { if (this.isRepeaterPowered) { @@ -238,13 +241,13 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile this.onStateChange(worldIn, pos, state); } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { super.onBlockAdded(worldIn, pos, state); - worldIn.setTileEntity(pos, this.createNewTileEntity(worldIn, 0)); + worldIn.setTileEntity(pos, this.createNewTileEntity(worldIn)); } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { super.onBlockRemoved(worldIn, pos, state); worldIn.removeTileEntity(pos); @@ -264,7 +267,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return new TileEntityComparator(); } @@ -312,8 +315,8 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile return this.getState().withProperty(FACING, placer.getHorizontalFacing().getOpposite()).withProperty(POWERED, Boolean.valueOf(false)).withProperty(MODE, BlockRedstoneComparator.Mode.COMPARE); } - public ModelBlock getModel(String name, State state) { - return (state.getValue(POWERED) ? (state.getValue(MODE) == Mode.SUBTRACT ? new ModelBlock("comparator_on").noOcclude() + public Model getModel(ModelProvider provider, String name, State state) { + return (state.getValue(POWERED) ? (state.getValue(MODE) == Mode.SUBTRACT ? provider.getModel("comparator_on") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -344,7 +347,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile .e("redstone_torch").uv(6, 5, 10, 9).noCull() .add(6, 2, 2, 10, 6, 4) .n("redstone_torch").uv(6, 5, 10, 9).noCull() - .s("redstone_torch").uv(6, 5, 10, 9).noCull() : new ModelBlock("comparator_on").noOcclude() + .s("redstone_torch").uv(6, 5, 10, 9).noCull() : provider.getModel("comparator_on") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -375,7 +378,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile .s("unlit_redstone_torch").uv(7, 6, 9, 8).noCull() .w("unlit_redstone_torch").uv(7, 6, 9, 8).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 8).noCull()) - : (state.getValue(MODE) == Mode.SUBTRACT ? new ModelBlock("comparator_off").noOcclude() + : (state.getValue(MODE) == Mode.SUBTRACT ? provider.getModel("comparator_off") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -404,7 +407,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile .e("redstone_torch").uv(6, 5, 10, 9).noCull() .add(6, 2, 2, 10, 6, 4) .n("redstone_torch").uv(6, 5, 10, 9).noCull() - .s("redstone_torch").uv(6, 5, 10, 9).noCull() : new ModelBlock("comparator_off").noOcclude() + .s("redstone_torch").uv(6, 5, 10, 9).noCull() : provider.getModel("comparator_off") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -436,7 +439,7 @@ public class BlockRedstoneComparator extends BlockRedstoneDiode implements ITile .rotate(ModelRotation.getNorthRot(state.getValue(FACING).getOpposite())); } - public static enum Mode implements IStringSerializable + public static enum Mode implements Identifyable { COMPARE("compare"), SUBTRACT("subtract"); diff --git a/java/src/game/block/BlockRedstoneDiode.java b/common/src/main/java/common/block/tech/BlockRedstoneDiode.java similarity index 90% rename from java/src/game/block/BlockRedstoneDiode.java rename to common/src/main/java/common/block/tech/BlockRedstoneDiode.java index 766c5d9..5c61033 100755 --- a/java/src/game/block/BlockRedstoneDiode.java +++ b/common/src/main/java/common/block/tech/BlockRedstoneDiode.java @@ -1,17 +1,19 @@ -package game.block; +package common.block.tech; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.item.ItemStack; -import game.material.Material; -import game.renderer.BlockLayer; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockDirectional; +import common.block.Material; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.item.ItemStack; +import common.model.BlockLayer; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public abstract class BlockRedstoneDiode extends BlockDirectional { @@ -20,7 +22,7 @@ public abstract class BlockRedstoneDiode extends BlockDirectional public BlockRedstoneDiode(boolean powered) { - super(Material.circuits); + super(Material.SMALL); this.isRepeaterPowered = powered; this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.125F, 1.0F); } @@ -43,11 +45,11 @@ public abstract class BlockRedstoneDiode extends BlockDirectional /** * Called randomly when setTickRandomly is set to true (used by e.g. crops to grow, etc.) */ - public void randomTick(WorldServer worldIn, BlockPos pos, State state, Random random) + public void randomTick(AWorldServer worldIn, BlockPos pos, State state, Random random) { } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { if (!this.isLocked(worldIn, pos, state)) { @@ -116,7 +118,7 @@ public abstract class BlockRedstoneDiode extends BlockDirectional { boolean flag = this.shouldBePowered(worldIn, pos, state); - if ((this.isRepeaterPowered && !flag || !this.isRepeaterPowered && flag) && (worldIn.client || !((WorldServer)worldIn).isBlockTickPending(pos, this))) + if ((this.isRepeaterPowered && !flag || !this.isRepeaterPowered && flag) && (worldIn.client || !((AWorldServer)worldIn).isBlockTickPending(pos, this))) { int i = -1; @@ -130,7 +132,7 @@ public abstract class BlockRedstoneDiode extends BlockDirectional } if(!worldIn.client) - ((WorldServer)worldIn).updateBlockTick(pos, this, this.getDelay(state), i); + ((AWorldServer)worldIn).updateBlockTick(pos, this, this.getDelay(state), i); } } } @@ -205,7 +207,7 @@ public abstract class BlockRedstoneDiode extends BlockDirectional } } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { this.notifyNeighbors(worldIn, pos, state); } diff --git a/java/src/game/block/BlockRedstoneLight.java b/common/src/main/java/common/block/tech/BlockRedstoneLight.java similarity index 78% rename from java/src/game/block/BlockRedstoneLight.java rename to common/src/main/java/common/block/tech/BlockRedstoneLight.java index b3fda33..dad8d50 100755 --- a/java/src/game/block/BlockRedstoneLight.java +++ b/common/src/main/java/common/block/tech/BlockRedstoneLight.java @@ -1,15 +1,16 @@ -package game.block; +package common.block.tech; -import game.init.Blocks; -import game.init.ItemRegistry; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.item.Item; +import common.item.ItemStack; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockRedstoneLight extends Block { @@ -17,7 +18,7 @@ public class BlockRedstoneLight extends Block public BlockRedstoneLight(boolean isOn) { - super(Material.redstoneLight); + super(Material.LOOSE); this.isOn = isOn; if (isOn) @@ -26,7 +27,7 @@ public class BlockRedstoneLight extends Block } } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { if (!worldIn.client) { @@ -59,7 +60,7 @@ public class BlockRedstoneLight extends Block } } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { // if (!worldIn.client) // { diff --git a/java/src/game/block/BlockRedstoneRepeater.java b/common/src/main/java/common/block/tech/BlockRedstoneRepeater.java similarity index 90% rename from java/src/game/block/BlockRedstoneRepeater.java rename to common/src/main/java/common/block/tech/BlockRedstoneRepeater.java index 4c1283f..07499f2 100755 --- a/java/src/game/block/BlockRedstoneRepeater.java +++ b/common/src/main/java/common/block/tech/BlockRedstoneRepeater.java @@ -1,23 +1,25 @@ -package game.block; +package common.block.tech; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Items; -import game.item.Item; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.Block; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.item.Item; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.ParticleType; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockRedstoneRepeater extends BlockRedstoneDiode { @@ -104,7 +106,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode return isRedstoneRepeaterBlockID(blockIn); } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { if (this.isRepeaterPowered) { @@ -126,7 +128,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { super.onBlockRemoved(worldIn, pos, state); this.notifyNeighbors(worldIn, pos, state); @@ -156,11 +158,11 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode return new IProperty[] {FACING, DELAY, LOCKED}; } - private static ModelBlock getModelOff(int delay) { + private static Model getModelOff(int delay) { switch(delay) { case 1: default: - return new ModelBlock("repeater_off").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_off") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -183,7 +185,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 2: - return new ModelBlock("repeater_off").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_off") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -206,7 +208,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 3: - return new ModelBlock("repeater_off").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_off") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -229,7 +231,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 4: - return new ModelBlock("repeater_off").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_off") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -254,11 +256,11 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode } } - private static ModelBlock getModelOn(int delay) { + private static Model getModelOn(int delay) { switch(delay) { case 1: default: - return new ModelBlock("repeater_on").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_on") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -283,7 +285,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 2: - return new ModelBlock("repeater_on").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_on") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -308,7 +310,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 3: - return new ModelBlock("repeater_on").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_on") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -333,7 +335,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 4: - return new ModelBlock("repeater_on").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_on") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -360,11 +362,11 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode } } - private static ModelBlock getModelOffLocked(int delay) { + private static Model getModelOffLocked(int delay) { switch(delay) { case 1: default: - return new ModelBlock("repeater_off").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_off") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -387,7 +389,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 2: - return new ModelBlock("repeater_off").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_off") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -410,7 +412,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 3: - return new ModelBlock("repeater_off").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_off") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -433,7 +435,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .w("unlit_redstone_torch").uv(7, 6, 9, 11).noCull() .e("unlit_redstone_torch").uv(7, 6, 9, 11).noCull(); case 4: - return new ModelBlock("repeater_off").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_off") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -458,11 +460,11 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode } } - private static ModelBlock getModelOnLocked(int delay) { + private static Model getModelOnLocked(int delay) { switch(delay) { case 1: default: - return new ModelBlock("repeater_on").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_on") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -486,7 +488,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 2: - return new ModelBlock("repeater_on").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_on") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -510,7 +512,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 3: - return new ModelBlock("repeater_on").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_on") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -534,7 +536,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode .n("redstone_torch").uv(6, 5, 10, 11).noCull() .s("redstone_torch").uv(6, 5, 10, 11).noCull(); case 4: - return new ModelBlock("repeater_on").noOcclude() + return ModelProvider.getModelProvider().getModel("repeater_on") .add(0, 0, 0, 16, 2, 16) .d("double_stone_top").uv(0, 0, 16, 16) .u().uv(0, 0, 16, 16).noCull() @@ -560,7 +562,7 @@ public class BlockRedstoneRepeater extends BlockRedstoneDiode } } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { return (this.isRepeaterPowered ? (state.getValue(LOCKED) ? getModelOnLocked(state.getValue(DELAY)) : getModelOn(state.getValue(DELAY))) : (state.getValue(LOCKED) ? getModelOffLocked(state.getValue(DELAY)) : getModelOff(state.getValue(DELAY)))) diff --git a/java/src/game/block/BlockRedstoneTorch.java b/common/src/main/java/common/block/tech/BlockRedstoneTorch.java similarity index 85% rename from java/src/game/block/BlockRedstoneTorch.java rename to common/src/main/java/common/block/tech/BlockRedstoneTorch.java index 1ad83e1..7f73f2b 100755 --- a/java/src/game/block/BlockRedstoneTorch.java +++ b/common/src/main/java/common/block/tech/BlockRedstoneTorch.java @@ -1,32 +1,32 @@ -package game.block; +package common.block.tech; import java.util.List; import java.util.Map; -import game.collect.Lists; -import game.collect.Maps; - -import game.init.Blocks; -import game.init.ItemRegistry; -import game.init.SoundEvent; -import game.item.CheatTab; -import game.item.Item; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.Block; +import common.collect.Lists; +import common.collect.Maps; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.SoundEvent; +import common.item.CheatTab; +import common.item.Item; +import common.model.ParticleType; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockRedstoneTorch extends BlockTorch { private static Map> toggles = Maps.>newHashMap(); private final boolean isOn; - private boolean isBurnedOut(WorldServer worldIn, BlockPos pos, boolean turnOff) + private boolean isBurnedOut(AWorldServer worldIn, BlockPos pos, boolean turnOff) { if (!toggles.containsKey(worldIn)) { @@ -75,7 +75,7 @@ public class BlockRedstoneTorch extends BlockTorch return 2; } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { if (this.isOn) { @@ -86,7 +86,7 @@ public class BlockRedstoneTorch extends BlockTorch } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { if (this.isOn) { @@ -111,11 +111,11 @@ public class BlockRedstoneTorch extends BlockTorch /** * Called randomly when setTickRandomly is set to true (used by e.g. crops to grow, etc.) */ - public void randomTick(WorldServer worldIn, BlockPos pos, State state, Random random) + public void randomTick(AWorldServer worldIn, BlockPos pos, State state, Random random) { } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { boolean flag = this.shouldBeOff(worldIn, pos, state); List list = (List)toggles.get(worldIn); @@ -188,7 +188,7 @@ public class BlockRedstoneTorch extends BlockTorch return true; } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { if (this.isOn) { diff --git a/java/src/game/block/BlockRedstoneWire.java b/common/src/main/java/common/block/tech/BlockRedstoneWire.java similarity index 89% rename from java/src/game/block/BlockRedstoneWire.java rename to common/src/main/java/common/block/tech/BlockRedstoneWire.java index ef33571..514b546 100755 --- a/java/src/game/block/BlockRedstoneWire.java +++ b/common/src/main/java/common/block/tech/BlockRedstoneWire.java @@ -1,51 +1,52 @@ -package game.block; +package common.block.tech; import java.util.EnumSet; import java.util.List; import java.util.Set; -import game.collect.Lists; -import game.collect.Sets; - -import game.init.Blocks; -import game.init.Items; -import game.item.Item; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.IStringSerializable; -import game.properties.PropertyEnum; -import game.properties.PropertyInteger; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.collect.Lists; +import common.collect.Sets; +import common.init.Blocks; +import common.init.Items; +import common.item.Item; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.ParticleType; +import common.properties.IProperty; +import common.properties.PropertyEnum; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Facing; +import common.util.Identifyable; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockRedstoneWire extends Block { - private static final ModelBlock redstone_none = new ModelBlock("redstone_dust_cross").noOcclude() + private static final Model redstone_none = ModelProvider.getModelProvider().getModel("redstone_dust_cross") .add(5, 0.25f, 5, 11, 0.25f, 11).noShade() .u().uv(5, 5, 11, 11).tint().noCull() .add(5, 0.25f, 5, 11, 0.25f, 11).noShade() .u("redstone_dust_cross_overlay").uv(5, 5, 11, 11).noCull() ; - private static final ModelBlock redstone_nsew = new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static final Model redstone_nsew = ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_cross_overlay").uv(0, 0, 16, 16).noCull() ; - private static final ModelBlock redstone_unusueuw = new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static final Model redstone_unusueuw = ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -67,7 +68,7 @@ public class BlockRedstoneWire extends Block .add(0.25f, 0, 0, 0.25f, 16, 16).noShade() .e("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() ; - private static final ModelBlock redstone_unus = new ModelBlock("redstone_dust_cross").noOcclude() + private static final Model redstone_unus = ModelProvider.getModelProvider().getModel("redstone_dust_cross") .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_line").uv(0, 0, 16, 16).rot(90).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -81,7 +82,7 @@ public class BlockRedstoneWire extends Block .add(0, 0, 15.75f, 16, 16, 15.75f).noShade() .n("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() ; - private static final ModelBlock redstone_ueuw = new ModelBlock("redstone_dust_cross").noOcclude() + private static final Model redstone_ueuw = ModelProvider.getModelProvider().getModel("redstone_dust_cross") .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_line").uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -96,8 +97,8 @@ public class BlockRedstoneWire extends Block .w("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() ; - private static ModelBlock redstone_n(boolean rot) { - return new ModelBlock("redstone_dust_cross").noOcclude() + private static Model redstone_n(boolean rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross") .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_line").uv(0, 0, 16, 16).rot(90).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -105,8 +106,8 @@ public class BlockRedstoneWire extends Block .rotate(rot ? ModelRotation.X0_Y90 : ModelRotation.X0_Y0); } - private static ModelBlock redstone_ne(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_ne(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() .u().uv(5, 0, 16, 11).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() @@ -114,8 +115,8 @@ public class BlockRedstoneWire extends Block .rotate(rot); } - private static ModelBlock redstone_uew(boolean rot) { - ModelBlock model = new ModelBlock("redstone_dust_cross").noOcclude() + private static Model redstone_uew(boolean rot) { + Model model = ModelProvider.getModelProvider().getModel("redstone_dust_cross") .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_line").uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -126,8 +127,8 @@ public class BlockRedstoneWire extends Block .w("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull(); return rot ? model.uvLock().rotate(ModelRotation.X0_Y180) : model; } - private static ModelBlock redstone_nue(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_nue(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() .u().uv(5, 0, 16, 11).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() @@ -138,8 +139,8 @@ public class BlockRedstoneWire extends Block .w("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(270).noCull() .rotate(rot); } - private static ModelBlock redstone_une(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_une(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() .u().uv(5, 0, 16, 11).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() @@ -150,16 +151,16 @@ public class BlockRedstoneWire extends Block .s("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() .rotate(rot); } - private static ModelBlock redstone_nse(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_nse(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_cross_overlay").uv(5, 0, 16, 16).noCull() .rotate(rot); } - private static ModelBlock redstone_uns(boolean lock, ModelRotation rot) { - ModelBlock model = new ModelBlock("redstone_dust_cross").noOcclude() + private static Model redstone_uns(boolean lock, ModelRotation rot) { + Model model = ModelProvider.getModelProvider().getModel("redstone_dust_cross") .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u("redstone_dust_line").uv(0, 0, 16, 16).rot(90).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -172,8 +173,8 @@ public class BlockRedstoneWire extends Block return lock ? model.uvLock() : model; } - private static ModelBlock redstone_nsue(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_nsue(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -184,8 +185,8 @@ public class BlockRedstoneWire extends Block .w("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(270).noCull() .rotate(rot); } - private static ModelBlock redstone_unse(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_unse(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -196,8 +197,8 @@ public class BlockRedstoneWire extends Block .s("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() .rotate(rot); } - private static ModelBlock redstone_nuse(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_nuse(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -208,8 +209,8 @@ public class BlockRedstoneWire extends Block .n("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() .rotate(rot); } - private static ModelBlock redstone_unue(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_unue(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() .u().uv(5, 0, 16, 11).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 11).noShade() @@ -225,8 +226,8 @@ public class BlockRedstoneWire extends Block .rotate(rot); } - private static ModelBlock redstone_unusue(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_unusue(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -245,8 +246,8 @@ public class BlockRedstoneWire extends Block .w("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() .rotate(rot); } - private static ModelBlock redstone_unusew(boolean rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_unusew(boolean rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -261,8 +262,8 @@ public class BlockRedstoneWire extends Block .n("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() .rotate(rot ? ModelRotation.X0_Y90 : ModelRotation.X0_Y0); } - private static ModelBlock redstone_unusuew(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_unusuew(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -281,8 +282,8 @@ public class BlockRedstoneWire extends Block .w("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() .rotate(rot); } - private static ModelBlock redstone_unuse(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_unuse(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -297,8 +298,8 @@ public class BlockRedstoneWire extends Block .n("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() .rotate(rot); } - private static ModelBlock redstone_nusue(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_nusue(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -313,8 +314,8 @@ public class BlockRedstoneWire extends Block .w("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() .rotate(rot); } - private static ModelBlock redstone_unsew(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_unsew(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -325,8 +326,8 @@ public class BlockRedstoneWire extends Block .s("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() .rotate(rot); } - private static ModelBlock redstone_unsuew(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_unsuew(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(0, 0, 16, 16).tint().noCull() .add(0, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -341,8 +342,8 @@ public class BlockRedstoneWire extends Block .w("redstone_dust_line_overlay").uv(0, 0, 16, 16).rot(90).noCull() .rotate(rot); } - private static ModelBlock redstone_unsue(ModelRotation rot) { - return new ModelBlock("redstone_dust_cross").noOcclude().uvLock() + private static Model redstone_unsue(ModelRotation rot) { + return ModelProvider.getModelProvider().getModel("redstone_dust_cross").uvLock() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() .u().uv(5, 0, 16, 16).tint().noCull() .add(5, 0.25f, 0, 16, 0.25f, 16).noShade() @@ -368,7 +369,7 @@ public class BlockRedstoneWire extends Block public BlockRedstoneWire() { - super(Material.circuits); + super(Material.SMALL); this.setDefaultState(this.getBaseState().withProperty(NORTH, BlockRedstoneWire.EnumAttachPosition.NONE).withProperty(EAST, BlockRedstoneWire.EnumAttachPosition.NONE).withProperty(SOUTH, BlockRedstoneWire.EnumAttachPosition.NONE).withProperty(WEST, BlockRedstoneWire.EnumAttachPosition.NONE).withProperty(POWER, Integer.valueOf(0))); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.0625F, 1.0F); } @@ -540,7 +541,7 @@ public class BlockRedstoneWire extends Block } } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { if (!worldIn.client) { @@ -572,7 +573,7 @@ public class BlockRedstoneWire extends Block } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { super.onBlockRemoved(worldIn, pos, state); @@ -773,7 +774,7 @@ public class BlockRedstoneWire extends Block return -16777216 | i << 16 | j << 8 | k; } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { int i = ((Integer)state.getValue(POWER)).intValue(); @@ -825,7 +826,7 @@ public class BlockRedstoneWire extends Block return true; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { boolean na = state.getValue(NORTH) == EnumAttachPosition.NONE; boolean sa = state.getValue(SOUTH) == EnumAttachPosition.NONE; boolean wa = state.getValue(WEST) == EnumAttachPosition.NONE; @@ -1026,7 +1027,7 @@ public class BlockRedstoneWire extends Block return new IProperty[] {POWER}; } - static enum EnumAttachPosition implements IStringSerializable + static enum EnumAttachPosition implements Identifyable { UP("up"), SIDE("side"), diff --git a/java/src/game/block/BlockTNT.java b/common/src/main/java/common/block/tech/BlockTNT.java similarity index 82% rename from java/src/game/block/BlockTNT.java rename to common/src/main/java/common/block/tech/BlockTNT.java index 843a60b..45c5fbf 100755 --- a/java/src/game/block/BlockTNT.java +++ b/common/src/main/java/common/block/tech/BlockTNT.java @@ -1,28 +1,30 @@ -package game.block; +package common.block.tech; import java.util.List; -import game.entity.Entity; -import game.entity.item.EntityTnt; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityArrow; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.init.SoundEvent; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.Explosion; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.entity.item.EntityTnt; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityArrow; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.init.SoundEvent; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyInteger; +import common.util.BlockPos; +import common.util.Facing; +import common.world.Explosion; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockTNT extends Block { @@ -31,12 +33,12 @@ public class BlockTNT extends Block public BlockTNT() { - super(Material.tnt); + super(Material.EXPLOSIVE); this.setDefaultState(this.getBaseState().withProperty(EXPLODE, Boolean.valueOf(false))); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { super.onBlockAdded(worldIn, pos, state); @@ -110,7 +112,7 @@ public class BlockTNT extends Block } else // if (!playerIn.creative) { - --playerIn.getCurrentEquippedItem().stackSize; + --playerIn.getCurrentEquippedItem().size; } return true; @@ -183,9 +185,9 @@ public class BlockTNT extends Block return true; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { String power = state.getValue(POWER) == 0 ? "" : ("_" + state.getValue(POWER)); - return new ModelBlock("tnt_side" + power).add().nswe().d("tnt_bottom" + power).u("tnt_top" + power); + return provider.getModel("tnt_side" + power).add().nswe().d("tnt_bottom" + power).u("tnt_top" + power); } public IProperty[] getIgnoredProperties() { diff --git a/common/src/main/java/common/block/tech/BlockTianReactor.java b/common/src/main/java/common/block/tech/BlockTianReactor.java new file mode 100755 index 0000000..9d3ae88 --- /dev/null +++ b/common/src/main/java/common/block/tech/BlockTianReactor.java @@ -0,0 +1,26 @@ +package common.block.tech; + +import java.util.Map; + +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityTianReactor; +import common.world.State; +import common.world.World; + +public class BlockTianReactor extends BlockMachine { + public TileEntity createNewTileEntity(World world) { + return new TileEntityTianReactor(); + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("tian_reactor_front").add().d("tian_reactor_bottom").u("tian_reactor_top").n().s("tian_reactor_side") + .we("tian_reactor_side").rotate(ModelRotation.getNorthRot(state.getValue(FACING))); + } + + public void getAnimatedTextures(Map map) { + map.put("blocks/tian_reactor_front", 5); + } +} diff --git a/java/src/game/block/BlockTorch.java b/common/src/main/java/common/block/tech/BlockTorch.java similarity index 87% rename from java/src/game/block/BlockTorch.java rename to common/src/main/java/common/block/tech/BlockTorch.java index 5aff3b1..91d82e4 100755 --- a/java/src/game/block/BlockTorch.java +++ b/common/src/main/java/common/block/tech/BlockTorch.java @@ -1,28 +1,31 @@ -package game.block; +package common.block.tech; import java.util.function.Predicate; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.item.CheatTab; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Chunk; -import game.world.Facing; -import game.world.HitPosition; -import game.world.State; -import game.world.Vec3; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockDirectional; +import common.block.Material; +import common.block.artificial.BlockFence; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.item.CheatTab; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.ParticleType; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.util.HitPosition; +import common.util.Vec3; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockTorch extends Block { @@ -35,28 +38,18 @@ public class BlockTorch extends Block }); private static boolean isBlockNormalCube(World world, BlockPos pos, boolean def) { - if(!World.isValid(pos)) { + if(!World.isValid(pos) || (world.client && !world.isBlockLoaded(pos, false))) return def; - } - else { - Chunk chunk = world.getChunk(pos.getX() >> 4, pos.getZ() >> 4); - - if(chunk.isEmpty()) { - return def; - } - else { - Block block = world.getState(pos).getBlock(); - return block.getMaterial().isOpaque() && block.isFullCube(); - } - } + Block block = world.getState(pos).getBlock(); + return block.getMaterial().isOpaque() && block.isFullCube(); } public BlockTorch() { - super(Material.circuits); + super(Material.SMALL); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.UP)); // this.setTickRandomly(true); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); } public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) @@ -134,7 +127,7 @@ public class BlockTorch extends Block } } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { this.checkForDrop(worldIn, pos, state); } @@ -233,7 +226,7 @@ public class BlockTorch extends Block return super.collisionRayTrace(worldIn, pos, start, end); } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { Facing enumfacing = (Facing)state.getValue(FACING); double d0 = (double)pos.getX() + 0.5D; @@ -332,9 +325,9 @@ public class BlockTorch extends Block return new IProperty[] {FACING}; } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { if(state.getValue(FACING) == Facing.UP) - return new ModelBlock(name).noOcclude() + return provider.getModel(name) .add(7, 0, 7, 9, 10, 9).noShade() .d().uv(7, 13, 9, 15).noCull() .u().uv(7, 6, 9, 8).noCull() @@ -345,7 +338,7 @@ public class BlockTorch extends Block .n().uv(0, 0, 16, 16).noCull() .s().uv(0, 0, 16, 16).noCull(); else - return new ModelBlock(name).noOcclude() + return provider.getModel(name) .add(-1, 3.5f, 7, 1, 13.5f, 9).noShade().rotate(0, 3.5f, 8, Facing.Axis.Z, -22.5f, false) .d().uv(7, 13, 9, 15).noCull() .u().uv(7, 6, 9, 8).noCull() diff --git a/java/src/game/block/BlockTripWire.java b/common/src/main/java/common/block/tech/BlockTripWire.java similarity index 89% rename from java/src/game/block/BlockTripWire.java rename to common/src/main/java/common/block/tech/BlockTripWire.java index 7252904..8ed734d 100755 --- a/java/src/game/block/BlockTripWire.java +++ b/common/src/main/java/common/block/tech/BlockTripWire.java @@ -1,28 +1,30 @@ -package game.block; +package common.block.tech; import java.util.List; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Items; -import game.item.Item; -import game.item.ItemShears; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.item.Item; +import common.item.ItemShears; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IBlockAccess; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockTripWire extends Block { @@ -37,7 +39,7 @@ public class BlockTripWire extends Block public BlockTripWire() { - super(Material.circuits); + super(Material.SMALL); this.setDefaultState(this.getBaseState().withProperty(POWERED, Boolean.valueOf(false)).withProperty(SUSPENDED, Boolean.valueOf(false)).withProperty(ATTACHED, Boolean.valueOf(false)).withProperty(DISARMED, Boolean.valueOf(false)).withProperty(NORTH, Boolean.valueOf(false)).withProperty(EAST, Boolean.valueOf(false)).withProperty(SOUTH, Boolean.valueOf(false)).withProperty(WEST, Boolean.valueOf(false))); this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 0.15625F, 1.0F); // this.setTickRandomly(true); @@ -123,14 +125,14 @@ public class BlockTripWire extends Block } } - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) + public void onBlockAdded(AWorldServer worldIn, BlockPos pos, State state) { state = state.withProperty(SUSPENDED, Boolean.valueOf(!worldIn.isBlockSolid(pos.down()))); worldIn.setState(pos, state, 3); this.notifyHook(worldIn, pos, state); } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { this.notifyHook(worldIn, pos, state.withProperty(POWERED, Boolean.valueOf(true))); } @@ -190,11 +192,11 @@ public class BlockTripWire extends Block /** * Called randomly when setTickRandomly is set to true (used by e.g. crops to grow, etc.) */ - public void randomTick(WorldServer worldIn, BlockPos pos, State state, Random random) + public void randomTick(AWorldServer worldIn, BlockPos pos, State state, Random random) { } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { // if (!worldIn.client) // { @@ -303,9 +305,9 @@ public class BlockTripWire extends Block return new IProperty[] {POWERED, SUSPENDED, ATTACHED, DISARMED, NORTH, EAST, WEST, SOUTH}; } - private static ModelBlock getModelDetached(boolean n, boolean s, boolean w, boolean e, int sides) { + private static Model getModelDetached(boolean n, boolean s, boolean w, boolean e, int sides) { if(sides == 1) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -317,7 +319,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -333,7 +335,7 @@ public class BlockTripWire extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -348,7 +350,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(sides == 3) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -369,7 +371,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).noCull() .rotate(!w ? ModelRotation.X0_Y0 : (!e ? ModelRotation.X0_Y180 : (!s ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -396,9 +398,9 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).noCull(); } - private static ModelBlock getModelAttached(boolean n, boolean s, boolean w, boolean e, int sides) { + private static Model getModelAttached(boolean n, boolean s, boolean w, boolean e, int sides) { if(sides == 1) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -410,7 +412,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -426,7 +428,7 @@ public class BlockTripWire extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -441,7 +443,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(sides == 3) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -462,7 +464,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).noCull() .rotate(!w ? ModelRotation.X0_Y0 : (!e ? ModelRotation.X0_Y180 : (!s ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -489,9 +491,9 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).noCull(); } - private static ModelBlock getModelDetSuspend(boolean n, boolean s, boolean w, boolean e, int sides) { + private static Model getModelDetSuspend(boolean n, boolean s, boolean w, boolean e, int sides) { if(sides == 1) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -503,7 +505,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -519,7 +521,7 @@ public class BlockTripWire extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -534,7 +536,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(sides == 3) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -555,7 +557,7 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).noCull() .rotate(!w ? ModelRotation.X0_Y0 : (!e ? ModelRotation.X0_Y180 : (!s ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 2, 16, 0).rot(90).noCull() .u().uv(0, 0, 16, 2).rot(90).noCull() @@ -582,9 +584,9 @@ public class BlockTripWire extends Block .u().uv(0, 0, 16, 2).noCull(); } - private static ModelBlock getModelAttSuspend(boolean n, boolean s, boolean w, boolean e, int sides) { + private static Model getModelAttSuspend(boolean n, boolean s, boolean w, boolean e, int sides) { if(sides == 1) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -596,7 +598,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : (s ? ModelRotation.X0_Y180 : (w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2 && ((e != w) || (n != s))) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -612,7 +614,7 @@ public class BlockTripWire extends Block .rotate(n && e ? ModelRotation.X0_Y0 : (s && w ? ModelRotation.X0_Y180 : (n && w ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else if(sides == 2) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -627,7 +629,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).rot(90).noCull() .rotate(n ? ModelRotation.X0_Y0 : ModelRotation.X0_Y90); else if(sides == 3) - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -648,7 +650,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).noCull() .rotate(!w ? ModelRotation.X0_Y0 : (!e ? ModelRotation.X0_Y180 : (!s ? ModelRotation.X0_Y270 : ModelRotation.X0_Y90))); else - return new ModelBlock("trip_wire").noOcclude() + return ModelProvider.getModelProvider().getModel("trip_wire") .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 4).noShade() .d().uv(0, 4, 16, 2).rot(90).noCull() .u().uv(0, 2, 16, 4).rot(90).noCull() @@ -675,7 +677,7 @@ public class BlockTripWire extends Block .u().uv(0, 2, 16, 4).noCull(); } - public ModelBlock getModel(String name, State state) { + public Model getModel(ModelProvider provider, String name, State state) { boolean n = state.getValue(NORTH); boolean s = state.getValue(SOUTH); boolean w = state.getValue(WEST); diff --git a/java/src/game/block/BlockTripWireHook.java b/common/src/main/java/common/block/tech/BlockTripWireHook.java similarity index 93% rename from java/src/game/block/BlockTripWireHook.java rename to common/src/main/java/common/block/tech/BlockTripWireHook.java index c1cfb43..95cb387 100755 --- a/java/src/game/block/BlockTripWireHook.java +++ b/common/src/main/java/common/block/tech/BlockTripWireHook.java @@ -1,25 +1,27 @@ -package game.block; +package common.block.tech; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.SoundEvent; -import game.item.CheatTab; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyBool; -import game.properties.PropertyDirection; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.SoundEvent; +import common.item.CheatTab; +import common.item.ItemStack; +import common.model.BlockLayer; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.properties.IProperty; +import common.properties.PropertyBool; +import common.properties.PropertyDirection; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class BlockTripWireHook extends Block { @@ -30,9 +32,9 @@ public class BlockTripWireHook extends Block public BlockTripWireHook() { - super(Material.circuits); + super(Material.SMALL); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH).withProperty(POWERED, Boolean.valueOf(false)).withProperty(ATTACHED, Boolean.valueOf(false)).withProperty(SUSPENDED, Boolean.valueOf(false))); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); // this.setTickRandomly(true); } @@ -224,11 +226,11 @@ public class BlockTripWireHook extends Block /** * Called randomly when setTickRandomly is set to true (used by e.g. crops to grow, etc.) */ - public void randomTick(WorldServer worldIn, BlockPos pos, State state, Random random) + public void randomTick(AWorldServer worldIn, BlockPos pos, State state, Random random) { } - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) + public void updateTick(AWorldServer worldIn, BlockPos pos, State state, Random rand) { this.triggerHookAt(worldIn, pos, state, false, true, -1, (State)null); } @@ -297,7 +299,7 @@ public class BlockTripWireHook extends Block } } - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) + public void onBlockRemoved(AWorldServer worldIn, BlockPos pos, State state) { boolean flag = ((Boolean)state.getValue(ATTACHED)).booleanValue(); boolean flag1 = ((Boolean)state.getValue(POWERED)).booleanValue(); @@ -377,12 +379,12 @@ public class BlockTripWireHook extends Block return true; } - public ModelBlock getModel(String name, State state) { - ModelBlock model; + public Model getModel(ModelProvider provider, String name, State state) { + Model model; if(state.getValue(ATTACHED)) { if(state.getValue(SUSPENDED)) { if(state.getValue(POWERED)) - model = new ModelBlock("oak_planks") + model = provider.getModel("oak_planks") .add(7.75f, 2.5f, 0, 8.25f, 2.5f, 6.7f).rotate(8, 0, 0, Facing.Axis.X, -22.5f, true) .d("trip_wire").uv(0, 8, 16, 6).rot(90).noCull() .u("trip_wire").uv(0, 6, 16, 8).rot(90).noCull() @@ -416,7 +418,7 @@ public class BlockTripWireHook extends Block .w().uv(0, 7, 2, 15).noCull() .e().uv(14, 7, 16, 15).noCull(); else - model = new ModelBlock("oak_planks") + model = provider.getModel("oak_planks") .add(7.75f, 3.5f, 0, 8.25f, 3.5f, 6.7f).rotate(8, 0, 0, Facing.Axis.X, -22.5f, true) .d("trip_wire").uv(0, 8, 16, 6).rot(90).noCull() .u("trip_wire").uv(0, 6, 16, 8).rot(90).noCull() @@ -452,7 +454,7 @@ public class BlockTripWireHook extends Block } else { if(state.getValue(POWERED)) - model = new ModelBlock("oak_planks") + model = provider.getModel("oak_planks") .add(7.75f, 0.5f, 0, 8.25f, 0.5f, 6.7f).rotate(8, 0, 0, Facing.Axis.X, -22.5f, true) .d("trip_wire").uv(0, 8, 16, 6).rot(90).noCull() .u("trip_wire").uv(0, 6, 16, 8).rot(90).noCull() @@ -486,7 +488,7 @@ public class BlockTripWireHook extends Block .w().uv(0, 7, 2, 15).noCull() .e().uv(14, 7, 16, 15).noCull(); else - model = new ModelBlock("oak_planks") + model = provider.getModel("oak_planks") .add(7.75f, 1.5f, 0, 8.25f, 1.5f, 6.7f).rotate(8, 0, 0, Facing.Axis.X, -22.5f, true) .d("trip_wire").uv(0, 8, 16, 6).rot(90).noCull() .u("trip_wire").uv(0, 6, 16, 8).rot(90).noCull() @@ -523,7 +525,7 @@ public class BlockTripWireHook extends Block } else { if(state.getValue(POWERED)) - model = new ModelBlock("oak_planks") + model = provider.getModel("oak_planks") .add(6.2f, 4.2f, 6.7f, 9.8f, 5, 10.3f) .d("tripwire_hook").uv(5, 3, 11, 9).noCull() .u("tripwire_hook").uv(5, 3, 11, 9).noCull() @@ -554,7 +556,7 @@ public class BlockTripWireHook extends Block .w().uv(0, 7, 2, 15).noCull() .e().uv(14, 7, 16, 15).noCull(); else - model = new ModelBlock("oak_planks") + model = provider.getModel("oak_planks") .add(6.2f, 3.8f, 7.9f, 9.8f, 4.6f, 11.5f).rotate(8, 6, 5.2f, Facing.Axis.X, -45, false) .d("tripwire_hook").uv(5, 3, 11, 9).noCull() .u("tripwire_hook").uv(5, 3, 11, 9).noCull() diff --git a/java/src/game/block/BlockWarpChest.java b/common/src/main/java/common/block/tech/BlockWarpChest.java similarity index 79% rename from java/src/game/block/BlockWarpChest.java rename to common/src/main/java/common/block/tech/BlockWarpChest.java index 423ad01..e1cfa54 100755 --- a/java/src/game/block/BlockWarpChest.java +++ b/common/src/main/java/common/block/tech/BlockWarpChest.java @@ -1,25 +1,27 @@ -package game.block; +package common.block.tech; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.ItemRegistry; -import game.inventory.InventoryWarpChest; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldClient; +import common.block.Block; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.inventory.InventoryWarpChest; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemStack; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ModelRotation; +import common.model.ParticleType; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.AWorldClient; +import common.world.State; +import common.world.World; public class BlockWarpChest extends Block { @@ -27,9 +29,9 @@ public class BlockWarpChest extends Block public BlockWarpChest() { - super(Material.rock); + super(Material.SOLID); this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); this.setBlockBounds(0.0625F, 0.0F, 0.0625F, 0.9375F, 0.875F, 0.9375F); } @@ -54,8 +56,8 @@ public class BlockWarpChest extends Block // return 2; // } - public ModelBlock getModel(String name, State state) { - return new ModelBlock("warp_chest_side").add(1, 0, 1, 15, 14, 15).d("warp_chest_top").u("warp_chest_top").noCull() + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("warp_chest_side").add(1, 0, 1, 15, 14, 15).d("warp_chest_top").u("warp_chest_top").noCull() .n("warp_chest_front").noCull().s().noCull().we().noCull().rotate(ModelRotation.getNorthRot(state.getValue(FACING))); } @@ -116,7 +118,7 @@ public class BlockWarpChest extends Block // return new TileEntityWarpChest(); // } - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) + public void randomDisplayTick(AWorldClient worldIn, BlockPos pos, State state, Random rand) { for (int i = 0; i < 3; ++i) { diff --git a/common/src/main/java/common/block/tech/BlockWorkbench.java b/common/src/main/java/common/block/tech/BlockWorkbench.java new file mode 100755 index 0000000..5e803da --- /dev/null +++ b/common/src/main/java/common/block/tech/BlockWorkbench.java @@ -0,0 +1,81 @@ +package common.block.tech; + +import common.block.Block; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.init.BlockRegistry; +import common.inventory.Container; +import common.inventory.ContainerWorkbench; +import common.inventory.InventoryPlayer; +import common.item.CheatTab; +import common.model.Model; +import common.model.ModelProvider; +import common.tileentity.IInteractionObject; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; + +public class BlockWorkbench extends Block +{ + private final int size; + + public BlockWorkbench(int size) + { + super(Material.WOOD); + this.setTab(CheatTab.TECHNOLOGY); + this.size = size; + } + + public int getSize() { + return this.size; + } + + public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) + { + if (worldIn.client) + { + return true; + } + else + { + playerIn.displayGui(new BlockWorkbench.InterfaceCraftingTable(worldIn, pos, this)); +// playerIn.triggerAchievement(StatRegistry.craftingTableStat); + return true; + } + } + + public Model getModel(ModelProvider provider, String name, State state) { + return provider.getModel("crafting_table_front").add().d("oak_planks").u("crafting_table_top").n().s("crafting_table_side") + .w().e("crafting_table_side"); + } + + public static class InterfaceCraftingTable implements IInteractionObject + { + private final World world; + private final BlockPos position; + private final BlockWorkbench block; + + public InterfaceCraftingTable(World worldIn, BlockPos pos, BlockWorkbench block) + { + this.world = worldIn; + this.position = pos; + this.block = block; + } + + public String getCommandName() + { + return this.block.getDisplay(); + } + + public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) + { + return new ContainerWorkbench(playerInventory, this.world, this.position, this.block); + } + + public String getGuiID() + { + return BlockRegistry.getNameFromBlock(this.block); + } + } +} diff --git a/common/src/main/java/common/block/tile/BlockBanner.java b/common/src/main/java/common/block/tile/BlockBanner.java new file mode 100755 index 0000000..e34b8e8 --- /dev/null +++ b/common/src/main/java/common/block/tile/BlockBanner.java @@ -0,0 +1,165 @@ +package common.block.tile; + +import common.block.BlockContainer; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.item.Item; +import common.item.ItemStack; +import common.model.Transforms; +import common.properties.PropertyDirection; +import common.properties.PropertyInteger; +import common.rng.Random; +import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityBanner; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.IBlockAccess; +import common.world.State; +import common.world.World; + +public class BlockBanner extends BlockContainer +{ + public static final PropertyDirection FACING = PropertyDirection.create("facing", Facing.Plane.HORIZONTAL); + public static final PropertyInteger ROTATION = PropertyInteger.create("rotation", 0, 15); + + public BlockBanner() + { + super(Material.WOOD); + float f = 0.25F; + float f1 = 1.0F; + this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); + } + +// /** +// * Gets the localized name of this block. Used for the statistics page. +// */ +// public String getLocalizedName() +// { +// return "Banner"; +// } + + public boolean isPickStrict() + { + return true; + } + + public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) + { + return null; + } + + public BoundingBox getSelectedBoundingBox(World worldIn, BlockPos pos) + { + this.setBlockBoundsBasedOnState(worldIn, pos); + return super.getSelectedBoundingBox(worldIn, pos); + } + + public boolean isFullCube() + { + return false; + } + + public boolean isPassable(IBlockAccess worldIn, BlockPos pos) + { + return true; + } + + /** + * Used to determine ambient occlusion and culling when rebuilding chunks for render + */ + public boolean isOpaqueCube() + { + return false; + } + + /** + * Return true if an entity can be spawned inside the block (used to get the player's bed spawn location) + */ + public boolean canSpawnInBlock() + { + return true; + } + + /** + * Returns a new instance of a block's tile entity class. Called on placing the block. + */ + public TileEntity createNewTileEntity(World worldIn) + { + return new TileEntityBanner(); + } + + /** + * Get the Item that this Block should drop when harvested. + */ + public Item getItemDropped(State state, Random rand, int fortune) + { + return Items.banner; + } + + public Item getItem(World worldIn, BlockPos pos) + { + return Items.banner; + } + + public int getDamageValue(World worldIn, BlockPos pos) + { + TileEntity te = worldIn.getTileEntity(pos); + if(te instanceof TileEntityBanner) + return ((TileEntityBanner)te).getBaseColor(); + return super.getDamageValue(worldIn, pos); + } + + /** + * Spawns this Block's drops into the World as EntityItems. + */ + public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) + { + TileEntity tileentity = worldIn.getTileEntity(pos); + + if (tileentity instanceof TileEntityBanner) + { + ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner)tileentity).getBaseColor()); + TagObject tag = new TagObject(); + tileentity.writeTags(tag); + tag.remove("x"); + tag.remove("y"); + tag.remove("z"); + tag.remove("id"); + itemstack.setTagInfo("BlockEntityTag", tag); + spawnAsEntity(worldIn, pos, itemstack); + } + else + { + super.dropBlockAsItemWithChance(worldIn, pos, state, chance, fortune); + } + } + + public boolean canPlaceBlockAt(World worldIn, BlockPos pos) + { + return !this.hasInvalidNeighbor(worldIn, pos) && super.canPlaceBlockAt(worldIn, pos); + } + + public void harvestBlock(World worldIn, EntityNPC player, BlockPos pos, State state, TileEntity te) + { + if (te instanceof TileEntityBanner) + { + TileEntityBanner tileentitybanner = (TileEntityBanner)te; + ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner)te).getBaseColor()); + TagObject tag = new TagObject(); + TileEntityBanner.setBaseColorAndPatterns(tag, tileentitybanner.getBaseColor(), tileentitybanner.getPatterns()); + itemstack.setTagInfo("BlockEntityTag", tag); + spawnAsEntity(worldIn, pos, itemstack); + } + else + { + super.harvestBlock(worldIn, player, pos, state, (TileEntity)null); + } + } + + public Transforms getTransform() { + return Transforms.BANNER; + } +} diff --git a/common/src/main/java/common/block/tile/BlockBannerHanging.java b/common/src/main/java/common/block/tile/BlockBannerHanging.java new file mode 100644 index 0000000..1d54303 --- /dev/null +++ b/common/src/main/java/common/block/tile/BlockBannerHanging.java @@ -0,0 +1,82 @@ +package common.block.tile; + +import common.block.Block; +import common.properties.IProperty; +import common.util.BlockPos; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; + +public class BlockBannerHanging extends BlockBanner +{ + public BlockBannerHanging() + { + this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); + } + + public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos) + { + Facing enumfacing = (Facing)worldIn.getState(pos).getValue(FACING); + float f = 0.0F; + float f1 = 0.78125F; + float f2 = 0.0F; + float f3 = 1.0F; + float f4 = 0.125F; + this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); + + switch (enumfacing) + { + case NORTH: + default: + this.setBlockBounds(f2, f, 1.0F - f4, f3, f1, 1.0F); + break; + + case SOUTH: + this.setBlockBounds(f2, f, 0.0F, f3, f1, f4); + break; + + case WEST: + this.setBlockBounds(1.0F - f4, f, f2, 1.0F, f1, f3); + break; + + case EAST: + this.setBlockBounds(0.0F, f, f2, f4, f1, f3); + } + } + + public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) + { + Facing enumfacing = (Facing)state.getValue(FACING); + + if (!worldIn.getState(pos.offset(enumfacing.getOpposite())).getBlock().getMaterial().isSolid()) + { + this.dropBlockAsItem(worldIn, pos, state, 0); + worldIn.setBlockToAir(pos); + } + + super.onNeighborBlockChange(worldIn, pos, state, neighborBlock); + } + + public State getStateFromMeta(int meta) + { + Facing enumfacing = Facing.getFront(meta); + + if (enumfacing.getAxis() == Facing.Axis.Y) + { + enumfacing = Facing.NORTH; + } + + return this.getState().withProperty(FACING, enumfacing); + } + + public int getMetaFromState(State state) + { + return ((Facing)state.getValue(FACING)).getIndex(); + } + + protected IProperty[] getProperties() + { + return new IProperty[] {FACING}; + } +} \ No newline at end of file diff --git a/common/src/main/java/common/block/tile/BlockBannerStanding.java b/common/src/main/java/common/block/tile/BlockBannerStanding.java new file mode 100644 index 0000000..9a6e28c --- /dev/null +++ b/common/src/main/java/common/block/tile/BlockBannerStanding.java @@ -0,0 +1,41 @@ +package common.block.tile; + +import common.block.Block; +import common.properties.IProperty; +import common.util.BlockPos; +import common.world.State; +import common.world.World; + +public class BlockBannerStanding extends BlockBanner +{ + public BlockBannerStanding() + { + this.setDefaultState(this.getBaseState().withProperty(ROTATION, Integer.valueOf(0))); + } + + public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) + { + if (!worldIn.getState(pos.down()).getBlock().getMaterial().isSolid()) + { + this.dropBlockAsItem(worldIn, pos, state, 0); + worldIn.setBlockToAir(pos); + } + + super.onNeighborBlockChange(worldIn, pos, state, neighborBlock); + } + + public State getStateFromMeta(int meta) + { + return this.getState().withProperty(ROTATION, Integer.valueOf(meta)); + } + + public int getMetaFromState(State state) + { + return ((Integer)state.getValue(ROTATION)).intValue(); + } + + protected IProperty[] getProperties() + { + return new IProperty[] {ROTATION}; + } +} \ No newline at end of file diff --git a/java/src/game/block/BlockSign.java b/common/src/main/java/common/block/tile/BlockSign.java similarity index 70% rename from java/src/game/block/BlockSign.java rename to common/src/main/java/common/block/tile/BlockSign.java index 28730a3..d467d32 100755 --- a/java/src/game/block/BlockSign.java +++ b/common/src/main/java/common/block/tile/BlockSign.java @@ -1,27 +1,45 @@ -package game.block; +package common.block.tile; -import game.init.Items; -import game.item.Item; -import game.material.Material; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntitySign; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.IBlockAccess; -import game.world.State; -import game.world.World; +import common.block.BlockContainer; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.item.Item; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.tileentity.TileEntitySign; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.vars.Vars; +import common.world.IBlockAccess; +import common.world.State; +import common.world.World; public class BlockSign extends BlockContainer { public BlockSign() { - super(Material.wood); + super(Material.WOOD); float f = 0.25F; float f1 = 1.0F; this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); } + public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) + { + if (!worldIn.client && Vars.editSigns) + { + TileEntity tileentity = worldIn.getTileEntity(pos); + + if (tileentity instanceof TileEntitySign) + { + playerIn.openEditSign((TileEntitySign)tileentity); + } + } + return true; + } + public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) { return null; @@ -62,7 +80,7 @@ public class BlockSign extends BlockContainer /** * Returns a new instance of a block's tile entity class. Called on placing the block. */ - public TileEntity createNewTileEntity(World worldIn, int meta) + public TileEntity createNewTileEntity(World worldIn) { return new TileEntitySign(); } @@ -94,7 +112,7 @@ public class BlockSign extends BlockContainer // return true; // } -// public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) +// public void onBlockRemoved(IWorldServer worldIn, BlockPos pos, State state) // { // if(!worldIn.client) { // TileEntity tileentity = worldIn.getTileEntity(pos); diff --git a/java/src/game/block/BlockStandingSign.java b/common/src/main/java/common/block/tile/BlockStandingSign.java similarity index 85% rename from java/src/game/block/BlockStandingSign.java rename to common/src/main/java/common/block/tile/BlockStandingSign.java index 0eaaf14..f6a616a 100755 --- a/java/src/game/block/BlockStandingSign.java +++ b/common/src/main/java/common/block/tile/BlockStandingSign.java @@ -1,10 +1,11 @@ -package game.block; +package common.block.tile; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.properties.IProperty; +import common.properties.PropertyInteger; +import common.util.BlockPos; +import common.world.State; +import common.world.World; public class BlockStandingSign extends BlockSign { diff --git a/java/src/game/block/BlockWallSign.java b/common/src/main/java/common/block/tile/BlockWallSign.java similarity index 89% rename from java/src/game/block/BlockWallSign.java rename to common/src/main/java/common/block/tile/BlockWallSign.java index 55133c0..b390bd6 100755 --- a/java/src/game/block/BlockWallSign.java +++ b/common/src/main/java/common/block/tile/BlockWallSign.java @@ -1,12 +1,13 @@ -package game.block; +package common.block.tile; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.util.BlockPos; +import common.util.Facing; +import common.world.IWorldAccess; +import common.world.State; +import common.world.World; public class BlockWallSign extends BlockSign { diff --git a/java/src/game/collect/AbstractBiMap.java b/common/src/main/java/common/collect/AbstractBiMap.java similarity index 98% rename from java/src/game/collect/AbstractBiMap.java rename to common/src/main/java/common/collect/AbstractBiMap.java index d2c3336..f1ebdfa 100644 --- a/java/src/game/collect/AbstractBiMap.java +++ b/common/src/main/java/common/collect/AbstractBiMap.java @@ -14,11 +14,11 @@ * limitations under the License. */ -package game.collect; +package common.collect; -import static game.collect.CollectPreconditions.checkRemove; -import static game.collect.Preconditions.checkArgument; -import static game.collect.Preconditions.checkState; +import static common.collect.CollectPreconditions.checkRemove; +import static common.collect.Preconditions.checkArgument; +import static common.collect.Preconditions.checkState; import java.io.IOException; import java.io.ObjectInputStream; diff --git a/java/src/game/collect/AbstractIndexedListIterator.java b/common/src/main/java/common/collect/AbstractIndexedListIterator.java similarity index 97% rename from java/src/game/collect/AbstractIndexedListIterator.java rename to common/src/main/java/common/collect/AbstractIndexedListIterator.java index a2056ae..224444d 100644 --- a/java/src/game/collect/AbstractIndexedListIterator.java +++ b/common/src/main/java/common/collect/AbstractIndexedListIterator.java @@ -14,9 +14,9 @@ * limitations under the License. */ -package game.collect; +package common.collect; -import static game.collect.Preconditions.checkPositionIndex; +import static common.collect.Preconditions.checkPositionIndex; import java.util.NoSuchElementException; diff --git a/java/src/game/collect/AbstractIterator.java b/common/src/main/java/common/collect/AbstractIterator.java similarity index 98% rename from java/src/game/collect/AbstractIterator.java rename to common/src/main/java/common/collect/AbstractIterator.java index 7ba15e0..a33bfe7 100644 --- a/java/src/game/collect/AbstractIterator.java +++ b/common/src/main/java/common/collect/AbstractIterator.java @@ -14,9 +14,9 @@ * limitations under the License. */ -package game.collect; +package common.collect; -import static game.collect.Preconditions.checkState; +import static common.collect.Preconditions.checkState; import java.util.NoSuchElementException; diff --git a/java/src/game/collect/AbstractMapEntry.java b/common/src/main/java/common/collect/AbstractMapEntry.java similarity index 98% rename from java/src/game/collect/AbstractMapEntry.java rename to common/src/main/java/common/collect/AbstractMapEntry.java index 4c89223..18c350c 100644 --- a/java/src/game/collect/AbstractMapEntry.java +++ b/common/src/main/java/common/collect/AbstractMapEntry.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; import java.util.Map.Entry; diff --git a/java/src/game/collect/AbstractTable.java b/common/src/main/java/common/collect/AbstractTable.java similarity index 99% rename from java/src/game/collect/AbstractTable.java rename to common/src/main/java/common/collect/AbstractTable.java index b19ada4..60a7906 100644 --- a/java/src/game/collect/AbstractTable.java +++ b/common/src/main/java/common/collect/AbstractTable.java @@ -12,7 +12,7 @@ * the License. */ -package game.collect; +package common.collect; import java.util.AbstractCollection; import java.util.AbstractSet; diff --git a/java/src/game/collect/BiMap.java b/common/src/main/java/common/collect/BiMap.java similarity index 99% rename from java/src/game/collect/BiMap.java rename to common/src/main/java/common/collect/BiMap.java index 3b920df..7effc10 100644 --- a/java/src/game/collect/BiMap.java +++ b/common/src/main/java/common/collect/BiMap.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; import java.util.Map; import java.util.Set; diff --git a/java/src/game/collect/CollectPreconditions.java b/common/src/main/java/common/collect/CollectPreconditions.java similarity index 94% rename from java/src/game/collect/CollectPreconditions.java rename to common/src/main/java/common/collect/CollectPreconditions.java index 520d5d2..f84a833 100644 --- a/java/src/game/collect/CollectPreconditions.java +++ b/common/src/main/java/common/collect/CollectPreconditions.java @@ -14,9 +14,9 @@ * limitations under the License. */ -package game.collect; +package common.collect; -import static game.collect.Preconditions.checkState; +import static common.collect.Preconditions.checkState; /** * Precondition checks useful in collection implementations. diff --git a/java/src/game/collect/DenseImmutableTable.java b/common/src/main/java/common/collect/DenseImmutableTable.java similarity index 98% rename from java/src/game/collect/DenseImmutableTable.java rename to common/src/main/java/common/collect/DenseImmutableTable.java index 5afd429..a4e1611 100644 --- a/java/src/game/collect/DenseImmutableTable.java +++ b/common/src/main/java/common/collect/DenseImmutableTable.java @@ -12,9 +12,9 @@ * the License. */ -package game.collect; +package common.collect; -import static game.collect.Preconditions.checkArgument; +import static common.collect.Preconditions.checkArgument; import java.util.Map; diff --git a/java/src/game/collect/EmptyImmutableMap.java b/common/src/main/java/common/collect/EmptyImmutableMap.java similarity index 99% rename from java/src/game/collect/EmptyImmutableMap.java rename to common/src/main/java/common/collect/EmptyImmutableMap.java index 866868a..84d8d06 100644 --- a/java/src/game/collect/EmptyImmutableMap.java +++ b/common/src/main/java/common/collect/EmptyImmutableMap.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; /** * Bimap with no mappings. diff --git a/java/src/game/collect/EmptyImmutableSet.java b/common/src/main/java/common/collect/EmptyImmutableSet.java similarity index 98% rename from java/src/game/collect/EmptyImmutableSet.java rename to common/src/main/java/common/collect/EmptyImmutableSet.java index f86b50f..9605ea9 100644 --- a/java/src/game/collect/EmptyImmutableSet.java +++ b/common/src/main/java/common/collect/EmptyImmutableSet.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; import java.util.Collection; import java.util.Set; diff --git a/java/src/game/collect/Filter.java b/common/src/main/java/common/collect/Filter.java similarity index 98% rename from java/src/game/collect/Filter.java rename to common/src/main/java/common/collect/Filter.java index 3d45f77..c403295 100644 --- a/java/src/game/collect/Filter.java +++ b/common/src/main/java/common/collect/Filter.java @@ -14,20 +14,20 @@ * limitations under the License. */ -package game.collect; +package common.collect; -import static game.collect.Preconditions.checkArgument; -import static game.collect.Preconditions.checkNotNull; -import static game.util.Predicates.and; -import static game.util.Predicates.in; -import static game.util.Predicates.not; +import static common.collect.Preconditions.checkArgument; +import static common.collect.Preconditions.checkNotNull; +import static common.util.Predicates.and; +import static common.util.Predicates.in; +import static common.util.Predicates.not; import java.util.AbstractCollection; import java.util.Collection; import java.util.Iterator; import java.util.function.Predicate; -import game.util.Predicates; +import common.util.Predicates; /** * Provides static methods for working with {@code Collection} instances. @@ -183,12 +183,12 @@ public final class Filter { @Override public boolean removeAll(final Collection collection) { - return Iterables.removeIf(unfiltered, and(predicate, in(collection))); + return Iterables.removeIf(unfiltered, and(predicate, in((Collection)collection))); } @Override public boolean retainAll(final Collection collection) { - return Iterables.removeIf(unfiltered, and(predicate, not(in(collection)))); + return Iterables.removeIf(unfiltered, and(predicate, not(in((Collection)collection)))); } @Override diff --git a/java/src/game/collect/ForwardingCollection.java b/common/src/main/java/common/collect/ForwardingCollection.java similarity index 99% rename from java/src/game/collect/ForwardingCollection.java rename to common/src/main/java/common/collect/ForwardingCollection.java index 3d1733a..57b8d80 100644 --- a/java/src/game/collect/ForwardingCollection.java +++ b/common/src/main/java/common/collect/ForwardingCollection.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; import java.util.Collection; import java.util.Iterator; diff --git a/java/src/game/collect/ForwardingMap.java b/common/src/main/java/common/collect/ForwardingMap.java similarity index 99% rename from java/src/game/collect/ForwardingMap.java rename to common/src/main/java/common/collect/ForwardingMap.java index b810066..8294acf 100644 --- a/java/src/game/collect/ForwardingMap.java +++ b/common/src/main/java/common/collect/ForwardingMap.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; import java.util.Collection; import java.util.Map; diff --git a/java/src/game/collect/ForwardingMapEntry.java b/common/src/main/java/common/collect/ForwardingMapEntry.java similarity index 99% rename from java/src/game/collect/ForwardingMapEntry.java rename to common/src/main/java/common/collect/ForwardingMapEntry.java index a4f4d03..515a3b1 100644 --- a/java/src/game/collect/ForwardingMapEntry.java +++ b/common/src/main/java/common/collect/ForwardingMapEntry.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; import java.util.Map; import java.util.Map.Entry; diff --git a/java/src/game/collect/ForwardingObject.java b/common/src/main/java/common/collect/ForwardingObject.java similarity index 99% rename from java/src/game/collect/ForwardingObject.java rename to common/src/main/java/common/collect/ForwardingObject.java index d5b64e8..6894d30 100644 --- a/java/src/game/collect/ForwardingObject.java +++ b/common/src/main/java/common/collect/ForwardingObject.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; /** * An abstract base class for implementing the Iterable unmodifiableIterable( -// final Iterable iterable) { -// checkNotNull(iterable); -// if (iterable instanceof UnmodifiableIterable || -// iterable instanceof ImmutableCollection) { -// return iterable; -// } -// return new UnmodifiableIterable(iterable); -// } - - /** - * Simply returns its argument. - * - * @deprecated no need to use this - * @since 10.0 - */ -// @Deprecated public static Iterable unmodifiableIterable( -// ImmutableCollection iterable) { -// return checkNotNull(iterable); -// } - -// private static final class UnmodifiableIterable extends FluentIterable { -// private final Iterable iterable; -// -// private UnmodifiableIterable(Iterable iterable) { -// this.iterable = iterable; -// } -// -// @Override -// public Iterator iterator() { -// return Iterators.unmodifiableIterator(iterable.iterator()); -// } -// -// @Override -// public String toString() { -// return iterable.toString(); -// } -// // no equals and hashCode; it would break the contract! -// } - - /** - * Returns the number of elements in {@code iterable}. - */ -// public static int size(Iterable iterable) { -// return (iterable instanceof Collection) -// ? ((Collection) iterable).size() -// : Iterators.size(iterable.iterator()); -// } - - /** - * Returns {@code true} if {@code iterable} contains any object for which {@code equals(element)} - * is true. - */ -// public static boolean contains(Iterable iterable, Object element) { -// if (iterable instanceof Collection) { -// Collection collection = (Collection) iterable; -// return Filter.safeContains(collection, element); -// } -// return Iterators.contains(iterable.iterator(), element); -// } - - /** - * Removes, from an iterable, every element that belongs to the provided - * collection. - * - *

This method calls {@link Collection#removeAll} if {@code iterable} is a - * collection, and {@link Iterators#removeAll} otherwise. - * - * @param removeFrom the iterable to (potentially) remove elements from - * @param elementsToRemove the elements to remove - * @return {@code true} if any element was removed from {@code iterable} - */ -// public static boolean removeAll( -// Iterable removeFrom, Collection elementsToRemove) { -// return (removeFrom instanceof Collection) -// ? ((Collection) removeFrom).removeAll(checkNotNull(elementsToRemove)) -// : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); -// } - - /** - * Removes, from an iterable, every element that does not belong to the - * provided collection. - * - *

This method calls {@link Collection#retainAll} if {@code iterable} is a - * collection, and {@link Iterators#retainAll} otherwise. - * - * @param removeFrom the iterable to (potentially) remove elements from - * @param elementsToRetain the elements to retain - * @return {@code true} if any element was removed from {@code iterable} - */ -// public static boolean retainAll( -// Iterable removeFrom, Collection elementsToRetain) { -// return (removeFrom instanceof Collection) -// ? ((Collection) removeFrom).retainAll(checkNotNull(elementsToRetain)) -// : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); -// } - /** * Removes, from an iterable, every element that satisfies the provided * predicate. diff --git a/java/src/game/collect/Iterators.java b/common/src/main/java/common/collect/Iterators.java similarity index 80% rename from java/src/game/collect/Iterators.java rename to common/src/main/java/common/collect/Iterators.java index d486067..c92d91c 100644 --- a/java/src/game/collect/Iterators.java +++ b/common/src/main/java/common/collect/Iterators.java @@ -14,15 +14,15 @@ * limitations under the License. */ -package game.collect; +package common.collect; -import static game.collect.CollectPreconditions.checkRemove; -import static game.collect.Preconditions.checkArgument; -import static game.collect.Preconditions.checkNotNull; -import static game.util.Predicates.equalTo; -import static game.util.Predicates.in; -import static game.util.Predicates.instanceOf; -import static game.util.Predicates.not; +import static common.collect.CollectPreconditions.checkRemove; +import static common.collect.Preconditions.checkArgument; +import static common.collect.Preconditions.checkNotNull; +import static common.util.Predicates.equalTo; +import static common.util.Predicates.in; +import static common.util.Predicates.instanceOf; +import static common.util.Predicates.not; import java.util.Collection; import java.util.Iterator; @@ -148,17 +148,6 @@ public final class Iterators { }; } - /** - * Simply returns its argument. - * - * @deprecated no need to use this - * @since 10.0 - */ -// @Deprecated public static UnmodifiableIterator unmodifiableIterator( -// UnmodifiableIterator iterator) { -// return checkNotNull(iterator); -// } - /** * Returns the number of elements remaining in {@code iterator}. The iterator * will be left exhausted: its {@code hasNext()} method will return @@ -1040,253 +1029,6 @@ public final class Iterators { }; } - /** - * Returns an iterator containing only {@code value}. - * - *

The {@link Iterable} equivalent of this method is {@link - * Collections#singleton}. - */ -// public static UnmodifiableIterator singletonIterator( -// final T value) { -// return new UnmodifiableIterator() { -// boolean done; -// @Override -// public boolean hasNext() { -// return !done; -// } -// @Override -// public T next() { -// if (done) { -// throw new NoSuchElementException(); -// } -// done = true; -// return value; -// } -// }; -// } - - /** - * Adapts an {@code Enumeration} to the {@code Iterator} interface. - * - *

This method has no equivalent in {@link Iterables} because viewing an - * {@code Enumeration} as an {@code Iterable} is impossible. However, the - * contents can be copied into a collection using {@link - * Collections#list}. - */ -// public static UnmodifiableIterator forEnumeration( -// final Enumeration enumeration) { -// checkNotNull(enumeration); -// return new UnmodifiableIterator() { -// @Override -// public boolean hasNext() { -// return enumeration.hasMoreElements(); -// } -// @Override -// public T next() { -// return enumeration.nextElement(); -// } -// }; -// } - - /** - * Adapts an {@code Iterator} to the {@code Enumeration} interface. - * - *

The {@code Iterable} equivalent of this method is either {@link - * Collections#enumeration} (if you have a {@link Collection}), or - * {@code Iterators.asEnumeration(collection.iterator())}. - */ -// public static Enumeration asEnumeration(final Iterator iterator) { -// checkNotNull(iterator); -// return new Enumeration() { -// @Override -// public boolean hasMoreElements() { -// return iterator.hasNext(); -// } -// @Override -// public T nextElement() { -// return iterator.next(); -// } -// }; -// } - - /** - * Implementation of PeekingIterator that avoids peeking unless necessary. - */ -// private static class PeekingImpl implements PeekingIterator { -// -// private final Iterator iterator; -// private boolean hasPeeked; -// private E peekedElement; -// -// public PeekingImpl(Iterator iterator) { -// this.iterator = checkNotNull(iterator); -// } -// -// @Override -// public boolean hasNext() { -// return hasPeeked || iterator.hasNext(); -// } -// -// @Override -// public E next() { -// if (!hasPeeked) { -// return iterator.next(); -// } -// E result = peekedElement; -// hasPeeked = false; -// peekedElement = null; -// return result; -// } -// -// @Override -// public void remove() { -// checkState(!hasPeeked, "Can't remove after you've peeked at next"); -// iterator.remove(); -// } -// -// @Override -// public E peek() { -// if (!hasPeeked) { -// peekedElement = iterator.next(); -// hasPeeked = true; -// } -// return peekedElement; -// } -// } - - /** - * Returns a {@code PeekingIterator} backed by the given iterator. - * - *

Calls to the {@code peek} method with no intervening calls to {@code - * next} do not affect the iteration, and hence return the same object each - * time. A subsequent call to {@code next} is guaranteed to return the same - * object again. For example:

   {@code
-   *
-   *   PeekingIterator peekingIterator =
-   *       Iterators.peekingIterator(Iterators.forArray("a", "b"));
-   *   String a1 = peekingIterator.peek(); // returns "a"
-   *   String a2 = peekingIterator.peek(); // also returns "a"
-   *   String a3 = peekingIterator.next(); // also returns "a"}
- * - *

Any structural changes to the underlying iteration (aside from those - * performed by the iterator's own {@link PeekingIterator#remove()} method) - * will leave the iterator in an undefined state. - * - *

The returned iterator does not support removal after peeking, as - * explained by {@link PeekingIterator#remove()}. - * - *

Note: If the given iterator is already a {@code PeekingIterator}, - * it might be returned to the caller, although this is neither - * guaranteed to occur nor required to be consistent. For example, this - * method might choose to pass through recognized implementations of - * {@code PeekingIterator} when the behavior of the implementation is - * known to meet the contract guaranteed by this method. - * - *

There is no {@link Iterable} equivalent to this method, so use this - * method to wrap each individual iterator as it is generated. - * - * @param iterator the backing iterator. The {@link PeekingIterator} assumes - * ownership of this iterator, so users should cease making direct calls - * to it after calling this method. - * @return a peeking iterator backed by that iterator. Apart from the - * additional {@link PeekingIterator#peek()} method, this iterator behaves - * exactly the same as {@code iterator}. - */ -// public static PeekingIterator peekingIterator( -// Iterator iterator) { -// if (iterator instanceof PeekingImpl) { -// // Safe to cast to because PeekingImpl only uses T -// // covariantly (and cannot be subclassed to add non-covariant uses). -// -// PeekingImpl peeking = (PeekingImpl) iterator; -// return peeking; -// } -// return new PeekingImpl(iterator); -// } - - /** - * Simply returns its argument. - * - * @deprecated no need to use this - * @since 10.0 - */ -// @Deprecated public static PeekingIterator peekingIterator( -// PeekingIterator iterator) { -// return checkNotNull(iterator); -// } - - /** - * Returns an iterator over the merged contents of all given - * {@code iterators}, traversing every element of the input iterators. - * Equivalent entries will not be de-duplicated. - * - *

Callers must ensure that the source {@code iterators} are in - * non-descending order as this method does not sort its input. - * - *

For any equivalent elements across all {@code iterators}, it is - * undefined which element is returned first. - * - * @since 11.0 - */ -// @Beta -// public static UnmodifiableIterator mergeSorted( -// Iterable> iterators, -// Comparator comparator) { -// checkNotNull(iterators, "iterators"); -// checkNotNull(comparator, "comparator"); -// -// return new MergingIterator(iterators, comparator); -// } - - /** - * An iterator that performs a lazy N-way merge, calculating the next value - * each time the iterator is polled. This amortizes the sorting cost over the - * iteration and requires less memory than sorting all elements at once. - * - *

Retrieving a single element takes approximately O(log(M)) time, where M - * is the number of iterators. (Retrieving all elements takes approximately - * O(N*log(M)) time, where N is the total number of elements.) - */ -// private static class MergingIterator extends UnmodifiableIterator { -// final Queue> queue; -// -// public MergingIterator(Iterable> iterators, -// final Comparator itemComparator) { -// // A comparator that's used by the heap, allowing the heap -// // to be sorted based on the top of each iterator. -// Comparator> heapComparator = -// new Comparator>() { -// @Override -// public int compare(PeekingIterator o1, PeekingIterator o2) { -// return itemComparator.compare(o1.peek(), o2.peek()); -// } -// }; -// -// queue = new PriorityQueue>(2, heapComparator); -// -// for (Iterator iterator : iterators) { -// if (iterator.hasNext()) { -// queue.add(Iterators.peekingIterator(iterator)); -// } -// } -// } -// -// @Override -// public boolean hasNext() { -// return !queue.isEmpty(); -// } -// -// @Override -// public T next() { -// PeekingIterator nextIter = queue.remove(); -// T next = nextIter.next(); -// if (nextIter.hasNext()) { -// queue.add(nextIter); -// } -// return next; -// } -// } - /** * Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ diff --git a/java/src/game/collect/Lists.java b/common/src/main/java/common/collect/Lists.java similarity index 98% rename from java/src/game/collect/Lists.java rename to common/src/main/java/common/collect/Lists.java index ed6b25b..6143eac 100644 --- a/java/src/game/collect/Lists.java +++ b/common/src/main/java/common/collect/Lists.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; import java.util.ArrayList; import java.util.Collection; diff --git a/java/src/game/collect/Maps.java b/common/src/main/java/common/collect/Maps.java similarity index 99% rename from java/src/game/collect/Maps.java rename to common/src/main/java/common/collect/Maps.java index 36f0b4d..205f87c 100644 --- a/java/src/game/collect/Maps.java +++ b/common/src/main/java/common/collect/Maps.java @@ -14,11 +14,11 @@ * limitations under the License. */ -package game.collect; +package common.collect; -import static game.collect.CollectPreconditions.checkNonnegative; -import static game.collect.Preconditions.checkNotNull; -import static game.util.Predicates.compose; +import static common.collect.CollectPreconditions.checkNonnegative; +import static common.collect.Preconditions.checkNotNull; +import static common.util.Predicates.compose; import java.util.AbstractCollection; import java.util.AbstractMap; diff --git a/java/src/game/collect/ObjectArrays.java b/common/src/main/java/common/collect/ObjectArrays.java similarity index 99% rename from java/src/game/collect/ObjectArrays.java rename to common/src/main/java/common/collect/ObjectArrays.java index 2087cbe..e533dc5 100644 --- a/java/src/game/collect/ObjectArrays.java +++ b/common/src/main/java/common/collect/ObjectArrays.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; import java.lang.reflect.Array; import java.util.Collection; diff --git a/java/src/game/collect/Preconditions.java b/common/src/main/java/common/collect/Preconditions.java similarity index 99% rename from java/src/game/collect/Preconditions.java rename to common/src/main/java/common/collect/Preconditions.java index 18dbe7e..625d971 100644 --- a/java/src/game/collect/Preconditions.java +++ b/common/src/main/java/common/collect/Preconditions.java @@ -1,4 +1,4 @@ -package game.collect; +package common.collect; final class Preconditions { private Preconditions() {} diff --git a/java/src/game/collect/RegularImmutableAsList.java b/common/src/main/java/common/collect/RegularImmutableAsList.java similarity index 98% rename from java/src/game/collect/RegularImmutableAsList.java rename to common/src/main/java/common/collect/RegularImmutableAsList.java index a5d724d..8de27e8 100644 --- a/java/src/game/collect/RegularImmutableAsList.java +++ b/common/src/main/java/common/collect/RegularImmutableAsList.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; /** * An {@link ImmutableAsList} implementation specialized for when the delegate collection is diff --git a/java/src/game/collect/RegularImmutableList.java b/common/src/main/java/common/collect/RegularImmutableList.java similarity index 99% rename from java/src/game/collect/RegularImmutableList.java rename to common/src/main/java/common/collect/RegularImmutableList.java index e129981..dea9884 100644 --- a/java/src/game/collect/RegularImmutableList.java +++ b/common/src/main/java/common/collect/RegularImmutableList.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; /** * Implementation of {@link ImmutableList} with one or more elements. diff --git a/java/src/game/collect/RegularImmutableMap.java b/common/src/main/java/common/collect/RegularImmutableMap.java similarity index 97% rename from java/src/game/collect/RegularImmutableMap.java rename to common/src/main/java/common/collect/RegularImmutableMap.java index 81023b5..2f396f5 100644 --- a/java/src/game/collect/RegularImmutableMap.java +++ b/common/src/main/java/common/collect/RegularImmutableMap.java @@ -14,11 +14,11 @@ * limitations under the License. */ -package game.collect; +package common.collect; -import static game.collect.CollectPreconditions.checkEntryNotNull; +import static common.collect.CollectPreconditions.checkEntryNotNull; -import game.collect.ImmutableMapEntry.TerminalEntry; +import common.collect.ImmutableMapEntry.TerminalEntry; /** * Implementation of {@link ImmutableMap} with two or more entries. diff --git a/java/src/game/collect/RegularImmutableSet.java b/common/src/main/java/common/collect/RegularImmutableSet.java similarity index 98% rename from java/src/game/collect/RegularImmutableSet.java rename to common/src/main/java/common/collect/RegularImmutableSet.java index c10f204..f0bfd66 100644 --- a/java/src/game/collect/RegularImmutableSet.java +++ b/common/src/main/java/common/collect/RegularImmutableSet.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; /** * Implementation of {@link ImmutableSet} with two or more elements. diff --git a/java/src/game/collect/RegularImmutableTable.java b/common/src/main/java/common/collect/RegularImmutableTable.java similarity index 98% rename from java/src/game/collect/RegularImmutableTable.java rename to common/src/main/java/common/collect/RegularImmutableTable.java index 9f48e21..5eea96b 100644 --- a/java/src/game/collect/RegularImmutableTable.java +++ b/common/src/main/java/common/collect/RegularImmutableTable.java @@ -12,9 +12,9 @@ * the License. */ -package game.collect; +package common.collect; -import static game.collect.Preconditions.checkNotNull; +import static common.collect.Preconditions.checkNotNull; import java.util.Collections; import java.util.Comparator; diff --git a/java/src/game/collect/Sets.java b/common/src/main/java/common/collect/Sets.java similarity index 99% rename from java/src/game/collect/Sets.java rename to common/src/main/java/common/collect/Sets.java index 3d807ba..ff1520b 100644 --- a/java/src/game/collect/Sets.java +++ b/common/src/main/java/common/collect/Sets.java @@ -14,9 +14,9 @@ * limitations under the License. */ -package game.collect; +package common.collect; -import static game.collect.Preconditions.checkNotNull; +import static common.collect.Preconditions.checkNotNull; import java.util.AbstractSet; import java.util.Collection; diff --git a/java/src/game/collect/SparseImmutableTable.java b/common/src/main/java/common/collect/SparseImmutableTable.java similarity index 99% rename from java/src/game/collect/SparseImmutableTable.java rename to common/src/main/java/common/collect/SparseImmutableTable.java index 4c1d867..ff151bd 100644 --- a/java/src/game/collect/SparseImmutableTable.java +++ b/common/src/main/java/common/collect/SparseImmutableTable.java @@ -12,7 +12,7 @@ * the License. */ -package game.collect; +package common.collect; import java.util.LinkedHashMap; import java.util.Map; diff --git a/java/src/game/collect/StandardTable.java b/common/src/main/java/common/collect/StandardTable.java similarity index 98% rename from java/src/game/collect/StandardTable.java rename to common/src/main/java/common/collect/StandardTable.java index 0f4d1c8..7ee74cd 100644 --- a/java/src/game/collect/StandardTable.java +++ b/common/src/main/java/common/collect/StandardTable.java @@ -14,15 +14,15 @@ * limitations under the License. */ -package game.collect; +package common.collect; -import static game.collect.Maps.safeContainsKey; -import static game.collect.Maps.safeGet; -import static game.collect.Preconditions.checkNotNull; -import static game.util.Predicates.alwaysTrue; -import static game.util.Predicates.equalTo; -import static game.util.Predicates.in; -import static game.util.Predicates.not; +import static common.collect.Maps.safeContainsKey; +import static common.collect.Maps.safeGet; +import static common.collect.Preconditions.checkNotNull; +import static common.util.Predicates.alwaysTrue; +import static common.util.Predicates.equalTo; +import static common.util.Predicates.in; +import static common.util.Predicates.not; import java.io.Serializable; import java.util.Collection; @@ -35,8 +35,8 @@ import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; -import game.collect.Maps.ImprovedAbstractMap; -import game.collect.Sets.ImprovedAbstractSet; +import common.collect.Maps.ImprovedAbstractMap; +import common.collect.Sets.ImprovedAbstractSet; /** * {@link Table} implementation backed by a map that associates row keys with diff --git a/java/src/game/collect/Table.java b/common/src/main/java/common/collect/Table.java similarity index 99% rename from java/src/game/collect/Table.java rename to common/src/main/java/common/collect/Table.java index 7ed64a2..05c0b0a 100644 --- a/java/src/game/collect/Table.java +++ b/common/src/main/java/common/collect/Table.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; import java.util.Collection; import java.util.Map; diff --git a/java/src/game/collect/TransformedIterator.java b/common/src/main/java/common/collect/TransformedIterator.java similarity index 94% rename from java/src/game/collect/TransformedIterator.java rename to common/src/main/java/common/collect/TransformedIterator.java index 1c12f07..f68b793 100644 --- a/java/src/game/collect/TransformedIterator.java +++ b/common/src/main/java/common/collect/TransformedIterator.java @@ -14,9 +14,9 @@ * limitations under the License. */ -package game.collect; +package common.collect; -import static game.collect.Preconditions.checkNotNull; +import static common.collect.Preconditions.checkNotNull; import java.util.Iterator; diff --git a/java/src/game/collect/UnmodifiableIterator.java b/common/src/main/java/common/collect/UnmodifiableIterator.java similarity index 98% rename from java/src/game/collect/UnmodifiableIterator.java rename to common/src/main/java/common/collect/UnmodifiableIterator.java index 95024eb..73fe703 100644 --- a/java/src/game/collect/UnmodifiableIterator.java +++ b/common/src/main/java/common/collect/UnmodifiableIterator.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; import java.util.Iterator; diff --git a/java/src/game/collect/UnmodifiableListIterator.java b/common/src/main/java/common/collect/UnmodifiableListIterator.java similarity index 98% rename from java/src/game/collect/UnmodifiableListIterator.java rename to common/src/main/java/common/collect/UnmodifiableListIterator.java index 1a62751..7dc5727 100644 --- a/java/src/game/collect/UnmodifiableListIterator.java +++ b/common/src/main/java/common/collect/UnmodifiableListIterator.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.collect; +package common.collect; import java.util.ListIterator; diff --git a/java/src/game/color/Colorizer.java b/common/src/main/java/common/color/Colorizer.java similarity index 75% rename from java/src/game/color/Colorizer.java rename to common/src/main/java/common/color/Colorizer.java index 2b42b87..dcae2c9 100755 --- a/java/src/game/color/Colorizer.java +++ b/common/src/main/java/common/color/Colorizer.java @@ -1,12 +1,8 @@ -package game.color; +package common.color; -import java.awt.image.BufferedImage; - -import game.biome.Biome; -import game.renderer.texture.TextureUtil; -import game.util.FileUtils; -import game.world.BlockPos; -import game.world.IWorldAccess; +import common.biome.Biome; +import common.util.BlockPos; +import common.world.IWorldAccess; public enum Colorizer { NONE(0xffffff), BASIC(0x37b500), PINE(0x3f993f), BIRCH(0x68a723); @@ -30,12 +26,18 @@ public enum Colorizer { return biome.waterColor; } }; - private static final String GRASS_TEX = "textures/world/grass.png"; - private static final String FOLIAGE_TEX = "textures/world/foliage.png"; private static final int[] GRASS = new int[65536]; private static final int[] FOLIAGE = new int[65536]; private final int color; + + public static int[] getGrassMap() { + return GRASS; + } + + public static int[] getFoliageMap() { + return FOLIAGE; + } public static int getGrassColor(double temp, double rain) { rain = rain * temp; @@ -52,22 +54,6 @@ public enum Colorizer { return FOLIAGE[j << 8 | i]; } - public static void reload() { - BufferedImage img; - try { - img = TextureUtil.readImage(FileUtils.getResource(GRASS_TEX)); - img.getRGB(0, 0, 256, 256, GRASS, 0, 256); - } - catch(Exception e) { - } - try { - img = TextureUtil.readImage(FileUtils.getResource(FOLIAGE_TEX)); - img.getRGB(0, 0, 256, 256, FOLIAGE, 0, 256); - } - catch(Exception e) { - } - } - private static int getColor(IWorldAccess access, BlockPos pos, ColorResolver resolver) { int r = 0; int g = 0; diff --git a/java/src/game/color/DyeColor.java b/common/src/main/java/common/color/DyeColor.java similarity index 97% rename from java/src/game/color/DyeColor.java rename to common/src/main/java/common/color/DyeColor.java index 8681ee5..b197b36 100755 --- a/java/src/game/color/DyeColor.java +++ b/common/src/main/java/common/color/DyeColor.java @@ -1,12 +1,11 @@ -package game.color; +package common.color; import java.util.Map; -import game.collect.Maps; +import common.collect.Maps; +import common.util.Identifyable; -import game.properties.IStringSerializable; - -public enum DyeColor implements IStringSerializable +public enum DyeColor implements Identifyable { WHITE(0, 15, "white", "Weiß", "Weißes", "Weißer", "Weiße", "Knochenmehl", 16777215, TextColor.WHITE), ORANGE(1, 14, "orange", "Orange", "Oranges", "Oranger", "Orange", "Oranger Farbstoff", 14188339, TextColor.ORANGE), diff --git a/java/src/game/color/TextColor.java b/common/src/main/java/common/color/TextColor.java similarity index 97% rename from java/src/game/color/TextColor.java rename to common/src/main/java/common/color/TextColor.java index 65b3312..44f2262 100755 --- a/java/src/game/color/TextColor.java +++ b/common/src/main/java/common/color/TextColor.java @@ -1,8 +1,8 @@ -package game.color; +package common.color; import java.util.regex.Pattern; -import game.util.Util; +import common.util.Util; public enum TextColor { NULL(0x00), diff --git a/java/src/game/dimension/Area.java b/common/src/main/java/common/dimension/Area.java similarity index 93% rename from java/src/game/dimension/Area.java rename to common/src/main/java/common/dimension/Area.java index 06b8375..125d1cb 100755 --- a/java/src/game/dimension/Area.java +++ b/common/src/main/java/common/dimension/Area.java @@ -1,4 +1,4 @@ -package game.dimension; +package common.dimension; public final class Area extends Dimension { Area(int id, String name) { diff --git a/common/src/main/java/common/dimension/CloudType.java b/common/src/main/java/common/dimension/CloudType.java new file mode 100644 index 0000000..a3f1b14 --- /dev/null +++ b/common/src/main/java/common/dimension/CloudType.java @@ -0,0 +1,39 @@ +package common.dimension; + +import java.util.Map; + +import common.collect.Maps; + +public enum CloudType { + NORMAL("normal", "clouds"), + DENSE("dense", "clouds_dense"); + + private static final Map LOOKUP = Maps.newHashMap(); + + private final String name; + private final String texture; + + private CloudType(String name, String texture) { + this.name = name; + this.texture = texture; + } + + public String toString() { + return this.name; + } + + public String getTexture() { + return this.texture; + } + + public static CloudType getByName(String name) { + CloudType type = LOOKUP.get(name.toLowerCase()); + return type == null ? NORMAL : type; + } + + static { + for(CloudType type : values()) { + LOOKUP.put(type.name, type); + } + } +} \ No newline at end of file diff --git a/java/src/game/dimension/DimType.java b/common/src/main/java/common/dimension/DimType.java similarity index 96% rename from java/src/game/dimension/DimType.java rename to common/src/main/java/common/dimension/DimType.java index e2fa8e4..48d4086 100755 --- a/java/src/game/dimension/DimType.java +++ b/common/src/main/java/common/dimension/DimType.java @@ -1,8 +1,8 @@ -package game.dimension; +package common.dimension; import java.util.Map; -import game.collect.Maps; +import common.collect.Maps; public enum DimType { STAR("star", "Stern %s", true, false, false, false, false, false, true), diff --git a/java/src/game/dimension/Dimension.java b/common/src/main/java/common/dimension/Dimension.java similarity index 56% rename from java/src/game/dimension/Dimension.java rename to common/src/main/java/common/dimension/Dimension.java index 3cad8cf..42b720c 100755 --- a/java/src/game/dimension/Dimension.java +++ b/common/src/main/java/common/dimension/Dimension.java @@ -1,50 +1,22 @@ -package game.dimension; +package common.dimension; import java.util.List; import java.util.Map; -import java.util.Set; - -import game.collect.Lists; -import game.collect.Maps; -import game.collect.Sets; - -import game.biome.Biome; -import game.block.LeavesType; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.MetalType; -import game.init.UniverseRegistry; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.nbt.NBTTagString; -import game.rng.Random; -import game.util.ExtMath; -import game.world.State; -import game.world.Vec3; -import game.world.Weather; -import game.worldgen.BiomeGenLayered; -import game.worldgen.BiomeGenPerlin; -import game.worldgen.BiomeGenSingle; -import game.worldgen.BiomeGenerator; -import game.worldgen.BlockReplacer; -import game.worldgen.ChunkGenerator; -import game.worldgen.FeatureDungeons; -import game.worldgen.FeatureLakes; -import game.worldgen.FeatureLiquids; -import game.worldgen.FeatureOres; -import game.worldgen.GeneratorCavern; -import game.worldgen.GeneratorDestroyed; -import game.worldgen.GeneratorFlat; -import game.worldgen.GeneratorIsland; -import game.worldgen.GeneratorPerlin; -import game.worldgen.GeneratorSimple; -import game.worldgen.ReplacerAltBiome; -import game.worldgen.ReplacerAltSurface; -import game.worldgen.ReplacerBiome; -import game.worldgen.ReplacerTopLayer; -import game.worldgen.caves.MapGenBigCaves; -import game.worldgen.caves.MapGenCaves; -import game.worldgen.caves.MapGenRavine; +import common.biome.Biome; +import common.biome.IBiome; +import common.block.Block; +import common.block.foliage.LeavesType; +import common.collect.Lists; +import common.collect.Maps; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.MetalType; +import common.init.UniverseRegistry; +import common.tags.TagObject; +import common.util.ExtMath; +import common.util.Vec3; +import common.world.State; +import common.world.Weather; public abstract class Dimension extends Nameable implements Comparable { public class GeneratorSettings { @@ -66,59 +38,6 @@ public abstract class Dimension extends Nameable implements Comparable SAFE_CHARS = Sets.newHashSet(); - -// private static final FeatureOres[] DEFAULT_ORES; -// -// static { -// List ores = Lists.newArrayList(); -// OreRegistry.populateDefault(ores); -// DEFAULT_ORES = new FeatureOres[ores.size()]; -// for(int z = 0; z < DEFAULT_ORES.length; z++) { -// DEFAULT_ORES[z] = ores.get(z).createGenerator(); -// } -// } + private static final int[] METAL_OFFSETS = new int[] { 0, -12, -32, -48, -64, -72, -96, -112, -142, -168}; + private static final int[] METAL_HEIGHTS = new int[] {64, 32, 12, -10, -32, -48, -68, -84, -102, -136}; private final int id; private final String name; @@ -247,8 +155,8 @@ public abstract class Dimension extends Nameable implements Comparable ores = Lists.newArrayList(); - private final List lakes = Lists.newArrayList(); - private final List liquids = Lists.newArrayList(); + private final List ores = Lists.newArrayList(); + private final List lakes = Lists.newArrayList(); + private final List liquids = Lists.newArrayList(); private long seed = 0L; - static { - final String safe = "0123456789abcdefghijklmnopqrstuvwxyz_"; - for(int z = 0; z < safe.length(); z++) { - SAFE_CHARS.add(safe.charAt(z)); - } - } - - private static String getSafeFilename(String name, String fallback) { - if(name.length() < 1 || name.length() > 32) - return fallback; - for(int z = 0; z < name.length(); z++) { - if(!SAFE_CHARS.contains(name.charAt(z))) { - return fallback; - } - } - return name; + public static void writeState(TagObject tag, String name, String dname, State state) { + if(state == null) + return; + tag.setString(name, BlockRegistry.getNameFromBlock(state.getBlock())); + if(state != state.getBlock().getState()) + tag.setByte(dname, (byte)state.getBlock().getMetaFromState(state)); } + public static void writeState(TagObject tag, String name, State state) { + writeState(tag, name, name + "Data", state); + } + + public static void writeState(TagObject tag, State state) { + writeState(tag, "Block", "Data", state); + } + + public static State readState(TagObject tag, String name, String dname, State def) { + if(!tag.hasString(name)) + return def; + Block block = BlockRegistry.getRegisteredBlock(tag.getString(name)); + if(tag.hasByte(dname)) { + byte data = tag.getByte(dname); + return data < 0 || data >= 16 ? block.getState() : block.getStateFromMeta(data); + } + return block.getState(); + } + + public static State readState(TagObject tag, String name, State def) { + return readState(tag, name, name + "Data", def); + } + + public static State readState(TagObject tag, State def) { + return readState(tag, "Block", "Data", def); + } + public Dimension(int id, String name) { this.id = id; this.name = name; @@ -345,11 +268,7 @@ public abstract class Dimension extends Nameable implements Comparable 0 ? new BiomeGenLayered(rand.longv(), this.defaultBiome, this.semiFixed, this.biomeSize, this.riverSize, - this.snowRarity, this.seaRarity, this.addBiomes == null ? new Biome[0] : this.addBiomes, this.addRarity, - this.hotBiomes == null ? new Biome[] {this.defaultBiome} : this.hotBiomes, - this.mediumBiomes == null ? new Biome[] {this.defaultBiome} : this.mediumBiomes, - this.coldBiomes == null ? new Biome[] {this.defaultBiome} : this.coldBiomes, - this.frostBiomes == null ? new Biome[] {this.defaultBiome} : this.frostBiomes) : new BiomeGenSingle(this.defaultBiome); - } - - public final ChunkGenerator createChunkGenerator(Random rand) { - switch(this.generatorType) { - case FLAT: - return this.layers == null ? new GeneratorFlat(this.seaLevel, this.filler) : new GeneratorFlat(this.layers); - case PERLIN: - default: - return new GeneratorPerlin(rand, this.filler, this.liquid, this.noiseGen); - case SIMPLE: - return new GeneratorSimple(rand, this.filler, this.liquid, - this.biomeSize > 0 ? null : new BiomeGenPerlin(rand.longv())); - case ISLAND: - return new GeneratorIsland(rand, this.filler); - case CAVERN: - return new GeneratorCavern(rand, this.filler, this.liquid); - case DESTROYED: - return new GeneratorDestroyed(this.seaLevel); - } - } - - public final BlockReplacer createBlockReplacer(Random rand) { - switch(this.replacerType) { - case BIOMES: - default: - return new ReplacerBiome(rand); - case SIMPLE: - return new ReplacerAltBiome(rand, this.filler, this.liquid, this.alt2, this.alt1); - case ALTERNATE: - return new ReplacerAltSurface(rand, this.filler, this.alt1, this.alt2, this.liquid); - case TOPLAYER: - return new ReplacerTopLayer(this.surface, this.filler.getBlock()); - case NONE: - return null; - } - } - - public final FeatureDungeons createDungeonGenerator() { - return this.dungeons > 0 ? new FeatureDungeons(this.dungeons) : null; - } - - public final MapGenCaves createCaveGenerator() { - return this.caves ? - (new MapGenCaves(this.caveFiller, this.filler.getBlock(), this.top.getBlock(), - this.surface.getBlock(), this.alt1.getBlock())) : null; - } - - public final MapGenRavine createRavineGenerator() { - return this.ravines ? - (new MapGenRavine(this.caveFiller, this.filler.getBlock(), - this.top.getBlock(), this.surface.getBlock())) : null; - } - - public final MapGenBigCaves createBigCaveGenerator() { - return this.strideCaves ? - (new MapGenBigCaves(this.filler.getBlock(), - this.top.getBlock(), this.surface.getBlock())) : null; - } - - public final FeatureOres[] getOres() { - return this.ores.isEmpty() ? null : this.ores.toArray(new FeatureOres[this.ores.size()]); - } - - public final FeatureLakes[] getLakes() { - return this.lakes.isEmpty() ? null : this.lakes.toArray(new FeatureLakes[this.lakes.size()]); - } - - public final FeatureLiquids[] getLiquids() { - return this.liquids.isEmpty() ? null : this.liquids.toArray(new FeatureLiquids[this.liquids.size()]); - } - public final long getSeed() { return this.seed; } @@ -903,11 +734,11 @@ public abstract class Dimension extends Nameable implements Comparable= UniverseRegistry.MORE_DIM_ID) { + this.seaLevel = tag.getInt("SeaLevel"); + this.filler = readState(tag, "FillerBlock", Blocks.stone.getState()); + this.liquid = readState(tag, "LiquidBlock", Blocks.water.getState()); + } + } + if(generator) { if(all || this.id >= UniverseRegistry.MORE_DIM_ID) { this.noiseGen.coordinateScale = tag.getFloat("CoordScale"); this.noiseGen.heightScale = tag.getFloat("HeightScale"); @@ -1091,126 +925,117 @@ public abstract class Dimension extends Nameable implements Comparable list = tag.getList("Ores"); + for(int z = 0; z < list.size(); z++) { + TagObject gen = list.get(z); + this.ores.add(new Ore(readState(gen, Blocks.iron_ore.getState()), + gen.getInt("Count"), gen.getInt("Add"), gen.getInt("Size"), + gen.getInt("MinC"), gen.getInt("MaxS"), gen.getBool("Distrib"))); } } this.lakes.clear(); - if(tag.hasKey("Lakes", 9)) { - NBTTagList list = tag.getTagList("Lakes", 10); - for(int z = 0; z < list.tagCount(); z++) { - NBTTagCompound gen = list.getCompoundTagAt(z); - this.lakes.add(new FeatureLakes( - BlockRegistry.getFromIdName(gen.getString("Block"), Blocks.iron_ore.getState()), - gen.hasKey("Filler", 8) ? BlockRegistry.getFromIdName(gen.getString("Filler"), null) : null, - gen.hasKey("Top", 8) ? BlockRegistry.getFromIdName(gen.getString("Top"), null) : null, - gen.getInteger("Chance"), gen.getInteger("Min"), gen.getInteger("Max"), gen.getBoolean("Ratiod"))); + if(tag.hasList("Lakes")) { + List list = tag.getList("Lakes"); + for(int z = 0; z < list.size(); z++) { + TagObject gen = list.get(z); + this.lakes.add(new Lake( + readState(gen, Blocks.water.getState()), + readState(gen, "Filler", null), readState(gen, "Top", null), + gen.getInt("Chance"), gen.getInt("Min"), gen.getInt("Max"), gen.getBool("Ratiod"))); } } this.liquids.clear(); - if(tag.hasKey("Liquids", 9)) { - NBTTagList list = tag.getTagList("Liquids", 10); - for(int z = 0; z < list.tagCount(); z++) { - NBTTagCompound gen = list.getCompoundTagAt(z); - this.liquids.add(new FeatureLiquids( - BlockRegistry.getFromIdName(gen.getString("Block"), Blocks.iron_ore.getState()), - gen.getInteger("Chance"), gen.getInteger("Min"), gen.getInteger("Max"), gen.getBoolean("Lower"))); + if(tag.hasList("Liquids")) { + List list = tag.getList("Liquids"); + for(int z = 0; z < list.size(); z++) { + TagObject gen = list.get(z); + this.liquids.add(new Liquid( + readState(gen, Blocks.flowing_water.getState()), + gen.getInt("Chance"), gen.getInt("Min"), gen.getInt("Max"), gen.getBool("Lower"))); } } - this.populated = !tag.hasKey("NoPopulation", 1) || !tag.getBoolean("NoPopulation"); + this.populated = !tag.hasBool("NoPopulation") || !tag.getBool("NoPopulation"); } } else { this.fullName = tag.getString("FullName"); - this.readNbt(tag); + this.readTags(tag); } -// this.readNbt(tag); -// this.customName = tag.hasKey("CustomName", 8) ? tag.getString("CustomName") : null; +// this.customName = tag.hasString("CustomName") ? tag.getString("CustomName") : null; if(all || !generator || this.id >= UniverseRegistry.MORE_DIM_ID) { - this.denseFog = tag.getBoolean("DenseFog"); - this.timeQualifier = tag.getInteger("ImperialTime"); - this.brightness = tag.getInteger("Brightness"); - this.skyColor = tag.getInteger("SkyColor"); - this.fogColor = tag.getInteger("FogColor"); - this.cloudColor = tag.getInteger("CloudColor"); + this.denseFog = tag.getBool("DenseFog"); + this.timeQualifier = tag.getInt("ImperialTime"); + this.brightness = tag.getInt("Brightness"); + this.skyColor = tag.getInt("SkyColor"); + this.fogColor = tag.getInt("FogColor"); + this.cloudColor = tag.getInt("CloudColor"); this.gravity = tag.getFloat("Gravity"); this.temperature = tag.getFloat("Temperature"); this.orbitOffset = tag.getFloat("OrbitOffset"); @@ -1273,27 +1096,27 @@ public abstract class Dimension extends Nameable implements Comparable= UniverseRegistry.MORE_DIM_ID) ? this.toNbt() : new NBTTagCompound(); + public final TagObject toTags(boolean generator) { + return this.toTags(generator, !generator, false); + } + + private final TagObject toTags(boolean generator, boolean partialGen, boolean all) { + TagObject tag = (all || !generator || this.id >= UniverseRegistry.MORE_DIM_ID) ? this.toTags() : new TagObject(); if(this == Space.INSTANCE) { - if(generator) + if(generator || partialGen) tag.setLong("Seed", this.seed); return tag; } - if(generator) { + if(generator || partialGen) { tag.setLong("Seed", this.seed); + if(partialGen || all || this.id >= UniverseRegistry.MORE_DIM_ID) { + tag.setInt("SeaLevel", this.seaLevel); + writeState(tag, "FillerBlock", this.filler); + writeState(tag, "LiquidBlock", this.liquid); + } + } + if(generator) { if(all || this.id >= UniverseRegistry.MORE_DIM_ID) { tag.setFloat("CoordScale", this.noiseGen.coordinateScale); tag.setFloat("HeightScale", this.noiseGen.heightScale); @@ -1333,146 +1167,144 @@ public abstract class Dimension extends Nameable implements Comparable list = Lists.newArrayList(); + for(Ore gen : this.ores) { + TagObject ore = new TagObject(); + writeState(ore, gen.state()); + ore.setBool("Distrib", gen.dist()); + ore.setInt("Size", gen.size()); + ore.setInt("Count", gen.count()); + ore.setInt("Add", gen.more()); + ore.setInt("MinC", gen.min()); + ore.setInt("MaxS", gen.max()); + list.add(ore); } - tag.setTag("Ores", list); + tag.setList("Ores", list); } if(!this.lakes.isEmpty()) { - NBTTagList list = new NBTTagList(); - for(FeatureLakes gen : this.lakes) { - NBTTagCompound lake = new NBTTagCompound(); - lake.setString("Block", BlockRegistry.toIdName(gen.state)); - if(gen.filler != null) - lake.setString("Filler", BlockRegistry.toIdName(gen.filler)); - if(gen.top != null) - lake.setString("Top", BlockRegistry.toIdName(gen.top)); - lake.setBoolean("Ratiod", gen.ratiod); - lake.setInteger("Chance", gen.chance); - lake.setInteger("Min", gen.minHeight); - lake.setInteger("Max", gen.maxHeight); - list.appendTag(lake); + List list = Lists.newArrayList(); + for(Lake gen : this.lakes) { + TagObject lake = new TagObject(); + writeState(lake, gen.state()); + writeState(lake, "Filler", gen.filler()); + writeState(lake, "Top", gen.top()); + lake.setBool("Ratiod", gen.ratiod()); + lake.setInt("Chance", gen.chance()); + lake.setInt("Min", gen.minHeight()); + lake.setInt("Max", gen.maxHeight()); + list.add(lake); } - tag.setTag("Lakes", list); + tag.setList("Lakes", list); } if(!this.liquids.isEmpty()) { - NBTTagList list = new NBTTagList(); - for(FeatureLiquids gen : this.liquids) { - NBTTagCompound liquid = new NBTTagCompound(); - liquid.setString("Block", BlockRegistry.toIdName(gen.state)); - liquid.setBoolean("Lower", gen.lower); - liquid.setInteger("Chance", gen.chance); - liquid.setInteger("Min", gen.minHeight); - liquid.setInteger("Max", gen.maxHeight); - list.appendTag(liquid); + List list = Lists.newArrayList(); + for(Liquid gen : this.liquids) { + TagObject liquid = new TagObject(); + writeState(liquid, gen.state()); + liquid.setBool("Lower", gen.lower()); + liquid.setInt("Chance", gen.chance()); + liquid.setInt("Min", gen.minHeight()); + liquid.setInt("Max", gen.maxHeight()); + list.add(liquid); } - tag.setTag("Liquids", list); + tag.setList("Liquids", list); } if(!this.populated) - tag.setBoolean("NoPopulation", true); + tag.setBool("NoPopulation", true); } } else { tag.setString("FullName", this.getFormattedName(true)); - this.writeNbt(tag); + this.writeTags(tag); } -// this.writeNbt(tag); // if(this.customName != null) // tag.setString("CustomName", this.customName); if(all || !generator || this.id >= UniverseRegistry.MORE_DIM_ID) { - tag.setBoolean("DenseFog", this.denseFog); - tag.setInteger("ImperialTime", this.timeQualifier); - tag.setInteger("Brightness", this.brightness); - tag.setInteger("SkyColor", this.skyColor); - tag.setInteger("FogColor", this.fogColor); - tag.setInteger("CloudColor", this.cloudColor); + tag.setBool("DenseFog", this.denseFog); + tag.setInt("ImperialTime", this.timeQualifier); + tag.setInt("Brightness", this.brightness); + tag.setInt("SkyColor", this.skyColor); + tag.setInt("FogColor", this.fogColor); + tag.setInt("CloudColor", this.cloudColor); tag.setFloat("Gravity", this.gravity); tag.setFloat("Temperature", this.temperature); tag.setFloat("OrbitOffset", this.orbitOffset); @@ -1481,42 +1313,42 @@ public abstract class Dimension extends Nameable implements Comparable getOres() { + return this.ores; + } + + public List getLakes() { + return this.lakes; + } + + public List getLiquids() { + return this.liquids; + } } diff --git a/java/src/game/dimension/Domain.java b/common/src/main/java/common/dimension/Domain.java similarity index 90% rename from java/src/game/dimension/Domain.java rename to common/src/main/java/common/dimension/Domain.java index 91e640c..f209714 100755 --- a/java/src/game/dimension/Domain.java +++ b/common/src/main/java/common/dimension/Domain.java @@ -1,8 +1,8 @@ -package game.dimension; +package common.dimension; import java.util.Set; -import game.collect.Sets; +import common.collect.Sets; public final class Domain extends Nameable implements Comparable { public final String id; diff --git a/java/src/game/dimension/Galaxy.java b/common/src/main/java/common/dimension/Galaxy.java similarity index 90% rename from java/src/game/dimension/Galaxy.java rename to common/src/main/java/common/dimension/Galaxy.java index fa44e2f..9203107 100755 --- a/java/src/game/dimension/Galaxy.java +++ b/common/src/main/java/common/dimension/Galaxy.java @@ -1,8 +1,8 @@ -package game.dimension; +package common.dimension; import java.util.Set; -import game.collect.Sets; +import common.collect.Sets; public final class Galaxy extends Nameable implements Comparable { public final String id; diff --git a/common/src/main/java/common/dimension/Lake.java b/common/src/main/java/common/dimension/Lake.java new file mode 100644 index 0000000..6b32f6b --- /dev/null +++ b/common/src/main/java/common/dimension/Lake.java @@ -0,0 +1,6 @@ +package common.dimension; + +import common.world.State; + +public record Lake(State state, State filler, State top, int chance, int minHeight, int maxHeight, boolean ratiod) { +} diff --git a/common/src/main/java/common/dimension/Liquid.java b/common/src/main/java/common/dimension/Liquid.java new file mode 100644 index 0000000..191a84d --- /dev/null +++ b/common/src/main/java/common/dimension/Liquid.java @@ -0,0 +1,6 @@ +package common.dimension; + +import common.world.State; + +public record Liquid(State state, int chance, int minHeight, int maxHeight, boolean lower) { +} diff --git a/java/src/game/dimension/Moon.java b/common/src/main/java/common/dimension/Moon.java similarity index 95% rename from java/src/game/dimension/Moon.java rename to common/src/main/java/common/dimension/Moon.java index 10eeff6..cab561c 100755 --- a/java/src/game/dimension/Moon.java +++ b/common/src/main/java/common/dimension/Moon.java @@ -1,4 +1,4 @@ -package game.dimension; +package common.dimension; public final class Moon extends Dimension { Moon(int id, String name) { diff --git a/java/src/game/dimension/Nameable.java b/common/src/main/java/common/dimension/Nameable.java similarity index 57% rename from java/src/game/dimension/Nameable.java rename to common/src/main/java/common/dimension/Nameable.java index 9e9454b..17cd47a 100755 --- a/java/src/game/dimension/Nameable.java +++ b/common/src/main/java/common/dimension/Nameable.java @@ -1,6 +1,6 @@ -package game.dimension; +package common.dimension; -import game.nbt.NBTTagCompound; +import common.tags.TagObject; public abstract class Nameable { protected String customName = null; @@ -13,11 +13,11 @@ public abstract class Nameable { this.customName = name; } - public void readNbt(NBTTagCompound tag) { - this.customName = tag.hasKey("CustomName", 8) ? tag.getString("CustomName") : null; + public void readTags(TagObject tag) { + this.customName = tag.hasString("CustomName") ? tag.getString("CustomName") : null; } - public void writeNbt(NBTTagCompound tag) { + public void writeTags(TagObject tag) { if(this.customName != null) tag.setString("CustomName", this.customName); } @@ -32,12 +32,4 @@ public abstract class Nameable { String.format(this.getNameIdentifier(), this.customName)) : String.format(this.getNameIdentifier(), this.getIdentifier()); } - -// public final Text getNameComponent() { -// return this.customName != null && !this.customName.isEmpty() -// ? (this.customName.startsWith("'") && this.customName.endsWith("'") && this.customName.length() > 2 -// ? new Text(this.customName.substring(1, this.customName.length() - 1)) : -// new Text(this.getNameIdentifier(), this.customName)) : -// new Text(this.getNameIdentifier(), this.getIdentifier()); -// } } diff --git a/common/src/main/java/common/dimension/Ore.java b/common/src/main/java/common/dimension/Ore.java new file mode 100644 index 0000000..6bbdb93 --- /dev/null +++ b/common/src/main/java/common/dimension/Ore.java @@ -0,0 +1,6 @@ +package common.dimension; + +import common.world.State; + +public record Ore(State state, int count, int more, int size, int min, int max, boolean dist) { +} diff --git a/java/src/game/dimension/Planet.java b/common/src/main/java/common/dimension/Planet.java similarity index 96% rename from java/src/game/dimension/Planet.java rename to common/src/main/java/common/dimension/Planet.java index 19689b7..37fa250 100755 --- a/java/src/game/dimension/Planet.java +++ b/common/src/main/java/common/dimension/Planet.java @@ -1,8 +1,8 @@ -package game.dimension; +package common.dimension; import java.util.Set; -import game.collect.Sets; +import common.collect.Sets; public final class Planet extends Dimension { private final Set moons = Sets.newTreeSet(); diff --git a/java/src/game/dimension/Sector.java b/common/src/main/java/common/dimension/Sector.java similarity index 90% rename from java/src/game/dimension/Sector.java rename to common/src/main/java/common/dimension/Sector.java index 4d11d4e..6327744 100755 --- a/java/src/game/dimension/Sector.java +++ b/common/src/main/java/common/dimension/Sector.java @@ -1,8 +1,8 @@ -package game.dimension; +package common.dimension; import java.util.Set; -import game.collect.Sets; +import common.collect.Sets; public final class Sector extends Nameable implements Comparable { public final String id; diff --git a/java/src/game/dimension/Semi.java b/common/src/main/java/common/dimension/Semi.java similarity index 95% rename from java/src/game/dimension/Semi.java rename to common/src/main/java/common/dimension/Semi.java index 798d6ca..d5e8b58 100755 --- a/java/src/game/dimension/Semi.java +++ b/common/src/main/java/common/dimension/Semi.java @@ -1,4 +1,4 @@ -package game.dimension; +package common.dimension; public final class Semi extends Dimension { Semi(int id, String name) { diff --git a/common/src/main/java/common/dimension/SkyboxType.java b/common/src/main/java/common/dimension/SkyboxType.java new file mode 100644 index 0000000..3183956 --- /dev/null +++ b/common/src/main/java/common/dimension/SkyboxType.java @@ -0,0 +1,37 @@ +package common.dimension; + +import java.util.Map; + +import common.collect.Maps; + +public enum SkyboxType { + ; + + private static final Map LOOKUP = Maps.newHashMap(); + + private final String name; + private final String texture; + + private SkyboxType(String name, String texture) { + this.name = name; + this.texture = texture; + } + + public String toString() { + return this.name; + } + + public String getTexture() { + return this.texture; + } + + public static SkyboxType getByName(String name) { + return LOOKUP.get(name.toLowerCase()); + } + + static { + for(SkyboxType type : values()) { + LOOKUP.put(type.name, type); + } + } +} \ No newline at end of file diff --git a/java/src/game/dimension/Space.java b/common/src/main/java/common/dimension/Space.java similarity index 95% rename from java/src/game/dimension/Space.java rename to common/src/main/java/common/dimension/Space.java index 02f21bc..bab2129 100755 --- a/java/src/game/dimension/Space.java +++ b/common/src/main/java/common/dimension/Space.java @@ -1,6 +1,6 @@ -package game.dimension; +package common.dimension; -import game.biome.Biome; +import common.biome.Biome; public final class Space extends Dimension { public static final Space INSTANCE = new Space(); @@ -8,7 +8,7 @@ public final class Space extends Dimension { private Space() { super(0, "space"); this.setPhysics(1L, 1L, 0.0f, 0.0f, 2.7f, 15).setTimeQualifier(8); - this.setBiome(Biome.space).setStarBrightness(1.0f).setDeepStarBrightness(1.0f); + this.setBiome(Biome.SPACE).setStarBrightness(1.0f).setDeepStarBrightness(1.0f); this.setCustomName("Der Weltraum"); } diff --git a/java/src/game/dimension/Star.java b/common/src/main/java/common/dimension/Star.java similarity index 96% rename from java/src/game/dimension/Star.java rename to common/src/main/java/common/dimension/Star.java index 6cfa58d..14af9e6 100755 --- a/java/src/game/dimension/Star.java +++ b/common/src/main/java/common/dimension/Star.java @@ -1,10 +1,9 @@ -package game.dimension; +package common.dimension; import java.util.Set; -import game.collect.Sets; - -import game.world.State; +import common.collect.Sets; +import common.world.State; public final class Star extends Dimension { private final Set planets = Sets.newTreeSet(); diff --git a/java/src/game/dispenser/BehaviorDefaultDispenseItem.java b/common/src/main/java/common/dispenser/BehaviorDefaultDispenseItem.java similarity index 93% rename from java/src/game/dispenser/BehaviorDefaultDispenseItem.java rename to common/src/main/java/common/dispenser/BehaviorDefaultDispenseItem.java index 50057a4..e8c65a5 100755 --- a/java/src/game/dispenser/BehaviorDefaultDispenseItem.java +++ b/common/src/main/java/common/dispenser/BehaviorDefaultDispenseItem.java @@ -1,10 +1,10 @@ -package game.dispenser; +package common.dispenser; -import game.block.BlockDispenser; -import game.entity.item.EntityItem; -import game.item.ItemStack; -import game.world.Facing; -import game.world.World; +import common.block.tech.BlockDispenser; +import common.entity.item.EntityItem; +import common.item.ItemStack; +import common.util.Facing; +import common.world.World; public class BehaviorDefaultDispenseItem implements IBehaviorDispenseItem { diff --git a/java/src/game/dispenser/BehaviorProjectileDispense.java b/common/src/main/java/common/dispenser/BehaviorProjectileDispense.java similarity index 86% rename from java/src/game/dispenser/BehaviorProjectileDispense.java rename to common/src/main/java/common/dispenser/BehaviorProjectileDispense.java index 98ce906..96d6eb1 100755 --- a/java/src/game/dispenser/BehaviorProjectileDispense.java +++ b/common/src/main/java/common/dispenser/BehaviorProjectileDispense.java @@ -1,11 +1,11 @@ -package game.dispenser; +package common.dispenser; -import game.block.BlockDispenser; -import game.entity.Entity; -import game.entity.types.IProjectile; -import game.item.ItemStack; -import game.world.Facing; -import game.world.World; +import common.block.tech.BlockDispenser; +import common.entity.Entity; +import common.entity.types.IProjectile; +import common.item.ItemStack; +import common.util.Facing; +import common.world.World; public abstract class BehaviorProjectileDispense extends BehaviorDefaultDispenseItem { diff --git a/common/src/main/java/common/dispenser/DispenserPos.java b/common/src/main/java/common/dispenser/DispenserPos.java new file mode 100755 index 0000000..d3e5f5f --- /dev/null +++ b/common/src/main/java/common/dispenser/DispenserPos.java @@ -0,0 +1,4 @@ +package common.dispenser; + +public record DispenserPos(double getX, double getY, double getZ) implements IPosition { +} diff --git a/common/src/main/java/common/dispenser/DispenserSource.java b/common/src/main/java/common/dispenser/DispenserSource.java new file mode 100755 index 0000000..2709dba --- /dev/null +++ b/common/src/main/java/common/dispenser/DispenserSource.java @@ -0,0 +1,29 @@ +package common.dispenser; + +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.world.State; +import common.world.World; + +public record DispenserSource(World getWorld, BlockPos getBlockPos) implements IBlockSource { + public double getX() { + return (double)this.getBlockPos.getX() + 0.5D; + } + + public double getY() { + return (double)this.getBlockPos.getY() + 0.5D; + } + + public double getZ() { + return (double)this.getBlockPos.getZ() + 0.5D; + } + + public int getBlockMetadata() { + State state = this.getWorld.getState(this.getBlockPos); + return state.getBlock().getMetaFromState(state); + } + + public T getBlockTileEntity() { + return (T)this.getWorld.getTileEntity(this.getBlockPos); + } +} diff --git a/java/src/game/dispenser/IBehaviorDispenseItem.java b/common/src/main/java/common/dispenser/IBehaviorDispenseItem.java similarity index 87% rename from java/src/game/dispenser/IBehaviorDispenseItem.java rename to common/src/main/java/common/dispenser/IBehaviorDispenseItem.java index 2b68bf5..d15ef84 100755 --- a/java/src/game/dispenser/IBehaviorDispenseItem.java +++ b/common/src/main/java/common/dispenser/IBehaviorDispenseItem.java @@ -1,6 +1,6 @@ -package game.dispenser; +package common.dispenser; -import game.item.ItemStack; +import common.item.ItemStack; public interface IBehaviorDispenseItem { diff --git a/common/src/main/java/common/dispenser/IBlockSource.java b/common/src/main/java/common/dispenser/IBlockSource.java new file mode 100755 index 0000000..21cb62e --- /dev/null +++ b/common/src/main/java/common/dispenser/IBlockSource.java @@ -0,0 +1,22 @@ +package common.dispenser; + +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.world.World; + +public interface IBlockSource extends IPosition +{ + double getX(); + + double getY(); + + double getZ(); + + World getWorld(); + + BlockPos getBlockPos(); + + int getBlockMetadata(); + + T getBlockTileEntity(); +} diff --git a/java/src/game/dispenser/IPosition.java b/common/src/main/java/common/dispenser/IPosition.java similarity index 77% rename from java/src/game/dispenser/IPosition.java rename to common/src/main/java/common/dispenser/IPosition.java index d7ec2f1..aa1ebe7 100755 --- a/java/src/game/dispenser/IPosition.java +++ b/common/src/main/java/common/dispenser/IPosition.java @@ -1,4 +1,4 @@ -package game.dispenser; +package common.dispenser; public interface IPosition { diff --git a/common/src/main/java/common/enchantment/Enchantment.java b/common/src/main/java/common/enchantment/Enchantment.java new file mode 100755 index 0000000..90d69ef --- /dev/null +++ b/common/src/main/java/common/enchantment/Enchantment.java @@ -0,0 +1,650 @@ +package common.enchantment; + +import java.util.Map; +import common.collect.Maps; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.item.ItemArmor; +import common.item.ItemAxe; +import common.item.ItemShears; +import common.item.ItemStack; +import common.rng.Random; +import common.util.Displayable; +import common.util.ExtMath; +import common.util.Identifyable; +import common.vars.Vars; + +public enum Enchantment implements Displayable, Identifyable +{ + PROTECTION("protection", 10, EnchantmentType.ARMOR, "Schutz") { + public int getMinEnchantability(int enchantmentLevel) + { + return 1 + (enchantmentLevel - 1) * 11; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 20; + } + + public int getMaxLevel() + { + return 4; + } + + public int calcDamageReduction(int level, DamageSource source) + { + if (source == DamageSource.outOfWorld) + { + return 0; + } + else + { + float f = (float)(6 + level * level) / 3.0F; + return ExtMath.floorf(f * 0.75F); + } + } + }, + FIRE_PROTECTION("fire_protection", 5, EnchantmentType.ARMOR, "Feuerschutz") { + public int getMinEnchantability(int enchantmentLevel) + { + return 10 + (enchantmentLevel - 1) * 8; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 12; + } + + public int getMaxLevel() + { + return 4; + } + + public int calcDamageReduction(int level, DamageSource source) + { + if (source == DamageSource.outOfWorld) + { + return 0; + } + else + { + float f = (float)(6 + level * level) / 3.0F; + return source.isFireDamage() ? ExtMath.floorf(f * 1.25F) : 0; + } + } + }, + FEATHER_FALLING("feather_falling", 5, EnchantmentType.ARMOR_FEET, "Federfall") { + public int getMinEnchantability(int enchantmentLevel) + { + return 5 + (enchantmentLevel - 1) * 6; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 10; + } + + public int getMaxLevel() + { + return 4; + } + + public int calcDamageReduction(int level, DamageSource source) + { + if (source == DamageSource.outOfWorld) + { + return 0; + } + else + { + float f = (float)(6 + level * level) / 3.0F; + return source == DamageSource.fall ? ExtMath.floorf(f * 2.5F) : 0; + } + } + }, + BLAST_PROTECTION("blast_protection", 2, EnchantmentType.ARMOR, "Explosionsschutz") { + public int getMinEnchantability(int enchantmentLevel) + { + return 5 + (enchantmentLevel - 1) * 8; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 12; + } + + public int getMaxLevel() + { + return 4; + } + + public int calcDamageReduction(int level, DamageSource source) + { + if (source == DamageSource.outOfWorld) + { + return 0; + } + else + { + float f = (float)(6 + level * level) / 3.0F; + return source.isExplosion() ? ExtMath.floorf(f * 1.5F) : 0; + } + } + }, + PROJECTILE_PROTECTION("projectile_protection", 5, EnchantmentType.ARMOR, "Schusssicher") { + public int getMinEnchantability(int enchantmentLevel) + { + return 3 + (enchantmentLevel - 1) * 6; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 15; + } + + public int getMaxLevel() + { + return 4; + } + + public int calcDamageReduction(int level, DamageSource source) + { + if (source == DamageSource.outOfWorld) + { + return 0; + } + else + { + float f = (float)(6 + level * level) / 3.0F; + return source.isProjectile() ? ExtMath.floorf(f * 1.5F) : 0; + } + } + }, + THORNS("thorns", 1, EnchantmentType.ARMOR_TORSO, "Dornen") { + public int getMinEnchantability(int enchantmentLevel) + { + return 10 + 20 * (enchantmentLevel - 1); + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + public int getMaxLevel() + { + return 3; + } + + public boolean canApply(ItemStack stack) + { + return stack.getItem() instanceof ItemArmor ? true : super.canApply(stack); + } + + public void onUserHurt(EntityLiving user, Entity attacker, int level) + { + Random random = user.getRNG(); + ItemStack itemstack = EnchantmentHelper.getEnchantedItem(Enchantment.THORNS, user); + + if ((user.worldObj.client || Vars.damageThorns) && isThornsHurting(level, random)) + { + if (attacker != null) + { + attacker.attackEntityFrom(DamageSource.causeThornsDamage(user), getThornsDamage(level, random)); +// attacker.playSound("damage.thorns", 0.5F, 1.0F); + } + + if (itemstack != null) + { + itemstack.damageItem(3, user); + } + } + else if (itemstack != null) + { + itemstack.damageItem(1, user); + } + } + }, + SHARPNESS("sharpness", 10, EnchantmentType.WEAPON, "Schärfe") { + public int getMinEnchantability(int enchantmentLevel) + { + return 1 + (enchantmentLevel - 1) * 11; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 20; + } + + public int getMaxLevel() + { + return 5; + } + + public int calcAdditionalDamage(int level) + { + return (int)(/*this.damageType == 0 ? */ (float)level * 1.25F); // : (this.damageType == 1 && creatureType == CreatureType.UNDEAD ? (float)level * 2.5F : (this.damageType == 2 && creatureType == CreatureType.ARTHROPOD ? (float)level * 2.5F : 0.0F))); + } + + public boolean canApply(ItemStack stack) + { + return stack.getItem() instanceof ItemAxe ? true : super.canApply(stack); + } + +// /** +// * Called whenever a mob is damaged with an item that has this enchantment on it. +// */ +// public void onEntityDamaged(EntityLivingBase user, Entity target, int level) +// { +// if (target instanceof EntityLivingBase) +// { +// EntityLivingBase entitylivingbase = (EntityLivingBase)target; + // +// if (this.damageType == 2 && entitylivingbase.getCreatureType() == CreatureType.ARTHROPOD) +// { +// int i = 20 + user.getRNG().zrange(10 * level); +// entitylivingbase.addEffect(new PotionEffect(Potion.moveSlowdown.id, i, 3)); +// } +// } +// } + }, + KNOCKBACK("knockback", 5, EnchantmentType.WEAPON, "Rückstoß") { + public int getMinEnchantability(int enchantmentLevel) + { + return 5 + 20 * (enchantmentLevel - 1); + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + public int getMaxLevel() + { + return 2; + } + }, + FIRE_ASPECT("fire_aspect", 2, EnchantmentType.WEAPON, "Verbrennung") { + public int getMinEnchantability(int enchantmentLevel) + { + return 10 + 20 * (enchantmentLevel - 1); + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + public int getMaxLevel() + { + return 2; + } + }, + LOOTING("looting", 2, EnchantmentType.WEAPON, "Plünderung") { + public int getMinEnchantability(int enchantmentLevel) + { + return 15 + (enchantmentLevel - 1) * 9; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + public int getMaxLevel() + { + return 3; + } + }, + EFFICIENCY("efficiency", 10, EnchantmentType.DIGGER, "Effizienz") { + public int getMinEnchantability(int enchantmentLevel) + { + return 1 + 10 * (enchantmentLevel - 1); + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + public int getMaxLevel() + { + return 5; + } + + public boolean canApply(ItemStack stack) + { + return stack.getItem() instanceof ItemShears ? true : super.canApply(stack); + } + }, + SILK_TOUCH("silk_touch", 1, EnchantmentType.DIGGER, "Behutsamkeit") { + public int getMinEnchantability(int enchantmentLevel) + { + return 15; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + public int getMaxLevel() + { + return 1; + } + + public boolean canApplyTogether(Enchantment ench) + { + return super.canApplyTogether(ench) && ench != FORTUNE; + } + + public boolean canApply(ItemStack stack) + { + return stack.getItem() instanceof ItemShears ? true : super.canApply(stack); + } + }, + UNBREAKING("unbreaking", 5, EnchantmentType.BREAKABLE, "Haltbarkeit") { + public int getMinEnchantability(int enchantmentLevel) + { + return 5 + (enchantmentLevel - 1) * 8; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + public int getMaxLevel() + { + return 3; + } + + public boolean canApply(ItemStack stack) + { + return stack.isItemStackDamageable() ? true : super.canApply(stack); + } + }, + FORTUNE("fortune", 2, EnchantmentType.DIGGER, "Glück") { + public int getMinEnchantability(int enchantmentLevel) + { + return 15 + (enchantmentLevel - 1) * 9; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + public int getMaxLevel() + { + return 3; + } + + public boolean canApplyTogether(Enchantment ench) + { + return super.canApplyTogether(ench) && ench != SILK_TOUCH; + } + }, + POWER("power", 10, EnchantmentType.BOW, "Stärke") { + public int getMinEnchantability(int enchantmentLevel) + { + return 1 + (enchantmentLevel - 1) * 10; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 15; + } + + public int getMaxLevel() + { + return 5; + } + }, + PUNCH("punch", 2, EnchantmentType.BOW, "Schlag") { + public int getMinEnchantability(int enchantmentLevel) + { + return 12 + (enchantmentLevel - 1) * 20; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 25; + } + + public int getMaxLevel() + { + return 2; + } + }, + FLAME("flame", 2, EnchantmentType.BOW, "Flamme") { + public int getMinEnchantability(int enchantmentLevel) + { + return 20; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return 50; + } + + public int getMaxLevel() + { + return 1; + } + }, + INFINITY("infinity", 1, EnchantmentType.BOW, "Unendlich") { + public int getMinEnchantability(int enchantmentLevel) + { + return 20; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return 50; + } + + public int getMaxLevel() + { + return 1; + } + }, + LUCK_OF_THE_SEA("luck_of_the_sea", 2, EnchantmentType.FISHING_ROD, "Glück des Meeres") { + public int getMinEnchantability(int enchantmentLevel) + { + return 15 + (enchantmentLevel - 1) * 9; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + public int getMaxLevel() + { + return 3; + } + }, + LURE("lure", 2, EnchantmentType.FISHING_ROD, "Köder") { + public int getMinEnchantability(int enchantmentLevel) + { + return 15 + (enchantmentLevel - 1) * 9; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return super.getMinEnchantability(enchantmentLevel) + 50; + } + + public int getMaxLevel() + { + return 3; + } + }, + DRAINING("draining", 1, EnchantmentType.WEAPON, "Seelenentzug") { + public int getMinEnchantability(int enchantmentLevel) { + return 2 + (enchantmentLevel - 1) * 11; + } + + public int getMaxEnchantability(int enchantmentLevel) { + return this.getMinEnchantability(enchantmentLevel) + 20; + } + + public int getMaxLevel() { + return 16; + } + + public boolean canApply(ItemStack stack) { + return stack.getItem() instanceof ItemAxe ? true : super.canApply(stack); + } + + public void onEntityDamaged(EntityLiving user, Entity target, int level) { + if(target instanceof EntityLiving) { + EntityLiving entity = (EntityLiving)target; + entity.attackEntityFrom(DamageSource.causeIndirectMagicDamage(user, user), (int)((float)level * 1.25F)); + user.heal((int)((entity.arePotionsInverted() ? 0.2f : 1.0f) * (float)level)); + } + } + }; + + private static final String[] LEVELS = new String[] {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"}; + private static final Map LOOKUP = Maps.newHashMap(); + + private final String name; + private final int weight; + private final EnchantmentType type; + private final String display; + + static { + for(Enchantment ench : values()) { + if(LOOKUP.containsKey(ench.name)) + throw new IllegalArgumentException("Verzauberung " + ench.name + " ist bereits registriert"); + LOOKUP.put(ench.name, ench); + } + } + + public static Enchantment getEnchantment(String name) + { + return LOOKUP.get(name); + } + + private Enchantment(String name, int weight, EnchantmentType type, String display) + { + this.name = name; + this.weight = weight; + this.type = type; + this.display = display; + } + + public int getWeight() + { + return this.weight; + } + + public int getMinLevel() + { + return 1; + } + + public int getMaxLevel() + { + return 1; + } + + public int getMinEnchantability(int enchantmentLevel) + { + return 1 + enchantmentLevel * 10; + } + + public int getMaxEnchantability(int enchantmentLevel) + { + return this.getMinEnchantability(enchantmentLevel) + 5; + } + + public int calcDamageReduction(int level, DamageSource source) + { + return 0; + } + + public int calcAdditionalDamage(int level) + { + return 0; + } + + public boolean canApplyTogether(Enchantment ench) + { + return this != ench; + } + + public final String getName() { + return this.name; + } + + public String getDisplay() + { + return this.display; + } + + public EnchantmentType getType() { + return this.type; + } + + public String getFormattedName(int level) + { + return this.getDisplay() + " " + ((level >= 1 && level <= LEVELS.length) ? LEVELS[level - 1] : "" + level); + } + + public boolean canApply(ItemStack stack) + { + return this.type.canEnchantItem(stack.getItem()); + } + + public void onEntityDamaged(EntityLiving user, Entity target, int level) + { + } + + public void onUserHurt(EntityLiving user, Entity attacker, int level) + { + } + + public static int getFireTimeForEntity(Entity entity, int duration) + { + int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.FIRE_PROTECTION, entity.getInventory()); + + if (i > 0) + { + duration -= ExtMath.floorf((float)duration * (float)i * 0.15F); + } + + return duration; + } + + public static double getKnockbackFactor(Entity entity, double strength) + { + int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.BLAST_PROTECTION, entity.getInventory()); + + if (i > 0) + { + strength -= (double)ExtMath.floord(strength * (double)((float)i * 0.15F)); + } + + return strength; + } + + public static boolean negateDamage(ItemStack stack, int level, Random rand) + { + return stack.getItem() instanceof ItemArmor && rand.floatv() < 0.6F ? false : rand.rarity(level + 1); + } + + public static boolean isThornsHurting(int level, Random rand) + { + return level <= 0 ? false : rand.floatv() < 0.15F * (float)level; + } + + public static int getThornsDamage(int level, Random rand) + { + return level > 10 ? level - 10 : rand.roll(4); + } +} diff --git a/java/src/game/enchantment/EnchantmentHelper.java b/common/src/main/java/common/enchantment/EnchantmentHelper.java similarity index 73% rename from java/src/game/enchantment/EnchantmentHelper.java rename to common/src/main/java/common/enchantment/EnchantmentHelper.java index 364d437..a7a6edf 100755 --- a/java/src/game/enchantment/EnchantmentHelper.java +++ b/common/src/main/java/common/enchantment/EnchantmentHelper.java @@ -1,44 +1,30 @@ -package game.enchantment; +package common.enchantment; import java.util.Iterator; import java.util.List; import java.util.Map; -import game.collect.Lists; -import game.collect.Maps; - -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.item.Item; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.rng.Random; -import game.rng.WeightedList; +import common.collect.Lists; +import common.collect.Maps; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.item.Item; +import common.item.ItemStack; +import common.rng.Random; +import common.rng.WeightedList; +import common.tags.TagObject; public class EnchantmentHelper { - /** Is the random seed of enchantment effects. */ private static final Random enchantmentRand = new Random(); - - /** - * Used to calculate the extra armor of enchantments on armors equipped on player. - */ private static final EnchantmentHelper.ModifierDamage enchantmentModifierDamage = new EnchantmentHelper.ModifierDamage(); - - /** - * Used to calculate the (magic) extra damage done by enchantments on current equipped item of player. - */ private static final EnchantmentHelper.ModifierLiving enchantmentModifierLiving = new EnchantmentHelper.ModifierLiving(); private static final EnchantmentHelper.HurtIterator ENCHANTMENT_ITERATOR_HURT = new EnchantmentHelper.HurtIterator(); private static final EnchantmentHelper.DamageIterator ENCHANTMENT_ITERATOR_DAMAGE = new EnchantmentHelper.DamageIterator(); - /** - * Returns the level of enchantment on the ItemStack passed. - */ - public static int getEnchantmentLevel(int enchID, ItemStack stack) + public static int getEnchantmentLevel(Enchantment enchID, ItemStack stack) { if (stack == null) { @@ -46,21 +32,21 @@ public class EnchantmentHelper } else { - NBTTagList nbttaglist = stack.getEnchantmentTagList(); + List list = stack.getEnchantmentTagList(); - if (nbttaglist == null) + if (list == null) { return 0; } else { - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < list.size(); ++i) { - int j = nbttaglist.getCompoundTagAt(i).getShort("id"); - int k = nbttaglist.getCompoundTagAt(i).getShort("lvl"); + Enchantment j = Enchantment.getEnchantment(list.get(i).getString("id")); if (j == enchID) { + int k = list.get(i).getShort("lvl"); return k; } } @@ -70,68 +56,63 @@ public class EnchantmentHelper } } - public static Map getEnchantments(ItemStack stack) + public static Map getEnchantments(ItemStack stack) { - Map map = Maps.newLinkedHashMap(); - NBTTagList nbttaglist = stack.getItem() == Items.enchanted_book ? Items.enchanted_book.getEnchantments(stack) : stack.getEnchantmentTagList(); + Map map = Maps.newLinkedHashMap(); + List list = stack.getItem() == Items.enchanted_book ? Items.enchanted_book.getEnchantments(stack) : stack.getEnchantmentTagList(); - if (nbttaglist != null) + if (list != null) { - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < list.size(); ++i) { - int j = nbttaglist.getCompoundTagAt(i).getShort("id"); - int k = nbttaglist.getCompoundTagAt(i).getShort("lvl"); - map.put(j, k); + Enchantment j = Enchantment.getEnchantment(list.get(i).getString("id")); + if(j != null) { + int k = list.get(i).getShort("lvl"); + map.put(j, k); + } } } return map; } - /** - * Set the enchantments for the specified stack. - */ - public static void setEnchantments(Map enchMap, ItemStack stack) + public static void setEnchantments(Map enchMap, ItemStack stack) { - NBTTagList nbttaglist = new NBTTagList(); - Iterator iterator = enchMap.keySet().iterator(); + List list = Lists.newArrayList(); + Iterator iterator = enchMap.keySet().iterator(); while (iterator.hasNext()) { - int i = ((Integer)iterator.next()).intValue(); - Enchantment enchantment = Enchantment.getEnchantmentById(i); + Enchantment enchantment = iterator.next(); - if (enchantment != null) + TagObject tag = new TagObject(); + tag.setString("id", enchantment.getName()); + tag.setShort("lvl", (short)enchMap.get(enchantment).intValue()); + list.add(tag); + + if (stack.getItem() == Items.enchanted_book) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setShort("id", (short)i); - nbttagcompound.setShort("lvl", (short)enchMap.get(i).intValue()); - nbttaglist.appendTag(nbttagcompound); - - if (stack.getItem() == Items.enchanted_book) - { - Items.enchanted_book.addEnchantment(stack, new RngEnchantment(enchantment, enchMap.get(i).intValue())); - } + Items.enchanted_book.addEnchantment(stack, new RngEnchantment(enchantment, enchMap.get(enchantment).intValue())); } } - if (nbttaglist.tagCount() > 0) + if (list.size() > 0) { if (stack.getItem() != Items.enchanted_book) { - stack.setTagInfo("ench", nbttaglist); + stack.setTagInfo("ench", list); } } else if (stack.hasTagCompound()) { - stack.getTagCompound().removeTag("ench"); + stack.getTagCompound().remove("ench"); } } /** * Returns the biggest level of the enchantment on the array of ItemStack passed. */ - public static int getMaxEnchantmentLevel(int enchID, ItemStack[] stacks) + public static int getMaxEnchantmentLevel(Enchantment enchID, ItemStack[] stacks) { if (stacks == null) { @@ -162,18 +143,18 @@ public class EnchantmentHelper { if (stack != null) { - NBTTagList nbttaglist = stack.getEnchantmentTagList(); + List list = stack.getEnchantmentTagList(); - if (nbttaglist != null) + if (list != null) { - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < list.size(); ++i) { - int j = nbttaglist.getCompoundTagAt(i).getShort("id"); - int k = nbttaglist.getCompoundTagAt(i).getShort("lvl"); + String j = list.get(i).getString("id"); + int k = list.get(i).getShort("lvl"); - if (Enchantment.getEnchantmentById(j) != null) + if (Enchantment.getEnchantment(j) != null) { - modifier.calculateModifier(Enchantment.getEnchantmentById(j), k); + modifier.calculateModifier(Enchantment.getEnchantment(j), k); } } } @@ -256,7 +237,7 @@ public class EnchantmentHelper */ public static int getKnockbackModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.knockback.effectId, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.KNOCKBACK, player.getHeldItem()); } /** @@ -264,7 +245,7 @@ public class EnchantmentHelper */ public static int getFireAspectModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.fireAspect.effectId, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.FIRE_ASPECT, player.getHeldItem()); } // /** @@ -288,7 +269,7 @@ public class EnchantmentHelper */ public static int getEfficiencyModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.efficiency.effectId, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.EFFICIENCY, player.getHeldItem()); } /** @@ -296,7 +277,7 @@ public class EnchantmentHelper */ public static boolean getSilkTouchModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.silkTouch.effectId, player.getHeldItem()) > 0; + return getEnchantmentLevel(Enchantment.SILK_TOUCH, player.getHeldItem()) > 0; } /** @@ -304,7 +285,7 @@ public class EnchantmentHelper */ public static int getFortuneModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.fortune.effectId, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.FORTUNE, player.getHeldItem()); } /** @@ -312,7 +293,7 @@ public class EnchantmentHelper */ public static int getLuckOfSeaModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.luckOfTheSea.effectId, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.LUCK_OF_THE_SEA, player.getHeldItem()); } /** @@ -320,7 +301,7 @@ public class EnchantmentHelper */ public static int getLureModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.lure.effectId, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.LURE, player.getHeldItem()); } /** @@ -328,7 +309,7 @@ public class EnchantmentHelper */ public static int getLootingModifier(EntityLiving player) { - return getEnchantmentLevel(Enchantment.looting.effectId, player.getHeldItem()); + return getEnchantmentLevel(Enchantment.LOOTING, player.getHeldItem()); } // /** @@ -343,7 +324,7 @@ public class EnchantmentHelper { for (ItemStack itemstack : p_92099_1_.getInventory()) { - if (itemstack != null && getEnchantmentLevel(p_92099_0_.effectId, itemstack) > 0) + if (itemstack != null && getEnchantmentLevel(p_92099_0_, itemstack) > 0) { return itemstack; } @@ -400,7 +381,7 @@ public class EnchantmentHelper } else { - p_77504_1_.addEnchantment(enchantmentdata.enchantmentobj, enchantmentdata.enchantmentLevel); + p_77504_1_.addEnchantment(enchantmentdata.enchantment, enchantmentdata.level); } } } @@ -431,7 +412,7 @@ public class EnchantmentHelper } List list = null; - Map map = mapEnchantmentData(k, itemStackIn); + Map map = mapEnchantmentData(k, itemStackIn); if (map != null && !map.isEmpty()) { @@ -444,16 +425,16 @@ public class EnchantmentHelper for (int l = k; randomIn.zrange(50) <= l; l >>= 1) { - Iterator iterator = map.keySet().iterator(); + Iterator iterator = map.keySet().iterator(); while (iterator.hasNext()) { - Integer integer = (Integer)iterator.next(); + Enchantment ench = iterator.next(); boolean flag = true; for (RngEnchantment enchantmentdata1 : list) { - if (!enchantmentdata1.enchantmentobj.canApplyTogether(Enchantment.getEnchantmentById(integer.intValue()))) + if (!enchantmentdata1.enchantment.canApplyTogether(ench)) { flag = false; break; @@ -479,15 +460,15 @@ public class EnchantmentHelper } } - public static Map mapEnchantmentData(int p_77505_0_, ItemStack p_77505_1_) + public static Map mapEnchantmentData(int p_77505_0_, ItemStack p_77505_1_) { Item item = p_77505_1_.getItem(); - Map map = null; + Map map = null; boolean flag = p_77505_1_.getItem() == Items.book; - for (Enchantment enchantment : Enchantment.enchantmentsBookList) + for (Enchantment enchantment : Enchantment.values()) { - if (enchantment != null && (enchantment.type.canEnchantItem(item) || flag)) + if (enchantment != null && (enchantment.getType().canEnchantItem(item) || flag)) { for (int i = enchantment.getMinLevel(); i <= enchantment.getMaxLevel(); ++i) { @@ -495,10 +476,10 @@ public class EnchantmentHelper { if (map == null) { - map = Maps.newHashMap(); + map = Maps.newEnumMap(Enchantment.class); } - map.put(enchantment.effectId, new RngEnchantment(enchantment, i)); + map.put(enchantment, new RngEnchantment(enchantment, i)); } } } diff --git a/common/src/main/java/common/enchantment/EnchantmentType.java b/common/src/main/java/common/enchantment/EnchantmentType.java new file mode 100755 index 0000000..22ea489 --- /dev/null +++ b/common/src/main/java/common/enchantment/EnchantmentType.java @@ -0,0 +1,52 @@ +package common.enchantment; + +import common.attributes.UsageSlot; +import common.item.Item; +import common.item.ItemArmor; +import common.item.ItemBow; +import common.item.ItemFishingRod; +import common.item.ItemSword; +import common.item.ItemTool; + +public enum EnchantmentType +{ + ALL, + ARMOR, + ARMOR_FEET, + ARMOR_LEGS, + ARMOR_TORSO, + ARMOR_HEAD, + WEAPON, + DIGGER, + FISHING_ROD, + BREAKABLE, + BOW; + + public boolean canEnchantItem(Item item) + { + if (this == ALL) + { + return true; + } + else if (this == BREAKABLE && item.isDamageable()) + { + return true; + } + else if (item instanceof ItemArmor) + { + if (this == ARMOR) + { + return true; + } + else + { + ItemArmor armor = (ItemArmor)item; + return armor.armorType == UsageSlot.HEAD ? this == ARMOR_HEAD : (armor.armorType == UsageSlot.LEGS ? this == ARMOR_LEGS : (armor.armorType == UsageSlot.BODY ? this == ARMOR_TORSO : (armor.armorType == UsageSlot.FEET ? this == ARMOR_FEET : false))); + } + } + else + { + return item instanceof ItemSword ? this == WEAPON : (item instanceof ItemTool ? this == DIGGER : (item instanceof ItemBow ? this == BOW : (item instanceof ItemFishingRod ? this == FISHING_ROD : false))); + } + } +} diff --git a/common/src/main/java/common/enchantment/RngEnchantment.java b/common/src/main/java/common/enchantment/RngEnchantment.java new file mode 100755 index 0000000..d2ba1ad --- /dev/null +++ b/common/src/main/java/common/enchantment/RngEnchantment.java @@ -0,0 +1,14 @@ +package common.enchantment; + +import common.rng.RngItem; + +public class RngEnchantment extends RngItem { + public final Enchantment enchantment; + public final int level; + + public RngEnchantment(Enchantment enchantment, int level) { + super(enchantment.getWeight()); + this.enchantment = enchantment; + this.level = level; + } +} diff --git a/java/src/game/entity/DamageSource.java b/common/src/main/java/common/entity/DamageSource.java similarity index 98% rename from java/src/game/entity/DamageSource.java rename to common/src/main/java/common/entity/DamageSource.java index abb897f..e46f59b 100755 --- a/java/src/game/entity/DamageSource.java +++ b/common/src/main/java/common/entity/DamageSource.java @@ -1,9 +1,9 @@ -package game.entity; +package common.entity; -import game.color.TextColor; -import game.entity.projectile.EntityProjectile; -import game.entity.types.EntityLiving; -import game.world.Explosion; +import common.color.TextColor; +import common.entity.projectile.EntityProjectile; +import common.entity.types.EntityLiving; +import common.world.Explosion; public class DamageSource { diff --git a/java/src/game/entity/DataWatcher.java b/common/src/main/java/common/entity/DataWatcher.java similarity index 97% rename from java/src/game/entity/DataWatcher.java rename to common/src/main/java/common/entity/DataWatcher.java index 5b95477..222676a 100755 --- a/java/src/game/entity/DataWatcher.java +++ b/common/src/main/java/common/entity/DataWatcher.java @@ -1,4 +1,4 @@ -package game.entity; +package common.entity; import java.io.IOException; import java.util.List; @@ -6,12 +6,11 @@ import java.util.Map; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; -import game.collect.Lists; -import game.collect.Maps; - -import game.item.ItemStack; -import game.network.PacketBuffer; -import game.world.BlockPos; +import common.collect.Lists; +import common.collect.Maps; +import common.item.ItemStack; +import common.network.PacketBuffer; +import common.util.BlockPos; public class DataWatcher { private static final Map, Integer> dataTypes = Maps., Integer>newHashMap(); @@ -203,7 +202,7 @@ public class DataWatcher { case 5: ItemStack itemstack = (ItemStack)object.getObject(); - buffer.writeItemStackToBuffer(itemstack); + buffer.writeItemStack(itemstack); break; case 6: @@ -251,11 +250,11 @@ public class DataWatcher { break; case 4: - datawatcher$watchableobject = new DataWatcher.WatchableObject(j, k, buffer.readStringFromBuffer(32767)); + datawatcher$watchableobject = new DataWatcher.WatchableObject(j, k, buffer.readString(32767)); break; case 5: - datawatcher$watchableobject = new DataWatcher.WatchableObject(j, k, buffer.readItemStackFromBuffer()); + datawatcher$watchableobject = new DataWatcher.WatchableObject(j, k, buffer.readItemStack()); break; case 6: diff --git a/java/src/game/entity/Entity.java b/common/src/main/java/common/entity/Entity.java similarity index 90% rename from java/src/game/entity/Entity.java rename to common/src/main/java/common/entity/Entity.java index e972e30..15a3e9d 100755 --- a/java/src/game/entity/Entity.java +++ b/common/src/main/java/common/entity/Entity.java @@ -1,49 +1,46 @@ -package game.entity; +package common.entity; import java.util.List; -import game.audio.SoundType; -import game.block.Block; -import game.block.BlockFence; -import game.block.BlockFenceGate; -import game.block.BlockLiquid; -import game.block.BlockWall; -import game.color.TextColor; -import game.dimension.DimType; -import game.enchantment.EnchantmentHelper; -import game.enchantment.EnchantmentProtection; -import game.entity.effect.EntityLightning; -import game.entity.item.EntityItem; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.Config; -import game.init.EntityRegistry; -import game.init.ItemRegistry; -import game.init.SoundEvent; -import game.init.UniverseRegistry; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagDouble; -import game.nbt.NBTTagFloat; -import game.nbt.NBTTagList; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Explosion; -import game.world.Facing; -import game.world.HitPosition; -import game.world.PortalType; -import game.world.Position; -import game.world.State; -import game.world.Vec3; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.SoundType; +import common.block.artificial.BlockFence; +import common.block.artificial.BlockFenceGate; +import common.block.artificial.BlockWall; +import common.block.liquid.BlockLiquid; +import common.color.TextColor; +import common.dimension.DimType; +import common.enchantment.Enchantment; +import common.enchantment.EnchantmentHelper; +import common.entity.effect.EntityLightning; +import common.entity.item.EntityItem; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.EntityRegistry; +import common.init.ItemRegistry; +import common.init.SoundEvent; +import common.init.UniverseRegistry; +import common.item.Item; +import common.item.ItemStack; +import common.model.ParticleType; +import common.rng.Random; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Facing; +import common.util.HitPosition; +import common.util.PortalType; +import common.util.Position; +import common.util.Vec3; +import common.vars.Vars; +import common.world.Explosion; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public abstract class Entity { @@ -150,10 +147,7 @@ public abstract class Entity this.dataWatcher = new DataWatcher(this); this.dataWatcher.addObject(0, Byte.valueOf((byte)0)); -// this.dataWatcher.addObject(1, Short.valueOf((short)300)); -// this.dataWatcher.addObject(3, Byte.valueOf((byte)0)); this.dataWatcher.addObject(1, ""); -// this.dataWatcher.addObject(4, Byte.valueOf((byte)0)); this.entityInit(); } @@ -273,7 +267,7 @@ public abstract class Entity protected void checkPortal() { if(this.inPortal != null) { - if(this.vehicle == null && this.passenger == null && Config.portals) { + if(this.vehicle == null && this.passenger == null && Vars.portals) { int current = this.worldObj.dimension.getDimensionId(); int dest = UniverseRegistry.getPortalDest(current, this.inPortal); if(dest != current) { @@ -328,7 +322,7 @@ public abstract class Entity } else { - if (Config.damageFire && this.fire % 20 == 0) + if (Vars.damageFire && this.fire % 20 == 0) { this.attackEntityFrom(DamageSource.onFire, 1); } @@ -346,7 +340,7 @@ public abstract class Entity this.setOnFireFromMolten(); } - if (this.posY < -64.0D) + if (this.posY < (double)(-World.MAX_SIZE_Y) - 64.0) { this.onVoidUpdate(); } @@ -364,7 +358,7 @@ public abstract class Entity if(!this.worldObj.client && this.worldObj.dimension.getType() != DimType.SPACE) { // this.worldObj.profiler.start("descent"); int current = this.worldObj.dimension.getDimensionId(); - int dim = Config.voidPortal ? UniverseRegistry.getPortalDest(current, PortalType.VOID) : current; + int dim = Vars.voidPortal ? UniverseRegistry.getPortalDest(current, PortalType.VOID) : current; if(dim == current) { // && (!(this.isPlayer()) || !((EntityNPCMP)this).creative)) { this.kill(); } @@ -374,7 +368,7 @@ public abstract class Entity // } else if(this.vehicle == null && this.passenger == null) { Entity ent = this.travelToDimension(dim, - new BlockPos(this.posX, (float)ExtMath.clampi(Config.portalHeight, 0, 16384), this.posZ), + new BlockPos(this.posX, (float)ExtMath.clampi(Vars.portalHeight, 0, 16384), this.posZ), this.rotYaw, this.rotPitch, PortalType.VOID); ent.ignoreFall = true; } @@ -400,7 +394,7 @@ public abstract class Entity { if (!this.isImmuneToFire()) { - if(Config.damageLava) + if(Vars.damageLava) this.attackEntityFrom(DamageSource.hotLiquid, 4); this.setFire(15); } @@ -410,7 +404,7 @@ public abstract class Entity { if (!this.isImmuneToFire()) { - if(Config.damageMolten) + if(Vars.damageMolten) this.attackEntityFrom(DamageSource.molten, 2); this.setFire(10); } @@ -428,7 +422,7 @@ public abstract class Entity public void setFire(int seconds) { int i = seconds * 20; - i = EnchantmentProtection.getFireTimeForEntity(this, i); + i = Enchantment.getFireTimeForEntity(this, i); if (this.fire < i) { @@ -704,7 +698,7 @@ public abstract class Entity BlockPos blockpos = new BlockPos(i, j, k); Block block1 = this.worldObj.getState(blockpos).getBlock(); - if (block1.getMaterial() == Material.air) + if (block1 == Blocks.air) { Block block = this.worldObj.getState(blockpos.down()).getBlock(); @@ -751,7 +745,7 @@ public abstract class Entity this.walkDistMod = (float)((double)this.walkDistMod + (double)ExtMath.sqrtd(d12 * d12 + d14 * d14) * 0.6D); this.stepDistMod = (float)((double)this.stepDistMod + (double)ExtMath.sqrtd(d12 * d12 + d13 * d13 + d14 * d14) * 0.6D); - if (this.stepDistMod > (float)this.nextStepDist && block1.getMaterial() != Material.air) + if (this.stepDistMod > (float)this.nextStepDist && block1 != Blocks.air) { this.nextStepDist = (int)this.stepDistMod + 1; @@ -932,7 +926,7 @@ public abstract class Entity */ protected void dealFireDamage(int amount) { - if(!this.isImmuneToFire() && Config.damageFire) + if(!this.isImmuneToFire() && Vars.damageFire) this.attackEntityFrom(DamageSource.inFire, amount); } @@ -1014,7 +1008,7 @@ public abstract class Entity this.worldObj.spawnParticle(ParticleType.WATER_BUBBLE, this.posX + (double)f2, (double)(f1 + 1.0F), this.posZ + (double)f3, this.motionX, this.motionY - (double)(this.rand.floatv() * 0.2F), this.motionZ); } - if(this.worldObj.getState(new BlockPos(this.posX, this.posY, this.posZ)).getBlock().getMaterial() == Material.water) { + if(this.worldObj.getState(new BlockPos(this.posX, this.posY, this.posZ)).getBlock().getMaterial() == Material.WATER) { for (int j = 0; (float)j < 1.0F + this.width * 20.0F; ++j) { float f4 = (this.rand.floatv() * 2.0F - 1.0F) * this.width; @@ -1299,7 +1293,7 @@ public abstract class Entity public void addKnockback(double x, double y, double z) { - float mult = this.worldObj.client ? 1.0f : Config.knockback; + float mult = this.worldObj.client ? 1.0f : Vars.knockback; this.addVelocity(x * mult, y * mult, z * mult); } @@ -1422,17 +1416,17 @@ public abstract class Entity } /** - * Like writeToNBTOptional but does not check if the entity is ridden. Used for saving ridden entities with their + * Like writeOptional but does not check if the entity is ridden. Used for saving ridden entities with their * riders. */ - public boolean writeMountToNBT(NBTTagCompound tagCompund) + public boolean writeMount(TagObject tag) { String s = EntityRegistry.getEntityString(this); if (!this.dead && !this.isPlayer() && s != null) { - tagCompund.setString("id", s); - this.writeToNBT(tagCompund); + tag.setString("id", s); + this.writeTags(tag); return true; } else @@ -1442,18 +1436,18 @@ public abstract class Entity } /** - * Either write this entity to the NBT tag given and return true, or return false without doing anything. If this + * Either write this entity to the tag given and return true, or return false without doing anything. If this * returns false the entity is not saved on disk. Ridden entities return false here as they are saved with their * rider. */ - public boolean writeToNBTOptional(NBTTagCompound tagCompund) + public boolean writeOptional(TagObject tag) { String s = EntityRegistry.getEntityString(this); if (!this.dead && !this.isPlayer() && s != null && (this.passenger == null || this.passenger.isPlayer())) { - tagCompund.setString("id", s); - this.writeToNBT(tagCompund); + tag.setString("id", s); + this.writeTags(tag); return true; } else @@ -1487,9 +1481,9 @@ public abstract class Entity // } /** - * Save the entity to NBT (calls an abstract helper method to write extra data) + * Save the entity to tags (calls an abstract helper method to write extra data) */ - public void writeToNBT(NBTTagCompound tagCompund) + public void writeTags(TagObject tag) { // if(this.persistentId != 0L) { // tagCompund.setLong("PersistID", this.persistentId); @@ -1497,20 +1491,25 @@ public abstract class Entity // if(this.tag != null) { // tagCompund.setString("ObjectTag", this.tag); // } - - tagCompund.setTag("Pos", this.newDoubleNBTList(this.posX, this.posY, this.posZ)); - tagCompund.setTag("Motion", this.newDoubleNBTList(this.motionX, this.motionY, this.motionZ)); - tagCompund.setTag("Rotation", this.newFloatNBTList(this.rotYaw, this.rotPitch)); - tagCompund.setFloat("FallDistance", this.fallDistance); - tagCompund.setShort("Fire", (short)this.fire); + + tag.setDouble("PosX", this.posX); + tag.setDouble("PosY", this.posY); + tag.setDouble("PosZ", this.posZ); + tag.setDouble("MotionX", this.motionX); + tag.setDouble("MotionY", this.motionY); + tag.setDouble("MotionZ", this.motionZ); + tag.setFloat("Yaw", this.rotYaw); + tag.setFloat("Pitch", this.rotPitch); + tag.setFloat("FallDistance", this.fallDistance); + tag.setShort("Fire", (short)this.fire); // tagCompund.setShort("Air", (short)this.getAir()); - tagCompund.setBoolean("OnGround", this.onGround); + tag.setBool("OnGround", this.onGround); // tagCompund.setBoolean("Invulnerable", this.invulnerable); // tagCompund.setInteger("PortalCooldown", this.portalTimer); if (this.getCustomNameTag() != null && this.getCustomNameTag().length() > 0) { - tagCompund.setString("CustomName", this.getCustomNameTag()); + tag.setString("CustomName", this.getCustomNameTag()); // tagCompund.setBoolean("CustomNameVisible", this.getAlwaysRenderNameTag()); } @@ -1520,36 +1519,33 @@ public abstract class Entity // } if(this.ignoreFall) - tagCompund.setBoolean("IgnoreFall", this.ignoreFall); + tag.setBool("IgnoreFall", this.ignoreFall); - this.writeEntityToNBT(tagCompund); + this.writeEntity(tag); if (this.vehicle != null && !(this.isPlayer())) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject mount = new TagObject(); - if (this.vehicle.writeMountToNBT(nbttagcompound)) + if (this.vehicle.writeMount(mount)) { - tagCompund.setTag("Riding", nbttagcompound); + tag.setObject("Riding", mount); } } } /** - * Reads the entity from NBT (calls an abstract helper method to read specialized data) + * Reads the entity from tags (calls an abstract helper method to read specialized data) */ - public void readFromNBT(NBTTagCompound tagCompund) + public void readTags(TagObject tag) { -// if(tagCompund.hasKey("PersistID", 4)) +// if(tagCompund.hasLong("PersistID")) // this.setPersistentId(tagCompund.getLong("PersistID")); // this.setTag(tagCompund.getString("ObjectTag")); - NBTTagList nbttaglist = tagCompund.getTagList("Pos", 6); - NBTTagList nbttaglist1 = tagCompund.getTagList("Motion", 6); - NBTTagList nbttaglist2 = tagCompund.getTagList("Rotation", 5); - this.motionX = nbttaglist1.getDoubleAt(0); - this.motionY = nbttaglist1.getDoubleAt(1); - this.motionZ = nbttaglist1.getDoubleAt(2); + this.motionX = tag.getDouble("MotionX"); + this.motionY = tag.getDouble("MotionY"); + this.motionZ = tag.getDouble("MotionZ"); if (Math.abs(this.motionX) > 10.0D) { @@ -1566,32 +1562,32 @@ public abstract class Entity this.motionZ = 0.0D; } - this.prevX = this.lastTickPosX = this.posX = nbttaglist.getDoubleAt(0); - this.prevY = this.lastTickPosY = this.posY = nbttaglist.getDoubleAt(1); - this.prevZ = this.lastTickPosZ = this.posZ = nbttaglist.getDoubleAt(2); - this.prevYaw = this.rotYaw = nbttaglist2.getFloatAt(0); - this.prevPitch = this.rotPitch = nbttaglist2.getFloatAt(1); + this.prevX = this.lastTickPosX = this.posX = tag.getDouble("PosX"); + this.prevY = this.lastTickPosY = this.posY = tag.getDouble("PosY"); + this.prevZ = this.lastTickPosZ = this.posZ = tag.getDouble("PosZ"); + this.prevYaw = this.rotYaw = tag.getFloat("Yaw"); + this.prevPitch = this.rotPitch = tag.getFloat("Pitch"); this.setRotationYawHead(this.rotYaw); this.setRenderYawOffset(this.rotYaw); - this.fallDistance = tagCompund.getFloat("FallDistance"); - this.fire = tagCompund.getShort("Fire"); + this.fallDistance = tag.getFloat("FallDistance"); + this.fire = tag.getShort("Fire"); // this.setAir(tagCompund.getShort("Air")); - this.onGround = tagCompund.getBoolean("OnGround"); + this.onGround = tag.getBool("OnGround"); // this.invulnerable = tagCompund.getBoolean("Invulnerable"); // this.portalTimer = tagCompund.getInteger("PortalCooldown"); this.setPosition(this.posX, this.posY, this.posZ); this.setRotation(this.rotYaw, this.rotPitch); - if (tagCompund.hasKey("CustomName", 8) && tagCompund.getString("CustomName").length() > 0) + if (tag.hasString("CustomName") && tag.getString("CustomName").length() > 0) { - this.setCustomNameTag(tagCompund.getString("CustomName")); + this.setCustomNameTag(tag.getString("CustomName")); } // this.setAlwaysRenderNameTag(tagCompund.getBoolean("CustomNameVisible")); // this.setSilent(tagCompund.getBoolean("Silent")); - this.ignoreFall = tagCompund.getBoolean("IgnoreFall"); - this.readEntityFromNBT(tagCompund); + this.ignoreFall = tag.getBool("IgnoreFall"); + this.readEntity(tag); if (this.shouldSetPosAfterLoading()) { @@ -1613,49 +1609,19 @@ public abstract class Entity // } /** - * (abstract) Protected helper method to read subclass entity data from NBT. + * (abstract) Protected helper method to read subclass entity data from tags. */ - protected abstract void readEntityFromNBT(NBTTagCompound tagCompund); + protected abstract void readEntity(TagObject tag); /** - * (abstract) Protected helper method to write subclass entity data to NBT. + * (abstract) Protected helper method to write subclass entity data to tags. */ - protected abstract void writeEntityToNBT(NBTTagCompound tagCompound); + protected abstract void writeEntity(TagObject tag); public void onChunkLoad() { } - /** - * creates a NBT list from the array of doubles passed to this function - */ - protected NBTTagList newDoubleNBTList(double... numbers) - { - NBTTagList nbttaglist = new NBTTagList(); - - for (double d0 : numbers) - { - nbttaglist.appendTag(new NBTTagDouble(d0)); - } - - return nbttaglist; - } - - /** - * Returns a new NBTTagList filled with the specified floats - */ - protected NBTTagList newFloatNBTList(float... numbers) - { - NBTTagList nbttaglist = new NBTTagList(); - - for (float f : numbers) - { - nbttaglist.appendTag(new NBTTagFloat(f)); - } - - return nbttaglist; - } - public EntityItem dropItem(Item itemIn, int size) { return this.dropItemWithOffset(itemIn, size, 0.0F); @@ -1671,7 +1637,7 @@ public abstract class Entity */ public EntityItem entityDropItem(ItemStack itemStackIn, float offsetY) { - if (itemStackIn.stackSize != 0 && itemStackIn.getItem() != null) + if (itemStackIn.size != 0 && itemStackIn.getItem() != null) { EntityItem entityitem = new EntityItem(this.worldObj, this.posX, this.posY + (double)offsetY, this.posZ, itemStackIn); entityitem.setDefaultPickupDelay(); @@ -1857,7 +1823,7 @@ public abstract class Entity // } public final void teleport(Position pos) { - this.teleport(pos.x, pos.y, pos.z, pos.yaw, pos.pitch, pos.dim); + this.teleport(pos.x(), pos.y(), pos.z(), pos.yaw(), pos.pitch(), pos.dim()); } public final void teleport(BlockPos pos, int dim) { @@ -1909,7 +1875,7 @@ public abstract class Entity } } - public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) + public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) { this.setPosition(x, y, z); this.setRotation(yaw, pitch); @@ -2144,7 +2110,7 @@ public abstract class Entity */ public void onStruckByLightning(EntityLightning bolt) { - if((this.worldObj.client || Config.damageLightning) && bolt.damage > 0) + if((this.worldObj.client || Vars.damageLightning) && bolt.damage > 0) this.attackEntityFrom(DamageSource.causeLightningDamage(bolt.summoner), this.worldObj.rand.range(bolt.damage, ((bolt.damage * 3) / 2))); if(bolt.fire) { ++this.fire; @@ -2347,13 +2313,13 @@ public abstract class Entity } /** - * Prepares this entity in new dimension by copying NBT data from entity in old dimension + * Prepares this entity in new dimension by copying data from entity in old dimension */ public void copyDataFromOld(Entity entityIn) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - entityIn.writeToNBT(nbttagcompound); - this.readFromNBT(nbttagcompound); + TagObject tag = new TagObject(); + entityIn.writeTags(tag); + this.readTags(tag); // this.portalTimer = entityIn.portalTimer; // this.portalPos = entityIn.portalPos; // this.portalVec = entityIn.portalVec; @@ -2370,8 +2336,8 @@ public abstract class Entity // this.worldObj.profiler.start("changeDimension"); // Server server = Server.getServer(); // int oldDim = this.dimension; - WorldServer worldserver = (WorldServer)this.worldObj; // server.getWorld(oldDim); - WorldServer worldserver1 = worldserver.getServer().getWorld(dimensionId); + AWorldServer worldserver = (AWorldServer)this.worldObj; // server.getWorld(oldDim); + AWorldServer worldserver1 = worldserver.getOtherWorld(dimensionId); // this.dimension = dimensionId; // if (i == 1 && dimensionId == 1) @@ -2383,7 +2349,7 @@ public abstract class Entity this.worldObj.removeEntity(this); this.dead = false; // this.worldObj.profiler.start("reposition"); - worldserver.getServer().placeInDimension(this, worldserver, worldserver1, pos, portal); + worldserver.placeInDimension(this, worldserver, worldserver1, pos, portal); if(this.isEntityAlive()) worldserver1.updateEntity(this, false); // this.worldObj.profiler.next("reloading"); @@ -2550,25 +2516,6 @@ public abstract class Entity return Facing.getHorizontal(ExtMath.floord((double)(this.rotYaw * 4.0F / 360.0F) + 0.5D) & 3); } -// protected HoverEvent getHoverEvent() -// { -// NBTTagCompound nbttagcompound = new NBTTagCompound(); -// String s = EntityRegistry.getEntityString(this); -// nbttagcompound.setString("id", "#" + this.getId()); -// if(this.hasPersistentId()) -// nbttagcompound.setString("pid", String.format("$%016x", this.getPersistentId())); -// if(this.hasTag()) -// nbttagcompound.setString("otag", this.getTag()); -// -// if (s != null) -// { -// nbttagcompound.setString("type", s); -// } -// -// nbttagcompound.setString("name", IChatComponent.Serializer.componentToJson(this.getTypeName())); -// return new HoverEvent(HoverEvent.Action.SHOW_ENTITY, new ChatComponentText(nbttagcompound.toString())); -// } - public boolean isVisibleTo(EntityNPC player) { return true; @@ -2613,15 +2560,15 @@ public abstract class Entity return new BlockPos(this.posX, this.posY + 0.5D, this.posZ); } - public NBTTagCompound getNBTTagCompound() + public TagObject getTag() { return null; } /** - * Called when client receives entity's NBTTagCompound from server. + * Called when client receives entity's tags from server. */ - public void clientUpdateEntityNBT(NBTTagCompound compound) + public void clientUpdateEntityTags(TagObject compound) { } diff --git a/java/src/game/entity/EntityDamageSource.java b/common/src/main/java/common/entity/EntityDamageSource.java similarity index 94% rename from java/src/game/entity/EntityDamageSource.java rename to common/src/main/java/common/entity/EntityDamageSource.java index ecb22c7..971a33c 100755 --- a/java/src/game/entity/EntityDamageSource.java +++ b/common/src/main/java/common/entity/EntityDamageSource.java @@ -1,8 +1,8 @@ -package game.entity; +package common.entity; -import game.color.TextColor; -import game.entity.types.EntityLiving; -import game.item.ItemStack; +import common.color.TextColor; +import common.entity.types.EntityLiving; +import common.item.ItemStack; public class EntityDamageSource extends DamageSource { diff --git a/java/src/game/entity/EntityDamageSourceIndirect.java b/common/src/main/java/common/entity/EntityDamageSourceIndirect.java similarity index 92% rename from java/src/game/entity/EntityDamageSourceIndirect.java rename to common/src/main/java/common/entity/EntityDamageSourceIndirect.java index a50bb18..a28b70a 100755 --- a/java/src/game/entity/EntityDamageSourceIndirect.java +++ b/common/src/main/java/common/entity/EntityDamageSourceIndirect.java @@ -1,8 +1,8 @@ -package game.entity; +package common.entity; -import game.color.TextColor; -import game.entity.types.EntityLiving; -import game.item.ItemStack; +import common.color.TextColor; +import common.entity.types.EntityLiving; +import common.item.ItemStack; public class EntityDamageSourceIndirect extends EntityDamageSource { diff --git a/java/src/game/entity/EntityTrackerEntry.java b/common/src/main/java/common/entity/EntityTrackerEntry.java similarity index 80% rename from java/src/game/entity/EntityTrackerEntry.java rename to common/src/main/java/common/entity/EntityTrackerEntry.java index b560415..1ed7535 100755 --- a/java/src/game/entity/EntityTrackerEntry.java +++ b/common/src/main/java/common/entity/EntityTrackerEntry.java @@ -1,35 +1,32 @@ -package game.entity; +package common.entity; -import java.util.Collection; import java.util.List; import java.util.Set; -import game.collect.Sets; - -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.AttributeMap; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityArrow; -import game.entity.types.EntityLiving; -import game.item.ItemStack; -import game.log.Log; -import game.nbt.NBTTagCompound; -import game.network.Packet; -import game.packet.S14PacketEntity; -import game.packet.S18PacketEntityTeleport; -import game.packet.S19PacketEntityHeadLook; -import game.packet.S1BPacketEntityAttach; -import game.packet.S1CPacketEntityMetadata; -import game.packet.S1DPacketEntityEffect; -import game.packet.S20PacketEntityProperties; -import game.packet.S43PacketUpdateEntityNBT; -import game.packet.SPacketEntityEquipment; -import game.packet.SPacketEntityVelocity; -import game.packet.SPacketSpawnMob; -import game.packet.SPacketSpawnObject; -import game.packet.SPacketSpawnPlayer; -import game.potion.PotionEffect; -import game.util.ExtMath; +import common.collect.Sets; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityArrow; +import common.entity.types.EntityLiving; +import common.item.ItemStack; +import common.log.Log; +import common.network.Packet; +import common.packet.SPacketEntityRelMove; +import common.packet.SPacketEntityLook; +import common.packet.SPacketEntityLookMove; +import common.packet.SPacketEntityTeleport; +import common.packet.SPacketEntityHeadLook; +import common.packet.SPacketEntityAttach; +import common.packet.SPacketEntityMetadata; +import common.packet.SPacketEntityEffect; +import common.packet.SPacketUpdateEntityTags; +import common.packet.SPacketEntityEquipment; +import common.packet.SPacketEntityVelocity; +import common.packet.SPacketSpawnMob; +import common.packet.SPacketSpawnObject; +import common.packet.SPacketSpawnPlayer; +import common.potion.PotionEffect; +import common.tags.TagObject; +import common.util.ExtMath; public class EntityTrackerEntry { public final Entity trackedEntity; @@ -97,7 +94,7 @@ public class EntityTrackerEntry { if(this.lastRiding != this.trackedEntity.vehicle || this.trackedEntity.vehicle != null && this.updateCounter % 60 == 0) { this.lastRiding = this.trackedEntity.vehicle; - this.sendPacketToTrackedPlayers(new S1BPacketEntityAttach(0, this.trackedEntity, this.trackedEntity.vehicle)); + this.sendPacketToTrackedPlayers(new SPacketEntityAttach(0, this.trackedEntity, this.trackedEntity.vehicle)); } // if(this.trackedEntity instanceof EntityFrame && this.updateCounter % 10 == 0) { @@ -142,23 +139,23 @@ public class EntityTrackerEntry { && !this.ridingEntity && this.onGround == this.trackedEntity.onGround) { if((!flag || !flag1) && !(this.trackedEntity instanceof EntityArrow)) { if(flag) { - packet1 = new S14PacketEntity.S15PacketEntityRelMove(this.trackedEntity.getId(), (byte)j2, (byte)k2, (byte)i, + packet1 = new SPacketEntityRelMove(this.trackedEntity.getId(), (byte)j2, (byte)k2, (byte)i, this.trackedEntity.onGround); } else if(flag1) { - packet1 = new S14PacketEntity.S16PacketEntityLook(this.trackedEntity.getId(), (byte)l1, (byte)i2, + packet1 = new SPacketEntityLook(this.trackedEntity.getId(), (byte)l1, (byte)i2, this.trackedEntity.onGround); } } else { - packet1 = new S14PacketEntity.S17PacketEntityLookMove(this.trackedEntity.getId(), (byte)j2, (byte)k2, (byte)i, + packet1 = new SPacketEntityLookMove(this.trackedEntity.getId(), (byte)j2, (byte)k2, (byte)i, (byte)l1, (byte)i2, this.trackedEntity.onGround); } } else { this.onGround = this.trackedEntity.onGround; this.ticksSinceLastForcedTeleport = 0; - packet1 = new S18PacketEntityTeleport(this.trackedEntity.getId(), k, j1, k1, (byte)l1, (byte)i2, + packet1 = new SPacketEntityTeleport(this.trackedEntity.getId(), k, j1, k1, (byte)l1, (byte)i2, this.trackedEntity.onGround); } } @@ -205,7 +202,7 @@ public class EntityTrackerEntry { boolean flag2 = Math.abs(j - this.encodedRotationYaw) >= 4 || Math.abs(i1 - this.encodedRotationPitch) >= 4; if(flag2) { - this.sendPacketToTrackedPlayers(new S14PacketEntity.S16PacketEntityLook(this.trackedEntity.getId(), (byte)j, (byte)i1, + this.sendPacketToTrackedPlayers(new SPacketEntityLook(this.trackedEntity.getId(), (byte)j, (byte)i1, this.trackedEntity.onGround)); this.encodedRotationYaw = j; this.encodedRotationPitch = i1; @@ -221,7 +218,7 @@ public class EntityTrackerEntry { int l = ExtMath.floorf(this.trackedEntity.getRotationYawHead() * 256.0F / 360.0F); if(Math.abs(l - this.lastHeadMotion) >= 4) { - this.sendPacketToTrackedPlayers(new S19PacketEntityHeadLook(this.trackedEntity, (byte)l)); + this.sendPacketToTrackedPlayers(new SPacketEntityHeadLook(this.trackedEntity, (byte)l)); this.lastHeadMotion = l; } @@ -240,18 +237,7 @@ public class EntityTrackerEntry { DataWatcher datawatcher = this.trackedEntity.getDataWatcher(); if(datawatcher.hasObjectChanged()) { - this.sendPacketToTrackedAndSelf(new S1CPacketEntityMetadata(this.trackedEntity.getId(), datawatcher, false)); - } - - if(this.trackedEntity instanceof EntityLiving) { - AttributeMap serversideattributemap = ((EntityLiving)this.trackedEntity).getAttributeMap(); - Set set = serversideattributemap.getDirty(); - - if(!set.isEmpty()) { - this.sendPacketToTrackedAndSelf(new S20PacketEntityProperties(this.trackedEntity.getId(), set)); - } - - set.clear(); + this.sendPacketToTrackedAndSelf(new SPacketEntityMetadata(this.trackedEntity.getId(), datawatcher, false)); } } @@ -292,22 +278,13 @@ public class EntityTrackerEntry { if(!this.trackedEntity.getDataWatcher().isBlank()) { playerMP.connection - .sendPacket(new S1CPacketEntityMetadata(this.trackedEntity.getId(), this.trackedEntity.getDataWatcher(), true)); + .sendPacket(new SPacketEntityMetadata(this.trackedEntity.getId(), this.trackedEntity.getDataWatcher(), true)); } - NBTTagCompound nbttagcompound = this.trackedEntity.getNBTTagCompound(); + TagObject nbttagcompound = this.trackedEntity.getTag(); if(nbttagcompound != null) { - playerMP.connection.sendPacket(new S43PacketUpdateEntityNBT(this.trackedEntity.getId(), nbttagcompound)); - } - - if(this.trackedEntity instanceof EntityLiving) { - AttributeMap serversideattributemap = ((EntityLiving)this.trackedEntity).getAttributeMap(); - Collection collection = serversideattributemap.getWatchedAttributes(); - - if(!collection.isEmpty()) { - playerMP.connection.sendPacket(new S20PacketEntityProperties(this.trackedEntity.getId(), collection)); - } + playerMP.connection.sendPacket(new SPacketUpdateEntityTags(this.trackedEntity.getId(), nbttagcompound)); } this.lastTrackedEntityMotionX = this.trackedEntity.motionX; @@ -323,12 +300,12 @@ public class EntityTrackerEntry { } if(this.trackedEntity.vehicle != null) { - playerMP.connection.sendPacket(new S1BPacketEntityAttach(0, this.trackedEntity, this.trackedEntity.vehicle)); + playerMP.connection.sendPacket(new SPacketEntityAttach(0, this.trackedEntity, this.trackedEntity.vehicle)); } if(this.trackedEntity instanceof EntityLiving && ((EntityLiving)this.trackedEntity).getLeashedTo() != null) { playerMP.connection.sendPacket( - new S1BPacketEntityAttach(1, this.trackedEntity, ((EntityLiving)this.trackedEntity).getLeashedTo())); + new SPacketEntityAttach(1, this.trackedEntity, ((EntityLiving)this.trackedEntity).getLeashedTo())); } if(this.trackedEntity instanceof EntityLiving) { @@ -354,7 +331,7 @@ public class EntityTrackerEntry { EntityLiving entitylivingbase = (EntityLiving)this.trackedEntity; for(PotionEffect potioneffect : entitylivingbase.getEffects()) { - playerMP.connection.sendPacket(new S1DPacketEntityEffect(this.trackedEntity.getId(), potioneffect)); + playerMP.connection.sendPacket(new SPacketEntityEffect(this.trackedEntity.getId(), potioneffect)); } } } @@ -387,7 +364,7 @@ public class EntityTrackerEntry { private Packet createSpawnPacket() { if(this.trackedEntity.dead) { - Log.JNI.warn("Erstelle Spawn-Paket für entferntes Objekt"); + Log.TICK.warn("Erstelle Spawn-Paket für entferntes Objekt"); } SPacketSpawnObject packet = null; diff --git a/java/src/game/entity/EntityType.java b/common/src/main/java/common/entity/EntityType.java similarity index 93% rename from java/src/game/entity/EntityType.java rename to common/src/main/java/common/entity/EntityType.java index 55ca7fe..1bfbfd7 100644 --- a/java/src/game/entity/EntityType.java +++ b/common/src/main/java/common/entity/EntityType.java @@ -1,8 +1,8 @@ -package game.entity; +package common.entity; import java.util.Map; -import game.collect.Maps; +import common.collect.Maps; public enum EntityType { OBJECT("Object", "Objekt"), diff --git a/java/src/game/entity/animal/EntityBat.java b/common/src/main/java/common/entity/animal/EntityBat.java similarity index 93% rename from java/src/game/entity/animal/EntityBat.java rename to common/src/main/java/common/entity/animal/EntityBat.java index 7478685..14297ea 100755 --- a/java/src/game/entity/animal/EntityBat.java +++ b/common/src/main/java/common/entity/animal/EntityBat.java @@ -1,17 +1,17 @@ -package game.entity.animal; +package common.entity.animal; -import game.block.Block; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.npc.Alignment; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.SoundEvent; -import game.nbt.NBTTagCompound; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.World; +import common.block.Block; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.npc.Alignment; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.SoundEvent; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.World; public class EntityBat extends EntityLiving { @@ -248,18 +248,18 @@ public class EntityBat extends EntityLiving /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); + super.readEntity(tagCompund); this.dataWatcher.updateObject(16, Byte.valueOf(tagCompund.getByte("BatFlags"))); } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); + super.writeEntity(tagCompound); tagCompound.setByte("BatFlags", this.dataWatcher.getWatchableObjectByte(16)); } diff --git a/common/src/main/java/common/entity/animal/EntityChicken.java b/common/src/main/java/common/entity/animal/EntityChicken.java new file mode 100755 index 0000000..eeae971 --- /dev/null +++ b/common/src/main/java/common/entity/animal/EntityChicken.java @@ -0,0 +1,209 @@ +package common.entity.animal; + +import common.ai.EntityAIAttackOnCollide; +import common.ai.EntityAIFollowParent; +import common.ai.EntityAILookIdle; +import common.ai.EntityAIMate; +import common.ai.EntityAINearestAttackableTarget; +import common.ai.EntityAIPanic; +import common.ai.EntityAISwimming; +import common.ai.EntityAITempt; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.npc.Alignment; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.init.SoundEvent; +import common.item.Item; +import common.item.ItemStack; +import common.tags.TagObject; +import common.util.ExtMath; +import common.vars.Vars; +import common.world.World; + +public class EntityChicken extends EntityAnimal { + private final EntityAIAttackOnCollide attack = new EntityAIAttackOnCollide(this, EntityNPC.class, 1.4, false); + private final EntityAINearestAttackableTarget targetter = new EntityAINearestAttackableTarget(this, EntityNPC.class, true); + + public float wingRotation; + public float lastWingRotation; + public float destPos; + public float lastDestPos; + private float wingRotDelta = 1.0F; + private int eggTimer; + private boolean noEggs; + private boolean attackSet; + + public EntityChicken(World world) { + super(world); + this.setSize(0.4F, 0.7F); + this.eggTimer = world.client || Vars.eggTimer <= 0 ? 1000 : this.rand.excl(Vars.eggTimer, Vars.eggTimer * 2); + this.tasks.addTask(0, new EntityAISwimming(this)); + this.tasks.addTask(1, new EntityAIPanic(this, 1.4D)); + this.tasks.addTask(2, new EntityAIMate(this, 1.0D)); + this.tasks.addTask(3, new EntityAITempt(this, 1.0D, Items.wheat, false)); + this.tasks.addTask(4, new EntityAIFollowParent(this, 1.1D)); + this.tasks.addTask(5, new EntityAIWander(this, 1.0D)); + this.tasks.addTask(6, new EntityAIWatchClosest(this, null, 6.0F)); + this.tasks.addTask(7, new EntityAILookIdle(this)); + } + + public float getEyeHeight() { + return this.height; + } + + protected void entityInit() { + super.entityInit(); + this.dataWatcher.addObject(18, Byte.valueOf((byte)0)); + } + + protected void applyEntityAttributes() { + super.applyEntityAttributes(); + this.setMaxHealth(4); + this.setSpeedBase(0.25f); + } + + public void onLivingUpdate() { + super.onLivingUpdate(); + this.lastWingRotation = this.wingRotation; + this.lastDestPos = this.destPos; + this.destPos = (float)((double)this.destPos + (double)(this.onGround ? -1 : 4) * 0.3D); + this.destPos = ExtMath.clampf(this.destPos, 0.0F, 1.0F); + if(!this.onGround && this.wingRotDelta < 1.0F) + this.wingRotDelta = 1.0F; + this.wingRotDelta = (float)((double)this.wingRotDelta * 0.9D); + if(!this.onGround && this.motionY < 0.0D) + this.motionY *= 0.6D; + this.wingRotation += this.wingRotDelta * 2.0F; + if(!this.worldObj.client) { + if(Vars.eggTimer > 0 && !this.isChild() && !this.noEggs && --this.eggTimer <= 0) { + this.playSound(SoundEvent.PLOP, 1.0F); + this.dropItem(Items.egg, 1); + this.eggTimer = this.rand.excl(Vars.eggTimer, Vars.eggTimer * 2); + } + boolean evil = this.canBeEvil(); + if(evil != this.attackSet) { + if(evil) { + this.tasks.addTask(1, this.attack); + this.targets.addTask(1, this.targetter); + } + else { + this.tasks.removeTask(this.attack); + this.targets.removeTask(this.targetter); + } + this.attackSet = evil; + } + } + } + + public void fall(float distance, float damage) { + } + + protected SoundEvent getLivingSound() { + return SoundEvent.CHICKEN_IDLE; + } + + protected SoundEvent getHurtSound() { + return SoundEvent.CHICKEN_HIT; + } + + protected SoundEvent getDeathSound() { + return SoundEvent.CHICKEN_HIT; + } + + protected Item getDropItem() { + return Items.feather; + } + + protected void dropFewItems(boolean hit, int looting) { + int amt = this.rand.zrange(3) + this.rand.zrange(1 + looting); + for(int z = 0; z < amt; z++) { + this.dropItem(Items.feather, 1); + } + this.dropItem(this.isBurning() ? Items.cooked_chicken : Items.chicken, 1); + } + + public EntityChicken createChild(EntityLiving entity) { + EntityChicken chick = new EntityChicken(this.worldObj); + chick.setEvil(this.isEvil()); + chick.setNotLaying(this.isNotLaying()); + return chick; + } + + public boolean isBreedingItem(ItemStack stack) { + return stack != null && stack.getItem() == Items.wheat; + } + + public void readEntity(TagObject tag) { + super.readEntity(tag); + this.setEvil(tag.getBool("evil")); + this.noEggs = tag.getBool("noEggs"); + this.eggTimer = tag.getInt("eggTime"); + } + + public void writeEntity(TagObject tag) { + super.writeEntity(tag); + tag.setBool("evil", this.isEvil()); + tag.setBool("noEggs", this.noEggs); + tag.setInt("eggTime", this.eggTimer); + } + + public void updateRiderPosition() { + super.updateRiderPosition(); + float x = ExtMath.sin(this.yawOffset * (float)Math.PI / 180.0F); + float z = ExtMath.cos(this.yawOffset * (float)Math.PI / 180.0F); + float mult = 0.1F; + float off = 0.0F; + this.passenger.setPosition(this.posX + (double)(mult * x), + this.posY + (double)(this.height * 0.5F) + this.passenger.getYOffset() + (double)off, this.posZ - (double)(mult * z)); + if(this.passenger instanceof EntityLiving) + ((EntityLiving)this.passenger).yawOffset = this.yawOffset; + } + + public boolean attackEntityAsMob(Entity entityIn) { + if(!this.worldObj.client && !Vars.damageMobs) + return false; + return entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), this.isChild() ? 1 : 2); + } + + public Object onInitialSpawn(Object livingdata) { + livingdata = super.onInitialSpawn(livingdata); + if(Vars.evilChickenChance > 0 && this.rand.chance(Vars.evilChickenChance)) + this.setEvil(true); + if(this.rand.chance(15)) + this.setGrowingAge(-24000); + return livingdata; + } + + protected boolean canBeEvil() { + return this.isEvil() || Vars.aggressiveChickens; + } + + public boolean isEvil() { + return this.dataWatcher.getWatchableObjectByte(18) != 0; + } + + public void setEvil(boolean evil) { + this.dataWatcher.updateObject(18, (byte)(evil ? 1 : 0)); + } + + public boolean isNotLaying() { + return this.noEggs; + } + + public void setNotLaying(boolean noEggs) { + this.noEggs = noEggs; + } + + public int getColor() { + return 0xdb5152; + } + + public Alignment getAlignment() { + return this.isEvil() ? Alignment.CHAOTIC_EVIL : Alignment.CHAOTIC; + } +} diff --git a/java/src/game/entity/animal/EntityCow.java b/common/src/main/java/common/entity/animal/EntityCow.java similarity index 83% rename from java/src/game/entity/animal/EntityCow.java rename to common/src/main/java/common/entity/animal/EntityCow.java index 84bef6e..4e14119 100755 --- a/java/src/game/entity/animal/EntityCow.java +++ b/common/src/main/java/common/entity/animal/EntityCow.java @@ -1,23 +1,22 @@ -package game.entity.animal; +package common.entity.animal; -import game.ai.EntityAIFollowParent; -import game.ai.EntityAILookIdle; -import game.ai.EntityAIMate; -import game.ai.EntityAIPanic; -import game.ai.EntityAISwimming; -import game.ai.EntityAITempt; -import game.ai.EntityAIWander; -import game.ai.EntityAIWatchClosest; -import game.entity.attributes.Attributes; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.init.SoundEvent; -import game.item.Item; -import game.item.ItemStack; -import game.pathfinding.PathNavigateGround; -import game.world.World; +import common.ai.EntityAIFollowParent; +import common.ai.EntityAILookIdle; +import common.ai.EntityAIMate; +import common.ai.EntityAIPanic; +import common.ai.EntityAISwimming; +import common.ai.EntityAITempt; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.init.SoundEvent; +import common.item.Item; +import common.item.ItemStack; +import common.pathfinding.PathNavigateGround; +import common.world.World; public class EntityCow extends EntityAnimal { @@ -40,7 +39,7 @@ public class EntityCow extends EntityAnimal { super.applyEntityAttributes(); this.setMaxHealth(10); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.20000000298023224D); + this.setSpeedBase(0.20000000298023224f); } /** @@ -125,7 +124,7 @@ public class EntityCow extends EntityAnimal if (itemstack != null && itemstack.getItem() == Items.bucket /* && !player.creative */ && !this.isChild()) { - if (itemstack.stackSize-- == 1) + if (itemstack.size-- == 1) { player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(Items.milk_bucket)); } diff --git a/java/src/game/entity/animal/EntityDragon.java b/common/src/main/java/common/entity/animal/EntityDragon.java similarity index 96% rename from java/src/game/entity/animal/EntityDragon.java rename to common/src/main/java/common/entity/animal/EntityDragon.java index 52653bc..04bb342 100755 --- a/java/src/game/entity/animal/EntityDragon.java +++ b/common/src/main/java/common/entity/animal/EntityDragon.java @@ -1,23 +1,23 @@ -package game.entity.animal; +package common.entity.animal; import java.util.List; -import game.collect.Lists; - -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.npc.Alignment; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.entity.types.IEntityMultiPart; -import game.init.Config; -import game.init.SoundEvent; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.Vec3; -import game.world.World; -import game.world.WorldClient; +import common.collect.Lists; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.npc.Alignment; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.entity.types.IEntityMultiPart; +import common.init.SoundEvent; +import common.model.ParticleType; +import common.potion.Potion; +import common.util.ExtMath; +import common.util.Vec3; +import common.vars.Vars; +import common.world.AWorldClient; +import common.world.World; public class EntityDragon extends EntityLiving implements IEntityMultiPart { @@ -57,6 +57,10 @@ public class EntityDragon extends EntityLiving implements IEntityMultiPart return true; } + public boolean isPotionApplicable(Potion potion, int amplifier) { + return false; + } + protected void applyEntityAttributes() { super.applyEntityAttributes(); @@ -106,7 +110,7 @@ public class EntityDragon extends EntityLiving implements IEntityMultiPart if (f1 <= -0.3F && f >= -0.3F) // && !this.isSilent()) { - ((WorldClient)this.worldObj).playSound(this.posX, this.posY, this.posZ, SoundEvent.DRAGON_WINGS, 5.0F); + ((AWorldClient)this.worldObj).playSound(this.posX, this.posY, this.posZ, SoundEvent.DRAGON_WINGS, 5.0F); } } @@ -130,7 +134,7 @@ public class EntityDragon extends EntityLiving implements IEntityMultiPart this.rotYaw = ExtMath.wrapf(this.rotYaw); // if (this.isAIDisabled() || - if(!this.worldObj.client && !Config.mobTick) // ) + if(!this.worldObj.client && !Vars.mobTick) // ) { this.animTime = 0.5F; } @@ -283,7 +287,7 @@ public class EntityDragon extends EntityLiving implements IEntityMultiPart { this.collideWithEntities(this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.dragonPartWing1.getEntityBoundingBox().expand(4.0D, 2.0D, 4.0D).offset(0.0D, -2.0D, 0.0D))); this.collideWithEntities(this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.dragonPartWing2.getEntityBoundingBox().expand(4.0D, 2.0D, 4.0D).offset(0.0D, -2.0D, 0.0D))); - if(Config.damageMobs) + if(Vars.damageMobs) this.attackEntitiesInList(this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.dragonPartHead.getEntityBoundingBox().expand(1.0D, 1.0D, 1.0D))); } diff --git a/java/src/game/entity/animal/EntityDragonPart.java b/common/src/main/java/common/entity/animal/EntityDragonPart.java similarity index 83% rename from java/src/game/entity/animal/EntityDragonPart.java rename to common/src/main/java/common/entity/animal/EntityDragonPart.java index 3f9bf65..74ce40a 100755 --- a/java/src/game/entity/animal/EntityDragonPart.java +++ b/common/src/main/java/common/entity/animal/EntityDragonPart.java @@ -1,10 +1,10 @@ -package game.entity.animal; +package common.entity.animal; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.types.IEntityMultiPart; -import game.nbt.NBTTagCompound; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.types.IEntityMultiPart; +import common.tags.TagObject; public class EntityDragonPart extends Entity { @@ -27,14 +27,14 @@ public class EntityDragonPart extends Entity /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntityFromNBT(NBTTagCompound tagCompund) + protected void readEntity(TagObject tagCompund) { } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntityToNBT(NBTTagCompound tagCompound) + protected void writeEntity(TagObject tagCompound) { } diff --git a/common/src/main/java/common/entity/animal/EntityFox.java b/common/src/main/java/common/entity/animal/EntityFox.java new file mode 100644 index 0000000..568bf97 --- /dev/null +++ b/common/src/main/java/common/entity/animal/EntityFox.java @@ -0,0 +1,111 @@ +package common.entity.animal; + +import common.ai.EntityAIAttackOnCollide; +import common.ai.EntityAIHurtByTarget; +import common.ai.EntityAILeapAtTarget; +import common.ai.EntityAILookIdle; +import common.ai.EntityAIMate; +import common.ai.EntityAINearestAttackableTarget; +import common.ai.EntityAISwimming; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.npc.Alignment; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.init.SoundEvent; +import common.item.Item; +import common.item.ItemStack; +import common.pathfinding.PathNavigateGround; +import common.vars.Vars; +import common.world.World; + +public class EntityFox extends EntityAnimal +{ + public EntityFox(World worldIn) + { + super(worldIn); + this.setSize(0.6F, 0.8F); + ((PathNavigateGround)this.getNavigator()).setAvoidsWater(true); + this.tasks.addTask(1, new EntityAISwimming(this)); + this.tasks.addTask(3, new EntityAILeapAtTarget(this, 0.4F)); + this.tasks.addTask(4, new EntityAIAttackOnCollide(this, 1.0D, true)); + this.tasks.addTask(6, new EntityAIMate(this, 1.0D)); + this.tasks.addTask(7, new EntityAIWander(this, 1.0D)); + this.tasks.addTask(9, new EntityAIWatchClosest(this, null, 8.0F)); + this.tasks.addTask(9, new EntityAILookIdle(this)); + this.targets.addTask(3, new EntityAIHurtByTarget(this, true)); + this.targets.addTask(5, new EntityAINearestAttackableTarget(this, EntityChicken.class, true)); + } + + protected void applyEntityAttributes() + { + super.applyEntityAttributes(); + this.setSpeedBase(0.35f); + this.setMaxHealth(6); + } + + protected SoundEvent getHurtSound() + { + return SoundEvent.FOX_HURT; + } + + protected SoundEvent getDeathSound() + { + return SoundEvent.FOX_DEATH; + } + + protected float getSoundVolume() + { + return 0.4F; + } + + protected Item getDropItem() + { + return null; + } + + public float getEyeHeight() + { + return this.height * 0.8F; + } + + public boolean attackEntityAsMob(Entity entityIn) + { + if(!this.worldObj.client && !Vars.damageMobs) + return false; + boolean flag = entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), 2); + + if (flag) + { + this.applyEnchantments(this, entityIn); + } + + return flag; + } + + public boolean isBreedingItem(ItemStack stack) + { + return stack != null && stack.getItem() == Items.apple; + } + + public int getMaxChunkSpawns() + { + return 6; + } + + public EntityFox createChild(EntityLiving ageable) + { + return new EntityFox(this.worldObj); + } + + public int getColor() { + return 0xc35d00; + } + + public Alignment getAlignment() { + return Alignment.CHAOTIC; + } +} diff --git a/java/src/game/entity/animal/EntityHorse.java b/common/src/main/java/common/entity/animal/EntityHorse.java similarity index 88% rename from java/src/game/entity/animal/EntityHorse.java rename to common/src/main/java/common/entity/animal/EntityHorse.java index b9ed9b2..e58770d 100755 --- a/java/src/game/entity/animal/EntityHorse.java +++ b/common/src/main/java/common/entity/animal/EntityHorse.java @@ -1,44 +1,42 @@ -package game.entity.animal; +package common.entity.animal; import java.util.function.Predicate; -import game.ai.EntityAIFollowParent; -import game.ai.EntityAILookIdle; -import game.ai.EntityAIMate; -import game.ai.EntityAIPanic; -import game.ai.EntityAIRunAroundLikeCrazy; -import game.ai.EntityAISwimming; -import game.ai.EntityAIWander; -import game.ai.EntityAIWatchClosest; -import game.audio.SoundType; -import game.block.Block; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.Attributes; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.init.ItemRegistry; -import game.init.Items; -import game.init.SoundEvent; -import game.inventory.AnimalChest; -import game.inventory.IInvBasic; -import game.inventory.InventoryBasic; -import game.item.Item; -import game.item.ItemMonsterPlacer; -import game.item.ItemStack; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.pathfinding.PathNavigateGround; -import game.potion.Potion; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.World; +import common.ai.EntityAIFollowParent; +import common.ai.EntityAILookIdle; +import common.ai.EntityAIMate; +import common.ai.EntityAIPanic; +import common.ai.EntityAIRunAroundLikeCrazy; +import common.ai.EntityAISwimming; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.block.Block; +import common.block.SoundType; +import common.collect.Lists; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; +import common.init.SoundEvent; +import common.inventory.AnimalChest; +import common.inventory.IInvBasic; +import common.inventory.InventoryBasic; +import common.item.Item; +import common.item.ItemMonsterPlacer; +import common.item.ItemStack; +import common.model.ParticleType; +import common.pathfinding.PathNavigateGround; +import common.potion.Potion; +import common.tags.TagObject; +import java.util.List; +import common.util.BlockPos; +import common.util.ExtMath; +import common.vars.Vars; +import common.world.World; public class EntityHorse extends EntityAnimal implements IInvBasic { @@ -108,7 +106,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic this.dataWatcher.addObject(16, Integer.valueOf(0)); this.dataWatcher.addObject(19, Byte.valueOf((byte)0)); this.dataWatcher.addObject(20, Integer.valueOf(0)); -// this.dataWatcher.addObject(21, String.valueOf((Object)"")); + this.dataWatcher.addObject(21, 0.7f); this.dataWatcher.addObject(22, Integer.valueOf(0)); } @@ -425,7 +423,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (i > 0) { - if(Config.damageFall) { + if(Vars.damageFall) { this.attackEntityFrom(DamageSource.fall, i); if (this.passenger != null) @@ -436,7 +434,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic Block block = this.worldObj.getState(new BlockPos(this.posX, this.posY - 0.2D - (double)this.prevYaw, this.posZ)).getBlock(); - if (block.getMaterial() != Material.air) // && !this.isSilent()) + if (block != Blocks.air) // && !this.isSilent()) { SoundType block$soundtype = block.sound; if(block$soundtype.getStepSound() != null) @@ -551,9 +549,14 @@ public class EntityHorse extends EntityAnimal implements IInvBasic return (EntityHorse)entity; } - public double getHorseJumpStrength() + public float getHorseJumpStrength() { - return this.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).getAttributeValue(); + return this.dataWatcher.getWatchableObjectFloat(21); + } + + public void setHorseJumpStrength(float value) + { + this.dataWatcher.updateObject(21, value); } /** @@ -663,9 +666,8 @@ public class EntityHorse extends EntityAnimal implements IInvBasic protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getAttributeMap().registerAttribute(Attributes.HORSE_JUMP_STRENGTH); this.setMaxHealth(53); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.22499999403953552D); + this.setSpeedBase(0.22499999403953552f); } /** @@ -789,7 +791,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (!this.worldObj.client && (this.passenger == null || this.passenger == playerEntity) && this.isTame()) { this.horseChest.setCustomName(this.getName()); - playerEntity.displayGUIHorse(this, this.horseChest); + playerEntity.displayEntityGui(this, this.horseChest); } } @@ -959,7 +961,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (flag) { - if (/* !player.creative && */ --itemstack.stackSize == 0) + if (/* !player.creative && */ --itemstack.size == 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } @@ -1354,7 +1356,7 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (!this.worldObj.client) { - this.setAIMoveSpeed((float)this.getEntityAttribute(Attributes.MOVEMENT_SPEED).getAttributeValue()); + this.setAIMoveSpeed(this.getMovementSpeed()); super.moveEntityWithHeading(strafe, forward); } @@ -1388,22 +1390,23 @@ public class EntityHorse extends EntityAnimal implements IInvBasic /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setBoolean("EatingHaystack", this.isEatingHaystack()); - tagCompound.setBoolean("ChestedHorse", this.isChested()); - tagCompound.setBoolean("HasReproduced", this.getHasReproduced()); - tagCompound.setBoolean("Bred", this.isBreeding()); - tagCompound.setInteger("Type", this.getHorseType()); - tagCompound.setInteger("Variant", this.getHorseVariant()); - tagCompound.setInteger("Temper", this.getTemper()); - tagCompound.setBoolean("Tame", this.isTame()); + super.writeEntity(tagCompound); + tagCompound.setBool("EatingHaystack", this.isEatingHaystack()); + tagCompound.setBool("ChestedHorse", this.isChested()); + tagCompound.setBool("HasReproduced", this.getHasReproduced()); + tagCompound.setBool("Bred", this.isBreeding()); + tagCompound.setInt("Type", this.getHorseType()); + tagCompound.setInt("Variant", this.getHorseVariant()); + tagCompound.setInt("Temper", this.getTemper()); + tagCompound.setBool("Tame", this.isTame()); + tagCompound.setFloat("JumpStrength", this.getHorseJumpStrength()); // tagCompound.setString("Owner", this.getOwnerId()); if (this.isChested()) { - NBTTagList nbttaglist = new NBTTagList(); + List nbttaglist = Lists.newArrayList(); for (int i = 2; i < this.horseChest.getSizeInventory(); ++i) { @@ -1411,44 +1414,45 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (itemstack != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject nbttagcompound = new TagObject(); nbttagcompound.setByte("Slot", (byte)i); - itemstack.writeToNBT(nbttagcompound); - nbttaglist.appendTag(nbttagcompound); + itemstack.writeTags(nbttagcompound); + nbttaglist.add(nbttagcompound); } } - tagCompound.setTag("Items", nbttaglist); + tagCompound.setList("Items", nbttaglist); } if (this.horseChest.getStackInSlot(1) != null) { - tagCompound.setTag("ArmorItem", this.horseChest.getStackInSlot(1).writeToNBT(new NBTTagCompound())); + tagCompound.setObject("ArmorItem", this.horseChest.getStackInSlot(1).writeTags(new TagObject())); } if (this.horseChest.getStackInSlot(0) != null) { - tagCompound.setTag("SaddleItem", this.horseChest.getStackInSlot(0).writeToNBT(new NBTTagCompound())); + tagCompound.setObject("SaddleItem", this.horseChest.getStackInSlot(0).writeTags(new TagObject())); } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - this.setEatingHaystack(tagCompund.getBoolean("EatingHaystack")); - this.setBreeding(tagCompund.getBoolean("Bred")); - this.setChested(tagCompund.getBoolean("ChestedHorse")); - this.setHasReproduced(tagCompund.getBoolean("HasReproduced")); - this.setHorseType(tagCompund.getInteger("Type")); - this.setHorseVariant(tagCompund.getInteger("Variant")); - this.setTemper(tagCompund.getInteger("Temper")); - this.setHorseTamed(tagCompund.getBoolean("Tame")); + super.readEntity(tagCompund); + this.setEatingHaystack(tagCompund.getBool("EatingHaystack")); + this.setBreeding(tagCompund.getBool("Bred")); + this.setChested(tagCompund.getBool("ChestedHorse")); + this.setHasReproduced(tagCompund.getBool("HasReproduced")); + this.setHorseType(tagCompund.getInt("Type")); + this.setHorseVariant(tagCompund.getInt("Variant")); + this.setTemper(tagCompund.getInt("Temper")); + this.setHorseTamed(tagCompund.getBool("Tame")); + this.setHorseJumpStrength(tagCompund.getFloat("JumpStrength")); // String s = ""; // -// if (tagCompund.hasKey("Owner", 8)) +// if (tagCompund.hasString("Owner")) // { // s = tagCompund.getString("Owner"); // } @@ -1458,33 +1462,33 @@ public class EntityHorse extends EntityAnimal implements IInvBasic // this.setOwnerId(s); // } - AttributeInstance iattributeinstance = this.getAttributeMap().getAttributeInstanceByName("Speed"); - - if (iattributeinstance != null) - { - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(iattributeinstance.getBaseValue() * 0.25D); - } +// AttributeInstance iattributeinstance = this.getAttributeMap().getAttributeInstanceByName("Speed"); +// +// if (iattributeinstance != null) +// { +// this.getEntityAttribute(Attribute.MOVEMENT_SPEED).setBaseValue(iattributeinstance.getBaseValue() * 0.25D); +// } if (this.isChested()) { - NBTTagList nbttaglist = tagCompund.getTagList("Items", 10); + List nbttaglist = tagCompund.getList("Items"); this.initHorseChest(); - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + TagObject nbttagcompound = nbttaglist.get(i); int j = nbttagcompound.getByte("Slot") & 255; if (j >= 2 && j < this.horseChest.getSizeInventory()) { - this.horseChest.setInventorySlotContents(j, ItemStack.loadItemStackFromNBT(nbttagcompound)); + this.horseChest.setInventorySlotContents(j, ItemStack.readFromTag(nbttagcompound)); } } } - if (tagCompund.hasKey("ArmorItem", 10)) + if (tagCompund.hasObject("ArmorItem")) { - ItemStack itemstack = ItemStack.loadItemStackFromNBT(tagCompund.getCompoundTag("ArmorItem")); + ItemStack itemstack = ItemStack.readFromTag(tagCompund.getObject("ArmorItem")); if (itemstack != null && isArmorItem(itemstack.getItem())) { @@ -1492,16 +1496,16 @@ public class EntityHorse extends EntityAnimal implements IInvBasic } } - if (tagCompund.hasKey("SaddleItem", 10)) + if (tagCompund.hasObject("SaddleItem")) { - ItemStack itemstack1 = ItemStack.loadItemStackFromNBT(tagCompund.getCompoundTag("SaddleItem")); + ItemStack itemstack1 = ItemStack.readFromTag(tagCompund.getObject("SaddleItem")); if (itemstack1 != null && itemstack1.getItem() == Items.saddle) { this.horseChest.setInventorySlotContents(0, itemstack1); } } - else if (tagCompund.getBoolean("Saddle")) + else if (tagCompund.getBool("Saddle")) { this.horseChest.setInventorySlotContents(0, new ItemStack(Items.saddle)); } @@ -1593,12 +1597,12 @@ public class EntityHorse extends EntityAnimal implements IInvBasic } entityhorse1.setHorseType(k); - int d1 = this.getRawMaxHealth() + ageable.getRawMaxHealth() + this.getModifiedMaxHealth(); + int d1 = this.getMaxHealth() + ageable.getMaxHealth() + this.getModifiedMaxHealth(); entityhorse1.setMaxHealth(d1 / 3); - double d2 = this.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).getBaseValue() + ageable.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).getBaseValue() + this.getModifiedJumpStrength(); - entityhorse1.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).setBaseValue(d2 / 3.0D); - double d0 = this.getEntityAttribute(Attributes.MOVEMENT_SPEED).getBaseValue() + ageable.getEntityAttribute(Attributes.MOVEMENT_SPEED).getBaseValue() + this.getModifiedMovementSpeed(); - entityhorse1.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(d0 / 3.0D); + float d2 = this.getHorseJumpStrength() + entityhorse.getHorseJumpStrength() + this.getModifiedJumpStrength(); + entityhorse1.setHorseJumpStrength(d2 / 3.0f); + float d0 = this.getSpeedBase() + ageable.getSpeedBase() + this.getModifiedMovementSpeed(); + entityhorse1.setSpeedBase(d0 / 3.0f); return entityhorse1; } @@ -1648,26 +1652,26 @@ public class EntityHorse extends EntityAnimal implements IInvBasic if (i == 0) { - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(this.getModifiedMovementSpeed()); + this.setSpeedBase(this.getModifiedMovementSpeed()); } else { - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.17499999701976776D); + this.setSpeedBase(0.17499999701976776f); } } else { this.setMaxHealth(15); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.20000000298023224D); + this.setSpeedBase(0.20000000298023224f); } if (i != 2 && i != 1) { - this.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).setBaseValue(this.getModifiedJumpStrength()); + this.setHorseJumpStrength(this.getModifiedJumpStrength()); } else { - this.getEntityAttribute(Attributes.HORSE_JUMP_STRENGTH).setBaseValue(0.5D); + this.setHorseJumpStrength(0.5f); } this.setHealth(this.getMaxHealth()); @@ -1776,17 +1780,17 @@ public class EntityHorse extends EntityAnimal implements IInvBasic /** * Returns randomized jump strength */ - private double getModifiedJumpStrength() + private float getModifiedJumpStrength() { - return 0.4000000059604645D + this.rand.doublev() * 0.2D + this.rand.doublev() * 0.2D + this.rand.doublev() * 0.2D; + return 0.4000000059604645f + this.rand.floatv() * 0.2f + this.rand.floatv() * 0.2f + this.rand.floatv() * 0.2f; } /** * Returns randomized movement speed */ - private double getModifiedMovementSpeed() + private float getModifiedMovementSpeed() { - return (0.44999998807907104D + this.rand.doublev() * 0.3D + this.rand.doublev() * 0.3D + this.rand.doublev() * 0.3D) * 0.25D; + return (0.44999998807907104f + this.rand.floatv() * 0.3f + this.rand.floatv() * 0.3f + this.rand.floatv() * 0.3f) * 0.25f; } /** diff --git a/java/src/game/entity/animal/EntityMooshroom.java b/common/src/main/java/common/entity/animal/EntityMooshroom.java similarity index 86% rename from java/src/game/entity/animal/EntityMooshroom.java rename to common/src/main/java/common/entity/animal/EntityMooshroom.java index 610c8bb..76747d4 100755 --- a/java/src/game/entity/animal/EntityMooshroom.java +++ b/common/src/main/java/common/entity/animal/EntityMooshroom.java @@ -1,15 +1,15 @@ -package game.entity.animal; +package common.entity.animal; -import game.entity.item.EntityItem; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Items; -import game.init.SoundEvent; -import game.item.ItemShears; -import game.item.ItemStack; -import game.renderer.particle.ParticleType; -import game.world.World; +import common.entity.item.EntityItem; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.Items; +import common.init.SoundEvent; +import common.item.ItemShears; +import common.item.ItemStack; +import common.model.ParticleType; +import common.world.World; public class EntityMooshroom extends EntityCow { @@ -30,7 +30,7 @@ public class EntityMooshroom extends EntityCow if (itemstack != null && itemstack.getItem() == Items.bowl && !this.isChild()) { - if (itemstack.stackSize == 1) + if (itemstack.size == 1) { player.inventory.setInventorySlotContents(player.inventory.currentItem, new ItemStack(Items.mushroom_stew)); return true; diff --git a/java/src/game/entity/animal/EntityMouse.java b/common/src/main/java/common/entity/animal/EntityMouse.java similarity index 69% rename from java/src/game/entity/animal/EntityMouse.java rename to common/src/main/java/common/entity/animal/EntityMouse.java index f1c803f..2564c4d 100755 --- a/java/src/game/entity/animal/EntityMouse.java +++ b/common/src/main/java/common/entity/animal/EntityMouse.java @@ -1,27 +1,25 @@ -package game.entity.animal; +package common.entity.animal; import java.util.Collections; -import game.ai.EntityAIFollowParent; -import game.ai.EntityAILookIdle; -import game.ai.EntityAIMate; -import game.ai.EntityAIPanic; -import game.ai.EntityAISwimming; -import game.ai.EntityAITempt; -import game.ai.EntityAIWander; -import game.ai.EntityAIWatchClosest; -import game.block.Block; -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.Attributes; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Items; -import game.init.SoundEvent; -import game.item.ItemStack; -import game.world.BlockPos; -import game.world.World; +import common.ai.EntityAIFollowParent; +import common.ai.EntityAILookIdle; +import common.ai.EntityAIMate; +import common.ai.EntityAIPanic; +import common.ai.EntityAISwimming; +import common.ai.EntityAITempt; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.block.Block; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.Items; +import common.init.SoundEvent; +import common.item.ItemStack; +import common.util.BlockPos; +import common.world.World; public class EntityMouse extends EntityAnimal { public EntityMouse(World world) { @@ -46,7 +44,7 @@ public class EntityMouse extends EntityAnimal { protected void applyEntityAttributes() { super.applyEntityAttributes(); this.setMaxHealth(1); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.25D); + this.setSpeedBase(0.25f); } // protected String getLivingSound() { @@ -118,12 +116,8 @@ public class EntityMouse extends EntityAnimal { public void setCustomNameTag(String name) { super.setCustomNameTag(name); - if(this.worldObj != null && !this.worldObj.client) { - AttributeInstance speed = this.getEntityAttribute(Attributes.MOVEMENT_SPEED); - speed.removeModifier(Attributes.MOUSE_SPEEDY_MOD); - if(name.equals("Gonzales") || name.equals("Gonzalez")) - speed.applyModifier(Attributes.MOUSE_SPEEDY_MOD); - } + if(this.worldObj != null && !this.worldObj.client) + this.setSpeedBase(name.equals("Gonzales") || name.equals("Gonzalez") ? 0.5f : 0.25f); } public int getColor() { diff --git a/java/src/game/entity/animal/EntityOcelot.java b/common/src/main/java/common/entity/animal/EntityOcelot.java similarity index 88% rename from java/src/game/entity/animal/EntityOcelot.java rename to common/src/main/java/common/entity/animal/EntityOcelot.java index 85b685c..67483ae 100755 --- a/java/src/game/entity/animal/EntityOcelot.java +++ b/common/src/main/java/common/entity/animal/EntityOcelot.java @@ -1,34 +1,33 @@ -package game.entity.animal; +package common.entity.animal; import java.util.function.Predicate; -import game.ai.EntityAIAvoidEntity; -import game.ai.EntityAIFollowOwner; -import game.ai.EntityAILeapAtTarget; -import game.ai.EntityAIMate; -import game.ai.EntityAIOcelotAttack; -import game.ai.EntityAIOcelotSit; -import game.ai.EntityAISwimming; -import game.ai.EntityAITargetNonTamed; -import game.ai.EntityAITempt; -import game.ai.EntityAIWander; -import game.ai.EntityAIWatchClosest; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.attributes.Attributes; -import game.entity.npc.Alignment; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.entity.types.EntityTameable; -import game.init.Config; -import game.init.Items; -import game.init.SoundEvent; -import game.item.Item; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.pathfinding.PathNavigateGround; -import game.world.World; +import common.ai.EntityAIAvoidEntity; +import common.ai.EntityAIFollowOwner; +import common.ai.EntityAILeapAtTarget; +import common.ai.EntityAIMate; +import common.ai.EntityAIOcelotAttack; +import common.ai.EntityAIOcelotSit; +import common.ai.EntityAISwimming; +import common.ai.EntityAITargetNonTamed; +import common.ai.EntityAITempt; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.npc.Alignment; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.entity.types.EntityTameable; +import common.init.Items; +import common.init.SoundEvent; +import common.item.Item; +import common.item.ItemStack; +import common.pathfinding.PathNavigateGround; +import common.tags.TagObject; +import common.vars.Vars; +import common.world.World; public class EntityOcelot extends EntityTameable { @@ -113,7 +112,7 @@ public class EntityOcelot extends EntityTameable { super.applyEntityAttributes(); this.setMaxHealth(10); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.30000001192092896D); + this.setSpeedBase(0.30000001192092896f); } public void fall(float distance, float damageMultiplier) @@ -123,19 +122,19 @@ public class EntityOcelot extends EntityTameable /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setInteger("CatType", this.getTameSkin()); + super.writeEntity(tagCompound); + tagCompound.setInt("CatType", this.getTameSkin()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - this.setTameSkin(tagCompund.getInteger("CatType")); + super.readEntity(tagCompund); + this.setTameSkin(tagCompund.getInt("CatType")); } /** @@ -177,7 +176,7 @@ public class EntityOcelot extends EntityTameable public boolean attackEntityAsMob(Entity entityIn) { - if(!this.worldObj.client && !Config.damageMobs) + if(!this.worldObj.client && !Vars.damageMobs) return false; return entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), 3); } @@ -227,10 +226,10 @@ public class EntityOcelot extends EntityTameable { // if (!player.creative) // { - --itemstack.stackSize; + --itemstack.size; // } - if (itemstack.stackSize <= 0) + if (itemstack.size <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } diff --git a/java/src/game/entity/animal/EntityPig.java b/common/src/main/java/common/entity/animal/EntityPig.java similarity index 85% rename from java/src/game/entity/animal/EntityPig.java rename to common/src/main/java/common/entity/animal/EntityPig.java index 6a9e189..512e6f7 100755 --- a/java/src/game/entity/animal/EntityPig.java +++ b/common/src/main/java/common/entity/animal/EntityPig.java @@ -1,25 +1,24 @@ -package game.entity.animal; +package common.entity.animal; -import game.ai.EntityAIControlledByPlayer; -import game.ai.EntityAIFollowParent; -import game.ai.EntityAILookIdle; -import game.ai.EntityAIMate; -import game.ai.EntityAIPanic; -import game.ai.EntityAISwimming; -import game.ai.EntityAITempt; -import game.ai.EntityAIWander; -import game.ai.EntityAIWatchClosest; -import game.entity.attributes.Attributes; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.init.SoundEvent; -import game.item.Item; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.pathfinding.PathNavigateGround; -import game.world.World; +import common.ai.EntityAIControlledByPlayer; +import common.ai.EntityAIFollowParent; +import common.ai.EntityAILookIdle; +import common.ai.EntityAIMate; +import common.ai.EntityAIPanic; +import common.ai.EntityAISwimming; +import common.ai.EntityAITempt; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.init.SoundEvent; +import common.item.Item; +import common.item.ItemStack; +import common.pathfinding.PathNavigateGround; +import common.tags.TagObject; +import common.world.World; public class EntityPig extends EntityAnimal { @@ -47,7 +46,7 @@ public class EntityPig extends EntityAnimal { super.applyEntityAttributes(); this.setMaxHealth(10); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.25D); + this.setSpeedBase(0.25f); } /** @@ -69,19 +68,19 @@ public class EntityPig extends EntityAnimal /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setBoolean("Saddle", this.getSaddled()); + super.writeEntity(tagCompound); + tagCompound.setBool("Saddle", this.getSaddled()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - this.setSaddled(tagCompund.getBoolean("Saddle")); + super.readEntity(tagCompund); + this.setSaddled(tagCompund.getBool("Saddle")); } /** diff --git a/java/src/game/entity/animal/EntityRabbit.java b/common/src/main/java/common/entity/animal/EntityRabbit.java similarity index 86% rename from java/src/game/entity/animal/EntityRabbit.java rename to common/src/main/java/common/entity/animal/EntityRabbit.java index 7878ba3..4b34e12 100755 --- a/java/src/game/entity/animal/EntityRabbit.java +++ b/common/src/main/java/common/entity/animal/EntityRabbit.java @@ -1,48 +1,47 @@ -package game.entity.animal; +package common.entity.animal; import java.util.function.Predicate; -import game.ai.EntityAIAttackOnCollide; -import game.ai.EntityAIAvoidEntity; -import game.ai.EntityAIHurtByTarget; -import game.ai.EntityAIMate; -import game.ai.EntityAIMoveToBlock; -import game.ai.EntityAINearestAttackableTarget; -import game.ai.EntityAIPanic; -import game.ai.EntityAISwimming; -import game.ai.EntityAITempt; -import game.ai.EntityAIWander; -import game.ai.EntityAIWatchClosest; -import game.ai.EntityJumpHelper; -import game.ai.EntityMoveHelper; -import game.block.Block; -import game.block.BlockTallGrass; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.attributes.Attributes; -import game.entity.npc.Alignment; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.Config; -import game.init.ItemRegistry; -import game.init.Items; -import game.init.SoundEvent; -import game.item.Item; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.pathfinding.PathEntity; -import game.pathfinding.PathNavigateGround; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.Vec3; -import game.world.World; +import common.ai.EntityAIAttackOnCollide; +import common.ai.EntityAIAvoidEntity; +import common.ai.EntityAIHurtByTarget; +import common.ai.EntityAIMate; +import common.ai.EntityAIMoveToBlock; +import common.ai.EntityAINearestAttackableTarget; +import common.ai.EntityAIPanic; +import common.ai.EntityAISwimming; +import common.ai.EntityAITempt; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.ai.EntityJumpHelper; +import common.ai.EntityMoveHelper; +import common.block.Block; +import common.block.foliage.BlockTallGrass; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.npc.Alignment; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; +import common.init.SoundEvent; +import common.item.Item; +import common.item.ItemStack; +import common.model.ParticleType; +import common.pathfinding.PathEntity; +import common.pathfinding.PathNavigateGround; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Vec3; +import common.vars.Vars; +import common.world.State; +import common.world.World; public class EntityRabbit extends EntityAnimal { private static final int TYPES = 10; @@ -85,6 +84,10 @@ public class EntityRabbit extends EntityAnimal { return this.moveHelper.isUpdating() && this.moveHelper.getY() > this.posY + 0.5D ? 0.5F : this.moveType.getUpwardsMotion(); } + public boolean isPotionApplicable(Potion potion, int amplifier) { + return super.isPotionApplicable(potion, amplifier) || potion == Potion.JUMP; + } + public void setMoveType(EntityRabbit.EnumMoveType type) { this.moveType = type; } @@ -195,19 +198,19 @@ public class EntityRabbit extends EntityAnimal { protected void applyEntityAttributes() { super.applyEntityAttributes(); this.setMaxHealth(5); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.30000001192092896D); + this.setSpeedBase(0.30000001192092896f); } - public void writeEntityToNBT(NBTTagCompound tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setInteger("RabbitType", this.getRabbitType()); - tagCompound.setInteger("MoreCarrotTicks", this.foodCooldown); + public void writeEntity(TagObject tagCompound) { + super.writeEntity(tagCompound); + tagCompound.setInt("RabbitType", this.getRabbitType()); + tagCompound.setInt("MoreCarrotTicks", this.foodCooldown); } - public void readEntityFromNBT(NBTTagCompound tagCompund) { - super.readEntityFromNBT(tagCompund); - this.setRabbitType(tagCompund.getInteger("RabbitType")); - this.foodCooldown = tagCompund.getInteger("MoreCarrotTicks"); + public void readEntity(TagObject tagCompund) { + super.readEntity(tagCompund); + this.setRabbitType(tagCompund.getInt("RabbitType")); + this.foodCooldown = tagCompund.getInt("MoreCarrotTicks"); } // protected String getJumpingSound() { @@ -227,7 +230,7 @@ public class EntityRabbit extends EntityAnimal { } public boolean attackEntityAsMob(Entity entityIn) { - if(!this.worldObj.client && !Config.damageMobs) + if(!this.worldObj.client && !Vars.damageMobs) return false; if(this.getRabbitType() == 99) { // this.playSound("mob.attack", 1.0F, (this.rand.floatv() - this.rand.floatv()) * 0.2F + 1.0F); @@ -302,7 +305,7 @@ public class EntityRabbit extends EntityAnimal { public Object onInitialSpawn(Object livingdata) { livingdata = super.onInitialSpawn(livingdata); - int type = Config.killerBunnyChance > 0 && this.rand.chance(Config.killerBunnyChance) ? 99 : this.rand.zrange(TYPES); + int type = Vars.killerBunnyChance > 0 && this.rand.chance(Vars.killerBunnyChance) ? 99 : this.rand.zrange(TYPES); boolean typeSet = false; if(livingdata instanceof EntityRabbit.RabbitTypeData) { type = ((EntityRabbit.RabbitTypeData)livingdata).typeData; @@ -334,7 +337,7 @@ public class EntityRabbit extends EntityAnimal { this.foodCooldown = this.rand.excl(10, this.isChild() ? 20 : 50); if(this.isChild()) this.grow(this.rand.range(250, 350)); - if(Config.rabbitMateChance > 0 && this.rand.chance(Config.rabbitMateChance) && this.getGrowingAge() == 0 && !this.isInLove() && + if(Vars.rabbitMateChance > 0 && this.rand.chance(Vars.rabbitMateChance) && this.getGrowingAge() == 0 && !this.isInLove() && !this.worldObj.getEntitiesWithinAABB(EntityRabbit.class, this.getEntityBoundingBox().expand(15.0f, 15.0f, 15.0f), new Predicate() { public boolean test(EntityRabbit entity) { return entity != EntityRabbit.this && entity.getGrowingAge() == 0; @@ -423,7 +426,7 @@ public class EntityRabbit extends EntityAnimal { public boolean shouldExecute() { if(this.runDelay <= 0) { - if(!Config.mobGrief) + if(!Vars.mobGrief) return false; this.foodFound = false; this.isHungry = this.entity.canEatMore(); @@ -456,10 +459,10 @@ public class EntityRabbit extends EntityAnimal { (double)this.destinationBlock.getZ() + 0.5D, 10.0F, (float)this.entity.getVerticalFaceSpeed()); if(this.getIsAboveDestination()) { World world = this.entity.worldObj; - BlockPos pos = Config.rabidRabbits ? this.destinationBlock : this.destinationBlock.up(); + BlockPos pos = Vars.rabidRabbits ? this.destinationBlock : this.destinationBlock.up(); State state = world.getState(pos); // Block block = iblockstate.getBlock(); - if(this.foodFound && canEat(state) && Config.mobGrief) // block instanceof BlockCarrot && ((Integer)iblockstate.getValue(BlockCarrot.AGE)).intValue() == 7) { + if(this.foodFound && canEat(state) && Vars.mobGrief) // block instanceof BlockCarrot && ((Integer)iblockstate.getValue(BlockCarrot.AGE)).intValue() == 7) { this.entity.consumeBlock(pos, state); this.foodFound = false; this.runDelay = 10; @@ -483,7 +486,7 @@ public class EntityRabbit extends EntityAnimal { private static boolean canEat(State state) { Block block = state.getBlock(); - if(Config.rabidRabbits) + if(Vars.rabidRabbits) return block != Blocks.bedrock; return block == Blocks.carrot || block == Blocks.potato || block == Blocks.wheat || block == Blocks.brown_mushroom || block == Blocks.flower || block == Blocks.blue_mushroom || diff --git a/java/src/game/entity/animal/EntitySheep.java b/common/src/main/java/common/entity/animal/EntitySheep.java similarity index 88% rename from java/src/game/entity/animal/EntitySheep.java rename to common/src/main/java/common/entity/animal/EntitySheep.java index 2410159..a2250da 100755 --- a/java/src/game/entity/animal/EntitySheep.java +++ b/common/src/main/java/common/entity/animal/EntitySheep.java @@ -1,40 +1,38 @@ -package game.entity.animal; +package common.entity.animal; import java.util.Map; -import game.collect.Maps; - -import game.ai.EntityAIEatGrass; -import game.ai.EntityAIFollowParent; -import game.ai.EntityAILookIdle; -import game.ai.EntityAIMate; -import game.ai.EntityAIPanic; -import game.ai.EntityAISwimming; -import game.ai.EntityAITempt; -import game.ai.EntityAIWander; -import game.ai.EntityAIWatchClosest; -import game.biome.Biome; -import game.color.DyeColor; -import game.entity.attributes.Attributes; -import game.entity.item.EntityItem; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.CraftingRegistry; -import game.init.ItemRegistry; -import game.init.Items; -import game.init.SoundEvent; -import game.inventory.Container; -import game.inventory.InventoryCrafting; -import game.item.Item; -import game.item.ItemShears; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.pathfinding.PathNavigateGround; -import game.rng.Random; -import game.util.ExtMath; -import game.world.World; +import common.ai.EntityAIEatGrass; +import common.ai.EntityAIFollowParent; +import common.ai.EntityAILookIdle; +import common.ai.EntityAIMate; +import common.ai.EntityAIPanic; +import common.ai.EntityAISwimming; +import common.ai.EntityAITempt; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.biome.Biome; +import common.collect.Maps; +import common.color.DyeColor; +import common.entity.item.EntityItem; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.CraftingRegistry; +import common.init.ItemRegistry; +import common.init.Items; +import common.init.SoundEvent; +import common.inventory.Container; +import common.inventory.InventoryCrafting; +import common.item.Item; +import common.item.ItemShears; +import common.item.ItemStack; +import common.pathfinding.PathNavigateGround; +import common.rng.Random; +import common.tags.TagObject; +import common.util.ExtMath; +import common.world.World; public class EntitySheep extends EntityAnimal { @@ -105,7 +103,7 @@ public class EntitySheep extends EntityAnimal { super.applyEntityAttributes(); this.setMaxHealth(8); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.23000000417232513D); + this.setSpeedBase(0.23000000417232513f); } protected void entityInit() @@ -211,20 +209,20 @@ public class EntitySheep extends EntityAnimal /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setBoolean("Sheared", this.getSheared()); + super.writeEntity(tagCompound); + tagCompound.setBool("Sheared", this.getSheared()); tagCompound.setByte("Color", (byte)this.getFleeceColor().getMetadata()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - this.setSheared(tagCompund.getBoolean("Sheared")); + super.readEntity(tagCompund); + this.setSheared(tagCompund.getBool("Sheared")); this.setFleeceColor(DyeColor.byMetadata(tagCompund.getByte("Color"))); } @@ -306,7 +304,7 @@ public class EntitySheep extends EntityAnimal public static DyeColor getRandomSheepColor(Random random, Biome biome) { - if(biome == Biome.snowLand) + if(biome == Biome.SNOWLAND) return DyeColor.WHITE; int i = random.zrange(140); return i < 20 ? DyeColor.BLACK : @@ -331,7 +329,7 @@ public class EntitySheep extends EntityAnimal * This function applies the benefits of growing back wool and faster growing up to the acting entity. (This * function is used in the AIEatGrass) */ - public void eatGrassBonus() + public void eatGrass() { this.setSheared(false); diff --git a/java/src/game/entity/animal/EntitySquid.java b/common/src/main/java/common/entity/animal/EntitySquid.java similarity index 96% rename from java/src/game/entity/animal/EntitySquid.java rename to common/src/main/java/common/entity/animal/EntitySquid.java index 22ccf33..1650e15 100755 --- a/java/src/game/entity/animal/EntitySquid.java +++ b/common/src/main/java/common/entity/animal/EntitySquid.java @@ -1,15 +1,15 @@ -package game.entity.animal; +package common.entity.animal; -import game.ai.EntityAIBase; -import game.color.DyeColor; -import game.entity.npc.Alignment; -import game.entity.types.EntityWaterMob; -import game.init.Items; -import game.init.SoundEvent; -import game.item.Item; -import game.item.ItemStack; -import game.util.ExtMath; -import game.world.World; +import common.ai.EntityAIBase; +import common.color.DyeColor; +import common.entity.npc.Alignment; +import common.entity.types.EntityWaterMob; +import common.init.Items; +import common.init.SoundEvent; +import common.item.Item; +import common.item.ItemStack; +import common.util.ExtMath; +import common.world.World; public class EntitySquid extends EntityWaterMob { diff --git a/java/src/game/entity/animal/EntityWolf.java b/common/src/main/java/common/entity/animal/EntityWolf.java similarity index 86% rename from java/src/game/entity/animal/EntityWolf.java rename to common/src/main/java/common/entity/animal/EntityWolf.java index 33c7ee3..cf694c0 100755 --- a/java/src/game/entity/animal/EntityWolf.java +++ b/common/src/main/java/common/entity/animal/EntityWolf.java @@ -1,40 +1,39 @@ -package game.entity.animal; +package common.entity.animal; import java.util.function.Predicate; -import game.ai.EntityAIAttackOnCollide; -import game.ai.EntityAIBeg; -import game.ai.EntityAIFollowOwner; -import game.ai.EntityAIHurtByTarget; -import game.ai.EntityAILeapAtTarget; -import game.ai.EntityAILookIdle; -import game.ai.EntityAIMate; -import game.ai.EntityAIOwnerHurtByTarget; -import game.ai.EntityAIOwnerHurtTarget; -import game.ai.EntityAISwimming; -import game.ai.EntityAITargetNonTamed; -import game.ai.EntityAIWander; -import game.ai.EntityAIWatchClosest; -import game.color.DyeColor; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.attributes.Attributes; -import game.entity.npc.Alignment; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.entity.types.EntityTameable; -import game.init.Config; -import game.init.Items; -import game.init.SoundEvent; -import game.item.Item; -import game.item.ItemFood; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.pathfinding.PathNavigateGround; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.World; +import common.ai.EntityAIAttackOnCollide; +import common.ai.EntityAIBeg; +import common.ai.EntityAIFollowOwner; +import common.ai.EntityAIHurtByTarget; +import common.ai.EntityAILeapAtTarget; +import common.ai.EntityAILookIdle; +import common.ai.EntityAIMate; +import common.ai.EntityAIOwnerHurtByTarget; +import common.ai.EntityAIOwnerHurtTarget; +import common.ai.EntityAISwimming; +import common.ai.EntityAITargetNonTamed; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.color.DyeColor; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.npc.Alignment; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityAnimal; +import common.entity.types.EntityLiving; +import common.entity.types.EntityTameable; +import common.init.Items; +import common.init.SoundEvent; +import common.item.Item; +import common.item.ItemFood; +import common.item.ItemStack; +import common.model.ParticleType; +import common.pathfinding.PathNavigateGround; +import common.tags.TagObject; +import common.util.ExtMath; +import common.vars.Vars; +import common.world.World; public class EntityWolf extends EntityTameable { @@ -86,19 +85,8 @@ public class EntityWolf extends EntityTameable protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.30000001192092896D); - - if (this.isTamed()) - { - this.setMaxHealth(20); - } - else - { - this.setMaxHealth(8); - } - - this.getAttributeMap().registerAttribute(Attributes.ATTACK_DAMAGE); - this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(2.0D); + this.setSpeedBase(0.30000001192092896f); + this.setMaxHealth(8); } /** @@ -139,25 +127,21 @@ public class EntityWolf extends EntityTameable /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setBoolean("Angry", this.isAngry()); + super.writeEntity(tagCompound); + tagCompound.setBool("Angry", this.isAngry()); tagCompound.setByte("CollarColor", (byte)this.getCollarColor().getDyeDamage()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - this.setAngry(tagCompund.getBoolean("Angry")); - - if (tagCompund.hasKey("CollarColor", 99)) - { - this.setCollarColor(DyeColor.byDyeDamage(tagCompund.getByte("CollarColor"))); - } + super.readEntity(tagCompund); + this.setAngry(tagCompund.getBool("Angry")); + this.setCollarColor(DyeColor.byDyeDamage(tagCompund.getByte("CollarColor"))); } /** @@ -352,9 +336,9 @@ public class EntityWolf extends EntityTameable public boolean attackEntityAsMob(Entity entityIn) { - if(!this.worldObj.client && !Config.damageMobs) + if(!this.worldObj.client && !Vars.damageMobs) return false; - boolean flag = entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), ((int)this.getEntityAttribute(Attributes.ATTACK_DAMAGE).getAttributeValue())); + boolean flag = entityIn.attackEntityFrom(DamageSource.causeMobDamage(this), this.rand.chance(2, 3, 8)); if (flag) { @@ -364,22 +348,6 @@ public class EntityWolf extends EntityTameable return flag; } - public void setTamed(boolean tamed) - { - super.setTamed(tamed); - - if (tamed) - { - this.setMaxHealth(20); - } - else - { - this.setMaxHealth(8); - } - - this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(4.0D); - } - /** * Called when a player interacts with a mob. e.g. gets milk from a cow, gets into the saddle on a pig. */ @@ -399,12 +367,12 @@ public class EntityWolf extends EntityTameable { // if (!player.creative) // { - --itemstack.stackSize; + --itemstack.size; // } this.heal(itemfood.getHealAmount(itemstack)); - if (itemstack.stackSize <= 0) + if (itemstack.size <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } @@ -420,7 +388,7 @@ public class EntityWolf extends EntityTameable { this.setCollarColor(enumdyecolor); - if (/* !player.creative && */ --itemstack.stackSize <= 0) + if (/* !player.creative && */ --itemstack.size <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } @@ -442,10 +410,10 @@ public class EntityWolf extends EntityTameable { // if (!player.creative) // { - --itemstack.stackSize; + --itemstack.size; // } - if (itemstack.stackSize <= 0) + if (itemstack.size <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } diff --git a/java/src/game/entity/effect/EntityLightning.java b/common/src/main/java/common/entity/effect/EntityLightning.java similarity index 78% rename from java/src/game/entity/effect/EntityLightning.java rename to common/src/main/java/common/entity/effect/EntityLightning.java index dd405db..04176fc 100755 --- a/java/src/game/entity/effect/EntityLightning.java +++ b/common/src/main/java/common/entity/effect/EntityLightning.java @@ -1,18 +1,17 @@ -package game.entity.effect; +package common.entity.effect; import java.util.List; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.entity.types.EntityWeatherEffect; -import game.init.Blocks; -import game.init.Config; -import game.init.SoundEvent; -import game.material.Material; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.World; -import game.world.WorldClient; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.entity.types.EntityWeatherEffect; +import common.init.Blocks; +import common.init.SoundEvent; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.vars.Vars; +import common.world.AWorldClient; +import common.world.World; public class EntityLightning extends EntityWeatherEffect { @@ -66,7 +65,7 @@ public class EntityLightning extends EntityWeatherEffect this.boltVertex = this.rand.longv(); BlockPos blockpos = new BlockPos(this); - if (!this.worldObj.client && this.fire && Config.fire && this.worldObj.isAreaLoaded(blockpos, 10) && this.worldObj.getState(blockpos).getBlock().getMaterial() == Material.air && Blocks.fire.canPlaceBlockAt(this.worldObj, blockpos)) + if (!this.worldObj.client && this.fire && Vars.fire && this.worldObj.isAreaLoaded(blockpos, 10) && this.worldObj.getState(blockpos).getBlock() == Blocks.air && Blocks.fire.canPlaceBlockAt(this.worldObj, blockpos)) { this.worldObj.setState(blockpos, Blocks.fire.getState()); } @@ -77,7 +76,7 @@ public class EntityLightning extends EntityWeatherEffect { if (this.worldObj.client) { - ((WorldClient)this.worldObj).setLastLightning(2, this.color); + ((AWorldClient)this.worldObj).setLastLightning(2, this.color); } else // if(this.damage > 0) { diff --git a/java/src/game/entity/item/EntityBoat.java b/common/src/main/java/common/entity/item/EntityBoat.java similarity index 94% rename from java/src/game/entity/item/EntityBoat.java rename to common/src/main/java/common/entity/item/EntityBoat.java index 77f22d2..1a17e85 100755 --- a/java/src/game/entity/item/EntityBoat.java +++ b/common/src/main/java/common/entity/item/EntityBoat.java @@ -1,25 +1,25 @@ -package game.entity.item; +package common.entity.item; import java.util.List; -import game.block.Block; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityDamageSourceIndirect; -import game.entity.EntityType; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.init.ItemRegistry; -import game.init.Items; -import game.item.Item; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.World; +import common.block.Block; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityDamageSourceIndirect; +import common.entity.EntityType; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; +import common.item.Item; +import common.model.ParticleType; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.vars.Vars; +import common.world.World; public class EntityBoat extends Entity { @@ -137,7 +137,7 @@ public class EntityBoat extends Entity this.passenger.mountEntity(this); } - if (/* !flag && */ Config.objectDrop) + if (/* !flag && */ Vars.objectDrop) { this.dropItemWithOffset(Items.boat, 1, 0.0F); } @@ -172,9 +172,9 @@ public class EntityBoat extends Entity return !this.dead; } - public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) + public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) { - if (p_180426_10_ && this.passenger != null) + if (teleport && this.passenger != null) { this.prevX = this.posX = x; this.prevY = this.posY = y; @@ -191,7 +191,7 @@ public class EntityBoat extends Entity { if (this.isBoatEmpty) { - this.boatPosRotationIncrements = posRotationIncrements + 5; + this.boatPosRotationIncrements = 8; } else { @@ -417,7 +417,7 @@ public class EntityBoat extends Entity { this.setDead(); - if (Config.objectDrop) + if (Vars.objectDrop) { for (int j1 = 0; j1 < 3; ++j1) { @@ -501,14 +501,14 @@ public class EntityBoat extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntityToNBT(NBTTagCompound tagCompound) + protected void writeEntity(TagObject tagCompound) { } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntityFromNBT(NBTTagCompound tagCompund) + protected void readEntity(TagObject tagCompund) { } @@ -548,7 +548,7 @@ public class EntityBoat extends Entity { this.setDead(); - if (Config.objectDrop) + if (Vars.objectDrop) { for (int i = 0; i < 3; ++i) { diff --git a/java/src/game/entity/item/EntityCart.java b/common/src/main/java/common/entity/item/EntityCart.java similarity index 93% rename from java/src/game/entity/item/EntityCart.java rename to common/src/main/java/common/entity/item/EntityCart.java index d1f0058..612c4ce 100755 --- a/java/src/game/entity/item/EntityCart.java +++ b/common/src/main/java/common/entity/item/EntityCart.java @@ -1,26 +1,26 @@ -package game.entity.item; +package common.entity.item; -import game.block.Block; -import game.block.BlockRailBase; -import game.block.BlockRailPowered; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.types.EntityLiving; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.Config; -import game.init.Items; -import game.item.Item; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.tileentity.IWorldNameable; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.State; -import game.world.Vec3; -import game.world.World; +import common.block.Block; +import common.block.tech.BlockRailBase; +import common.block.tech.BlockRailPowered; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.types.EntityLiving; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.Items; +import common.item.Item; +import common.item.ItemStack; +import common.tags.TagObject; +import common.tileentity.IWorldNameable; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Vec3; +import common.vars.Vars; +import common.world.State; +import common.world.World; public abstract class EntityCart extends Entity implements IWorldNameable { @@ -188,7 +188,7 @@ public abstract class EntityCart extends Entity implements IWorldNameable { this.setDead(); - if (Config.objectDrop) + if (Vars.objectDrop) { ItemStack itemstack = new ItemStack(Items.minecart, 1); @@ -242,7 +242,7 @@ public abstract class EntityCart extends Entity implements IWorldNameable this.setDamage(this.getDamage() - 1); } - if (this.posY < -64.0D) + if (this.posY < (double)(-World.MAX_SIZE_Y) - 64.0) { this.onVoidUpdate(); } @@ -753,43 +753,27 @@ public abstract class EntityCart extends Entity implements IWorldNameable /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntityFromNBT(NBTTagCompound tagCompund) + protected void readEntity(TagObject tagCompund) { - if (tagCompund.getBoolean("CustomDisplayTile")) + if (tagCompund.getBool("CustomDisplayTile")) { - int i = tagCompund.getInteger("DisplayData"); + int i = tagCompund.getInt("DisplayData"); - if (tagCompund.hasKey("DisplayTile", 8)) + if (tagCompund.hasString("DisplayTile")) { - Block block = BlockRegistry.getByIdFallback(tagCompund.getString("DisplayTile")); + Block block = BlockRegistry.getRegisteredBlock(tagCompund.getString("DisplayTile")); - if (block == null) - { - this.func_174899_a(Blocks.air.getState()); - } - else - { - this.func_174899_a(block.getStateFromMeta(i)); - } + this.func_174899_a(block.getStateFromMeta(i)); } else { - Block block1 = BlockRegistry.getBlockById(tagCompund.getInteger("DisplayTile")); - - if (block1 == null) - { - this.func_174899_a(Blocks.air.getState()); - } - else - { - this.func_174899_a(block1.getStateFromMeta(i)); - } + this.func_174899_a(Blocks.air.getState()); } - this.setDisplayTileOffset(tagCompund.getInteger("DisplayOffset")); + this.setDisplayTileOffset(tagCompund.getInt("DisplayOffset")); } - if (tagCompund.hasKey("CustomName", 8) && tagCompund.getString("CustomName").length() > 0) + if (tagCompund.hasString("CustomName") && tagCompund.getString("CustomName").length() > 0) { this.entityName = tagCompund.getString("CustomName"); } @@ -798,16 +782,16 @@ public abstract class EntityCart extends Entity implements IWorldNameable /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntityToNBT(NBTTagCompound tagCompound) + protected void writeEntity(TagObject tagCompound) { if (this.hasDisplayTile()) { - tagCompound.setBoolean("CustomDisplayTile", true); + tagCompound.setBool("CustomDisplayTile", true); State iblockstate = this.getDisplayTile(); - String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(iblockstate.getBlock()); - tagCompound.setString("DisplayTile", resourcelocation == null ? "" : resourcelocation.toString()); - tagCompound.setInteger("DisplayData", iblockstate.getBlock().getMetaFromState(iblockstate)); - tagCompound.setInteger("DisplayOffset", this.getDisplayTileOffset()); + String resourcelocation = BlockRegistry.getNameFromBlock(iblockstate.getBlock()); + tagCompound.setString("DisplayTile", resourcelocation == null ? "" : resourcelocation); + tagCompound.setInt("DisplayData", iblockstate.getBlock().getMetaFromState(iblockstate)); + tagCompound.setInt("DisplayOffset", this.getDisplayTileOffset()); } if (this.entityName != null && this.entityName.length() > 0) @@ -912,14 +896,14 @@ public abstract class EntityCart extends Entity implements IWorldNameable } } - public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) + public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) { this.minecartX = x; this.minecartY = y; this.minecartZ = z; this.minecartYaw = (double)yaw; this.minecartPitch = (double)pitch; - this.turnProgress = posRotationIncrements + 2; + this.turnProgress = 5; this.motionX = this.velocityX; this.motionY = this.velocityY; this.motionZ = this.velocityZ; diff --git a/java/src/game/entity/item/EntityCartContainer.java b/common/src/main/java/common/entity/item/EntityCartContainer.java similarity index 78% rename from java/src/game/entity/item/EntityCartContainer.java rename to common/src/main/java/common/entity/item/EntityCartContainer.java index 26c633a..90ed0e7 100755 --- a/java/src/game/entity/item/EntityCartContainer.java +++ b/common/src/main/java/common/entity/item/EntityCartContainer.java @@ -1,19 +1,20 @@ -package game.entity.item; +package common.entity.item; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.init.Config; -import game.inventory.Container; -import game.inventory.InventoryHelper; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.tileentity.ILockableContainer; -import game.tileentity.LockCode; -import game.world.BlockPos; -import game.world.PortalType; -import game.world.World; +import common.collect.Lists; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.inventory.Container; +import common.inventory.InventoryHelper; +import common.item.ItemStack; +import common.tags.TagObject; +import java.util.List; +import common.tileentity.ILockableContainer; +import common.tileentity.Passcode; +import common.util.BlockPos; +import common.util.PortalType; +import common.vars.Vars; +import common.world.World; public abstract class EntityCartContainer extends EntityCart implements ILockableContainer { @@ -39,7 +40,7 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl { super.killMinecart(source); - if (Config.objectDrop) + if (Vars.objectDrop) { InventoryHelper.dropInventoryItems(this.worldObj, this, this); } @@ -60,7 +61,7 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl { if (this.minecartContainerItems[index] != null) { - if (this.minecartContainerItems[index].stackSize <= count) + if (this.minecartContainerItems[index].size <= count) { ItemStack itemstack1 = this.minecartContainerItems[index]; this.minecartContainerItems[index] = null; @@ -70,7 +71,7 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl { ItemStack itemstack = this.minecartContainerItems[index].splitStack(count); - if (this.minecartContainerItems[index].stackSize == 0) + if (this.minecartContainerItems[index].size == 0) { this.minecartContainerItems[index] = null; } @@ -108,9 +109,9 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl { this.minecartContainerItems[index] = stack; - if (stack != null && stack.stackSize > this.getInventoryStackLimit()) + if (stack != null && stack.size > this.getInventoryStackLimit()) { - stack.stackSize = this.getInventoryStackLimit(); + stack.size = this.getInventoryStackLimit(); } } @@ -187,42 +188,42 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntityToNBT(NBTTagCompound tagCompound) + protected void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - NBTTagList nbttaglist = new NBTTagList(); + super.writeEntity(tagCompound); + List nbttaglist = Lists.newArrayList(); for (int i = 0; i < this.minecartContainerItems.length; ++i) { if (this.minecartContainerItems[i] != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject nbttagcompound = new TagObject(); nbttagcompound.setByte("Slot", (byte)i); - this.minecartContainerItems[i].writeToNBT(nbttagcompound); - nbttaglist.appendTag(nbttagcompound); + this.minecartContainerItems[i].writeTags(nbttagcompound); + nbttaglist.add(nbttagcompound); } } - tagCompound.setTag("Items", nbttaglist); + tagCompound.setList("Items", nbttaglist); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntityFromNBT(NBTTagCompound tagCompund) + protected void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - NBTTagList nbttaglist = tagCompund.getTagList("Items", 10); + super.readEntity(tagCompund); + List nbttaglist = tagCompund.getList("Items"); this.minecartContainerItems = new ItemStack[this.getSizeInventory()]; - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + TagObject nbttagcompound = nbttaglist.get(i); int j = nbttagcompound.getByte("Slot") & 255; if (j >= 0 && j < this.minecartContainerItems.length) { - this.minecartContainerItems[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); + this.minecartContainerItems[j] = ItemStack.readFromTag(nbttagcompound); } } } @@ -268,13 +269,13 @@ public abstract class EntityCartContainer extends EntityCart implements ILockabl return false; } - public void setLockCode(LockCode code) + public void setLockCode(Passcode code) { } - public LockCode getLockCode() + public Passcode getLockCode() { - return LockCode.EMPTY_CODE; + return Passcode.EMPTY_CODE; } public void clear() diff --git a/java/src/game/entity/item/EntityChestCart.java b/common/src/main/java/common/entity/item/EntityChestCart.java similarity index 72% rename from java/src/game/entity/item/EntityChestCart.java rename to common/src/main/java/common/entity/item/EntityChestCart.java index e39c128..f110cf0 100755 --- a/java/src/game/entity/item/EntityChestCart.java +++ b/common/src/main/java/common/entity/item/EntityChestCart.java @@ -1,17 +1,17 @@ -package game.entity.item; +package common.entity.item; -import game.block.BlockChest; -import game.entity.DamageSource; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Config; -import game.init.ItemRegistry; -import game.inventory.Container; -import game.inventory.ContainerChest; -import game.inventory.InventoryPlayer; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.tech.BlockChest; +import common.entity.DamageSource; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.inventory.Container; +import common.inventory.ContainerChest; +import common.inventory.InventoryPlayer; +import common.util.Facing; +import common.vars.Vars; +import common.world.State; +import common.world.World; public class EntityChestCart extends EntityCartContainer { @@ -29,7 +29,7 @@ public class EntityChestCart extends EntityCartContainer { super.killMinecart(source); - if (Config.objectDrop) + if (Vars.objectDrop) { this.dropItemWithOffset(ItemRegistry.getItemFromBlock(Blocks.chest), 1, 0.0F); } diff --git a/java/src/game/entity/item/EntityCrystal.java b/common/src/main/java/common/entity/item/EntityCrystal.java similarity index 90% rename from java/src/game/entity/item/EntityCrystal.java rename to common/src/main/java/common/entity/item/EntityCrystal.java index b348d57..855697f 100755 --- a/java/src/game/entity/item/EntityCrystal.java +++ b/common/src/main/java/common/entity/item/EntityCrystal.java @@ -1,10 +1,10 @@ -package game.entity.item; +package common.entity.item; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.nbt.NBTTagCompound; -import game.world.World; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.tags.TagObject; +import common.world.World; public class EntityCrystal extends Entity { @@ -63,14 +63,14 @@ public class EntityCrystal extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntityToNBT(NBTTagCompound tagCompound) + protected void writeEntity(TagObject tagCompound) { } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntityFromNBT(NBTTagCompound tagCompund) + protected void readEntity(TagObject tagCompund) { } diff --git a/java/src/game/entity/item/EntityExplosion.java b/common/src/main/java/common/entity/item/EntityExplosion.java similarity index 76% rename from java/src/game/entity/item/EntityExplosion.java rename to common/src/main/java/common/entity/item/EntityExplosion.java index 260e5b1..f457c71 100755 --- a/java/src/game/entity/item/EntityExplosion.java +++ b/common/src/main/java/common/entity/item/EntityExplosion.java @@ -1,10 +1,10 @@ -package game.entity.item; +package common.entity.item; -import game.entity.Entity; -import game.entity.EntityType; -import game.nbt.NBTTagCompound; -import game.world.Explosion; -import game.world.World; +import common.entity.Entity; +import common.entity.EntityType; +import common.tags.TagObject; +import common.world.Explosion; +import common.world.World; public class EntityExplosion extends Entity { @@ -62,16 +62,16 @@ public class EntityExplosion extends Entity Explosion.doExplosionAlgo3(this.worldObj, this.posX, this.posY + (double)(this.height / 2.0F), this.posZ, this.rand, min + 6.0d, min); } - protected void writeEntityToNBT(NBTTagCompound tagCompound) + protected void writeEntity(TagObject tagCompound) { - tagCompound.setInteger("Progress", this.progress); - tagCompound.setInteger("Radius", this.radius); + tagCompound.setInt("Progress", this.progress); + tagCompound.setInt("Radius", this.radius); } - protected void readEntityFromNBT(NBTTagCompound tagCompund) + protected void readEntity(TagObject tagCompund) { - this.progress = tagCompund.getInteger("Progress"); - this.radius = tagCompund.getInteger("Radius"); + this.progress = tagCompund.getInt("Progress"); + this.radius = tagCompund.getInt("Radius"); } public float getEyeHeight() diff --git a/java/src/game/entity/item/EntityFalling.java b/common/src/main/java/common/entity/item/EntityFalling.java similarity index 63% rename from java/src/game/entity/item/EntityFalling.java rename to common/src/main/java/common/entity/item/EntityFalling.java index b5e633f..75d3c6b 100755 --- a/java/src/game/entity/item/EntityFalling.java +++ b/common/src/main/java/common/entity/item/EntityFalling.java @@ -1,30 +1,25 @@ -package game.entity.item; +package common.entity.item; import java.util.List; -import game.collect.Lists; - -import game.block.Block; -import game.block.BlockAnvil; -import game.block.BlockFalling; -import game.block.ITileEntityProvider; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.types.IObjectData; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.Config; -import game.item.ItemStack; -import game.material.Material; -import game.nbt.NBTBase; -import game.nbt.NBTTagCompound; -import game.tileentity.TileEntity; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.BlockFalling; +import common.block.tech.BlockAnvil; +import common.collect.Lists; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.types.IObjectData; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.item.ItemStack; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.vars.Vars; +import common.world.State; +import common.world.World; public class EntityFalling extends Entity implements IObjectData { @@ -35,7 +30,6 @@ public class EntityFalling extends Entity implements IObjectData private boolean hurtEntities; private int fallHurtMax = 40; private float fallHurtAmount = 2.0F; - public NBTTagCompound tileEntityData; public EntityFalling(World worldIn) { @@ -90,7 +84,7 @@ public class EntityFalling extends Entity implements IObjectData { Block block = this.fallTile.getBlock(); - if (block.getMaterial() == Material.air) + if (block == Blocks.air) { this.setDead(); } @@ -143,41 +137,17 @@ public class EntityFalling extends Entity implements IObjectData { ((BlockFalling)block).onEndFalling(this.worldObj, blockpos1); } - - if (this.tileEntityData != null && block instanceof ITileEntityProvider) - { - TileEntity tileentity = this.worldObj.getTileEntity(blockpos1); - - if (tileentity != null) - { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - tileentity.writeToNBT(nbttagcompound); - - for (String s : this.tileEntityData.getKeySet()) - { - NBTBase nbtbase = this.tileEntityData.getTag(s); - - if (!s.equals("x") && !s.equals("y") && !s.equals("z")) - { - nbttagcompound.setTag(s, nbtbase.copy()); - } - } - - tileentity.readFromNBT(nbttagcompound); - tileentity.markDirty(); - } - } } - else if (this.shouldDropItem && Config.objectDrop) + else if (this.shouldDropItem && Vars.objectDrop) { this.entityDropItem(new ItemStack(block, 1, block.damageDropped(this.fallTile)), 0.0F); } } } } - else if (this.fallTime > 100 && !this.worldObj.client && (blockpos1.getY() < 1 || blockpos1.getY() > 512) || this.fallTime > 600) + else if (this.fallTime > 100 && !this.worldObj.client && (blockpos1.getY() < -World.MAX_SIZE_Y + 1 || blockpos1.getY() > World.MAX_SIZE_Y) || this.fallTime > 600) { - if (this.shouldDropItem && Config.objectDrop) + if (this.shouldDropItem && Vars.objectDrop) { this.entityDropItem(new ItemStack(block, 1, block.damageDropped(this.fallTile)), 0.0F); } @@ -202,14 +172,14 @@ public class EntityFalling extends Entity implements IObjectData boolean flag = block == Blocks.anvil; DamageSource damagesource = flag ? DamageSource.anvil : DamageSource.fallingBlock; - if(this.worldObj.client || (flag ? Config.damageAcme : Config.damageSquish)) { + if(this.worldObj.client || (flag ? Vars.damageAcme : Vars.damageSquish)) { for (Entity entity : list) { entity.attackEntityFrom(damagesource, Math.min(ExtMath.floorf((float)i * this.fallHurtAmount), this.fallHurtMax)); } } - if (flag && (this.worldObj.client || Config.anvilFallDecay) && (double)this.rand.floatv() < 0.05000000074505806D + (double)i * 0.05D) + if (flag && (this.worldObj.client || Vars.anvilFallDecay) && (double)this.rand.floatv() < 0.05000000074505806D + (double)i * 0.05D) { int j = ((Integer)this.fallTile.getValue(BlockAnvil.DAMAGE)).intValue(); ++j; @@ -230,69 +200,45 @@ public class EntityFalling extends Entity implements IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntityToNBT(NBTTagCompound tagCompound) + protected void writeEntity(TagObject tagCompound) { Block block = this.fallTile != null ? this.fallTile.getBlock() : Blocks.air; - String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(block); + String resourcelocation = BlockRegistry.getNameFromBlock(block); tagCompound.setString("Block", resourcelocation == null ? "" : resourcelocation.toString()); tagCompound.setByte("Data", (byte)block.getMetaFromState(this.fallTile)); tagCompound.setByte("Time", (byte)this.fallTime); - tagCompound.setBoolean("DropItem", this.shouldDropItem); - tagCompound.setBoolean("HurtEntities", this.hurtEntities); + tagCompound.setBool("DropItem", this.shouldDropItem); + tagCompound.setBool("HurtEntities", this.hurtEntities); tagCompound.setFloat("FallHurtAmount", this.fallHurtAmount); - tagCompound.setInteger("FallHurtMax", this.fallHurtMax); - - if (this.tileEntityData != null) - { - tagCompound.setTag("TileEntityData", this.tileEntityData); - } + tagCompound.setInt("FallHurtMax", this.fallHurtMax); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntityFromNBT(NBTTagCompound tagCompund) + protected void readEntity(TagObject tagCompund) { int i = tagCompund.getByte("Data") & 255; - if (tagCompund.hasKey("Block", 8)) + if (tagCompund.hasString("Block")) { - this.fallTile = BlockRegistry.getByIdFallback(tagCompund.getString("Block")).getStateFromMeta(i); - } - else if (tagCompund.hasKey("TileID", 99)) - { - this.fallTile = BlockRegistry.getBlockById(tagCompund.getInteger("TileID")).getStateFromMeta(i); + this.fallTile = BlockRegistry.getRegisteredBlock(tagCompund.getString("Block")).getStateFromMeta(i); } else { - this.fallTile = BlockRegistry.getBlockById(tagCompund.getByte("Tile") & 255).getStateFromMeta(i); + this.fallTile = Blocks.sand.getState(); } this.fallTime = tagCompund.getByte("Time") & 255; Block block = this.fallTile.getBlock(); - if (tagCompund.hasKey("HurtEntities", 99)) - { - this.hurtEntities = tagCompund.getBoolean("HurtEntities"); - this.fallHurtAmount = tagCompund.getFloat("FallHurtAmount"); - this.fallHurtMax = tagCompund.getInteger("FallHurtMax"); - } - else if (block == Blocks.anvil) - { - this.hurtEntities = true; - } + this.hurtEntities = tagCompund.getBool("HurtEntities"); + this.fallHurtAmount = tagCompund.getFloat("FallHurtAmount"); + this.fallHurtMax = tagCompund.getInt("FallHurtMax"); - if (tagCompund.hasKey("DropItem", 99)) - { - this.shouldDropItem = tagCompund.getBoolean("DropItem"); - } + this.shouldDropItem = tagCompund.getBool("DropItem"); - if (tagCompund.hasKey("TileEntityData", 10)) - { - this.tileEntityData = tagCompund.getCompoundTag("TileEntityData"); - } - - if (block == null || block.getMaterial() == Material.air) + if (block == null || block == Blocks.air) { this.fallTile = Blocks.sand.getState(); } diff --git a/java/src/game/entity/item/EntityFireworks.java b/common/src/main/java/common/entity/item/EntityFireworks.java similarity index 79% rename from java/src/game/entity/item/EntityFireworks.java rename to common/src/main/java/common/entity/item/EntityFireworks.java index a58c58b..d2cb725 100755 --- a/java/src/game/entity/item/EntityFireworks.java +++ b/common/src/main/java/common/entity/item/EntityFireworks.java @@ -1,14 +1,14 @@ -package game.entity.item; +package common.entity.item; -import game.entity.Entity; -import game.entity.EntityType; -import game.init.SoundEvent; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.World; -import game.world.WorldClient; +import common.entity.Entity; +import common.entity.EntityType; +import common.init.SoundEvent; +import common.item.ItemStack; +import common.model.ParticleType; +import common.tags.TagObject; +import common.util.ExtMath; +import common.world.AWorldClient; +import common.world.World; public class EntityFireworks extends Entity { @@ -51,8 +51,8 @@ public class EntityFireworks extends Entity if (givenItem != null && givenItem.hasTagCompound()) { this.dataWatcher.updateObject(8, givenItem); - NBTTagCompound nbttagcompound = givenItem.getTagCompound(); - NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("Fireworks"); + TagObject nbttagcompound = givenItem.getTagCompound(); + TagObject nbttagcompound1 = nbttagcompound.getObject("Fireworks"); if (nbttagcompound1 != null) { @@ -151,14 +151,14 @@ public class EntityFireworks extends Entity if (id == 17 && this.worldObj.client) { ItemStack itemstack = this.dataWatcher.getWatchableObjectItemStack(8); - NBTTagCompound nbttagcompound = null; + TagObject nbttagcompound = null; if (itemstack != null && itemstack.hasTagCompound()) { - nbttagcompound = itemstack.getTagCompound().getCompoundTag("Fireworks"); + nbttagcompound = itemstack.getTagCompound().getObject("Fireworks"); } - ((WorldClient)this.worldObj).makeFireworks(this.posX, this.posY, this.posZ, this.motionX, this.motionY, this.motionZ, nbttagcompound); + ((AWorldClient)this.worldObj).makeFireworks(this.posX, this.posY, this.posZ, this.motionX, this.motionY, this.motionZ, nbttagcompound); } super.handleStatusUpdate(id); @@ -167,32 +167,32 @@ public class EntityFireworks extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - tagCompound.setInteger("Life", this.fireworkAge); - tagCompound.setInteger("LifeTime", this.lifetime); + tagCompound.setInt("Life", this.fireworkAge); + tagCompound.setInt("LifeTime", this.lifetime); ItemStack itemstack = this.dataWatcher.getWatchableObjectItemStack(8); if (itemstack != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - itemstack.writeToNBT(nbttagcompound); - tagCompound.setTag("FireworksItem", nbttagcompound); + TagObject nbttagcompound = new TagObject(); + itemstack.writeTags(nbttagcompound); + tagCompound.setObject("FireworksItem", nbttagcompound); } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - this.fireworkAge = tagCompund.getInteger("Life"); - this.lifetime = tagCompund.getInteger("LifeTime"); - NBTTagCompound nbttagcompound = tagCompund.getCompoundTag("FireworksItem"); + this.fireworkAge = tagCompund.getInt("Life"); + this.lifetime = tagCompund.getInt("LifeTime"); + TagObject nbttagcompound = tagCompund.getObject("FireworksItem"); if (nbttagcompound != null) { - ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttagcompound); + ItemStack itemstack = ItemStack.readFromTag(nbttagcompound); if (itemstack != null) { diff --git a/java/src/game/entity/item/EntityHopperCart.java b/common/src/main/java/common/entity/item/EntityHopperCart.java similarity index 84% rename from java/src/game/entity/item/EntityHopperCart.java rename to common/src/main/java/common/entity/item/EntityHopperCart.java index d21856d..0c287ae 100755 --- a/java/src/game/entity/item/EntityHopperCart.java +++ b/common/src/main/java/common/entity/item/EntityHopperCart.java @@ -1,23 +1,22 @@ -package game.entity.item; +package common.entity.item; import java.util.List; - import java.util.function.Predicate; -import game.entity.DamageSource; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Config; -import game.init.ItemRegistry; -import game.inventory.Container; -import game.inventory.ContainerHopper; -import game.inventory.InventoryPlayer; -import game.nbt.NBTTagCompound; -import game.tileentity.IHopper; -import game.tileentity.TileEntityHopper; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.entity.DamageSource; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.inventory.Container; +import common.inventory.ContainerHopper; +import common.inventory.InventoryPlayer; +import common.tags.TagObject; +import common.tileentity.IHopper; +import common.tileentity.TileEntityHopper; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.World; public class EntityHopperCart extends EntityCartContainer implements IHopper { @@ -159,7 +158,7 @@ public class EntityHopperCart extends EntityCartContainer implements IHopper if (this.collectItems()) { - this.setTransferTicker(Config.hopperCartDelay); + this.setTransferTicker(Vars.hopperCartDelay); this.markDirty(); } } @@ -193,7 +192,7 @@ public class EntityHopperCart extends EntityCartContainer implements IHopper { super.killMinecart(source); - if (Config.objectDrop) + if (Vars.objectDrop) { this.dropItemWithOffset(ItemRegistry.getItemFromBlock(Blocks.hopper), 1, 0.0F); } @@ -202,19 +201,19 @@ public class EntityHopperCart extends EntityCartContainer implements IHopper /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntityToNBT(NBTTagCompound tagCompound) + protected void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setInteger("TransferCooldown", this.transferTicker); + super.writeEntity(tagCompound); + tagCompound.setInt("TransferCooldown", this.transferTicker); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntityFromNBT(NBTTagCompound tagCompund) + protected void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - this.transferTicker = tagCompund.getInteger("TransferCooldown"); + super.readEntity(tagCompund); + this.transferTicker = tagCompund.getInt("TransferCooldown"); } /** diff --git a/java/src/game/entity/item/EntityItem.java b/common/src/main/java/common/entity/item/EntityItem.java similarity index 88% rename from java/src/game/entity/item/EntityItem.java rename to common/src/main/java/common/entity/item/EntityItem.java index 01c751b..00e1f5a 100755 --- a/java/src/game/entity/item/EntityItem.java +++ b/common/src/main/java/common/entity/item/EntityItem.java @@ -1,25 +1,25 @@ -package game.entity.item; +package common.entity.item; -import game.color.TextColor; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.init.ItemRegistry; -import game.init.SoundEvent; -import game.item.ItemStack; -import game.log.Log; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.PortalType; -import game.world.World; -import game.world.WorldServer; +import common.block.Material; +import common.color.TextColor; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.SoundEvent; +import common.item.ItemStack; +import common.log.Log; +import common.model.ParticleType; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.PortalType; +import common.vars.Vars; +import common.world.World; +import common.world.AWorldServer; public class EntityItem extends Entity { @@ -63,9 +63,9 @@ public class EntityItem extends Entity public void fall(float distance, float damageMultiplier) { - if(!this.worldObj.client && Config.itemFallDamage && distance >= 1.0f && this.getEntityItem().getItem().isFragile()) { + if(!this.worldObj.client && Vars.itemFallDamage && distance >= 1.0f && this.getEntityItem().getItem().isFragile()) { // for(int z = 0; z < 8; z++) { - ((WorldServer)this.worldObj).spawnParticle(ParticleType.ITEM_CRACK, this.posX, this.posY, this.posZ, + ((AWorldServer)this.worldObj).spawnParticle(ParticleType.ITEM_CRACK, this.posX, this.posY, this.posZ, 8, this.rand.gaussian() * 0.15D, this.rand.doublev() * 0.2D, this.rand.gaussian() * 0.15D, 0.1f, ItemRegistry.getIdFromItem(this.getEntityItem().getItem()), this.getEntityItem().getMetadata()); // } @@ -125,7 +125,7 @@ public class EntityItem extends Entity if (flag || this.ticksExisted % 25 == 0) { - if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() == Material.lava) + if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() == Material.LAVA) { this.motionY = 0.20000000298023224D; this.motionX = (double)((this.rand.floatv() - this.rand.floatv()) * 0.2F); @@ -237,17 +237,17 @@ public class EntityItem extends Entity { return false; } - else if (itemstack1.stackSize < itemstack.stackSize) + else if (itemstack1.size < itemstack.size) { return other.combineItems(this); } - else if (itemstack1.stackSize + itemstack.stackSize > itemstack1.getMaxStackSize()) + else if (itemstack1.size + itemstack.size > itemstack1.getMaxStackSize()) { return false; } else { - itemstack1.stackSize += itemstack.stackSize; + itemstack1.size += itemstack.size; other.delayBeforeCanPickup = Math.max(other.delayBeforeCanPickup, this.delayBeforeCanPickup); other.age = Math.min(other.age, this.age); other.setEntityItemStack(itemstack1); @@ -308,7 +308,7 @@ public class EntityItem extends Entity */ protected void dealFireDamage(int amount) { - if(Config.itemBurn) + if(Vars.itemBurn) this.attackEntityFrom(DamageSource.inFire, amount); } @@ -342,7 +342,7 @@ public class EntityItem extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { tagCompound.setShort("Health", (short)((byte)this.health)); tagCompound.setShort("Age", (short)this.age); @@ -360,22 +360,19 @@ public class EntityItem extends Entity if (this.getEntityItem() != null) { - tagCompound.setTag("Item", this.getEntityItem().writeToNBT(new NBTTagCompound())); + tagCompound.setObject("Item", this.getEntityItem().writeTags(new TagObject())); } } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { this.health = tagCompund.getShort("Health") & 255; this.age = tagCompund.getShort("Age"); - if (tagCompund.hasKey("PickupDelay")) - { - this.delayBeforeCanPickup = tagCompund.getShort("PickupDelay"); - } + this.delayBeforeCanPickup = tagCompund.getShort("PickupDelay"); // if (tagCompund.hasKey("Owner")) // { @@ -387,8 +384,8 @@ public class EntityItem extends Entity // this.thrower = tagCompund.getString("Thrower"); // } - NBTTagCompound nbttagcompound = tagCompund.getCompoundTag("Item"); - this.setEntityItemStack(ItemStack.loadItemStackFromNBT(nbttagcompound)); + TagObject nbttagcompound = tagCompund.getObject("Item"); + this.setEntityItemStack(ItemStack.readFromTag(nbttagcompound)); if (this.getEntityItem() == null) { @@ -404,7 +401,7 @@ public class EntityItem extends Entity if (!this.worldObj.client) { ItemStack itemstack = this.getEntityItem(); - int i = itemstack.stackSize; + int i = itemstack.size; if (this.delayBeforeCanPickup == 0 // && (this.owner == null || 6000 - this.age <= 200 || this.owner.equals(entityIn.getUser())) && entityIn.inventory.addItemStackToInventory(itemstack)) @@ -451,7 +448,7 @@ public class EntityItem extends Entity entityIn.onItemPickup(this, i); - if (itemstack.stackSize <= 0) + if (itemstack.size <= 0) { this.setDead(); } @@ -467,8 +464,8 @@ public class EntityItem extends Entity if(this.hasCustomName()) return this.getCustomNameTag(); String comp = super.getTypeName(); - comp += " (" + this.getEntityItem().stackSize + " * " + - ItemRegistry.REGISTRY.getNameForObject(this.getEntityItem().getItem()) + ":" + this.getEntityItem().getMetadata() + ")"; + comp += " (" + this.getEntityItem().size + " * " + + ItemRegistry.getNameFromItem(this.getEntityItem().getItem()) + ":" + this.getEntityItem().getMetadata() + ")"; return comp; } @@ -507,7 +504,7 @@ public class EntityItem extends Entity { if (this.worldObj != null) { - Log.JNI.warn("Gegenstand-Objekt " + this.getId() + " hat kein Item?!"); + Log.TICK.warn("Gegenstand-Objekt " + this.getId() + " hat kein Item?!"); } return new ItemStack(Blocks.stone); @@ -615,9 +612,9 @@ public class EntityItem extends Entity public String getDisplayName() { ItemStack stack = this.getEntityItem(); - if(stack.stackSize <= 1) + if(stack.size <= 1) return null; - return TextColor.DGREEN + "" + stack.stackSize; + return TextColor.DGREEN + "" + stack.size; } public EntityType getType() { diff --git a/java/src/game/entity/item/EntityLeashKnot.java b/common/src/main/java/common/entity/item/EntityLeashKnot.java similarity index 95% rename from java/src/game/entity/item/EntityLeashKnot.java rename to common/src/main/java/common/entity/item/EntityLeashKnot.java index ff89910..d5c74e7 100755 --- a/java/src/game/entity/item/EntityLeashKnot.java +++ b/common/src/main/java/common/entity/item/EntityLeashKnot.java @@ -1,19 +1,19 @@ -package game.entity.item; +package common.entity.item; -import game.block.BlockFence; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.item.Item; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.World; +import common.block.artificial.BlockFence; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.item.Item; +import common.item.ItemStack; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.world.World; public class EntityLeashKnot extends Entity { @@ -375,7 +375,7 @@ public class EntityLeashKnot extends Entity * returns false the entity is not saved on disk. Ridden entities return false here as they are saved with their * rider. */ - public boolean writeToNBTOptional(NBTTagCompound tagCompund) + public boolean writeOptional(TagObject tagCompund) { return false; } @@ -383,14 +383,14 @@ public class EntityLeashKnot extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { } diff --git a/java/src/game/entity/item/EntityMinecart.java b/common/src/main/java/common/entity/item/EntityMinecart.java similarity index 93% rename from java/src/game/entity/item/EntityMinecart.java rename to common/src/main/java/common/entity/item/EntityMinecart.java index 52ae07e..008c898 100755 --- a/java/src/game/entity/item/EntityMinecart.java +++ b/common/src/main/java/common/entity/item/EntityMinecart.java @@ -1,8 +1,8 @@ -package game.entity.item; +package common.entity.item; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.world.World; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.world.World; public class EntityMinecart extends EntityCart { diff --git a/java/src/game/entity/item/EntityNuke.java b/common/src/main/java/common/entity/item/EntityNuke.java similarity index 87% rename from java/src/game/entity/item/EntityNuke.java rename to common/src/main/java/common/entity/item/EntityNuke.java index abca66f..a94953d 100755 --- a/java/src/game/entity/item/EntityNuke.java +++ b/common/src/main/java/common/entity/item/EntityNuke.java @@ -1,10 +1,10 @@ -package game.entity.item; +package common.entity.item; -import game.entity.Entity; -import game.entity.EntityType; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.world.World; +import common.entity.Entity; +import common.entity.EntityType; +import common.model.ParticleType; +import common.tags.TagObject; +import common.world.World; public class EntityNuke extends Entity { @@ -93,14 +93,14 @@ public class EntityNuke extends Entity // Explosion.doExplosionAlgo3(this.worldObj, this.posX, this.posY + (double)(this.height / 2.0F), this.posZ, this.rand, min + 6.0d, min); // } - protected void writeEntityToNBT(NBTTagCompound tagCompound) + protected void writeEntity(TagObject tagCompound) { - tagCompound.setInteger("Fuse", this.fuse); + tagCompound.setInt("Fuse", this.fuse); } - protected void readEntityFromNBT(NBTTagCompound tagCompund) + protected void readEntity(TagObject tagCompund) { - this.fuse = tagCompund.getInteger("Fuse"); + this.fuse = tagCompund.getInt("Fuse"); } public float getEyeHeight() diff --git a/java/src/game/entity/item/EntityOrb.java b/common/src/main/java/common/entity/item/EntityOrb.java similarity index 88% rename from java/src/game/entity/item/EntityOrb.java rename to common/src/main/java/common/entity/item/EntityOrb.java index ec9743b..1c0e462 100755 --- a/java/src/game/entity/item/EntityOrb.java +++ b/common/src/main/java/common/entity/item/EntityOrb.java @@ -1,13 +1,13 @@ -package game.entity.item; +package common.entity.item; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.entity.types.EntityThrowable; -import game.init.Config; -import game.renderer.particle.ParticleType; -import game.world.HitPosition; -import game.world.World; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.entity.types.EntityThrowable; +import common.model.ParticleType; +import common.util.HitPosition; +import common.vars.Vars; +import common.world.World; public class EntityOrb extends EntityThrowable { @@ -52,7 +52,7 @@ public class EntityOrb extends EntityThrowable // return; // } - if(Config.telefrag) { + if(Vars.telefrag) { x = pos.entity.posX; y = pos.entity.posY; z = pos.entity.posZ; @@ -92,8 +92,8 @@ public class EntityOrb extends EntityThrowable entitylivingbase.setPositionAndUpdate(x, y, z); entitylivingbase.fallDistance = 0.0F; - if(Config.orbDamageSelf > 0) - entitylivingbase.attackEntityFrom(DamageSource.fall, Config.orbDamageSelf); + if(Vars.orbDamageSelf > 0) + entitylivingbase.attackEntityFrom(DamageSource.fall, Vars.orbDamageSelf); } } // else if (entitylivingbase != null) @@ -109,13 +109,13 @@ public class EntityOrb extends EntityThrowable if (pos.entity != null) { - if(Config.telefrag) { + if(Vars.telefrag) { pos.entity.attackEntityFrom(DamageSource.causeTeleFragDamage(this, entitylivingbase), 10000); if(!this.worldObj.client) this.worldObj.playAuxSFX(1017, pos.entity.getPosition(), 0); } - else if(Config.knockOrb) { - pos.entity.attackEntityFrom(DamageSource.causeThrownDamage(this, entitylivingbase), Config.orbDamageOther); + else if(Vars.knockOrb) { + pos.entity.attackEntityFrom(DamageSource.causeThrownDamage(this, entitylivingbase), Vars.orbDamageOther); } } } diff --git a/java/src/game/entity/item/EntityTnt.java b/common/src/main/java/common/entity/item/EntityTnt.java similarity index 90% rename from java/src/game/entity/item/EntityTnt.java rename to common/src/main/java/common/entity/item/EntityTnt.java index f140c85..84e398c 100755 --- a/java/src/game/entity/item/EntityTnt.java +++ b/common/src/main/java/common/entity/item/EntityTnt.java @@ -1,12 +1,12 @@ -package game.entity.item; +package common.entity.item; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.types.EntityLiving; -import game.entity.types.IObjectData; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.world.World; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.types.EntityLiving; +import common.entity.types.IObjectData; +import common.model.ParticleType; +import common.tags.TagObject; +import common.world.World; public class EntityTnt extends Entity implements IObjectData { @@ -109,7 +109,7 @@ public class EntityTnt extends Entity implements IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntityToNBT(NBTTagCompound tagCompound) + protected void writeEntity(TagObject tagCompound) { tagCompound.setByte("Fuse", (byte)this.fuse); tagCompound.setByte("Power", (byte)this.explosionSize); @@ -118,7 +118,7 @@ public class EntityTnt extends Entity implements IObjectData /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntityFromNBT(NBTTagCompound tagCompund) + protected void readEntity(TagObject tagCompund) { this.fuse = tagCompund.getByte("Fuse"); this.explosionSize = ((int)tagCompund.getByte("Power")) & 7; diff --git a/java/src/game/entity/item/EntityTntCart.java b/common/src/main/java/common/entity/item/EntityTntCart.java similarity index 84% rename from java/src/game/entity/item/EntityTntCart.java rename to common/src/main/java/common/entity/item/EntityTntCart.java index f318b98..7d872c4 100755 --- a/java/src/game/entity/item/EntityTntCart.java +++ b/common/src/main/java/common/entity/item/EntityTntCart.java @@ -1,19 +1,19 @@ -package game.entity.item; +package common.entity.item; -import game.block.BlockRailBase; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.projectile.EntityArrow; -import game.init.Blocks; -import game.init.Config; -import game.init.SoundEvent; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.world.BlockPos; -import game.world.Explosion; -import game.world.State; -import game.world.World; +import common.block.tech.BlockRailBase; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.projectile.EntityArrow; +import common.init.Blocks; +import common.init.SoundEvent; +import common.item.ItemStack; +import common.model.ParticleType; +import common.tags.TagObject; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.Explosion; +import common.world.State; +import common.world.World; public class EntityTntCart extends EntityCart { @@ -92,7 +92,7 @@ public class EntityTntCart extends EntityCart super.killMinecart(source); double d0 = this.motionX * this.motionX + this.motionZ * this.motionZ; - if (!source.isExplosion() && Config.objectDrop) + if (!source.isExplosion() && Vars.objectDrop) { this.entityDropItem(new ItemStack(Blocks.tnt, 1), 0.0F); } @@ -206,22 +206,18 @@ public class EntityTntCart extends EntityCart /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - protected void readEntityFromNBT(NBTTagCompound tagCompund) + protected void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - - if (tagCompund.hasKey("TNTFuse", 99)) - { - this.minecartTNTFuse = tagCompund.getInteger("TNTFuse"); - } + super.readEntity(tagCompund); + this.minecartTNTFuse = tagCompund.getInt("TNTFuse"); } /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - protected void writeEntityToNBT(NBTTagCompound tagCompound) + protected void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setInteger("TNTFuse", this.minecartTNTFuse); + super.writeEntity(tagCompound); + tagCompound.setInt("TNTFuse", this.minecartTNTFuse); } } diff --git a/java/src/game/entity/item/EntityXp.java b/common/src/main/java/common/entity/item/EntityXp.java similarity index 94% rename from java/src/game/entity/item/EntityXp.java rename to common/src/main/java/common/entity/item/EntityXp.java index e8cae54..06d1342 100755 --- a/java/src/game/entity/item/EntityXp.java +++ b/common/src/main/java/common/entity/item/EntityXp.java @@ -1,20 +1,20 @@ -package game.entity.item; +package common.entity.item; -import game.color.TextColor; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.npc.EntityNPC; -import game.entity.types.IObjectData; -import game.init.Config; -import game.init.SoundEvent; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.PortalType; -import game.world.World; +import common.block.Material; +import common.color.TextColor; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.npc.EntityNPC; +import common.entity.types.IObjectData; +import common.init.SoundEvent; +import common.model.ParticleType; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.PortalType; +import common.vars.Vars; +import common.world.World; public class EntityXp extends Entity implements IObjectData { @@ -106,7 +106,7 @@ public class EntityXp extends Entity implements IObjectData this.prevZ = this.posZ; this.motionY -= 0.029999999329447746D; - if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() == Material.lava) + if (this.worldObj.getState(new BlockPos(this)).getBlock().getMaterial() == Material.LAVA) { this.motionY = 0.20000000298023224D; this.motionX = (double)((this.rand.floatv() - this.rand.floatv()) * 0.2F); @@ -263,7 +263,7 @@ public class EntityXp extends Entity implements IObjectData */ protected void dealFireDamage(int amount) { - if(Config.xpOrbBurn) + if(Vars.xpOrbBurn) this.attackEntityFrom(DamageSource.inFire, amount); } @@ -293,7 +293,7 @@ public class EntityXp extends Entity implements IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { tagCompound.setShort("Health", (short)((byte)this.xpOrbHealth)); tagCompound.setShort("Age", (short)this.xpOrbAge); @@ -303,7 +303,7 @@ public class EntityXp extends Entity implements IObjectData /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { this.xpOrbHealth = tagCompund.getShort("Health") & 255; this.xpOrbAge = tagCompund.getShort("Age"); @@ -320,7 +320,7 @@ public class EntityXp extends Entity implements IObjectData { if (this.delayBeforeCanPickup == 0 && entityIn.xpCooldown == 0) { - entityIn.xpCooldown = Config.xpDelay; + entityIn.xpCooldown = Vars.xpDelay; this.worldObj.playSoundAtEntity(entityIn, SoundEvent.ORB, 0.1F); entityIn.onItemPickup(this, this.xpValue); entityIn.addExperience(this.xpValue); diff --git a/java/src/game/entity/item/EntityXpBottle.java b/common/src/main/java/common/entity/item/EntityXpBottle.java similarity index 86% rename from java/src/game/entity/item/EntityXpBottle.java rename to common/src/main/java/common/entity/item/EntityXpBottle.java index f4c377d..fdef911 100755 --- a/java/src/game/entity/item/EntityXpBottle.java +++ b/common/src/main/java/common/entity/item/EntityXpBottle.java @@ -1,10 +1,10 @@ -package game.entity.item; +package common.entity.item; -import game.entity.types.EntityLiving; -import game.entity.types.EntityThrowable; -import game.world.BlockPos; -import game.world.HitPosition; -import game.world.World; +import common.entity.types.EntityLiving; +import common.entity.types.EntityThrowable; +import common.util.BlockPos; +import common.util.HitPosition; +import common.world.World; public class EntityXpBottle extends EntityThrowable { diff --git a/java/src/game/entity/npc/Alignment.java b/common/src/main/java/common/entity/npc/Alignment.java similarity index 95% rename from java/src/game/entity/npc/Alignment.java rename to common/src/main/java/common/entity/npc/Alignment.java index f38481c..9c5fba6 100755 --- a/java/src/game/entity/npc/Alignment.java +++ b/common/src/main/java/common/entity/npc/Alignment.java @@ -1,10 +1,9 @@ -package game.entity.npc; +package common.entity.npc; import java.util.Map; -import game.collect.Maps; - -import game.color.TextColor; +import common.collect.Maps; +import common.color.TextColor; public enum Alignment { LAWFUL_GOOD("lgood", "Rechtsch. gut", 1, 1, TextColor.NEON), diff --git a/java/src/game/entity/npc/CharacterInfo.java b/common/src/main/java/common/entity/npc/CharacterInfo.java similarity index 86% rename from java/src/game/entity/npc/CharacterInfo.java rename to common/src/main/java/common/entity/npc/CharacterInfo.java index 44c375c..02318a6 100755 --- a/java/src/game/entity/npc/CharacterInfo.java +++ b/common/src/main/java/common/entity/npc/CharacterInfo.java @@ -1,7 +1,7 @@ -package game.entity.npc; +package common.entity.npc; -import game.init.SpeciesRegistry; -import game.item.ItemStack; +import common.init.SpeciesRegistry; +import common.item.ItemStack; public class CharacterInfo extends NpcInfo { public final boolean spawner; diff --git a/java/src/game/entity/npc/Energy.java b/common/src/main/java/common/entity/npc/Energy.java similarity index 96% rename from java/src/game/entity/npc/Energy.java rename to common/src/main/java/common/entity/npc/Energy.java index da81e6e..1f060f2 100755 --- a/java/src/game/entity/npc/Energy.java +++ b/common/src/main/java/common/entity/npc/Energy.java @@ -1,4 +1,4 @@ -package game.entity.npc; +package common.entity.npc; public enum Energy { SPIRITUAL(-100, 'S', "spiritual", "SPR", 0x00ff00, 0x00ffff), // angelic diff --git a/java/src/game/entity/npc/EntityArachnoid.java b/common/src/main/java/common/entity/npc/EntityArachnoid.java similarity index 92% rename from java/src/game/entity/npc/EntityArachnoid.java rename to common/src/main/java/common/entity/npc/EntityArachnoid.java index ac04013..990e649 100755 --- a/java/src/game/entity/npc/EntityArachnoid.java +++ b/common/src/main/java/common/entity/npc/EntityArachnoid.java @@ -1,16 +1,16 @@ -package game.entity.npc; +package common.entity.npc; -import game.ai.EntityAIAttackOnCollide; -import game.ai.EntityAILeapAtTarget; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.pathfinding.PathNavigate; -import game.pathfinding.PathNavigateClimber; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.rng.Random; -import game.world.BlockPos; -import game.world.World; +import common.ai.EntityAIAttackOnCollide; +import common.ai.EntityAILeapAtTarget; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.pathfinding.PathNavigate; +import common.pathfinding.PathNavigateClimber; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.rng.Random; +import common.util.BlockPos; +import common.world.World; public class EntityArachnoid extends EntityNPC { @@ -69,7 +69,7 @@ public class EntityArachnoid extends EntityNPC public boolean isOnLadder() { - return super.isOnLadder() || (this.sendQueue != null ? this.collidedHorizontally && !this.noclip : this.isBesideClimbableBlock()); + return super.isOnLadder() || (this.client != null ? this.collidedHorizontally && !this.noclip : this.isBesideClimbableBlock()); } public void setInWeb() diff --git a/java/src/game/entity/npc/EntityBloodElf.java b/common/src/main/java/common/entity/npc/EntityBloodElf.java similarity index 91% rename from java/src/game/entity/npc/EntityBloodElf.java rename to common/src/main/java/common/entity/npc/EntityBloodElf.java index 66e5a4e..4870276 100755 --- a/java/src/game/entity/npc/EntityBloodElf.java +++ b/common/src/main/java/common/entity/npc/EntityBloodElf.java @@ -1,10 +1,10 @@ -package game.entity.npc; +package common.entity.npc; -import game.init.Items; -import game.init.NameRegistry; -import game.item.ItemStack; -import game.rng.Random; -import game.world.World; +import common.init.Items; +import common.init.NameRegistry; +import common.item.ItemStack; +import common.rng.Random; +import common.world.World; public class EntityBloodElf extends EntityNPC { public EntityBloodElf(World worldIn) { diff --git a/java/src/game/entity/npc/EntityChaosMarine.java b/common/src/main/java/common/entity/npc/EntityChaosMarine.java similarity index 87% rename from java/src/game/entity/npc/EntityChaosMarine.java rename to common/src/main/java/common/entity/npc/EntityChaosMarine.java index 51ade10..69966f5 100755 --- a/java/src/game/entity/npc/EntityChaosMarine.java +++ b/common/src/main/java/common/entity/npc/EntityChaosMarine.java @@ -1,19 +1,17 @@ -package game.entity.npc; +package common.entity.npc; import java.util.List; -import game.collect.Lists; - -import game.entity.attributes.Attributes; -import game.init.Items; -import game.init.SpeciesRegistry; -import game.item.ItemStack; -import game.properties.IStringSerializable; -import game.rng.Random; -import game.world.World; +import common.collect.Lists; +import common.init.Items; +import common.init.SpeciesRegistry; +import common.item.ItemStack; +import common.rng.Random; +import common.util.Identifyable; +import common.world.World; public class EntityChaosMarine extends EntityNPC { - public static enum Legion implements IStringSerializable { + public static enum Legion implements Identifyable { OTHER("other", null, 0x000000, 0x000000, 2.15f, 200), EMPERORS_CHILDREN("emperorchild", "Emperors Children", 0xa224cc, 0xccb963, 2.43f, 300, "emperors_child"); @@ -119,7 +117,7 @@ public class EntityChaosMarine extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(12.0D); + this.setAttackDamageBase(12); } protected ItemStack pickItem() { diff --git a/java/src/game/entity/npc/EntityCpu.java b/common/src/main/java/common/entity/npc/EntityCpu.java similarity index 89% rename from java/src/game/entity/npc/EntityCpu.java rename to common/src/main/java/common/entity/npc/EntityCpu.java index bd8ce4e..e9aaa3a 100755 --- a/java/src/game/entity/npc/EntityCpu.java +++ b/common/src/main/java/common/entity/npc/EntityCpu.java @@ -1,9 +1,9 @@ -package game.entity.npc; +package common.entity.npc; -import game.init.Items; -import game.item.ItemStack; -import game.rng.Random; -import game.world.World; +import common.init.Items; +import common.item.ItemStack; +import common.rng.Random; +import common.world.World; public class EntityCpu extends EntityNPC { public EntityCpu(World worldIn) { diff --git a/java/src/game/entity/npc/EntityCultivator.java b/common/src/main/java/common/entity/npc/EntityCultivator.java similarity index 91% rename from java/src/game/entity/npc/EntityCultivator.java rename to common/src/main/java/common/entity/npc/EntityCultivator.java index 5ce5805..2376c0a 100755 --- a/java/src/game/entity/npc/EntityCultivator.java +++ b/common/src/main/java/common/entity/npc/EntityCultivator.java @@ -1,14 +1,14 @@ -package game.entity.npc; +package common.entity.npc; -import game.ai.EntityAITakePlace; -import game.ai.EntityAITempt; -import game.ai.EntityAIWatchClosest2; -import game.entity.effect.EntityLightning; -import game.init.Items; -import game.item.ItemStack; -import game.rng.Random; -import game.world.BlockPos; -import game.world.World; +import common.ai.EntityAITakePlace; +import common.ai.EntityAITempt; +import common.ai.EntityAIWatchClosest2; +import common.entity.effect.EntityLightning; +import common.init.Items; +import common.item.ItemStack; +import common.rng.Random; +import common.util.BlockPos; +import common.world.World; public class EntityCultivator extends EntityNPC { public EntityCultivator(World worldIn) { diff --git a/java/src/game/entity/npc/EntityDarkMage.java b/common/src/main/java/common/entity/npc/EntityDarkMage.java similarity index 85% rename from java/src/game/entity/npc/EntityDarkMage.java rename to common/src/main/java/common/entity/npc/EntityDarkMage.java index cec4c6f..5f0476f 100755 --- a/java/src/game/entity/npc/EntityDarkMage.java +++ b/common/src/main/java/common/entity/npc/EntityDarkMage.java @@ -1,11 +1,11 @@ -package game.entity.npc; +package common.entity.npc; -import game.ai.AISmallFireballAttack; -import game.init.SoundEvent; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.World; -import game.world.WorldClient; +import common.ai.AISmallFireballAttack; +import common.init.SoundEvent; +import common.model.ParticleType; +import common.rng.Random; +import common.world.AWorldClient; +import common.world.World; public class EntityDarkMage extends EntityHoveringNPC { public EntityDarkMage(World worldIn) { @@ -85,7 +85,7 @@ public class EntityDarkMage extends EntityHoveringNPC { { if(this.worldObj.client && this.isAttacking()) { if(this.rand.chance(24)) { // && !this.isSilent()) { - ((WorldClient)this.worldObj).playSound(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, SoundEvent.FIRE, + ((AWorldClient)this.worldObj).playSound(this.posX + 0.5D, this.posY + 0.5D, this.posZ + 0.5D, SoundEvent.FIRE, 1.0F + this.rand.floatv()); } for(int i = 0; i < 2; ++i) { diff --git a/java/src/game/entity/npc/EntityDwarf.java b/common/src/main/java/common/entity/npc/EntityDwarf.java similarity index 92% rename from java/src/game/entity/npc/EntityDwarf.java rename to common/src/main/java/common/entity/npc/EntityDwarf.java index 0872ad5..8e78631 100755 --- a/java/src/game/entity/npc/EntityDwarf.java +++ b/common/src/main/java/common/entity/npc/EntityDwarf.java @@ -1,8 +1,8 @@ -package game.entity.npc; +package common.entity.npc; -import game.entity.types.EntityLiving; -import game.rng.Random; -import game.world.World; +import common.entity.types.EntityLiving; +import common.rng.Random; +import common.world.World; public class EntityDwarf extends EntityNPC { public EntityDwarf(World worldIn) { diff --git a/java/src/game/entity/npc/EntityElf.java b/common/src/main/java/common/entity/npc/EntityElf.java similarity index 89% rename from java/src/game/entity/npc/EntityElf.java rename to common/src/main/java/common/entity/npc/EntityElf.java index d61c7a6..2a70a38 100755 --- a/java/src/game/entity/npc/EntityElf.java +++ b/common/src/main/java/common/entity/npc/EntityElf.java @@ -1,11 +1,11 @@ -package game.entity.npc; +package common.entity.npc; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.init.NameRegistry; -import game.item.ItemStack; -import game.rng.Random; -import game.world.World; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.init.NameRegistry; +import common.item.ItemStack; +import common.rng.Random; +import common.world.World; public class EntityElf extends EntityNPC { public EntityElf(World worldIn) { diff --git a/java/src/game/entity/npc/EntityFireDemon.java b/common/src/main/java/common/entity/npc/EntityFireDemon.java similarity index 89% rename from java/src/game/entity/npc/EntityFireDemon.java rename to common/src/main/java/common/entity/npc/EntityFireDemon.java index 81a11db..e982fff 100755 --- a/java/src/game/entity/npc/EntityFireDemon.java +++ b/common/src/main/java/common/entity/npc/EntityFireDemon.java @@ -1,10 +1,10 @@ -package game.entity.npc; +package common.entity.npc; -import game.ai.AIFireballAttack; -import game.entity.DamageSource; -import game.entity.effect.EntityLightning; -import game.rng.Random; -import game.world.World; +import common.ai.AIFireballAttack; +import common.entity.DamageSource; +import common.entity.effect.EntityLightning; +import common.rng.Random; +import common.world.World; public class EntityFireDemon extends EntityFlyingNPC { public EntityFireDemon(World worldIn) { diff --git a/java/src/game/entity/npc/EntityFlyingNPC.java b/common/src/main/java/common/entity/npc/EntityFlyingNPC.java similarity index 91% rename from java/src/game/entity/npc/EntityFlyingNPC.java rename to common/src/main/java/common/entity/npc/EntityFlyingNPC.java index 886e41d..0218e90 100755 --- a/java/src/game/entity/npc/EntityFlyingNPC.java +++ b/common/src/main/java/common/entity/npc/EntityFlyingNPC.java @@ -1,16 +1,15 @@ -package game.entity.npc; +package common.entity.npc; -import game.ai.EntityAIBase; -import game.ai.EntityMoveHelper; -import game.block.Block; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; -import game.potion.Potion; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.World; +import common.ai.EntityAIBase; +import common.ai.EntityMoveHelper; +import common.block.Block; +import common.entity.types.EntityLiving; +import common.potion.Potion; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.world.World; public abstract class EntityFlyingNPC extends EntityNPC { @@ -21,12 +20,10 @@ public abstract class EntityFlyingNPC extends EntityNPC this.tasks.addTask(5, new AIRandomFly(this)); this.tasks.addTask(7, new AILookAround(this)); } - - protected void applyEntityAttributes() - { - super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.FOLLOW_RANGE).setBaseValue(48.0D); - } + + public int getPathingRange() { + return 48; + } public float getArmRotation() { return 0.0f; @@ -35,6 +32,10 @@ public abstract class EntityFlyingNPC extends EntityNPC public float getLegRotation() { return 0.2f; } + + public boolean isSneakingVisually() { + return false; + } public void fall(float distance, float damageMultiplier) { @@ -45,6 +46,10 @@ public abstract class EntityFlyingNPC extends EntityNPC } public boolean isFlying() { + return !this.isPlayer() || super.isFlying(); + } + + public boolean canNaturallyFly() { return true; } @@ -121,10 +126,9 @@ public abstract class EntityFlyingNPC extends EntityNPC return false; } - public boolean isPotionApplicable(Potion potion) - { - return potion != Potion.FLYING && super.isPotionApplicable(potion); - } + public boolean isPotionApplicable(Potion potion, int amplifier) { + return (potion != Potion.FLYING || amplifier > 0) && super.isPotionApplicable(potion, amplifier); + } static class AILookAround extends EntityAIBase { diff --git a/java/src/game/entity/npc/EntityGargoyle.java b/common/src/main/java/common/entity/npc/EntityGargoyle.java similarity index 86% rename from java/src/game/entity/npc/EntityGargoyle.java rename to common/src/main/java/common/entity/npc/EntityGargoyle.java index 8291424..065e07e 100755 --- a/java/src/game/entity/npc/EntityGargoyle.java +++ b/common/src/main/java/common/entity/npc/EntityGargoyle.java @@ -1,14 +1,13 @@ -package game.entity.npc; +package common.entity.npc; -import game.ai.AIFlyingBoxAttack; -import game.entity.DamageSource; -import game.entity.attributes.Attributes; -import game.init.Config; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.World; +import common.ai.AIFlyingBoxAttack; +import common.entity.DamageSource; +import common.item.ItemStack; +import common.model.ParticleType; +import common.rng.Random; +import common.tags.TagObject; +import common.vars.Vars; +import common.world.World; public class EntityGargoyle extends EntityFlyingNPC { @@ -35,16 +34,16 @@ public class EntityGargoyle extends EntityFlyingNPC this.dataWatcher.addObject(23, 0); } - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setInteger("Invul", this.getInvulTime()); + super.writeEntity(tagCompound); + tagCompound.setInt("Invul", this.getInvulTime()); } - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - this.setInvulTime(tagCompund.getInteger("Invul")); + super.readEntity(tagCompund); + this.setInvulTime(tagCompund.getInt("Invul")); } public void onLivingUpdate() @@ -112,7 +111,7 @@ public class EntityGargoyle extends EntityFlyingNPC if (j1 <= 0) { this.worldObj.newExplosion(this, this.posX, this.posY + (double)this.getEyeHeight(), this.posZ, 7.0F, false, - Config.mobGrief, false); + Vars.mobGrief, false); // this.worldObj.broadcastSound(1013, new BlockPos(this), 0); } @@ -165,9 +164,12 @@ public class EntityGargoyle extends EntityFlyingNPC protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.6000000238418579D); - this.getEntityAttribute(Attributes.FOLLOW_RANGE).setBaseValue(40.0D); + this.setSpeedBase(0.6000000238418579f); } + + public int getPathingRange() { + return 40; + } public int getInvulTime() { diff --git a/java/src/game/entity/npc/EntityGoblin.java b/common/src/main/java/common/entity/npc/EntityGoblin.java similarity index 82% rename from java/src/game/entity/npc/EntityGoblin.java rename to common/src/main/java/common/entity/npc/EntityGoblin.java index 44038c4..55a0ac8 100755 --- a/java/src/game/entity/npc/EntityGoblin.java +++ b/common/src/main/java/common/entity/npc/EntityGoblin.java @@ -1,9 +1,8 @@ -package game.entity.npc; +package common.entity.npc; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; -import game.rng.Random; -import game.world.World; +import common.entity.types.EntityLiving; +import common.rng.Random; +import common.world.World; public class EntityGoblin extends EntityNPC { public EntityGoblin(World worldIn) { @@ -44,7 +43,7 @@ public class EntityGoblin extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(1.0D); + this.setAttackDamageBase(1); } public boolean canAmbush(EntityLiving entity) { diff --git a/java/src/game/entity/npc/EntityHaunter.java b/common/src/main/java/common/entity/npc/EntityHaunter.java similarity index 87% rename from java/src/game/entity/npc/EntityHaunter.java rename to common/src/main/java/common/entity/npc/EntityHaunter.java index 9d1c216..ad266ed 100755 --- a/java/src/game/entity/npc/EntityHaunter.java +++ b/common/src/main/java/common/entity/npc/EntityHaunter.java @@ -1,18 +1,17 @@ -package game.entity.npc; +package common.entity.npc; -import game.ai.EntityAIExplode; -import game.entity.Entity; -import game.entity.attributes.Attributes; -import game.entity.effect.EntityLightning; -import game.entity.types.EntityLiving; -import game.init.Config; -import game.init.Items; -import game.init.SoundEvent; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.rng.Random; -import game.world.World; -import game.world.WorldServer; +import common.ai.EntityAIExplode; +import common.entity.Entity; +import common.entity.effect.EntityLightning; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.init.SoundEvent; +import common.item.ItemStack; +import common.rng.Random; +import common.tags.TagObject; +import common.vars.Vars; +import common.world.World; +import common.world.AWorldServer; public class EntityHaunter extends EntityNPC { // private int lastActiveTime; @@ -28,7 +27,7 @@ public class EntityHaunter extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.25D); + this.setSpeedBase(0.25f); } public int getMaxFallHeight() @@ -58,33 +57,30 @@ public class EntityHaunter extends EntityNPC { /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); + super.writeEntity(tagCompound); if (this.isCharged()) { - tagCompound.setBoolean("Charge", true); + tagCompound.setBool("Charge", true); } tagCompound.setShort("Fuse", (short)this.fuseTime); - tagCompound.setBoolean("ignited", this.hasIgnited()); + tagCompound.setBool("ignited", this.hasIgnited()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - this.setCharged(tagCompund.getBoolean("Charge")); + super.readEntity(tagCompund); + this.setCharged(tagCompund.getBool("Charge")); - if (tagCompund.hasKey("Fuse", 99)) - { - this.fuseTime = tagCompund.getShort("Fuse"); - } + this.fuseTime = tagCompund.getShort("Fuse"); - if (tagCompund.getBoolean("ignited")) + if (tagCompund.getBool("ignited")) { this.ignite(); } @@ -227,7 +223,7 @@ public class EntityHaunter extends EntityNPC { public void onStruckByLightning(EntityLightning lightningBolt) { // super.onStruckByLightning(lightningBolt); - if(!this.worldObj.client && Config.chargeHaunter) { + if(!this.worldObj.client && Vars.chargeHaunter) { // int power = this.getPower(); // if(++power < 256) // this.dataWatcher.updateObject(24, (byte)power); @@ -259,7 +255,7 @@ public class EntityHaunter extends EntityNPC { { if (!this.worldObj.client) { - boolean flag = Config.mobGrief; + boolean flag = Vars.mobGrief; float f = 1.0F + (float)(this.isCharged() ? this.rand.range(3, 5) : 0) / 8.0f; this.worldObj.createAltExplosion(this, this.posX, this.posY, this.posZ, (float)this.rand.range(3, 5) * f, flag); this.setDead(); @@ -346,7 +342,7 @@ public class EntityHaunter extends EntityNPC { } public boolean getCanSpawnHere() { - return !((WorldServer)this.worldObj).isDaytime(); + return !((AWorldServer)this.worldObj).isDaytime(); } // public boolean canAmbush(EntityLiving entity) { diff --git a/java/src/game/entity/npc/EntityHoveringNPC.java b/common/src/main/java/common/entity/npc/EntityHoveringNPC.java similarity index 89% rename from java/src/game/entity/npc/EntityHoveringNPC.java rename to common/src/main/java/common/entity/npc/EntityHoveringNPC.java index 6a09843..a4b0887 100755 --- a/java/src/game/entity/npc/EntityHoveringNPC.java +++ b/common/src/main/java/common/entity/npc/EntityHoveringNPC.java @@ -1,9 +1,8 @@ -package game.entity.npc; +package common.entity.npc; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; -import game.packet.CPacketAction; -import game.world.World; +import common.entity.types.EntityLiving; +import common.packet.CPacketAction; +import common.world.World; public abstract class EntityHoveringNPC extends EntityNPC { @@ -30,11 +29,13 @@ public abstract class EntityHoveringNPC extends EntityNPC // { // return true; // } - - protected void applyEntityAttributes() - { - super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.FOLLOW_RANGE).setBaseValue(32.0D); + + public int getPathingRange() { + return 32; + } + + public boolean isSneakingVisually() { + return false; } public boolean isHovering() @@ -98,11 +99,11 @@ public abstract class EntityHoveringNPC extends EntityNPC { if (flag) { - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.START_HOVER)); + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.START_HOVER)); } else { - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.STOP_HOVER)); + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.STOP_HOVER)); } this.serverHoverState = flag; @@ -113,10 +114,10 @@ public abstract class EntityHoveringNPC extends EntityNPC public void onLivingUpdate() { - if(this.sendQueue != null) { - if(this.gm.jump && this.gm.sprint && this.gm.moveForward == 0.0f && this.gm.moveStrafe == 0.0f) + if(this.client != null) { + if(this.client.isJumping() && this.client.isSprinting() && this.client.getMoveForward() == 0.0f && this.client.getMoveStrafe() == 0.0f) this.setHovering(true); - if(this.isFlying() || (!this.gm.jump && this.gm.sneak && this.onGround)) + if(this.isFlying() || (!this.client.isJumping() && this.client.isSneaking() && this.onGround)) this.setHovering(false); } if (!this.onGround && this.motionY < 0.0D && (!this.isPlayer() || (!this.isFlying() && this.isHovering() && !this.jumping))) diff --git a/java/src/game/entity/npc/EntityHuman.java b/common/src/main/java/common/entity/npc/EntityHuman.java similarity index 84% rename from java/src/game/entity/npc/EntityHuman.java rename to common/src/main/java/common/entity/npc/EntityHuman.java index 18af6a7..77a4d3d 100755 --- a/java/src/game/entity/npc/EntityHuman.java +++ b/common/src/main/java/common/entity/npc/EntityHuman.java @@ -1,17 +1,17 @@ -package game.entity.npc; +package common.entity.npc; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.item.ItemStack; -import game.properties.IStringSerializable; -import game.rng.Random; -import game.village.Village; -import game.world.BlockPos; -import game.world.World; -import game.world.WorldServer; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.item.ItemStack; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Identifyable; +import common.village.Village; +import common.world.World; +import common.world.AWorldServer; public class EntityHuman extends EntityNPC { - public static enum ClassType implements IStringSerializable { + public static enum ClassType implements Identifyable { NONE("none", ""), KNIGHT("knight", "Krieger"), PEASANT("peasant", "Bauer"), @@ -111,10 +111,10 @@ public class EntityHuman extends EntityNPC { protected void updateAITasks() { if(--this.checkTimer <= 0) { BlockPos blockpos = new BlockPos(this); -// if(((WorldServer)this.worldObj).isPrimary()) - ((WorldServer)this.worldObj).addToVillagerPositionList(blockpos); +// if(((IWorldServer)this.worldObj).isPrimary()) + ((AWorldServer)this.worldObj).addToVillagerPositionList(blockpos); this.checkTimer = this.rand.excl(70, 120); - this.village = ((WorldServer)this.worldObj).getNearestVillage(blockpos, 32); + this.village = ((AWorldServer)this.worldObj).getNearestVillage(blockpos, 32); if(this.village == null) { this.detachHome(); diff --git a/java/src/game/entity/npc/EntityMage.java b/common/src/main/java/common/entity/npc/EntityMage.java similarity index 82% rename from java/src/game/entity/npc/EntityMage.java rename to common/src/main/java/common/entity/npc/EntityMage.java index 691d82f..4811eb2 100755 --- a/java/src/game/entity/npc/EntityMage.java +++ b/common/src/main/java/common/entity/npc/EntityMage.java @@ -1,17 +1,15 @@ -package game.entity.npc; +package common.entity.npc; import java.util.List; -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.Attributes; -import game.entity.effect.EntityLightning; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.item.ItemStack; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.rng.Random; -import game.world.World; +import common.entity.effect.EntityLightning; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.item.ItemStack; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.rng.Random; +import common.world.World; public class EntityMage extends EntityNPC { @@ -29,7 +27,7 @@ public class EntityMage extends EntityNPC public void onLivingUpdate() { - if (!this.worldObj.client) + if (!this.worldObj.client && !this.isPlayer()) { if (this.drinking) { @@ -47,12 +45,15 @@ public class EntityMage extends EntityNPC { for (PotionEffect potioneffect : list) { - this.addEffect(new PotionEffect(potioneffect)); + if(potioneffect.getPotion().isInstant()) + potioneffect.getPotion().onImpact(null, null, this, potioneffect.getAmplifier(), 1.0); + else + this.addEffect(new PotionEffect(potioneffect)); } } } - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).removeModifier(Attributes.MAGE_POTSPEED_MOD); + this.setSpeedMod(1.0f); } } else @@ -86,9 +87,7 @@ public class EntityMage extends EntityNPC this.setItem(0, new ItemStack(Items.potion, 1, i)); this.attackTimer = this.getHeldItem().getMaxItemUseDuration(); this.drinking = true; - AttributeInstance iattributeinstance = this.getEntityAttribute(Attributes.MOVEMENT_SPEED); - iattributeinstance.removeModifier(Attributes.MAGE_POTSPEED_MOD); - iattributeinstance.applyModifier(Attributes.MAGE_POTSPEED_MOD); + this.setSpeedMod(0.165f); } else if(this.rand.chance(80)) { boolean far = this.getAttackTarget() != null && this.getAttackTarget().getDistanceSqToEntity(this) >= 256.0; diff --git a/java/src/game/entity/npc/EntityMagma.java b/common/src/main/java/common/entity/npc/EntityMagma.java similarity index 97% rename from java/src/game/entity/npc/EntityMagma.java rename to common/src/main/java/common/entity/npc/EntityMagma.java index 8d6e679..3610e17 100755 --- a/java/src/game/entity/npc/EntityMagma.java +++ b/common/src/main/java/common/entity/npc/EntityMagma.java @@ -1,7 +1,7 @@ -package game.entity.npc; +package common.entity.npc; -import game.renderer.particle.ParticleType; -import game.world.World; +import common.model.ParticleType; +import common.world.World; public class EntityMagma extends EntitySlime { diff --git a/java/src/game/entity/npc/EntityMetalhead.java b/common/src/main/java/common/entity/npc/EntityMetalhead.java similarity index 89% rename from java/src/game/entity/npc/EntityMetalhead.java rename to common/src/main/java/common/entity/npc/EntityMetalhead.java index 0113cbe..0de0841 100755 --- a/java/src/game/entity/npc/EntityMetalhead.java +++ b/common/src/main/java/common/entity/npc/EntityMetalhead.java @@ -1,11 +1,11 @@ -package game.entity.npc; +package common.entity.npc; -import game.init.ItemRegistry; -import game.init.MetalType; -import game.item.ItemMetal; -import game.item.ItemStack; -import game.rng.Random; -import game.world.World; +import common.init.ItemRegistry; +import common.init.MetalType; +import common.item.ItemMetal; +import common.item.ItemStack; +import common.rng.Random; +import common.world.World; public class EntityMetalhead extends EntityNPC { public EntityMetalhead(World worldIn) { diff --git a/java/src/game/entity/npc/EntityMobNPC.java b/common/src/main/java/common/entity/npc/EntityMobNPC.java similarity index 89% rename from java/src/game/entity/npc/EntityMobNPC.java rename to common/src/main/java/common/entity/npc/EntityMobNPC.java index 2a39783..a8f1be8 100755 --- a/java/src/game/entity/npc/EntityMobNPC.java +++ b/common/src/main/java/common/entity/npc/EntityMobNPC.java @@ -1,13 +1,11 @@ -package game.entity.npc; +package common.entity.npc; -import game.ai.EntityAIHurtByTarget; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; -import game.nbt.NBTTagCompound; -import game.world.World; +import common.ai.EntityAIHurtByTarget; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.tags.TagObject; +import common.world.World; public abstract class EntityMobNPC extends EntityNPC { @@ -62,20 +60,15 @@ public abstract class EntityMobNPC extends EntityNPC protected void updateAITasks() { - AttributeInstance iattributeinstance = this.getEntityAttribute(Attributes.MOVEMENT_SPEED); - if (this.isAngry()) { - if (/* !this.isChild() && */ !iattributeinstance.hasModifier(Attributes.RUSHING_SPEED_MOD)) - { - iattributeinstance.applyModifier(Attributes.RUSHING_SPEED_MOD); - } + this.setSpeedMod(1.05f); --this.angerLevel; } - else if (iattributeinstance.hasModifier(Attributes.RUSHING_SPEED_MOD)) + else { - iattributeinstance.removeModifier(Attributes.RUSHING_SPEED_MOD); + this.setSpeedMod(1.0f); } // if (this.randomSoundDelay > 0 && --this.randomSoundDelay == 0) @@ -107,9 +100,9 @@ public abstract class EntityMobNPC extends EntityNPC /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); + super.writeEntity(tagCompound); tagCompound.setShort("Anger", (short)this.angerLevel); // if (this.angerTarget != null) @@ -125,9 +118,9 @@ public abstract class EntityMobNPC extends EntityNPC /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); + super.readEntity(tagCompund); this.angerLevel = tagCompund.getShort("Anger"); // String s = tagCompund.getString("HurtBy"); // diff --git a/java/src/game/entity/npc/EntityNPC.java b/common/src/main/java/common/entity/npc/EntityNPC.java similarity index 81% rename from java/src/game/entity/npc/EntityNPC.java rename to common/src/main/java/common/entity/npc/EntityNPC.java index 5d53a6a..74452db 100755 --- a/java/src/game/entity/npc/EntityNPC.java +++ b/common/src/main/java/common/entity/npc/EntityNPC.java @@ -1,116 +1,103 @@ -package game.entity.npc; +package common.entity.npc; import java.lang.reflect.InvocationTargetException; import java.util.List; - import java.util.function.Predicate; -import game.Game; -import game.ai.AIRangedAttack; -import game.ai.EntityAIAttackOnCollide; -import game.ai.EntityAIAvoidEntity; -import game.ai.EntityAIHurtByTarget; -import game.ai.EntityAILookAtTalkingPlayer; -import game.ai.EntityAINagPlayer; -import game.ai.EntityAINearestAttackableTarget; -import game.ai.EntityAINpcInteract; -import game.ai.EntityAINpcMate; -import game.ai.EntityAIOpenDoor; -import game.ai.EntityAIPlay; -import game.ai.EntityAISwimming; -import game.ai.EntityAIWander; -import game.ai.EntityAIWatchClosest; -import game.ai.EntityAIWatchClosest2; -import game.audio.MovingSoundMinecartRiding; -import game.block.Block; -import game.block.BlockBed; -import game.dimension.Space; -import game.enchantment.Enchantment; -import game.enchantment.EnchantmentHelper; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.animal.EntityDragonPart; -import game.entity.animal.EntityHorse; -import game.entity.animal.EntityPig; -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.Attributes; -import game.entity.item.EntityBoat; -import game.entity.item.EntityCart; -import game.entity.item.EntityItem; -import game.entity.projectile.EntityArrow; -import game.entity.projectile.EntityBullet; -import game.entity.projectile.EntityHook; -import game.entity.projectile.EntityPotion; -import game.entity.projectile.EntitySnowball; -import game.entity.types.EntityLiving; -import game.entity.types.IEntityMultiPart; -import game.gui.container.GuiBrewing; -import game.gui.container.GuiChest; -import game.gui.container.GuiCrafting; -import game.gui.container.GuiDispenser; -import game.gui.container.GuiEnchant; -import game.gui.container.GuiFurnace; -import game.gui.container.GuiHopper; -import game.gui.container.GuiHorse; -import game.gui.container.GuiMerchant; -import game.gui.container.GuiRepair; -import game.gui.ingame.GuiSign; -import game.init.Config; -import game.init.ItemRegistry; -import game.init.Items; -import game.init.NameRegistry; -import game.init.SoundEvent; -import game.init.SpeciesRegistry; -import game.init.SpeciesRegistry.ModelType; -import game.init.TradeRegistry; -import game.inventory.Container; -import game.inventory.ContainerPlayer; -import game.inventory.IInventory; -import game.inventory.InventoryBasic; -import game.inventory.InventoryPlayer; -import game.inventory.InventoryWarpChest; -import game.item.Item; -import game.item.ItemAction; -import game.item.ItemArmor; -import game.item.ItemBow; -import game.item.ItemGunBase; -import game.item.ItemHoe; -import game.item.ItemShears; -import game.item.ItemStack; -import game.item.ItemSword; -import game.item.ItemTool; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.network.ClientPlayer; -import game.network.Player; -import game.packet.CPacketAction; -import game.packet.CPacketBreak; -import game.packet.CPacketInput; -import game.packet.CPacketPlayer; -import game.packet.SPacketEntityEquipment; -import game.packet.SPacketEntityVelocity; -import game.pathfinding.PathNavigateGround; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.renderer.layers.LayerExtra; -import game.renderer.particle.ParticleType; -import game.renderer.texture.EntityTexManager; -import game.rng.Random; -import game.tileentity.IInteractionObject; -import game.tileentity.LockCode; -import game.tileentity.TileEntitySign; -import game.util.ExtMath; -import game.village.MerchantRecipeList; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.PortalType; -import game.world.Vec3; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldPos; -import game.world.WorldServer; +import common.ai.AIRangedAttack; +import common.ai.EntityAIAttackOnCollide; +import common.ai.EntityAIAvoidEntity; +import common.ai.EntityAIHurtByTarget; +import common.ai.EntityAILookAtTalkingPlayer; +import common.ai.EntityAINagPlayer; +import common.ai.EntityAINearestAttackableTarget; +import common.ai.EntityAINpcInteract; +import common.ai.EntityAINpcMate; +import common.ai.EntityAIOpenDoor; +import common.ai.EntityAIPlay; +import common.ai.EntityAISwimming; +import common.ai.EntityAIWander; +import common.ai.EntityAIWatchClosest; +import common.ai.EntityAIWatchClosest2; +import common.attributes.UsageSlot; +import common.block.Block; +import common.block.artificial.BlockBed; +import common.collect.Lists; +import common.color.TextColor; +import common.dimension.Space; +import common.enchantment.Enchantment; +import common.enchantment.EnchantmentHelper; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.animal.EntityDragonPart; +import common.entity.animal.EntityHorse; +import common.entity.animal.EntityPig; +import common.entity.item.EntityCart; +import common.entity.item.EntityItem; +import common.entity.projectile.EntityArrow; +import common.entity.projectile.EntityBullet; +import common.entity.projectile.EntityHook; +import common.entity.projectile.EntityPotion; +import common.entity.projectile.EntitySnowball; +import common.entity.types.EntityLiving; +import common.entity.types.IEntityMultiPart; +import common.init.ItemRegistry; +import common.init.Items; +import common.init.NameRegistry; +import common.init.SoundEvent; +import common.init.SpeciesRegistry; +import common.init.TradeRegistry; +import common.init.SpeciesRegistry.ModelType; +import common.inventory.Container; +import common.inventory.ContainerPlayer; +import common.inventory.IInventory; +import common.inventory.InventoryBasic; +import common.inventory.InventoryPlayer; +import common.inventory.InventoryWarpChest; +import common.item.Item; +import common.item.ItemAction; +import common.item.ItemArmor; +import common.item.ItemBow; +import common.item.ItemGunBase; +import common.item.ItemHoe; +import common.item.ItemShears; +import common.item.ItemStack; +import common.item.ItemSword; +import common.item.ItemTool; +import common.model.ParticleType; +import common.network.IClientPlayer; +import common.network.IPlayer; +import common.packet.CPacketPlayerPosition; +import common.packet.CPacketPlayerLook; +import common.packet.CPacketPlayerPosLook; +import common.packet.CPacketAction; +import common.packet.CPacketBreak; +import common.packet.CPacketInput; +import common.packet.CPacketPlayer; +import common.packet.SPacketEntityEquipment; +import common.packet.SPacketEntityVelocity; +import common.pathfinding.PathNavigateGround; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.rng.Random; +import common.sound.MovingSoundMinecartRiding; +import common.tags.TagObject; +import common.tileentity.IInteractionObject; +import common.tileentity.Passcode; +import common.tileentity.TileEntitySign; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Facing; +import common.util.PortalType; +import common.util.Vec3; +import common.util.WorldPos; +import common.vars.Vars; +import common.village.MerchantRecipeList; +import common.world.AWorldClient; +import common.world.World; +import common.world.AWorldServer; public abstract class EntityNPC extends EntityLiving { @@ -199,9 +186,9 @@ public abstract class EntityNPC extends EntityLiving private int healTimer; private byte[] skin; - public Player connection; - public ClientPlayer sendQueue; - protected Game gm; + public IPlayer connection; + public IClientPlayer client; + protected boolean slave; public InventoryPlayer inventory; protected InventoryWarpChest warpChest; @@ -221,11 +208,10 @@ public abstract class EntityNPC extends EntityLiving public double chasingPosZ; private WorldPos originPos = new WorldPos(0, 64, 0, Space.INSTANCE.getDimensionId()); private WorldPos spawnPos; -// private BlockPos startMinecartRidingCoordinate; public int experienceLevel; public int experienceTotal; public float experience; - protected int xpSeed; + protected int enchSeed; private ItemStack itemInUse; private int itemInUseCount; protected float speedInAir = 0.02F; @@ -258,8 +244,8 @@ public abstract class EntityNPC extends EntityLiving public float prevRenderArmPitch; private int horseJumpPowerCounter; private float horseJumpPower; -// public float nausea; -// public float prevNausea; + private long movedDistance; + private int attackDamageBase = 2; public EntityNPC(World worldIn) { @@ -397,31 +383,31 @@ public abstract class EntityNPC extends EntityLiving this.fireResistance = 20; this.noPickup = true; // this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(1.0D); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(this.getEntityAttribute(Attributes.MOVEMENT_SPEED).getBaseValue() / 3.0); // 0.10000000149011612D); +// this.getEntityAttribute(Attribute.MOVEMENT_SPEED).setBaseValue(this.getEntityAttribute(Attribute.MOVEMENT_SPEED).getBaseValue() / 3.0); // 0.10000000149011612D); } - public final void setServerPlayer(Player connection) { + public final void setServerPlayer(IPlayer connection) { this.initPlayer(); this.connection = connection; this.stepHeight = 0.0F; } - public final void setClientPlayer(Game gm, ClientPlayer connection) { + public final void setClientPlayer(IClientPlayer connection) { this.initPlayer(); - this.gm = gm; - this.sendQueue = connection; + this.slave = true; + this.client = connection; } - public final void setOtherPlayer(Game gm) { + public final void setOtherPlayer() { this.initPlayer(); - this.gm = gm; + this.slave = true; this.stepHeight = 0.0F; this.noClip = true; this.renderDistWeight = 10.0D; } public final boolean isPlayer() { - return this.connection != null || this.gm != null; + return this.connection != null || this.slave; } @@ -452,8 +438,8 @@ public abstract class EntityNPC extends EntityLiving public boolean shouldFlee(EntityLiving entity) { return (this.getHealth() <= (this.getMaxHealth() / 4) || !this.canCounter(entity)) && - ((entity instanceof EntityNPC && (((EntityNPC)entity).canAttack(this)) || - (entity == this.getAttackedBy() && ((EntityNPC)entity).canCounter(this)))); + ((entity instanceof EntityNPC && ((((EntityNPC)entity).canAttack(this)) || + (entity == this.getAttackedBy() && ((EntityNPC)entity).canCounter(this))))); } // public void setCombatTask() @@ -557,13 +543,19 @@ public abstract class EntityNPC extends EntityLiving protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.FOLLOW_RANGE).setBaseValue(20.0D); - this.getAttributeMap().registerAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(2.0D); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.3D); + this.setSpeedBase(0.3f); this.setMaxHealth(this.getBaseHealth(this.rand)); - this.getAttributeMap().registerAttribute(Attributes.MANA_CAPACITY); - this.getEntityAttribute(Attributes.MANA_CAPACITY).setBaseValue(20.0D); + if(this.canUseMagic()) + this.setMaxMana(20); } + + public int getPathingRange() { + return 20; + } + + public boolean isPotionApplicable(Potion potion, int amplifier) { + return true; + } // protected int getExperiencePoints(EntityNPC player) // { @@ -574,9 +566,9 @@ public abstract class EntityNPC extends EntityLiving { // if (!player.creative) // { - --stack.stackSize; + --stack.size; - if (stack.stackSize <= 0) + if (stack.size <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } @@ -607,7 +599,7 @@ public abstract class EntityNPC extends EntityLiving { super.onLivingUpdate(); - if(!this.worldObj.client && /* this.canPickUpLoot() && */ !this.noPickup && Config.mobGrief) { + if(!this.worldObj.client && /* this.canPickUpLoot() && */ !this.noPickup && Vars.mobGrief) { for(EntityItem entityitem : this.worldObj.getEntitiesWithinAABB(EntityItem.class, this.getEntityBoundingBox().expand(1.0D, 0.0D, 1.0D))) { if(!entityitem.dead && entityitem.getEntityItem() != null && !entityitem.cannotPickup()) { this.updateEquipmentIfNeeded(entityitem); @@ -692,9 +684,9 @@ public abstract class EntityNPC extends EntityLiving public boolean attackEntityAsMob(Entity entityIn) { - if(!this.worldObj.client && !Config.damageMobs) + if(!this.worldObj.client && !Vars.damageMobs) return false; - int f = (int)this.getEntityAttribute(Attributes.ATTACK_DAMAGE).getAttributeValue(); + int f = this.getAttackDamage(); int i = 0; if (entityIn instanceof EntityLiving) @@ -734,8 +726,8 @@ public abstract class EntityNPC extends EntityLiving return; if(stack.getItem() == Items.bow) { EntityArrow entityarrow = new EntityArrow(this.worldObj, this, target, 1.6F, 2.0f); - int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, this.getHeldItem()); - int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, this.getHeldItem()); + int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.POWER, this.getHeldItem()); + int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.PUNCH, this.getHeldItem()); entityarrow.setDamage((double)(range * 2.0F) + this.rand.gaussian() * 0.25D + (double)(/* (float)this.worldObj.getDifficulty().getId() */ 3.0f * 0.11F)); if (i > 0) @@ -748,7 +740,7 @@ public abstract class EntityNPC extends EntityLiving entityarrow.setKnockbackStrength(j); } - if (EnchantmentHelper.getEnchantmentLevel(Enchantment.flame.effectId, this.getHeldItem()) > 0) + if (EnchantmentHelper.getEnchantmentLevel(Enchantment.FLAME, this.getHeldItem()) > 0) { entityarrow.setFire(100); } @@ -758,7 +750,7 @@ public abstract class EntityNPC extends EntityLiving } else if(stack.getItem() instanceof ItemGunBase) { EntityBullet bullet = new EntityBullet(this.worldObj, this, target, ((ItemGunBase)stack.getItem()).getVelocity(), 0.75f); - int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, this.getHeldItem()); + int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.POWER, this.getHeldItem()); // int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, this.getHeldItem()); bullet.setDamage(((ItemGunBase)stack.getItem()).getAmmo().getDamage(stack)); @@ -847,12 +839,12 @@ public abstract class EntityNPC extends EntityLiving public void setChar(String character) { - this.dataWatcher.updateObject(16, character); + this.dataWatcher.updateObject(9, character); } public String getChar() { - return this.dataWatcher.getWatchableObjectString(16); + return this.dataWatcher.getWatchableObjectString(9); } public void setCape(String cape) @@ -867,12 +859,12 @@ public abstract class EntityNPC extends EntityLiving public void setNpcClass(Enum type) { - this.dataWatcher.updateObject(22, (byte)(type == null ? -1 : type.ordinal())); + this.dataWatcher.updateObject(10, (byte)(type == null ? -1 : type.ordinal())); } public Enum getNpcClass() { - byte n = this.dataWatcher.getWatchableObjectByte(22); + byte n = this.dataWatcher.getWatchableObjectByte(10); return n < 0 || this.species == null || this.species.classEnum == null ? null : this.species.classEnum.getEnumConstants()[n % this.species.classEnum.getEnumConstants().length]; } @@ -880,22 +872,22 @@ public abstract class EntityNPC extends EntityLiving public void setAlignment(Alignment align) { this.alignment = align; - this.dataWatcher.updateObject(18, (byte)align.ordinal()); + this.dataWatcher.updateObject(8, (byte)align.ordinal()); } public Alignment getAlignment() { - return Alignment.values()[this.dataWatcher.getWatchableObjectByte(18) % Alignment.values().length]; + return Alignment.values()[this.dataWatcher.getWatchableObjectByte(8) % Alignment.values().length]; } public void setHeight(float height) { - this.dataWatcher.updateObject(29, ExtMath.clampf(height, 0.2f, 10.0f)); + this.dataWatcher.updateObject(11, ExtMath.clampf(height, 0.2f, 10.0f)); } public float getHeight() { - return this.dataWatcher.getWatchableObjectFloat(29); + return this.dataWatcher.getWatchableObjectFloat(11); } public SpeciesInfo getSpecies() { @@ -905,7 +897,7 @@ public abstract class EntityNPC extends EntityLiving public void setAttackedBy(EntityLiving livingBase) { if(livingBase != null && /* livingBase.isPlayer() && */ this.isEntityAlive() && /* !this.isPeaceful() && */ this.getAttackedBy() != livingBase && - Config.mobAttacks) { + Vars.mobAttacks && !this.isPlayer()) { this.worldObj.setEntityState(this, (byte)13); } super.setAttackedBy(livingBase); @@ -1072,11 +1064,6 @@ public abstract class EntityNPC extends EntityLiving // { // return this.getChar().startsWith("~"); // } - - public String getLocationCape() - { - return !this.getCape().isEmpty() ? EntityTexManager.getCape(this.getCape()) : null; - } // public boolean canRenderExtras() // { @@ -1093,11 +1080,11 @@ public abstract class EntityNPC extends EntityLiving } public int getManaPoints() { - return this.dataWatcher.getWatchableObjectInt(21); + return this.dataWatcher.getWatchableObjectInt(14); } public void setManaPoints(int pts) { - this.dataWatcher.updateObject(21, pts); + this.dataWatcher.updateObject(14, pts); } // public final boolean isAggressive() { @@ -1203,8 +1190,21 @@ public abstract class EntityNPC extends EntityLiving // return air; // } - public int getMaxMana() { - return (int)this.getEntityAttribute(Attributes.MANA_CAPACITY).getAttributeValue(); + public final int getMaxMana() { + return this.dataWatcher.getWatchableObjectInt(13); + } + + public final void setMaxMana(int mana) { + this.dataWatcher.updateObject(13, mana); + } + + public void healMana(int amount) { + if(this.client == null) + this.setManaPoints(ExtMath.clampi(this.getManaPoints() + amount, 0, this.getMaxMana())); + } + + public String formatStats() { + return super.formatStats() + (this.getManaPoints() == 0 ? "" : TextColor.GRAY + " [" + TextColor.MIDNIGHT + this.getManaPoints() + TextColor.GRAY + "]"); } public MerchantRecipeList getTrades(EntityNPC player) { @@ -1294,14 +1294,14 @@ public abstract class EntityNPC extends EntityLiving } else { this.worldObj.playAuxSFX(1013, new BlockPos(ox, oy, oz), 0); - ((WorldServer)this.worldObj).spawnParticle(ParticleType.PORTAL, + ((AWorldServer)this.worldObj).spawnParticle(ParticleType.PORTAL, ox + (this.rand.doublev() - 0.5D) * (double)this.width * 2.0D, oy + this.rand.doublev() * (double)this.height, oz + (this.rand.doublev() - 0.5D) * (double)this.width * 2.0D, 8, (this.rand.floatv() - 0.5F) * 0.2F, (this.rand.floatv() - 0.5F) * 0.2F, (this.rand.floatv() - 0.5F) * 0.2F, 0.15D); this.worldObj.playAuxSFX(1005, this.getPosition(), 0); - ((WorldServer)this.worldObj).spawnParticle(ParticleType.PORTAL, + ((AWorldServer)this.worldObj).spawnParticle(ParticleType.PORTAL, this.posX + (this.rand.doublev() - 0.5D) * (double)this.width * 2.0D, this.posY + this.rand.doublev() * (double)this.height, this.posZ + (this.rand.doublev() - 0.5D) * (double)this.width * 2.0D, 8, @@ -1462,7 +1462,7 @@ public abstract class EntityNPC extends EntityLiving } else { - stack.stackSize = remain.stackSize; + stack.size = remain.size; } } } @@ -1697,16 +1697,16 @@ public abstract class EntityNPC extends EntityLiving if (!ItemStack.areItemStacksEqual(itemstack1, itemstack)) { - ((WorldServer)this.worldObj).sendToAllTrackingEntity(this, new SPacketEntityEquipment(this.getId(), j, itemstack1)); + ((AWorldServer)this.worldObj).sendToAllTrackingEntity(this, new SPacketEntityEquipment(this.getId(), j, itemstack1)); if (itemstack != null) { - this.getAttributeMap().removeAttributeModifiers(itemstack.getAttributeModifiers(1)); + this.attributes.remove(itemstack.getAttributeModifiers(UsageSlot.getByIndex(j)), -1 - j); } if (itemstack1 != null) { - this.getAttributeMap().applyAttributeModifiers(itemstack1.getAttributeModifiers(1)); + this.attributes.add(itemstack1.getAttributeModifiers(UsageSlot.getByIndex(j)), -1 - j, itemstack1.size); } this.prevEquipment[j] = itemstack1 == null ? null : itemstack1.copy(); @@ -1714,7 +1714,7 @@ public abstract class EntityNPC extends EntityLiving } } super.onUpdate(); - if(!this.worldObj.client && Config.regeneration && this.shouldHeal()) { + if(!this.worldObj.client && Vars.regeneration && this.shouldHeal()) { ++this.healTimer; if(this.healTimer >= 80) { @@ -1733,8 +1733,8 @@ public abstract class EntityNPC extends EntityLiving // } protected boolean shouldHeal() { - return this.canRegenerateHealth() && Config.healChance > 0 && this.getHealth() > 0 && this.getHealth() < this.getMaxHealth() - && this.rand.chance(Config.healChance); + return this.canRegenerateHealth() && Vars.healChance > 0 && this.getHealth() > 0 && this.getHealth() < this.getMaxHealth() + && this.rand.chance(Vars.healChance); } public byte[] getSkin() { @@ -1755,8 +1755,8 @@ public abstract class EntityNPC extends EntityLiving public boolean attackEntityFrom(DamageSource source, int amount) { - if(this.gm != null) - return this.sendQueue == null; + if(this.slave) + return this.client == null; // if(this.isEntityInvulnerable(source)) // return false; if(this.connection != null) { @@ -1779,15 +1779,9 @@ public abstract class EntityNPC extends EntityLiving */ public void heal(int healAmount) { - if(this.sendQueue == null) + if(this.client == null) super.heal(healAmount); } - - public void healMana(int amount) - { - if(this.sendQueue == null) - super.healMana(amount); - } /** * Called when a player mounts an entity. e.g. mounts a pig, mounts a boat. @@ -1800,9 +1794,9 @@ public abstract class EntityNPC extends EntityLiving this.connection.mountEntity(entityIn); // super.mountEntity(entityIn); - if (this.sendQueue != null && entityIn instanceof EntityCart) + if (this.client != null && entityIn instanceof EntityCart) { - this.gm.getSoundManager().playSound(new MovingSoundMinecartRiding(this, (EntityCart)entityIn)); + this.client.playSound(new MovingSoundMinecartRiding(this, (EntityCart)entityIn)); } } @@ -1811,7 +1805,7 @@ public abstract class EntityNPC extends EntityLiving */ public void onUpdate() { - if(this.sendQueue != null) { + if(this.client != null) { if (this.worldObj.isBlockLoaded(new BlockPos(this.posX, 0.0D, this.posZ))) { // super.onUpdate(); @@ -1819,8 +1813,8 @@ public abstract class EntityNPC extends EntityLiving if (this.isRiding()) { - this.sendQueue.addToSendQueue(new CPacketPlayer.C05PacketPlayerLook(this.rotYaw, this.rotPitch, this.onGround)); - this.sendQueue.addToSendQueue(new CPacketInput(this.moveStrafe, this.moveForward, this.gm.jump, this.gm.sneak)); + this.client.addToSendQueue(new CPacketPlayerLook(this.rotYaw, this.rotPitch, this.onGround)); + this.client.addToSendQueue(new CPacketInput(this.moveStrafe, this.moveForward, this.client.isJumping(), this.client.isSneaking())); } else { @@ -1835,7 +1829,7 @@ public abstract class EntityNPC extends EntityLiving return; } - if(this.gm != null) { + if(this.slave) { // this.renderOffsetY = 0.0F; // super.onUpdate(); this.updatePlayer(); @@ -1985,12 +1979,12 @@ public abstract class EntityNPC extends EntityLiving */ public EntityItem dropOneItem(boolean dropAll) { - if(this.sendQueue != null) { + if(this.client != null) { CPacketBreak.Action c07packetplayerdigging$action = dropAll ? CPacketBreak.Action.DROP_ALL_ITEMS : CPacketBreak.Action.DROP_ITEM; - this.sendQueue.addToSendQueue(new CPacketBreak(c07packetplayerdigging$action, BlockPos.ORIGIN, Facing.DOWN)); + this.client.addToSendQueue(new CPacketBreak(c07packetplayerdigging$action, BlockPos.ORIGIN, Facing.DOWN)); return null; } - return this.dropItem(this.inventory.decrStackSize(this.inventory.currentItem, dropAll && this.inventory.getCurrentItem() != null ? this.inventory.getCurrentItem().stackSize : 1), false, true); + return this.dropItem(this.inventory.decrStackSize(this.inventory.currentItem, dropAll && this.inventory.getCurrentItem() != null ? this.inventory.getCurrentItem().size : 1), false, true); } /** @@ -1998,13 +1992,13 @@ public abstract class EntityNPC extends EntityLiving */ protected void joinEntityItemWithWorld(EntityItem itemIn) { - if(this.sendQueue == null) + if(this.client == null) this.worldObj.spawnEntityInWorld(itemIn); } protected void changeSize(float width, float height) { super.changeSize(width, height); - if(this.sendQueue != null) + if(this.client != null) this.stepHeight = height / 3.0f; } @@ -2014,8 +2008,8 @@ public abstract class EntityNPC extends EntityLiving public void swingItem() { super.swingItem(); - if(this.sendQueue != null) - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.SWING_ARM)); + if(this.client != null) + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.SWING_ARM)); } /** @@ -2024,7 +2018,7 @@ public abstract class EntityNPC extends EntityLiving */ protected void damageEntity(DamageSource damageSrc, int damageAmount) { - if(this.sendQueue != null) { + if(this.client != null) { // if(!this.isEntityInvulnerable(damageSrc)) this.setHealth(this.getHealth() - damageAmount); return; @@ -2069,19 +2063,13 @@ public abstract class EntityNPC extends EntityLiving { if(this.connection != null) this.connection.closeScreen(); - else if(this.sendQueue != null) { -// this.setScreenClosed(); -// this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.CLOSE_CONTAINER)); // , this.openContainer.windowId)); -// this.closeScreenAndDropStack(); - this.gm.displayGuiScreen(null); - } else this.openContainer = this.inventoryContainer; } public void setScreenClosed() { - if(this.sendQueue != null) { - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.CLOSE_CONTAINER, this.openContainer.windowId)); + if(this.client != null) { + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.CLOSE_CONTAINER, this.openContainer.windowId)); this.inventory.setItemStack((ItemStack)null); this.openContainer = this.inventoryContainer; } @@ -2089,7 +2077,7 @@ public abstract class EntityNPC extends EntityLiving protected boolean pushOutOfBlocks(double x, double y, double z) { - if(this.sendQueue == null) + if(this.client == null) return super.pushOutOfBlocks(x, y, z); if (this.noClip) { @@ -2163,7 +2151,7 @@ public abstract class EntityNPC extends EntityLiving public void setSprinting(boolean sprinting) { super.setSprinting(sprinting); - if(this.sendQueue != null) + if(this.client != null) this.sprintingTicksLeft = sprinting ? 600 : 0; } @@ -2171,23 +2159,21 @@ public abstract class EntityNPC extends EntityLiving { if(this.connection != null) this.connection.playSound(name, volume); - else if(this.sendQueue != null) - ((WorldClient)this.worldObj).playSound(this.posX, this.posY, this.posZ, name, volume); - else if(this.gm == null) + else if(this.client != null) + ((AWorldClient)this.worldObj).playSound(this.posX, this.posY, this.posZ, name, volume); + else if(!this.slave) super.playSound(name, volume); } public boolean isTicked() { - return (!this.worldObj.client && (Config.mobTick || this.connection != null)) || this.sendQueue != null; + return (!this.worldObj.client && (Vars.mobTick || this.connection != null)) || this.client != null; } public void openEditSign(TileEntitySign signTile) { if(this.connection != null) this.connection.openEditSign(signTile); - else if(this.sendQueue != null) - this.gm.displayGuiScreen(new GuiSign(signTile.getPos(), signTile.signText)); } /** @@ -2214,68 +2200,18 @@ public abstract class EntityNPC extends EntityLiving { if(this.connection != null) this.connection.displayGUIChest(chestInventory); - else if(this.sendQueue != null) { - String s = chestInventory instanceof IInteractionObject ? ((IInteractionObject)chestInventory).getGuiID() : "container"; - - if ("chest".equals(s)) - { - this.gm.displayGuiScreen(new GuiChest(this.inventory, chestInventory)); - } - else if ("hopper".equals(s)) - { - this.gm.displayGuiScreen(new GuiHopper(this.inventory, chestInventory)); - } - else if ("furnace".equals(s)) - { - this.gm.displayGuiScreen(new GuiFurnace(this.inventory, chestInventory)); - } - else if ("brewing_stand".equals(s)) - { - this.gm.displayGuiScreen(new GuiBrewing(this.inventory, chestInventory)); - } -// else if ("beacon".equals(s)) -// { -// this.gm.displayGuiScreen(new GuiBeacon(this.inventory, chestInventory)); -// } - else if (!"dispenser".equals(s) && !"dropper".equals(s)) - { - this.gm.displayGuiScreen(new GuiChest(this.inventory, chestInventory)); - } - else - { - this.gm.displayGuiScreen(new GuiDispenser(this.inventory, chestInventory)); - } - } } - public void displayGUIHorse(EntityHorse horse, IInventory horseInventory) + public void displayEntityGui(Entity entity, IInventory inventory) { if(this.connection != null) - this.connection.displayGUIHorse(horse, horseInventory); - else if(this.sendQueue != null) - this.gm.displayGuiScreen(new GuiHorse(this.inventory, horseInventory, horse)); + this.connection.displayEntityGui(entity, inventory); } public void displayGui(IInteractionObject guiOwner) { if(this.connection != null) this.connection.displayGui(guiOwner); - else if(this.sendQueue != null) { - String s = guiOwner.getGuiID(); - - if ("crafting_table".equals(s)) - { - this.gm.displayGuiScreen(new GuiCrafting(this.inventory, this.worldObj)); - } - else if ("enchanting_table".equals(s)) - { - this.gm.displayGuiScreen(new GuiEnchant(this.inventory, this.worldObj, guiOwner)); - } - else if ("anvil".equals(s)) - { - this.gm.displayGuiScreen(new GuiRepair(this.inventory, this.worldObj)); - } - } } /** @@ -2285,16 +2221,16 @@ public abstract class EntityNPC extends EntityLiving { if(this.connection != null) this.connection.onCriticalHit(entityHit); - else if(this.sendQueue != null) - this.gm.effectRenderer.emitParticleAtEntity(entityHit, ParticleType.CRIT); + else if(this.client != null) + this.client.emitParticleAtEntity(entityHit, ParticleType.CRIT); } public void onEnchantmentCritical(Entity entityHit) { if(this.connection != null) this.connection.onEnchantmentCritical(entityHit); - else if(this.sendQueue != null) - this.gm.effectRenderer.emitParticleAtEntity(entityHit, ParticleType.CRIT_MAGIC); + else if(this.client != null) + this.client.emitParticleAtEntity(entityHit, ParticleType.CRIT_MAGIC); } /** @@ -2302,7 +2238,7 @@ public abstract class EntityNPC extends EntityLiving */ public boolean isSneaking() { - return this.sendQueue != null ? this.gm.sneak : super.isSneaking(); + return this.client != null ? this.client.isSneaking() : super.isSneaking(); } public void updateEntityActionState() @@ -2315,11 +2251,11 @@ public abstract class EntityNPC extends EntityLiving this.headYaw = this.rotYaw; // super.updateEntityActionState(); - if (this.sendQueue != null && this.isCurrentViewEntity()) + if (this.client != null && this.client.isRenderViewEntity(this)) { - this.moveStrafe = this.gm.moveStrafe; - this.moveForward = this.gm.moveForward; - this.jumping = this.gm.jump; + this.moveStrafe = this.client.getMoveStrafe(); + this.moveForward = this.client.getMoveForward(); + this.jumping = this.client.isJumping(); this.prevRenderArmYaw = this.renderArmYaw; this.prevRenderArmPitch = this.renderArmPitch; this.renderArmPitch = (float)((double)this.renderArmPitch + (double)(this.rotPitch - this.renderArmPitch) * 0.5D); @@ -2333,7 +2269,7 @@ public abstract class EntityNPC extends EntityLiving */ public void onLivingUpdate() { - if(this.sendQueue != null) { + if(this.client != null) { if (this.sprintingTicksLeft > 0) { --this.sprintingTicksLeft; @@ -2399,16 +2335,16 @@ public abstract class EntityNPC extends EntityLiving // --this.portalTimer; // } - boolean flag = this.gm.jump; - boolean flag1 = this.gm.sneak; + boolean flag = this.client.isJumping(); + boolean flag1 = this.client.isSneaking(); float f = 0.8F; - boolean flag2 = this.gm.moveForward >= f; - this.gm.updatePlayerMoveState(); + boolean flag2 = this.client.getMoveForward() >= f; + this.client.updatePlayerMoveState(); if (this.isUsingItem() && !this.isRiding()) { - this.gm.moveStrafe *= 0.2F; - this.gm.moveForward *= 0.2F; + this.client.setMoveStrafe(this.client.getMoveStrafe() * 0.2F); + this.client.setMoveForward(this.client.getMoveForward() * 0.2F); this.sprintToggleTimer = 0; } @@ -2418,9 +2354,9 @@ public abstract class EntityNPC extends EntityLiving this.pushOutOfBlocks(this.posX + (double)this.width * 0.35D, this.getEntityBoundingBox().minY + 0.5D, this.posZ + (double)this.width * 0.35D); boolean canSprint = true; // (float)this.getFoodStats().getFoodLevel() > 6.0F || this.allowFlying; - if (this.onGround && !flag1 && !flag2 && this.gm.moveForward >= f && !this.isSprinting() && canSprint && !this.isUsingItem() && !this.hasEffect(Potion.BLINDNESS)) + if (this.onGround && !flag1 && !flag2 && this.client.getMoveForward() >= f && !this.isSprinting() && canSprint && !this.isUsingItem() && !this.hasEffect(Potion.BLINDNESS)) { - if (this.sprintToggleTimer <= 0 && !this.gm.sprint) + if (this.sprintToggleTimer <= 0 && !this.client.isSprinting()) { this.sprintToggleTimer = 7; } @@ -2430,12 +2366,12 @@ public abstract class EntityNPC extends EntityLiving } } - if (!this.isSprinting() && this.gm.moveForward >= f && canSprint && !this.isUsingItem() && !this.hasEffect(Potion.BLINDNESS) && this.gm.sprint) + if (!this.isSprinting() && this.client.getMoveForward() >= f && canSprint && !this.isUsingItem() && !this.hasEffect(Potion.BLINDNESS) && this.client.isSprinting()) { this.setSprinting(true); } - if (this.isSprinting() && (this.gm.moveForward < f || this.collidedHorizontally || !canSprint)) + if (this.isSprinting() && (this.client.getMoveForward() < f || this.collidedHorizontally || !canSprint)) { this.setSprinting(false); } @@ -2447,10 +2383,10 @@ public abstract class EntityNPC extends EntityLiving if (!this.flying) { this.flying = true; - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.START_FLYING)); + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.START_FLYING)); } } - else if (!flag && this.gm.jump) + else if (!flag && this.client.isJumping()) { if (this.flyToggleTimer == 0) { @@ -2459,7 +2395,7 @@ public abstract class EntityNPC extends EntityLiving else { this.flying = !this.flying; - this.sendQueue.addToSendQueue(new CPacketAction(this.flying ? + this.client.addToSendQueue(new CPacketAction(this.flying ? CPacketAction.Action.START_FLYING : CPacketAction.Action.STOP_FLYING)); this.flyToggleTimer = 0; } @@ -2470,15 +2406,15 @@ public abstract class EntityNPC extends EntityLiving } // this.firstEffectUpdate = false; - if (this.isFlying() && this.isCurrentViewEntity()) + if (this.isFlying() && this.client.isRenderViewEntity(this)) { - if (this.gm.sneak) + if (this.client.isSneaking()) { this.motionY -= (double)( this.landMovement * 0.5f * (this.canFlyFullSpeed() ? 3.0F : 1.0F)); } - if (this.gm.jump) + if (this.client.isJumping()) { this.motionY += (double)( this.landMovement * 0.5f * (this.canFlyFullSpeed() ? 3.0F : 1.0F)); @@ -2497,12 +2433,12 @@ public abstract class EntityNPC extends EntityLiving } } - if (flag && !this.gm.jump) + if (flag && !this.client.isJumping()) { this.horseJumpPowerCounter = -10; this.sendHorseJump(); } - else if (!flag && this.gm.jump) + else if (!flag && this.client.isJumping()) { this.horseJumpPowerCounter = 0; this.horseJumpPower = 0.0F; @@ -2532,12 +2468,12 @@ public abstract class EntityNPC extends EntityLiving if (this.onGround && this.flying && !this.noclip) { this.flying = false; - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.STOP_FLYING)); + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.STOP_FLYING)); } return; } - if(this.gm != null) { + if(this.slave) { if (this.otherPlayerMPPosRotationIncrements > 0) { double d0 = this.posX + (this.otherPlayerMPX - this.posX) / (double)this.otherPlayerMPPosRotationIncrements; @@ -2612,7 +2548,6 @@ public abstract class EntityNPC extends EntityLiving this.prevCameraYaw = this.cameraYaw; // super.onLivingUpdate(); this.onNpcUpdate(); - AttributeInstance iattributeinstance = this.getEntityAttribute(Attributes.MOVEMENT_SPEED); this.jumpMovement = this.speedInAir; @@ -2621,7 +2556,7 @@ public abstract class EntityNPC extends EntityLiving this.jumpMovement = (float)((double)this.jumpMovement + (double)this.speedInAir * 0.3D); } - this.setAIMoveSpeed((float)iattributeinstance.getAttributeValue()); + this.setAIMoveSpeed(this.getMovementSpeed() / 3.0f); float f = ExtMath.sqrtd(this.motionX * this.motionX + this.motionZ * this.motionZ); float f1 = (float)(Math.atan(-this.motionY * 0.20000000298023224D) * 15.0D); @@ -2689,11 +2624,11 @@ public abstract class EntityNPC extends EntityLiving { if (flag) { - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.START_SPRINTING)); + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.START_SPRINTING)); } else { - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.STOP_SPRINTING)); + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.STOP_SPRINTING)); } this.serverSprintState = flag; @@ -2705,17 +2640,17 @@ public abstract class EntityNPC extends EntityLiving { if (flag1) { - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.START_SNEAKING)); + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.START_SNEAKING)); } else { - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.STOP_SNEAKING)); + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.STOP_SNEAKING)); } this.serverSneakState = flag1; } - if (this.isCurrentViewEntity()) + if (this.client.isRenderViewEntity(this)) { double d0 = this.posX - this.lastReportedPosX; double d1 = this.getEntityBoundingBox().minY - this.lastReportedPosY; @@ -2729,24 +2664,24 @@ public abstract class EntityNPC extends EntityLiving { if (flag2 && flag3) { - this.sendQueue.addToSendQueue(new CPacketPlayer.C06PacketPlayerPosLook(this.posX, this.getEntityBoundingBox().minY, this.posZ, this.rotYaw, this.rotPitch, this.onGround)); + this.client.addToSendQueue(new CPacketPlayerPosLook(this.posX, this.getEntityBoundingBox().minY, this.posZ, this.rotYaw, this.rotPitch, this.onGround)); } else if (flag2) { - this.sendQueue.addToSendQueue(new CPacketPlayer.C04PacketPlayerPosition(this.posX, this.getEntityBoundingBox().minY, this.posZ, this.onGround)); + this.client.addToSendQueue(new CPacketPlayerPosition(this.posX, this.getEntityBoundingBox().minY, this.posZ, this.onGround)); } else if (flag3) { - this.sendQueue.addToSendQueue(new CPacketPlayer.C05PacketPlayerLook(this.rotYaw, this.rotPitch, this.onGround)); + this.client.addToSendQueue(new CPacketPlayerLook(this.rotYaw, this.rotPitch, this.onGround)); } else { - this.sendQueue.addToSendQueue(new CPacketPlayer(this.onGround)); + this.client.addToSendQueue(new CPacketPlayer(this.onGround)); } } else { - this.sendQueue.addToSendQueue(new CPacketPlayer.C06PacketPlayerPosLook(this.motionX, -999.0D, this.motionZ, this.rotYaw, this.rotPitch, this.onGround)); + this.client.addToSendQueue(new CPacketPlayerPosLook(this.motionX, -99999999.0D, this.motionZ, this.rotYaw, this.rotPitch, this.onGround)); flag2 = false; } @@ -2770,7 +2705,7 @@ public abstract class EntityNPC extends EntityLiving public void respawnPlayer() { - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.PERFORM_RESPAWN)); + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.PERFORM_RESPAWN)); } // public void closeScreenAndDropStack() @@ -2817,12 +2752,12 @@ public abstract class EntityNPC extends EntityLiving protected void sendHorseJump() { - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.RIDING_JUMP, (int)(this.getHorseJumpPower() * 100.0F))); + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.RIDING_JUMP, (int)(this.getHorseJumpPower() * 100.0F))); } public void sendHorseInventory() { - this.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.OPEN_INVENTORY)); + this.client.addToSendQueue(new CPacketAction(CPacketAction.Action.OPEN_INVENTORY)); } /** @@ -2833,9 +2768,6 @@ public abstract class EntityNPC extends EntityLiving return !this.worldObj.getState(pos).getBlock().isNormalCube() && (this.height <= 1.0f || !this.worldObj.getState(pos.up()).getBlock().isNormalCube()); } - /** - * Sets the current XP, total XP, and level number. - */ public void setXPStats(float currentXP, int maxXP, int level) { this.experience = currentXP; @@ -2853,38 +2785,30 @@ public abstract class EntityNPC extends EntityLiving return this.horseJumpPower; } - public void displayTradeGui(String title) - { - this.gm.displayGuiScreen(new GuiMerchant(this.inventory, title, this.worldObj)); - } - - protected boolean isCurrentViewEntity() - { - return this.gm.getRenderViewEntity() == this; - } + // END SP SPEC // START OTHER - public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) + public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) { - if(this.gm != null && this.sendQueue == null) { + if(this.slave && this.client == null) { this.otherPlayerMPX = x; this.otherPlayerMPY = y; this.otherPlayerMPZ = z; this.otherPlayerMPYaw = (double)yaw; this.otherPlayerMPPitch = (double)pitch; - this.otherPlayerMPPosRotationIncrements = posRotationIncrements; + this.otherPlayerMPPosRotationIncrements = 3; } else { - super.setPositionAndRotation2(x, y, z, yaw, pitch, posRotationIncrements, p_180426_10_); + super.setClientPosition(x, y, z, yaw, pitch, teleport); } } public void setItem(int slot, ItemStack stack) { - if(this.gm != null && this.sendQueue == null) { + if(this.slave && this.client == null) { if (slot == 0) this.inventory.mainInventory[this.inventory.currentItem] = stack; else @@ -2905,7 +2829,7 @@ public abstract class EntityNPC extends EntityLiving // START MP - public void addExperienceLevel(int levels) { + private void addExperienceLevel(int levels) { this.experienceLevel += levels; if (this.experienceLevel < 0) @@ -2926,20 +2850,8 @@ public abstract class EntityNPC extends EntityLiving this.connection.resetLastExperience(); } - public void removeExperienceLevel(int levels) { - this.experienceLevel -= levels; - - if (this.experienceLevel < 0) - { - this.experienceLevel = 0; - this.experience = 0.0F; - this.experienceTotal = 0; - } - - this.xpSeed = this.rand.intv(); -// super.removeExperienceLevel(levels); - if(this.connection != null) - this.connection.resetLastExperience(); + public void updateEnchSeed() { + this.enchSeed = this.rand.intv(); } public void onDeath(DamageSource cause) { @@ -2954,12 +2866,12 @@ public abstract class EntityNPC extends EntityLiving this.noPickup = true; super.onDeath(cause); - if(this.gm != null) { + if(this.slave) { this.changeSize(0.2F, 0.2F); this.setPosition(this.posX, this.posY, this.posZ); this.motionY = 0.10000000149011612D; - if (this.worldObj.client || (!Config.keepInventory && Config.playerDrop)) + if (this.worldObj.client || (!Vars.keepInventory && Vars.playerDrop)) { this.inventory.dropAllItems(); } @@ -3003,15 +2915,13 @@ public abstract class EntityNPC extends EntityLiving super.updateFallState(y, onGroundIn, blockIn, pos); } - public void addStat(int amount) { -// if(this.connection != null) -// this.connection.addStat(amount); + public void addMoved(int amount) { + this.movedDistance += (long)amount; + } + + public long getMovedDistance() { + return this.movedDistance; } - -// public void removeStat(StatBase stat) { -// if(this.connection != null) -// this.connection.removeStat(stat); -// } protected void onItemUseFinish() { if(this.connection != null) @@ -3020,14 +2930,14 @@ public abstract class EntityNPC extends EntityLiving if (this.itemInUse != null) { this.updateItemUse(this.itemInUse, 16); - int i = this.itemInUse.stackSize; + int i = this.itemInUse.size; ItemStack itemstack = this.itemInUse.onItemUseFinish(this.worldObj, this); - if (itemstack != this.itemInUse || itemstack != null && itemstack.stackSize != i) + if (itemstack != this.itemInUse || itemstack != null && itemstack.size != i) { this.inventory.mainInventory[this.inventory.currentItem] = itemstack; - if (itemstack.stackSize == 0) + if (itemstack.size == 0) { this.inventory.mainInventory[this.inventory.currentItem] = null; } @@ -3071,8 +2981,8 @@ public abstract class EntityNPC extends EntityLiving this.connection.updateEffectMeta(); } - public final WorldServer getServerWorld() { - return (WorldServer)this.worldObj; + public final AWorldServer getServerWorld() { + return (AWorldServer)this.worldObj; } public void onUpdateEntity() { @@ -3102,17 +3012,16 @@ public abstract class EntityNPC extends EntityLiving protected void entityInit() { super.entityInit(); - this.dataWatcher.addObject(16, ""); - this.dataWatcher.addObject(17, ""); - this.dataWatcher.addObject(18, Byte.valueOf((byte)Alignment.NEUTRAL.ordinal())); -// this.dataWatcher.addObject(20, Byte.valueOf((byte)0)); - this.dataWatcher.addObject(21, 0); - this.dataWatcher.addObject(22, Byte.valueOf((byte)-1)); - this.dataWatcher.addObject(29, 1.0f); -// super.entityInit(); - this.dataWatcher.addObject(30, Integer.valueOf(0)); -// this.dataWatcher.addObject(10, Integer.valueOf(~ModelPart.ARMS_SLIM.getMask())); -// this.dataWatcher.addObject(11, Byte.valueOf((byte)0)); + this.dataWatcher.addObject(8, (byte)Alignment.NEUTRAL.ordinal()); // alignment + this.dataWatcher.addObject(9, ""); // character + this.dataWatcher.addObject(10, (byte)-1); // class + this.dataWatcher.addObject(11, 1.0f); // height + this.dataWatcher.addObject(12, 0); // absorption + this.dataWatcher.addObject(13, 0); // max mana + this.dataWatcher.addObject(14, 0); // mana + this.dataWatcher.addObject(15, 0.7f); + + this.dataWatcher.addObject(17, ""); // TODO: remove capes } /** @@ -3241,7 +3150,7 @@ public abstract class EntityNPC extends EntityLiving super.updateRidden(); this.prevCameraYaw = this.cameraYaw; this.cameraYaw = 0.0F; - this.addMountedMovementStat(this.posX - d0, this.posY - d1, this.posZ - d2); + this.addMountedMovement(this.posX - d0, this.posY - d1, this.posZ - d2); if (this.vehicle instanceof EntityPig) { @@ -3270,7 +3179,7 @@ public abstract class EntityNPC extends EntityLiving } public void onDataWatcherUpdate(int data) { - if(this.isPlayer() && data == 29) // (data == 29 || data == 11)) // && this.worldObj.client) + if(this.isPlayer() && data == 11) // (data == 29 || data == 11)) // && this.worldObj.client) this.updateSize(); } @@ -3297,7 +3206,7 @@ public abstract class EntityNPC extends EntityLiving protected float getJumpUpwardsMotion() { - return 0.42F * (this.height /* this.getHeight() * 1.8f */ + 2.2f) / 4.0f; + return 0.42F * ((this.height < 1.9f ? 1.9f : this.height) /* this.getHeight() * 1.8f */ + 2.2f) / 4.0f; } public void setAIMoveSpeed(float speedIn) @@ -3326,7 +3235,7 @@ public abstract class EntityNPC extends EntityLiving { return null; } - else if (droppedItem.stackSize == 0) + else if (droppedItem.size == 0) { return null; } @@ -3438,31 +3347,44 @@ public abstract class EntityNPC extends EntityLiving { return this.inventory.canHeldItemHarvest(blockToHarvest); } + + public int getAttackDamage() { + int damage = this.attackDamageBase + (this.getHeldItem() == null ? 0 : this.getHeldItem().getItem().getAttackDamageBonus()); + return Math.max(0, damage + (this.hasEffect(Potion.STRENGTH) ? (damage / 2) * (this.getEffect(Potion.STRENGTH).getAmplifier() + 1) : 0) - (this.hasEffect(Potion.WEAKNESS) ? (damage / 5) * (this.getEffect(Potion.WEAKNESS).getAmplifier() + 1) : 0)); + } + + public int getAttackDamageBase() { + return this.attackDamageBase; + } + + public void setAttackDamageBase(int value) { + this.attackDamageBase = value; + } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { // super.readEntityFromNBT(tagCompund); - super.readEntityFromNBT(tagCompund); + super.readEntity(tagCompund); -// if(tagCompund.hasKey("CanPickUpLoot", 1)) { +// if(tagCompund.hasBoolean("CanPickUpLoot")) { // this.setCanPickUpLoot(tagCompund.getBoolean("CanPickUpLoot")); // } - if(tagCompund.hasKey("Equipment", 9)) { - NBTTagList nbttaglist = tagCompund.getTagList("Equipment", 10); + if(tagCompund.hasList("Equipment")) { + List nbttaglist = tagCompund.getList("Equipment"); for(int i = 0; i < this.equipment.length; ++i) { - this.equipment[i] = ItemStack.loadItemStackFromNBT(nbttaglist.getCompoundTagAt(i)); + this.equipment[i] = ItemStack.readFromTag(nbttaglist.get(i)); } } // this.setSpecies(tagCompund.getString("Species")); this.setChar(tagCompund.getString("Char")); this.setCape(tagCompund.getString("Cape")); - this.isWilling = tagCompund.getBoolean("Willing"); - this.setMating(tagCompund.getBoolean("Mating")); + this.isWilling = tagCompund.getBool("Willing"); + this.setMating(tagCompund.getBool("Mating")); Alignment // align; // try { align = Alignment.getByName(tagCompund.getString("Align")); @@ -3471,9 +3393,11 @@ public abstract class EntityNPC extends EntityLiving // align = this.getNaturalAlign(this.rand); // } this.setAlignment(align); - this.setManaPoints(tagCompund.getInteger("Mana")); + this.setMaxMana(Math.max(0, tagCompund.getInt("MaxMana"))); + this.setManaPoints(tagCompund.getInt("Mana")); + this.attackDamageBase = tagCompund.getInt("AttackDmg"); Enum type = null; - if(tagCompund.hasKey("ClassType", 8) && this.species != null && this.species.classEnum != null) { + if(tagCompund.hasString("ClassType") && this.species != null && this.species.classEnum != null) { type = this.species.classnames.get(tagCompund.getString("ClassType")); // try { // type = Enum.valueOf(this.species.classEnum, tagCompund.getString("ClassType").toUpperCase()); @@ -3483,13 +3407,13 @@ public abstract class EntityNPC extends EntityLiving // } } this.setNpcClass(type); - this.setHeight(tagCompund.hasKey("Height", 5) ? tagCompund.getFloat("Height") : this.getBaseSize()); + this.setHeight(tagCompund.hasFloat("Height") ? tagCompund.getFloat("Height") : this.getBaseSize()); - NBTTagList nbttaglist = tagCompund.getTagList("Items", 10); + List nbttaglist = tagCompund.getList("Items"); - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttaglist.getCompoundTagAt(i)); + ItemStack itemstack = ItemStack.readFromTag(nbttaglist.get(i)); if (itemstack != null) { @@ -3497,10 +3421,12 @@ public abstract class EntityNPC extends EntityLiving } } - if(tagCompund.hasKey("Offers", 10)) - this.trades = new MerchantRecipeList(tagCompund.getCompoundTag("Offers")); - this.healTimer = tagCompund.getInteger("healTimer"); - if(tagCompund.hasKey("Skin", 7)) + if(tagCompund.hasList("Offers")) { + this.trades = new MerchantRecipeList(); + this.trades.fromTags(tagCompund.getList("Offers")); + } + this.healTimer = tagCompund.getInt("healTimer"); + if(tagCompund.hasByteArray("Skin")) this.skin = tagCompund.getByteArray("Skin"); // this.setCanPickUpLoot(true); @@ -3508,19 +3434,19 @@ public abstract class EntityNPC extends EntityLiving if(this.isPlayer()) { // this.entityUniqueID = getOfflineUUID(this.user); - NBTTagList nbttaglist0 = tagCompund.getTagList("Inventory", 10); + List nbttaglist0 = tagCompund.getList("Inventory"); this.inventory.readFromNBT(nbttaglist0); - this.inventory.currentItem = tagCompund.getInteger("SelectedItemSlot"); + this.inventory.currentItem = tagCompund.getInt("SelectedItemSlot"); // this.sleeping = tagCompund.getBoolean("Sleeping"); // this.sleepTimer = tagCompund.getShort("SleepTimer"); this.experience = tagCompund.getFloat("XpP"); - this.experienceLevel = tagCompund.getInteger("XpLevel"); - this.experienceTotal = tagCompund.getInteger("XpTotal"); - this.xpSeed = tagCompund.getInteger("XpSeed"); + this.experienceLevel = tagCompund.getInt("XpLevel"); + this.experienceTotal = tagCompund.getInt("XpTotal"); + this.enchSeed = tagCompund.getInt("EnchSeed"); - if (this.xpSeed == 0) + if (this.enchSeed == 0) { - this.xpSeed = this.rand.intv(); + this.enchSeed = this.rand.intv(); } // this.setScore(tagCompund.getInteger("Score")); @@ -3532,35 +3458,37 @@ public abstract class EntityNPC extends EntityLiving // this.wakeUpPlayer(); // } - if (tagCompund.hasKey("SpawnX", 99) && tagCompund.hasKey("SpawnY", 99) && tagCompund.hasKey("SpawnZ", 99)) + if (tagCompund.hasInt("SpawnX") && tagCompund.hasInt("SpawnY") && tagCompund.hasInt("SpawnZ")) { - this.spawnPos = new WorldPos(tagCompund.getInteger("SpawnX"), tagCompund.getInteger("SpawnY"), - tagCompund.getInteger("SpawnZ"), tagCompund.getInteger("SpawnDim")); + this.spawnPos = new WorldPos(tagCompund.getInt("SpawnX"), tagCompund.getInt("SpawnY"), + tagCompund.getInt("SpawnZ"), tagCompund.getInt("SpawnDim")); // this.spawnForced = tagCompund.getBoolean("SpawnForced"); } - if (tagCompund.hasKey("OriginX", 99) && tagCompund.hasKey("OriginY", 99) && tagCompund.hasKey("OriginZ", 99)) + if (tagCompund.hasInt("OriginX") && tagCompund.hasInt("OriginY") && tagCompund.hasInt("OriginZ")) { - this.originPos = new WorldPos(tagCompund.getInteger("OriginX"), tagCompund.getInteger("OriginY"), - tagCompund.getInteger("OriginZ"), tagCompund.getInteger("OriginDim")); + this.originPos = new WorldPos(tagCompund.getInt("OriginX"), tagCompund.getInt("OriginY"), + tagCompund.getInt("OriginZ"), tagCompund.getInt("OriginDim")); } // this.foodStats.readNBT(tagCompund); // this.readCapabilitiesFromNBT(tagCompund); - this.flying = tagCompund.getBoolean("flying") && (this.hasEffect(Potion.FLYING) || this.canNaturallyFly()); + this.flying = tagCompund.getBool("flying") && (this.hasEffect(Potion.FLYING) || this.canNaturallyFly()); // if(tagCompund.hasKey("speed", 99)) // this.speed = tagCompund.getFloat("speed"); // this.disableDamagePersist = tagCompund.getBoolean("alwaysInvulnerable"); // this.disableTargetPersist = tagCompund.getBoolean("neverTarget"); // this.allowFlyingPersist = tagCompund.getBoolean("alwaysFly"); - this.noclip = tagCompund.getBoolean("noClip"); + this.noclip = tagCompund.getBool("noClip"); - if (tagCompund.hasKey("WarpItems", 9)) + if (tagCompund.hasList("WarpItems")) { - NBTTagList nbttaglist1 = tagCompund.getTagList("WarpItems", 10); - this.warpChest.loadInventoryFromNBT(nbttaglist1); + List nbttaglist1 = tagCompund.getList("WarpItems"); + this.warpChest.readTags(nbttaglist1); } + this.movedDistance = tagCompund.getLong("MovedDist"); + // ModelType // model; // try { // model = ModelType.getByName(tagCompund.getString("Model")); @@ -3569,8 +3497,8 @@ public abstract class EntityNPC extends EntityLiving // model = ModelType.HUMANOID; // } // this.setModel(model); -// this.setModelParts(tagCompund.hasKey("PartFlags", 3) ? tagCompund.getInteger("PartFlags") : ~ModelPart.ARMS_SLIM.getMask()); - // if(tagCompund.hasKey("PlayerScale", 5)) +// this.setModelParts(tagCompund.hasInt("PartFlags") ? tagCompund.getInteger("PartFlags") : ~ModelPart.ARMS_SLIM.getMask()); + // if(tagCompund.hasFloat("PlayerScale")) // this.setPlayerHeight(tagCompund.getFloat("PlayerScale")); } } @@ -3578,48 +3506,40 @@ public abstract class EntityNPC extends EntityLiving /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - if(this.isPlayer()) { - for (int z = 0; z < this.inventory.mainInventory.length; z++) - { - ItemStack itemstack = this.inventory.mainInventory[z]; - if (itemstack != null) - { - this.getAttributeMap().removeAttributeModifiers(itemstack.getAttributeModifiers(2), z, itemstack.stackSize); - } - } - } // super.writeEntityToNBT(tagCompound); - super.writeEntityToNBT(tagCompound); + super.writeEntity(tagCompound); // tagCompound.setBoolean("CanPickUpLoot", this.canPickUpLoot()); - NBTTagList nbttaglist0 = new NBTTagList(); + List nbttaglist0 = Lists.newArrayList(); for(int i = 0; i < this.equipment.length; ++i) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject nbttagcompound = new TagObject(); if(this.equipment[i] != null) { - this.equipment[i].writeToNBT(nbttagcompound); + this.equipment[i].writeTags(nbttagcompound); } - nbttaglist0.appendTag(nbttagcompound); + nbttaglist0.add(nbttagcompound); } - tagCompound.setTag("Equipment", nbttaglist0); + tagCompound.setList("Equipment", nbttaglist0); // tagCompound.setString("Species", this.getSpecies()); tagCompound.setString("Char", this.getChar()); tagCompound.setString("Cape", this.getCape()); - tagCompound.setBoolean("Willing", this.isWilling); - tagCompound.setBoolean("Mating", this.isMating()); + tagCompound.setBool("Willing", this.isWilling); + tagCompound.setBool("Mating", this.isMating()); tagCompound.setString("Align", this.alignment.name); tagCompound.setFloat("Height", this.getHeight()); - tagCompound.setInteger("Mana", this.getManaPoints()); + tagCompound.setInt("MaxMana", this.getMaxMana()); + tagCompound.setInt("Mana", this.getManaPoints()); + tagCompound.setInt("AttackDmg", this.attackDamageBase); Enum type = this.getNpcClass(); if(type != null) tagCompound.setString("ClassType", this.species.classnames.inverse().get(type)); - NBTTagList nbttaglist = new NBTTagList(); + List nbttaglist = Lists.newArrayList(); for (int i = 0; i < this.extraInventory.getSizeInventory(); ++i) { @@ -3627,71 +3547,65 @@ public abstract class EntityNPC extends EntityLiving if (itemstack != null) { - nbttaglist.appendTag(itemstack.writeToNBT(new NBTTagCompound())); + nbttaglist.add(itemstack.writeTags(new TagObject())); } } - tagCompound.setTag("Items", nbttaglist); + tagCompound.setList("Items", nbttaglist); if(this.trades != null) - tagCompound.setTag("Offers", this.trades.getRecipiesAsTags()); - tagCompound.setInteger("healTimer", this.healTimer); + tagCompound.setList("Offers", this.trades.toTags()); + tagCompound.setInt("healTimer", this.healTimer); if(this.skin != null) tagCompound.setByteArray("Skin", this.skin); if(this.isPlayer()) { - for (int z = 0; z < this.inventory.mainInventory.length; z++) - { - ItemStack itemstack = this.inventory.mainInventory[z]; - if (itemstack != null) - { - this.getAttributeMap().applyAttributeModifiers(itemstack.getAttributeModifiers(2), z, itemstack.stackSize); - } - } - tagCompound.setTag("Inventory", this.inventory.writeToNBT(new NBTTagList())); - tagCompound.setInteger("SelectedItemSlot", this.inventory.currentItem); + tagCompound.setList("Inventory", this.inventory.writeToNBT(Lists.newArrayList())); + tagCompound.setInt("SelectedItemSlot", this.inventory.currentItem); // tagCompound.setBoolean("Sleeping", this.sleeping); // tagCompound.setShort("SleepTimer", (short)this.sleepTimer); tagCompound.setFloat("XpP", this.experience); - tagCompound.setInteger("XpLevel", this.experienceLevel); - tagCompound.setInteger("XpTotal", this.experienceTotal); - tagCompound.setInteger("XpSeed", this.xpSeed); + tagCompound.setInt("XpLevel", this.experienceLevel); + tagCompound.setInt("XpTotal", this.experienceTotal); + tagCompound.setInt("EnchSeed", this.enchSeed); // tagCompound.setInteger("Score", this.getScore()); // tagCompound.setInteger("Mana", this.getManaPoints()); if (this.spawnPos != null) { - tagCompound.setInteger("SpawnX", this.spawnPos.getX()); - tagCompound.setInteger("SpawnY", this.spawnPos.getY()); - tagCompound.setInteger("SpawnZ", this.spawnPos.getZ()); - tagCompound.setInteger("SpawnDim", this.spawnPos.getDimension()); + tagCompound.setInt("SpawnX", this.spawnPos.getX()); + tagCompound.setInt("SpawnY", this.spawnPos.getY()); + tagCompound.setInt("SpawnZ", this.spawnPos.getZ()); + tagCompound.setInt("SpawnDim", this.spawnPos.getDimension()); // tagCompound.setBoolean("SpawnForced", this.spawnForced); } if (this.originPos != null) { - tagCompound.setInteger("OriginX", this.originPos.getX()); - tagCompound.setInteger("OriginY", this.originPos.getY()); - tagCompound.setInteger("OriginZ", this.originPos.getZ()); - tagCompound.setInteger("OriginDim", this.originPos.getDimension()); + tagCompound.setInt("OriginX", this.originPos.getX()); + tagCompound.setInt("OriginY", this.originPos.getY()); + tagCompound.setInt("OriginZ", this.originPos.getZ()); + tagCompound.setInt("OriginDim", this.originPos.getDimension()); } // this.foodStats.writeNBT(tagCompound); // this.writeCapabilitiesToNBT(tagCompound); - tagCompound.setBoolean("flying", this.flying); + tagCompound.setBool("flying", this.flying); // tagCompound.setFloat("speed", this.speed); // tagCompound.setBoolean("alwaysInvulnerable", this.disableDamagePersist); // tagCompound.setBoolean("neverTarget", this.disableTargetPersist); // tagCompound.setBoolean("alwaysFly", this.allowFlyingPersist); - tagCompound.setBoolean("noClip", this.noclip); + tagCompound.setBool("noClip", this.noclip); - tagCompound.setTag("WarpItems", this.warpChest.saveInventoryToNBT()); + tagCompound.setList("WarpItems", this.warpChest.writeTags()); ItemStack itemstack = this.inventory.getCurrentItem(); if (itemstack != null && itemstack.getItem() != null) { - tagCompound.setTag("SelectedItem", itemstack.writeToNBT(new NBTTagCompound())); + tagCompound.setObject("SelectedItem", itemstack.writeTags(new TagObject())); } + tagCompound.setLong("MovedDist", this.movedDistance); + // tagCompound.setString("Model", this.getModel().name); // tagCompound.setInteger("PartFlags", this.getModelParts()); // tagCompound.setFloat("PlayerScale", this.getPlayerHeight()); @@ -3739,7 +3653,7 @@ public abstract class EntityNPC extends EntityLiving if (itemstack.interactWithEntity(this, (EntityLiving)targetEntity)) { - if (itemstack.stackSize <= 0) // && !this.creative) + if (itemstack.size <= 0) // && !this.creative) { this.destroyCurrentEquippedItem(); } @@ -3754,7 +3668,7 @@ public abstract class EntityNPC extends EntityLiving { if (itemstack != null && itemstack == this.getCurrentEquippedItem()) { - if (itemstack.stackSize <= 0) // && !this.creative) + if (itemstack.size <= 0) // && !this.creative) { this.destroyCurrentEquippedItem(); } @@ -3800,7 +3714,7 @@ public abstract class EntityNPC extends EntityLiving public void attackTargetEntityWithCurrentItem(Entity targetEntity) { if(!this.worldObj.client) { - if(/* !this.creative && */ this.sinceLastAttack < Config.attackDelay) + if(/* !this.creative && */ this.sinceLastAttack < Vars.attackDelay) return; this.sinceLastAttack = 0; } @@ -3808,7 +3722,7 @@ public abstract class EntityNPC extends EntityLiving { if (!targetEntity.hitByEntity(this)) { - int f = (int)this.getEntityAttribute(Attributes.ATTACK_DAMAGE).getAttributeValue(); + int f = this.getAttackDamage(); int i = 0; int f1 = // 0; @@ -3851,7 +3765,7 @@ public abstract class EntityNPC extends EntityLiving double d0 = targetEntity.motionX; double d1 = targetEntity.motionY; double d2 = targetEntity.motionZ; - boolean flag2 = (this.worldObj.client || Config.attack) && targetEntity.attackEntityFrom(DamageSource.causeMobDamage(this), f); + boolean flag2 = (this.worldObj.client || Vars.attack) && targetEntity.attackEntityFrom(DamageSource.causeMobDamage(this), f); if (flag2) { @@ -3907,7 +3821,7 @@ public abstract class EntityNPC extends EntityLiving { itemstack.hitEntity((EntityLiving)entity, this); - if (itemstack.stackSize <= 0) + if (itemstack.size <= 0) { this.destroyCurrentEquippedItem(); } @@ -4020,7 +3934,7 @@ public abstract class EntityNPC extends EntityLiving { double d3 = this.motionY; float f = this.jumpMovement; - this.jumpMovement = this.landMovement * (this.canFlyFullSpeed() ? 0.5f : 0.2f) * (float)(this.isSprinting() ? 2 : 1); + this.jumpMovement = this.landMovement * (this.canFlyFullSpeed() ? 0.5f : 0.2f) * (this.isSprinting() ? (this.canFlyFullSpeed() ? 2.0f : 1.3f) : 1.0f); super.moveEntityWithHeading(strafe, forward); this.motionY = d3 * 0.6D; this.jumpMovement = f; @@ -4030,7 +3944,17 @@ public abstract class EntityNPC extends EntityLiving super.moveEntityWithHeading(strafe, forward); } - this.addMovementStat(this.posX - d0, this.posY - d1, this.posZ - d2); + if(!this.worldObj.client) + this.addMovement(this.posX - d0, this.posY - d1, this.posZ - d2); + } + + public float getSpeedBase() { + return this.worldObj.client ? this.dataWatcher.getWatchableObjectFloat(15) : super.getSpeedBase(); + } + + public void setSpeedBase(float value) { + super.setSpeedBase(value); + this.dataWatcher.updateObject(15, value); } /** @@ -4038,106 +3962,68 @@ public abstract class EntityNPC extends EntityLiving */ public float getAIMoveSpeed() { - return this.isPlayer() ? (float)this.getEntityAttribute(Attributes.MOVEMENT_SPEED).getAttributeValue() : super.getAIMoveSpeed(); + return this.isPlayer() ? this.getMovementSpeed() / 3.0f : super.getAIMoveSpeed(); } - /** - * Adds a value to a movement statistic field - like run, walk, swin or climb. - */ - public void addMovementStat(double p_71000_1_, double p_71000_3_, double p_71000_5_) + public void addMovement(double x, double y, double z) { if (this.vehicle == null) { if (this.isInsideOfLiquid()) { - int i = Math.round(ExtMath.sqrtd(p_71000_1_ * p_71000_1_ + p_71000_3_ * p_71000_3_ + p_71000_5_ * p_71000_5_) * 100.0F); + int i = Math.round(ExtMath.sqrtd(x * x + y * y + z * z) * 100.0F); if (i > 0) { - this.addStat(i); + this.addMoved(i); } } else if (this.isInLiquid()) { - int j = Math.round(ExtMath.sqrtd(p_71000_1_ * p_71000_1_ + p_71000_5_ * p_71000_5_) * 100.0F); + int j = Math.round(ExtMath.sqrtd(x * x + z * z) * 100.0F); if (j > 0) { - this.addStat(j); + this.addMoved(j); } } else if (this.isOnLadder()) { - if (p_71000_3_ > 0.0D) + if (y > 0.0D) { - this.addStat((int)Math.round(p_71000_3_ * 100.0D)); + this.addMoved((int)Math.round(y * 100.0D)); } } else if (this.onGround) { - int k = Math.round(ExtMath.sqrtd(p_71000_1_ * p_71000_1_ + p_71000_5_ * p_71000_5_) * 100.0F); + int k = Math.round(ExtMath.sqrtd(x * x + z * z) * 100.0F); if (k > 0) { - this.addStat(k); - -// if (this.isSprinting()) -// { -// this.addStat(StatRegistry.distanceSprintedStat, k); -// } -// else -// { -// if (this.isSneaking()) -// { -// this.addStat(StatRegistry.distanceCrouchedStat, k); -// } -// } + this.addMoved(k); } } else { - int l = Math.round(ExtMath.sqrtd(p_71000_1_ * p_71000_1_ + p_71000_5_ * p_71000_5_) * 100.0F); + int l = Math.round(ExtMath.sqrtd(x * x + z * z) * 100.0F); if (l > 25) { - this.addStat(l); + this.addMoved(l); } } } } - /** - * Adds a value to a mounted movement statistic field - by minecart, boat, or pig. - */ - private void addMountedMovementStat(double p_71015_1_, double p_71015_3_, double p_71015_5_) + private void addMountedMovement(double x, double y, double z) { if (this.vehicle != null) { - int i = Math.round(ExtMath.sqrtd(p_71015_1_ * p_71015_1_ + p_71015_3_ * p_71015_3_ + p_71015_5_ * p_71015_5_) * 100.0F); + int i = Math.round(ExtMath.sqrtd(x * x + y * y + z * z) * 100.0F); if (i > 0) { - if (this.vehicle instanceof EntityCart) - { - this.addStat(i); - -// if (this.startMinecartRidingCoordinate == null) -// { -// this.startMinecartRidingCoordinate = new BlockPos(this); -// } - } - else if (this.vehicle instanceof EntityBoat) - { - this.addStat(i); - } - else if (this.vehicle instanceof EntityPig) - { - this.addStat(i); - } - else if (this.vehicle instanceof EntityHorse) - { - this.addStat(i); - } + this.addMoved(i); } } } @@ -4152,7 +4038,7 @@ public abstract class EntityNPC extends EntityLiving { if (distance >= 2.0F) { - this.addStat((int)Math.round((double)distance * 100.0D)); + this.addMoved((int)Math.round((double)distance * 100.0D)); } if(!this.hasEffect(Potion.FLYING)) @@ -4206,10 +4092,12 @@ public abstract class EntityNPC extends EntityLiving { return this.isPlayer() ? this.inventory.armorItemInSlot(slot) : this.equipment[slot + 1]; } + + public void setExperience(int points) { + this.setXPStats(0.0f, 0, 0); + this.addExperience(points); + } - /** - * Add experience points to player. - */ public void addExperience(int amount) { int i = Integer.MAX_VALUE - this.experienceTotal; @@ -4228,14 +4116,14 @@ public abstract class EntityNPC extends EntityLiving } } - public int getXPSeed() + public int getEnchSeed() { - return this.xpSeed; + return this.enchSeed; } - public void setXPSeed(int xpSeed) + public void setEnchSeed(int seed) { - this.xpSeed = xpSeed; + this.enchSeed = seed; } /** @@ -4374,22 +4262,22 @@ public abstract class EntityNPC extends EntityLiving amount = 0; } - this.getDataWatcher().updateObject(30, Integer.valueOf(amount)); + this.getDataWatcher().updateObject(12, Integer.valueOf(amount)); } } public int getAbsorptionAmount() { - return this.isPlayer() ? this.getDataWatcher().getWatchableObjectInt(30) : super.getAbsorptionAmount(); + return this.isPlayer() ? this.getDataWatcher().getWatchableObjectInt(12) : super.getAbsorptionAmount(); } - public boolean canOpen(LockCode code) + public boolean canOpen(Passcode code) { - if (code.isEmpty()) + if (code.empty()) return true; ItemStack stack = this.getCurrentEquippedItem(); return stack != null && stack.getItem() == Items.key && - stack.hasDisplayName() && stack.getDisplayName().equals(code.getLock()); + stack.hasDisplayName() && stack.getDisplayName().equals(code.code()); } // public boolean isWearing(ModelPart part) @@ -4429,7 +4317,7 @@ public abstract class EntityNPC extends EntityLiving } public boolean canFlyFullSpeed() { - return this.flying; + return this.hasEffect(Potion.FLYING) && this.getEffect(Potion.FLYING).getAmplifier() > 0; } public int getEnergy(Energy type) { // TODO @@ -4480,7 +4368,7 @@ public abstract class EntityNPC extends EntityLiving if(info.items != null) { for(ItemStack stack : info.items) { if(stack.getItem() instanceof ItemArmor) - this.setItem(1 + ((ItemArmor)stack.getItem()).armorType, stack); + this.setItem(((ItemArmor)stack.getItem()).armorType.getIndex(), stack); else if(stack.getItem().canBeWielded()) this.setItem(0, stack); else @@ -4710,17 +4598,7 @@ public abstract class EntityNPC extends EntityLiving public int getColor() { return this.isPlayer() ? 0xff00ff : 0x5000ad; } - - public LayerExtra getExtrasLayer() - { - return EntityTexManager.getLayer(this.isPlayer() ? this.getId() : -1, this.getChar(), this.species.renderer); - } - - public String getLocationSkin() - { - return EntityTexManager.getSkin(this.isPlayer() ? this.getId() : -1, this.getChar(), this.species.renderer); - } - + public void sendDeathMessage() { this.sendDeathMessage(this.isPlayer(), true); } @@ -4752,4 +4630,36 @@ public abstract class EntityNPC extends EntityLiving public EntityType getType() { return EntityType.NPC; } + + public void setGodMode(boolean god) { + this.fallDistance = 0.0F; + if(!god) { + this.removeEffect(Potion.HASTE); + this.removeEffect(Potion.RESISTANCE); + this.removeEffect(Potion.FIRE_RESISTANCE); + this.removeEffect(Potion.FLYING); + this.removeEffect(Potion.MANA_GENERATION); + } + else { + this.extinguish(); + this.setHealth(this.getMaxHealth()); + this.setManaPoints(this.getMaxMana()); + this.clearEffects(false); + this.addEffect(new PotionEffect(Potion.HASTE, Integer.MAX_VALUE, 255, false, false)); + this.addEffect(new PotionEffect(Potion.RESISTANCE, Integer.MAX_VALUE, 255, false, false)); + this.addEffect(new PotionEffect(Potion.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, false, false)); + this.addEffect(new PotionEffect(Potion.FLYING, Integer.MAX_VALUE, 1, false, false)); + this.addEffect(new PotionEffect(Potion.MANA_GENERATION, Integer.MAX_VALUE, 255, false, false)); + } + } + + public void setNoclip(boolean noclip) { + if(noclip) + this.mountEntity(null); + this.noclip = noclip; + this.flying &= this.hasEffect(Potion.FLYING) || this.noclip || this.canNaturallyFly(); + this.fallDistance = 0.0F; + if(this.connection != null) + this.connection.sendPlayerAbilities(); + } } diff --git a/java/src/game/entity/npc/EntityOrc.java b/common/src/main/java/common/entity/npc/EntityOrc.java similarity index 88% rename from java/src/game/entity/npc/EntityOrc.java rename to common/src/main/java/common/entity/npc/EntityOrc.java index 47cc5df..b6a7bb3 100755 --- a/java/src/game/entity/npc/EntityOrc.java +++ b/common/src/main/java/common/entity/npc/EntityOrc.java @@ -1,8 +1,7 @@ -package game.entity.npc; +package common.entity.npc; -import game.entity.attributes.Attributes; -import game.rng.Random; -import game.world.World; +import common.rng.Random; +import common.world.World; public class EntityOrc extends EntityNPC { public EntityOrc(World worldIn) { @@ -72,6 +71,6 @@ public class EntityOrc extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(4.0D); + this.setAttackDamageBase(4); } } diff --git a/java/src/game/entity/npc/EntityPrimarch.java b/common/src/main/java/common/entity/npc/EntityPrimarch.java similarity index 94% rename from java/src/game/entity/npc/EntityPrimarch.java rename to common/src/main/java/common/entity/npc/EntityPrimarch.java index a09e4ec..682d756 100755 --- a/java/src/game/entity/npc/EntityPrimarch.java +++ b/common/src/main/java/common/entity/npc/EntityPrimarch.java @@ -1,16 +1,14 @@ -package game.entity.npc; +package common.entity.npc; import java.util.List; -import game.collect.Lists; - -import game.entity.attributes.Attributes; -import game.properties.IStringSerializable; -import game.rng.Random; -import game.world.World; +import common.collect.Lists; +import common.rng.Random; +import common.util.Identifyable; +import common.world.World; public class EntityPrimarch extends EntityMobNPC { - public static enum Founding implements IStringSerializable { + public static enum Founding implements Identifyable { OTHER("other", "", 0, 0x000000, 0x000000), DARK_ANGELS("darkangel", "Dark Angels", 1, 0xaf0000, 0x400000, "Lion El'Jonson:lion_el_jonson", 2.65f, 850, Alignment.GOOD), UNKNOWN_A("unkna", "[Legion 2]", 2, 0xaf0000, 0x400000), @@ -155,7 +153,7 @@ public class EntityPrimarch extends EntityMobNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(20.0D); + this.setAttackDamageBase(20); } // public TextComponent getPrefix() { diff --git a/java/src/game/entity/npc/EntitySlime.java b/common/src/main/java/common/entity/npc/EntitySlime.java similarity index 91% rename from java/src/game/entity/npc/EntitySlime.java rename to common/src/main/java/common/entity/npc/EntitySlime.java index e853c79..73fe074 100755 --- a/java/src/game/entity/npc/EntitySlime.java +++ b/common/src/main/java/common/entity/npc/EntitySlime.java @@ -1,23 +1,21 @@ -package game.entity.npc; +package common.entity.npc; -import game.ai.EntityAIBase; -import game.ai.EntityMoveHelper; -import game.biome.Biome; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; -import game.init.Config; -import game.init.SoundEvent; -import game.nbt.NBTTagCompound; -import game.pathfinding.PathNavigateGround; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Chunk; -import game.world.World; -import game.world.WorldServer; +import common.ai.EntityAIBase; +import common.ai.EntityMoveHelper; +import common.biome.Biome; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.init.SoundEvent; +import common.model.ParticleType; +import common.pathfinding.PathNavigateGround; +import common.rng.Random; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.ExtMath; +import common.vars.Vars; +import common.world.World; +import common.world.AWorldServer; public class EntitySlime extends EntityNPC { @@ -135,19 +133,19 @@ public class EntitySlime extends EntityNPC /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); + super.writeEntity(tagCompound); // tagCompound.setInteger("Size", this.getSlimeSize() - 1); - tagCompound.setBoolean("wasOnGround", this.wasOnGround); + tagCompound.setBool("wasOnGround", this.wasOnGround); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); + super.readEntity(tagCompund); // int i = tagCompund.getInteger("Size"); // // if (i < 0) @@ -156,7 +154,7 @@ public class EntitySlime extends EntityNPC // } // // this.setSlimeSize(i + 1); - this.wasOnGround = tagCompund.getBoolean("wasOnGround"); + this.wasOnGround = tagCompund.getBool("wasOnGround"); } protected ParticleType getParticleType() @@ -259,7 +257,7 @@ public class EntitySlime extends EntityNPC { int i = 1; - if (!this.worldObj.client && this.getHeight() >= 0.5f && this.getHealth() <= 0 && Config.mobs && Config.spawnSplitSlime) + if (!this.worldObj.client && this.getHeight() >= 0.5f && this.getHealth() <= 0 && Vars.mobs && Vars.spawnSplitSlime) { int j = this.rand.range(2, 4); float size = this.getHeight() / 2.0f; @@ -321,7 +319,7 @@ public class EntitySlime extends EntityNPC { double i = this.width * 2.0f; - if ((this.worldObj.client || Config.damageMobs) && this.canEntityBeSeen(p_175451_1_) + if ((this.worldObj.client || Vars.damageMobs) && this.canEntityBeSeen(p_175451_1_) && this.getDistanceSqToEntity(p_175451_1_) < 0.6D * i * 0.6D * i && this.canAttack(p_175451_1_) && p_175451_1_.attackEntityFrom(DamageSource.causeMobDamage(this), this.rand.range(1, 3))) { @@ -373,7 +371,7 @@ public class EntitySlime extends EntityNPC // } - public static Random getRandomWithSeed(WorldServer world, int xPosition, int zPosition, long seed) + public static Random getRandomWithSeed(AWorldServer world, int xPosition, int zPosition, long seed) { return new Random(world.getSeed() + (long)(xPosition * xPosition * 4987142) + (long)(xPosition * 5947611) + @@ -386,8 +384,7 @@ public class EntitySlime extends EntityNPC public boolean getCanSpawnHere() { BlockPos blockpos = new BlockPos(ExtMath.floord(this.posX), 0, ExtMath.floord(this.posZ)); - Chunk chunk = this.worldObj.getChunk(blockpos); - + // if (this.worldObj.getWorldInfo().getTerrainType() == WorldType.FLAT && this.rand.nextInt(4) != 1) // { // return false; @@ -396,14 +393,14 @@ public class EntitySlime extends EntityNPC // { // if (this.worldObj.getDifficulty() != Difficulty.PEACEFUL) // { - Biome biomegenbase = this.worldObj.getBiomeGenForCoords(blockpos); + Biome biomegenbase = this.worldObj.getBiomeGenForCoords(blockpos); - if (biomegenbase == Biome.swampland && this.posY > 50.0D && this.posY < 70.0D && this.rand.floatv() < 0.5F && this.rand.floatv() < this.worldObj.getCurrentMoonPhaseFactor() && this.worldObj.getLightFromNeighbors(new BlockPos(this)) <= this.rand.zrange(8)) + if (biomegenbase == Biome.SWAMPLAND && this.posY > 50.0D && this.posY < 70.0D && this.rand.floatv() < 0.5F && this.rand.floatv() < this.worldObj.getCurrentMoonPhaseFactor() && this.worldObj.getLightFromNeighbors(new BlockPos(this)) <= this.rand.zrange(8)) { return super.getCanSpawnHere(); } - if (this.rand.zrange(10) == 0 && getRandomWithSeed((WorldServer)this.worldObj, chunk.xPos, chunk.zPos, 987234911L).zrange(10) == 0 && this.posY < 40.0D) + if (this.rand.zrange(10) == 0 && getRandomWithSeed((AWorldServer)this.worldObj, blockpos.getX() >> 4, blockpos.getZ() >> 4, 987234911L).zrange(10) == 0 && this.posY < 40.0D) { return super.getCanSpawnHere(); } @@ -523,7 +520,7 @@ public class EntitySlime extends EntityNPC public boolean shouldExecute() { EntityLiving entitylivingbase = this.slime.getAttackTarget(); - return entitylivingbase == null ? false : (!entitylivingbase.isEntityAlive() ? false : Config.mobAttacks); + return entitylivingbase == null ? false : (!entitylivingbase.isEntityAlive() ? false : Vars.mobAttacks); } public void startExecuting() @@ -535,7 +532,7 @@ public class EntitySlime extends EntityNPC public boolean continueExecuting() { EntityLiving entitylivingbase = this.slime.getAttackTarget(); - return entitylivingbase == null ? false : (!entitylivingbase.isEntityAlive() ? false : (!Config.mobAttacks ? false : --this.attackTimer > 0)); + return entitylivingbase == null ? false : (!entitylivingbase.isEntityAlive() ? false : (!Vars.mobAttacks ? false : --this.attackTimer > 0)); } public void updateTask() @@ -663,7 +660,7 @@ public class EntitySlime extends EntityNPC if (this.entity.onGround) { - this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getEntityAttribute(Attributes.MOVEMENT_SPEED).getAttributeValue())); + this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getMovementSpeed())); if (this.jumpDelay-- <= 0) { @@ -690,7 +687,7 @@ public class EntitySlime extends EntityNPC } else { - this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getEntityAttribute(Attributes.MOVEMENT_SPEED).getAttributeValue())); + this.entity.setAIMoveSpeed((float)(this.speed * this.entity.getMovementSpeed())); } } } diff --git a/java/src/game/entity/npc/EntitySpaceMarine.java b/common/src/main/java/common/entity/npc/EntitySpaceMarine.java similarity index 87% rename from java/src/game/entity/npc/EntitySpaceMarine.java rename to common/src/main/java/common/entity/npc/EntitySpaceMarine.java index 7d48b33..841ee67 100755 --- a/java/src/game/entity/npc/EntitySpaceMarine.java +++ b/common/src/main/java/common/entity/npc/EntitySpaceMarine.java @@ -1,19 +1,17 @@ -package game.entity.npc; +package common.entity.npc; import java.util.List; -import game.collect.Lists; - -import game.entity.attributes.Attributes; -import game.init.Items; -import game.init.SpeciesRegistry; -import game.item.ItemStack; -import game.properties.IStringSerializable; -import game.rng.Random; -import game.world.World; +import common.collect.Lists; +import common.init.Items; +import common.init.SpeciesRegistry; +import common.item.ItemStack; +import common.rng.Random; +import common.util.Identifyable; +import common.world.World; public class EntitySpaceMarine extends EntityNPC { - public static enum Legion implements IStringSerializable { + public static enum Legion implements Identifyable { OTHER("other", null, 0x000000, 0x000000, 2.15f, 200), BLACK_TEMPLARS("blacktemplar", "Black Templars", 0x101010, 0xc0c0c0, 2.43f, 300, "black_templar"); @@ -119,7 +117,7 @@ public class EntitySpaceMarine extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(12.0D); + this.setAttackDamageBase(12); } protected ItemStack pickItem() { diff --git a/java/src/game/entity/npc/EntitySpirit.java b/common/src/main/java/common/entity/npc/EntitySpirit.java similarity index 92% rename from java/src/game/entity/npc/EntitySpirit.java rename to common/src/main/java/common/entity/npc/EntitySpirit.java index 9f27ab5..a2003b3 100755 --- a/java/src/game/entity/npc/EntitySpirit.java +++ b/common/src/main/java/common/entity/npc/EntitySpirit.java @@ -1,9 +1,9 @@ -package game.entity.npc; +package common.entity.npc; -import game.init.Items; -import game.item.ItemStack; -import game.rng.Random; -import game.world.World; +import common.init.Items; +import common.item.ItemStack; +import common.rng.Random; +import common.world.World; public class EntitySpirit extends EntityNPC { public EntitySpirit(World worldIn) { diff --git a/java/src/game/entity/npc/EntityTiefling.java b/common/src/main/java/common/entity/npc/EntityTiefling.java similarity index 88% rename from java/src/game/entity/npc/EntityTiefling.java rename to common/src/main/java/common/entity/npc/EntityTiefling.java index f41e20f..fb52552 100755 --- a/java/src/game/entity/npc/EntityTiefling.java +++ b/common/src/main/java/common/entity/npc/EntityTiefling.java @@ -1,8 +1,7 @@ -package game.entity.npc; +package common.entity.npc; -import game.entity.attributes.Attributes; -import game.rng.Random; -import game.world.World; +import common.rng.Random; +import common.world.World; public class EntityTiefling extends EntityMobNPC { public EntityTiefling(World worldIn) { @@ -80,6 +79,6 @@ public class EntityTiefling extends EntityMobNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(3.0D); + this.setAttackDamageBase(3); } } diff --git a/java/src/game/entity/npc/EntityUndead.java b/common/src/main/java/common/entity/npc/EntityUndead.java similarity index 83% rename from java/src/game/entity/npc/EntityUndead.java rename to common/src/main/java/common/entity/npc/EntityUndead.java index 47d471c..b16db28 100755 --- a/java/src/game/entity/npc/EntityUndead.java +++ b/common/src/main/java/common/entity/npc/EntityUndead.java @@ -1,14 +1,13 @@ -package game.entity.npc; +package common.entity.npc; -import game.ai.EntityAIAvoidEntity; -import game.entity.animal.EntityWolf; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.item.ItemStack; -import game.rng.Random; -import game.world.World; -import game.world.WorldServer; +import common.ai.EntityAIAvoidEntity; +import common.entity.animal.EntityWolf; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.item.ItemStack; +import common.rng.Random; +import common.world.World; +import common.world.AWorldServer; public class EntityUndead extends EntityNPC { @@ -21,7 +20,7 @@ public class EntityUndead extends EntityNPC protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.25D); + this.setSpeedBase(0.25f); } // protected String getLivingSound() @@ -107,7 +106,7 @@ public class EntityUndead extends EntityNPC } public boolean getCanSpawnHere() { - return !((WorldServer)this.worldObj).isDaytime(); + return !((AWorldServer)this.worldObj).isDaytime(); } // public boolean canAmbush(EntityLiving entity) { diff --git a/java/src/game/entity/npc/EntityVampire.java b/common/src/main/java/common/entity/npc/EntityVampire.java similarity index 86% rename from java/src/game/entity/npc/EntityVampire.java rename to common/src/main/java/common/entity/npc/EntityVampire.java index 38c57d7..507976e 100755 --- a/java/src/game/entity/npc/EntityVampire.java +++ b/common/src/main/java/common/entity/npc/EntityVampire.java @@ -1,9 +1,8 @@ -package game.entity.npc; +package common.entity.npc; -import game.entity.attributes.Attributes; -import game.entity.effect.EntityLightning; -import game.rng.Random; -import game.world.World; +import common.entity.effect.EntityLightning; +import common.rng.Random; +import common.world.World; public class EntityVampire extends EntityNPC { public EntityVampire(World worldIn) { @@ -75,6 +74,6 @@ public class EntityVampire extends EntityNPC { protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(5.0D); + this.setAttackDamageBase(5); } } diff --git a/java/src/game/entity/npc/EntityWoodElf.java b/common/src/main/java/common/entity/npc/EntityWoodElf.java similarity index 88% rename from java/src/game/entity/npc/EntityWoodElf.java rename to common/src/main/java/common/entity/npc/EntityWoodElf.java index 0e4fc0a..c131b6a 100755 --- a/java/src/game/entity/npc/EntityWoodElf.java +++ b/common/src/main/java/common/entity/npc/EntityWoodElf.java @@ -1,11 +1,11 @@ -package game.entity.npc; +package common.entity.npc; -import game.entity.types.EntityLiving; -import game.init.Items; -import game.init.NameRegistry; -import game.item.ItemStack; -import game.rng.Random; -import game.world.World; +import common.entity.types.EntityLiving; +import common.init.Items; +import common.init.NameRegistry; +import common.item.ItemStack; +import common.rng.Random; +import common.world.World; public class EntityWoodElf extends EntityNPC { public EntityWoodElf(World worldIn) { diff --git a/java/src/game/entity/npc/EntityZombie.java b/common/src/main/java/common/entity/npc/EntityZombie.java similarity index 81% rename from java/src/game/entity/npc/EntityZombie.java rename to common/src/main/java/common/entity/npc/EntityZombie.java index d61bec4..1378a88 100755 --- a/java/src/game/entity/npc/EntityZombie.java +++ b/common/src/main/java/common/entity/npc/EntityZombie.java @@ -1,21 +1,18 @@ -package game.entity.npc; +package common.entity.npc; import java.util.List; - import java.util.function.Predicate; -import game.ai.EntityAIMoveThroughVillage; -import game.entity.DamageSource; -import game.entity.animal.EntityChicken; -import game.entity.attributes.AttributeModifier; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; -import game.init.Config; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.World; -import game.world.WorldServer; +import common.ai.EntityAIMoveThroughVillage; +import common.entity.DamageSource; +import common.entity.animal.EntityChicken; +import common.entity.types.EntityLiving; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import common.vars.Vars; +import common.world.World; +import common.world.AWorldServer; public class EntityZombie extends EntityNPC { @@ -28,11 +25,13 @@ public class EntityZombie extends EntityNPC protected void applyEntityAttributes() { super.applyEntityAttributes(); - this.getEntityAttribute(Attributes.FOLLOW_RANGE).setBaseValue(28.0D); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.23000000417232513D); - this.getEntityAttribute(Attributes.ATTACK_DAMAGE).setBaseValue(3.0D); - this.getAttributeMap().registerAttribute(Attributes.REINFORCEMENT_CHANCE).setBaseValue(this.rand.doublev() * 0.10000000149011612D); + this.setSpeedBase(0.23000000417232513f); + this.setAttackDamageBase(3); } + + public int getPathingRange() { + return 28; + } public void onLivingUpdate() { @@ -54,7 +53,7 @@ public class EntityZombie extends EntityNPC entitylivingbase = (EntityLiving)source.getEntity(); } - if (entitylivingbase != null && /* this.worldObj.getDifficulty() == Difficulty.HARD && */ (double)this.rand.floatv() < this.getEntityAttribute(Attributes.REINFORCEMENT_CHANCE).getAttributeValue() && Config.mobs && Config.spawnMoreZombie) + if (entitylivingbase != null && Vars.mobs && Vars.spawnMoreZombie > 0 && this.rand.chance(Vars.spawnMoreZombie)) { int i = ExtMath.floord(this.posX); int j = ExtMath.floord(this.posY); @@ -76,8 +75,6 @@ public class EntityZombie extends EntityNPC this.worldObj.spawnEntityInWorld(entityzombie); entityzombie.setAttackTarget(entitylivingbase); entityzombie.onInitialSpawn(null); - this.getEntityAttribute(Attributes.REINFORCEMENT_CHANCE).applyModifier(new AttributeModifier("Zombie reinforcement caller charge", -0.05000000074505806D, false)); - entityzombie.getEntityAttribute(Attributes.REINFORCEMENT_CHANCE).applyModifier(new AttributeModifier("Zombie reinforcement callee charge", -0.05000000074505806D, false)); break; } } @@ -142,7 +139,7 @@ public class EntityZombie extends EntityNPC { super.onKillEntity(entityLivingIn); - if (/* (this.worldObj.getDifficulty() == Difficulty.NORMAL || this.worldObj.getDifficulty() == Difficulty.HARD) && */ entityLivingIn instanceof EntityNPC && !(entityLivingIn.isPlayer()) && Config.convertZombie) + if (/* (this.worldObj.getDifficulty() == Difficulty.NORMAL || this.worldObj.getDifficulty() == Difficulty.HARD) && */ entityLivingIn instanceof EntityNPC && !(entityLivingIn.isPlayer()) && Vars.convertZombie) { // if (this.worldObj.getDifficulty() != Difficulty.HARD && this.rand.chance()) // { @@ -220,7 +217,7 @@ public class EntityZombie extends EntityNPC if (!list.isEmpty()) { EntityChicken entitychicken = (EntityChicken)list.get(0); - entitychicken.setChickenJockey(true); + entitychicken.setNotLaying(true); this.mountEntity(entitychicken); } } @@ -229,7 +226,7 @@ public class EntityZombie extends EntityNPC EntityChicken entitychicken1 = new EntityChicken(this.worldObj); entitychicken1.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotYaw, 0.0F); entitychicken1.onInitialSpawn(null); - entitychicken1.setChickenJockey(true); + entitychicken1.setNotLaying(true); this.worldObj.spawnEntityInWorld(entitychicken1); this.mountEntity(entitychicken1); } @@ -251,24 +248,19 @@ public class EntityZombie extends EntityNPC // } // } - this.getEntityAttribute(Attributes.KNOCKBACK_RESISTANCE).applyModifier(new AttributeModifier("Random spawn bonus", this.rand.doublev() * 0.05000000074505806D, false)); - double d0 = this.rand.doublev() * 15.0; - - if (d0 > 1.0D) - { - this.getEntityAttribute(Attributes.FOLLOW_RANGE).applyModifier(new AttributeModifier("Random zombie-spawn bonus", d0, false)); - } - if (this.rand.chance(30)) { - this.getEntityAttribute(Attributes.REINFORCEMENT_CHANCE).applyModifier(new AttributeModifier("Leader zombie bonus", this.rand.doublev() * 0.25D + 0.5D, false)); - this.getEntityAttribute(Attributes.MAX_HEALTH).applyModifier(new AttributeModifier("Leader zombie bonus", this.rand.roll(4), true)); + this.setMaxHealth(this.getMaxHealth() + this.rand.roll(12)); // this.setBreakDoorsAItask(true); } return livingdata; } + public double getKnockBackResistance() { + return 0.05; + } + public int getColor() { return 0xff0000; } @@ -326,7 +318,7 @@ public class EntityZombie extends EntityNPC } public boolean getCanSpawnHere() { - return !((WorldServer)this.worldObj).isDaytime(); + return !((AWorldServer)this.worldObj).isDaytime(); } // public boolean canAmbush(EntityLiving entity) { diff --git a/java/src/game/entity/npc/NpcInfo.java b/common/src/main/java/common/entity/npc/NpcInfo.java similarity index 89% rename from java/src/game/entity/npc/NpcInfo.java rename to common/src/main/java/common/entity/npc/NpcInfo.java index b6b985a..f0ba67c 100644 --- a/java/src/game/entity/npc/NpcInfo.java +++ b/common/src/main/java/common/entity/npc/NpcInfo.java @@ -1,6 +1,6 @@ -package game.entity.npc; +package common.entity.npc; -import game.item.ItemStack; +import common.item.ItemStack; public class NpcInfo { public final Enum type; diff --git a/common/src/main/java/common/entity/npc/PlayerCharacter.java b/common/src/main/java/common/entity/npc/PlayerCharacter.java new file mode 100644 index 0000000..89874f4 --- /dev/null +++ b/common/src/main/java/common/entity/npc/PlayerCharacter.java @@ -0,0 +1,6 @@ +package common.entity.npc; + +import common.util.BlockPos; + +public record PlayerCharacter(String name, String info, Alignment align, String dim, BlockPos pos, String type, int level) { +} diff --git a/java/src/game/entity/npc/SpeciesInfo.java b/common/src/main/java/common/entity/npc/SpeciesInfo.java similarity index 90% rename from java/src/game/entity/npc/SpeciesInfo.java rename to common/src/main/java/common/entity/npc/SpeciesInfo.java index 33f341f..1c9cbad 100755 --- a/java/src/game/entity/npc/SpeciesInfo.java +++ b/common/src/main/java/common/entity/npc/SpeciesInfo.java @@ -1,13 +1,14 @@ -package game.entity.npc; +package common.entity.npc; import java.util.List; -import game.collect.BiMap; -import game.collect.HashBiMap; -import game.collect.Lists; -import game.init.SpeciesRegistry; -import game.init.SpeciesRegistry.ModelType; -import game.properties.IStringSerializable; -import game.rng.Random; + +import common.collect.BiMap; +import common.collect.HashBiMap; +import common.collect.Lists; +import common.init.SpeciesRegistry; +import common.init.SpeciesRegistry.ModelType; +import common.rng.Random; +import common.util.Identifyable; public class SpeciesInfo { public final BiMap classnames; @@ -76,7 +77,7 @@ public class SpeciesInfo { SpeciesRegistry.CLASSES.put(this.clazz, this); if(this.classEnum != null) { for(Enum type : this.classEnum.getEnumConstants()) { - this.classnames.put(((IStringSerializable)type).getName(), type); + this.classnames.put(((Identifyable)type).getName(), type); } } } diff --git a/java/src/game/entity/projectile/EntityArrow.java b/common/src/main/java/common/entity/projectile/EntityArrow.java similarity index 90% rename from java/src/game/entity/projectile/EntityArrow.java rename to common/src/main/java/common/entity/projectile/EntityArrow.java index 911c1bf..46ef690 100755 --- a/java/src/game/entity/projectile/EntityArrow.java +++ b/common/src/main/java/common/entity/projectile/EntityArrow.java @@ -1,31 +1,31 @@ -package game.entity.projectile; +package common.entity.projectile; import java.util.List; -import game.block.Block; -import game.enchantment.EnchantmentHelper; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.entity.types.IObjectData; -import game.entity.types.IProjectile; -import game.init.BlockRegistry; -import game.init.Config; -import game.init.Items; -import game.init.SoundEvent; -import game.item.ItemStack; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.HitPosition; -import game.world.State; -import game.world.Vec3; -import game.world.World; +import common.block.Block; +import common.enchantment.EnchantmentHelper; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.entity.types.IObjectData; +import common.entity.types.IProjectile; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.Items; +import common.init.SoundEvent; +import common.item.ItemStack; +import common.model.ParticleType; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.HitPosition; +import common.util.Vec3; +import common.vars.Vars; +import common.world.State; +import common.world.World; public class EntityArrow extends Entity implements IProjectile, IObjectData { @@ -156,7 +156,7 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData this.ticksInGround = 0; } - public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) + public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) { this.setPosition(x, y, z); this.setRotation(yaw, pitch); @@ -201,7 +201,7 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData State iblockstate = this.worldObj.getState(blockpos); Block block = iblockstate.getBlock(); - if (block.getMaterial() != Material.air) + if (block != Blocks.air) { block.setBlockBoundsBasedOnState(this.worldObj, blockpos); BoundingBox axisalignedbb = block.getCollisionBoundingBox(this.worldObj, blockpos, iblockstate); @@ -324,7 +324,7 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData movingobjectposition.entity.setFire(5); } - if ((this.worldObj.client || Config.damageArrow) && movingobjectposition.entity.attackEntityFrom(damagesource, l)) + if ((this.worldObj.client || Vars.damageArrow) && movingobjectposition.entity.attackEntityFrom(damagesource, l)) { if (movingobjectposition.entity instanceof EntityLiving) { @@ -397,7 +397,7 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData this.arrowShake = 7; this.setIsCritical(false); - if (this.inTile.getMaterial() != Material.air) + if (this.inTile != Blocks.air) { this.inTile.onEntityCollidedWithBlock(this.worldObj, blockpos1, iblockstate1, this); } @@ -471,17 +471,19 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { tagCompound.setShort("xTile", (short)this.xTile); tagCompound.setShort("yTile", (short)this.yTile); tagCompound.setShort("zTile", (short)this.zTile); tagCompound.setShort("life", (short)this.ticksInGround); - String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(this.inTile); - tagCompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); + if(this.inTile != null) { + String id = BlockRegistry.getNameFromBlock(this.inTile); + tagCompound.setString("inTile", id == null ? "" : id.toString()); + } tagCompound.setByte("inData", (byte)this.inData); tagCompound.setByte("shake", (byte)this.arrowShake); - tagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0)); + tagCompound.setBool("inGround", this.inGround); tagCompound.setByte("pickup", (byte)this.canBePickedUp); tagCompound.setDouble("damage", this.damage); } @@ -489,39 +491,29 @@ public class EntityArrow extends Entity implements IProjectile, IObjectData /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { this.xTile = tagCompund.getShort("xTile"); this.yTile = tagCompund.getShort("yTile"); this.zTile = tagCompund.getShort("zTile"); this.ticksInGround = tagCompund.getShort("life"); - if (tagCompund.hasKey("inTile", 8)) + if (tagCompund.hasString("inTile")) { - this.inTile = BlockRegistry.getByIdFallback(tagCompund.getString("inTile")); + this.inTile = BlockRegistry.getRegisteredBlock(tagCompund.getString("inTile")); } else { - this.inTile = BlockRegistry.getBlockById(tagCompund.getByte("inTile") & 255); + this.inTile = null; } this.inData = tagCompund.getByte("inData") & 255; this.arrowShake = tagCompund.getByte("shake") & 255; - this.inGround = tagCompund.getByte("inGround") == 1; + this.inGround = tagCompund.getBool("inGround"); - if (tagCompund.hasKey("damage", 99)) - { - this.damage = tagCompund.getDouble("damage"); - } + this.damage = tagCompund.getDouble("damage"); - if (tagCompund.hasKey("pickup", 99)) - { - this.canBePickedUp = tagCompund.getByte("pickup"); - } - else if (tagCompund.hasKey("player", 99)) - { - this.canBePickedUp = tagCompund.getBoolean("player") ? 1 : 0; - } + this.canBePickedUp = tagCompund.getByte("pickup"); } /** diff --git a/java/src/game/entity/projectile/EntityBox.java b/common/src/main/java/common/entity/projectile/EntityBox.java similarity index 93% rename from java/src/game/entity/projectile/EntityBox.java rename to common/src/main/java/common/entity/projectile/EntityBox.java index ccb85f1..0f094c5 100755 --- a/java/src/game/entity/projectile/EntityBox.java +++ b/common/src/main/java/common/entity/projectile/EntityBox.java @@ -1,13 +1,13 @@ -package game.entity.projectile; +package common.entity.projectile; -import game.entity.DamageSource; -import game.entity.npc.EntityGargoyle; -import game.entity.types.EntityLiving; -import game.init.Config; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.world.HitPosition; -import game.world.World; +import common.entity.DamageSource; +import common.entity.npc.EntityGargoyle; +import common.entity.types.EntityLiving; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.util.HitPosition; +import common.vars.Vars; +import common.world.World; public class EntityBox extends EntityProjectile { @@ -71,7 +71,7 @@ public class EntityBox extends EntityProjectile { if (movingObject.entity != null) { - if(Config.damageFlyingBox) { + if(Vars.damageFlyingBox) { if (this.shootingEntity != null) { if (movingObject.entity.attackEntityFrom(DamageSource.causeMobDamage(this.shootingEntity), diff --git a/common/src/main/java/common/entity/projectile/EntityBullet.java b/common/src/main/java/common/entity/projectile/EntityBullet.java new file mode 100755 index 0000000..b471f48 --- /dev/null +++ b/common/src/main/java/common/entity/projectile/EntityBullet.java @@ -0,0 +1,289 @@ +package common.entity.projectile; + +import java.util.List; + +import common.enchantment.EnchantmentHelper; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.types.EntityLiving; +import common.entity.types.IObjectData; +import common.entity.types.IProjectile; +import common.init.SoundEvent; +import common.tags.TagObject; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.HitPosition; +import common.util.Vec3; +import common.vars.Vars; +import common.world.State; +import common.world.World; + +public class EntityBullet extends Entity implements IProjectile, IObjectData { + private Entity shooter; + private int ticksMoved; + private int age; + private int damage = 5; + + public EntityBullet(World world) { + super(world); + this.renderDistWeight = 10.0D; + this.setSize(0.5F, 0.5F); + } + + public EntityBullet(World world, double x, double y, double z) { + super(world); + this.renderDistWeight = 10.0D; + this.setSize(0.5F, 0.5F); + this.setPosition(x, y, z); + } + + public EntityBullet(World world, double x, double y, double z, int data) { + this(world, x, y, z); + Entity entity = world.getEntityByID(data); + if(entity instanceof EntityLiving) + this.shooter = entity; + } + + public EntityBullet(World world, EntityLiving shooter, EntityLiving target, float velocity, float innacuracy) { + super(world); + this.renderDistWeight = 10.0D; + this.shooter = shooter; + this.posY = shooter.posY + (double)shooter.getEyeHeight() - 0.10000000149011612D; + double xd = target.posX - shooter.posX; + double yd = target.getEntityBoundingBox().minY + (double)(target.height * 0.7f) - this.posY; + double zd = target.posZ - shooter.posZ; + double xzd = (double)ExtMath.sqrtd(xd * xd + zd * zd); + if(xzd >= 1.0E-7D) { + float yaw = (float)(ExtMath.atan2(zd, xd) * 180.0D / Math.PI) - 90.0F; + float pitch = (float)(-(ExtMath.atan2(yd, xzd) * 180.0D / Math.PI)); + double x = xd / xzd; + double z = zd / xzd; + this.setLocationAndAngles(shooter.posX + x, this.posY, shooter.posZ + z, yaw, pitch); + this.setThrowableHeading(xd, yd, zd, velocity, innacuracy); + } + } + + public EntityBullet(World world, EntityLiving shooter, float velocity) { + super(world); + this.renderDistWeight = 10.0D; + this.shooter = shooter; + this.setSize(0.5F, 0.5F); + this.setLocationAndAngles(shooter.posX, shooter.posY + (double)shooter.getEyeHeight(), shooter.posZ, shooter.rotYaw, shooter.rotPitch); + this.posX -= (double)(ExtMath.cos(this.rotYaw / 180.0F * (float)Math.PI) * 0.16F); + this.posY -= 0.10000000149011612D; + this.posZ -= (double)(ExtMath.sin(this.rotYaw / 180.0F * (float)Math.PI) * 0.16F); + this.setPosition(this.posX, this.posY, this.posZ); + this.motionX = (double)(-ExtMath.sin(this.rotYaw / 180.0F * (float)Math.PI) * ExtMath.cos(this.rotPitch / 180.0F * (float)Math.PI)); + this.motionZ = (double)(ExtMath.cos(this.rotYaw / 180.0F * (float)Math.PI) * ExtMath.cos(this.rotPitch / 180.0F * (float)Math.PI)); + this.motionY = (double)(-ExtMath.sin(this.rotPitch / 180.0F * (float)Math.PI)); + this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, velocity, 0.5F); + } + + protected void entityInit() { + } + + public void setThrowableHeading(double x, double y, double z, float velocity, float inaccuracy) { + float sq = ExtMath.sqrtd(x * x + y * y + z * z); + x = x / (double)sq; + y = y / (double)sq; + z = z / (double)sq; + x = x + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; + y = y + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; + z = z + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; + x = x * (double)velocity; + y = y * (double)velocity; + z = z * (double)velocity; + this.motionX = x; + this.motionY = y; + this.motionZ = z; + float f1 = ExtMath.sqrtd(x * x + z * z); + this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(x, z) * 180.0D / Math.PI); + this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(y, (double)f1) * 180.0D / Math.PI); + } + + public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) { + this.setPosition(x, y, z); + this.setRotation(yaw, pitch); + } + + public void setVelocity(double x, double y, double z) { + this.motionX = x; + this.motionY = y; + this.motionZ = z; + if(this.prevPitch == 0.0F && this.prevYaw == 0.0F) { + float xz = ExtMath.sqrtd(x * x + z * z); + this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(x, z) * 180.0D / Math.PI); + this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(y, (double)xz) * 180.0D / Math.PI); + this.prevPitch = this.rotPitch; + this.prevYaw = this.rotYaw; + this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotYaw, this.rotPitch); + } + } + + public void onUpdate() { + super.onUpdate(); + + if(this.prevPitch == 0.0F && this.prevYaw == 0.0F) { + float xz = ExtMath.sqrtd(this.motionX * this.motionX + this.motionZ * this.motionZ); + this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI); + this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(this.motionY, (double)xz) * 180.0D / Math.PI); + } + + if(!this.worldObj.client && ++this.age >= 200) { + this.setDead(); + return; + } + ++this.ticksMoved; + Vec3 current = new Vec3(this.posX, this.posY, this.posZ); + Vec3 next = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); + HitPosition hit = this.worldObj.rayTraceBlocks(current, next, false, true, false); + current = new Vec3(this.posX, this.posY, this.posZ); + next = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); + + if(hit != null) { + next = new Vec3(hit.vec.xCoord, hit.vec.yCoord, hit.vec.zCoord); + } + + Entity entity = null; + List list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, + this.getEntityBoundingBox().addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D)); + double min = 0.0D; + + for(int i = 0; i < list.size(); ++i) { + Entity ent = list.get(i); + + if(ent.canBeCollidedWith() && (ent != this.shooter || this.ticksMoved >= 5)) { + float expand = 0.3F; + BoundingBox bb = ent.getEntityBoundingBox().expand((double)expand, (double)expand, (double)expand); + HitPosition entityHit = bb.calculateIntercept(current, next); + + if(entityHit != null) { + double dist = current.squareDistanceTo(entityHit.vec); + + if(dist < min || min == 0.0D) { + entity = ent; + min = dist; + } + } + } + } + + if(entity != null) { + hit = new HitPosition(entity); + } + + if(hit != null) { + if(hit.entity != null) { + float velo = ExtMath.sqrtd(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ); + int damage = ExtMath.ceild((double)velo * (double)this.damage); + + DamageSource source; + + if(this.shooter == null) { + source = DamageSource.causeShotDamage(this, this); + } + else { + source = DamageSource.causeShotDamage(this, this.shooter); + } + + if((this.worldObj.client || Vars.damageBullet) && hit.entity.attackEntityFrom(source, damage)) { + if(hit.entity instanceof EntityLiving living && this.shooter instanceof EntityLiving shooter) { + EnchantmentHelper.applyThornEnchantments(living, shooter); + EnchantmentHelper.applyArthropodEnchantments(shooter, living); + } + this.playSound(SoundEvent.METALHIT, 0.2F); + } + this.setDead(); + } + else if(!this.worldObj.client) { + State state = hit.block != null ? this.worldObj.getState(hit.block) : null; + if(state == null || state.getBlock().onShot(this.worldObj, hit.block, state, this)) { + this.playSound(SoundEvent.METALHIT, 0.5F); + this.setDead(); + } + } + } + + this.posX += this.motionX; + this.posY += this.motionY; + this.posZ += this.motionZ; + float xzMotion = ExtMath.sqrtd(this.motionX * this.motionX + this.motionZ * this.motionZ); + this.rotYaw = (float)(ExtMath.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI); + + for(this.rotPitch = (float)(ExtMath.atan2(this.motionY, (double)xzMotion) * 180.0D / Math.PI); this.rotPitch + - this.prevPitch < -180.0F; this.prevPitch -= 360.0F) { + ; + } + + while(this.rotPitch - this.prevPitch >= 180.0F) { + this.prevPitch += 360.0F; + } + + while(this.rotYaw - this.prevYaw < -180.0F) { + this.prevYaw -= 360.0F; + } + + while(this.rotYaw - this.prevYaw >= 180.0F) { + this.prevYaw += 360.0F; + } + + this.rotPitch = this.prevPitch + (this.rotPitch - this.prevPitch) * 0.2F; + this.rotYaw = this.prevYaw + (this.rotYaw - this.prevYaw) * 0.2F; + this.setPosition(this.posX, this.posY, this.posZ); + } + + public void writeEntity(TagObject tag) { + tag.setInt("damage", this.damage); + tag.setInt("age", this.age); + } + + public void readEntity(TagObject tag) { + this.damage = tag.getInt("damage"); + this.age = tag.getInt("age"); + } + + protected boolean canTriggerWalking() { + return false; + } + + public void setDamage(int damage) { + this.damage = damage; + } + + public int getDamage() { + return this.damage; + } + + public boolean canAttackWithItem() { + return false; + } + + public float getEyeHeight() { + return 0.0F; + } + + public int getTrackingRange() { + return 96; + } + + public int getUpdateFrequency() { + return 1; + } + + public boolean isSendingVeloUpdates() { + return false; + } + + public int getPacketData() { + return this.shooter != null ? this.shooter.getId() : this.getId(); + } + + public boolean hasSpawnVelocity() { + return true; + } + + public EntityType getType() { + return EntityType.PROJECTILE; + } +} diff --git a/java/src/game/entity/projectile/EntityDie.java b/common/src/main/java/common/entity/projectile/EntityDie.java similarity index 77% rename from java/src/game/entity/projectile/EntityDie.java rename to common/src/main/java/common/entity/projectile/EntityDie.java index f242b73..bc655a6 100755 --- a/java/src/game/entity/projectile/EntityDie.java +++ b/common/src/main/java/common/entity/projectile/EntityDie.java @@ -1,17 +1,17 @@ -package game.entity.projectile; +package common.entity.projectile; -import game.entity.DamageSource; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.entity.types.EntityThrowable; -import game.entity.types.IObjectData; -import game.init.Items; -import game.init.SoundEvent; -import game.item.ItemDie; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.world.HitPosition; -import game.world.World; +import common.entity.DamageSource; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.entity.types.EntityThrowable; +import common.entity.types.IObjectData; +import common.init.Items; +import common.init.SoundEvent; +import common.item.ItemDie; +import common.item.ItemStack; +import common.tags.TagObject; +import common.util.HitPosition; +import common.world.World; public class EntityDie extends EntityThrowable implements IObjectData { @@ -64,20 +64,20 @@ public class EntityDie extends EntityThrowable implements IObjectData return this.dataWatcher.getWatchableObjectInt(16); } - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setInteger("Sides", this.sides); - tagCompound.setInteger("Value", this.getValue()); - tagCompound.setBoolean("NoPickup", this.noPickup); + super.writeEntity(tagCompound); + tagCompound.setInt("Sides", this.sides); + tagCompound.setInt("Value", this.getValue()); + tagCompound.setBool("NoPickup", this.noPickup); } - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - this.sides = tagCompund.getInteger("Sides"); - this.setValue(tagCompund.getInteger("Value")); - this.noPickup = tagCompund.getBoolean("NoPickup"); + super.readEntity(tagCompund); + this.sides = tagCompund.getInt("Sides"); + this.setValue(tagCompund.getInt("Value")); + this.noPickup = tagCompund.getBool("NoPickup"); } public int getPacketData() { diff --git a/java/src/game/entity/projectile/EntityDynamite.java b/common/src/main/java/common/entity/projectile/EntityDynamite.java similarity index 72% rename from java/src/game/entity/projectile/EntityDynamite.java rename to common/src/main/java/common/entity/projectile/EntityDynamite.java index 0ca9029..e33b81e 100755 --- a/java/src/game/entity/projectile/EntityDynamite.java +++ b/common/src/main/java/common/entity/projectile/EntityDynamite.java @@ -1,17 +1,17 @@ -package game.entity.projectile; +package common.entity.projectile; -import game.entity.DamageSource; -import game.entity.EntityType; -import game.entity.types.EntityLiving; -import game.entity.types.EntityThrowable; -import game.entity.types.IObjectData; -import game.init.Config; -import game.init.ItemRegistry; -import game.init.Items; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.world.HitPosition; -import game.world.World; +import common.entity.DamageSource; +import common.entity.EntityType; +import common.entity.types.EntityLiving; +import common.entity.types.EntityThrowable; +import common.entity.types.IObjectData; +import common.init.ItemRegistry; +import common.init.Items; +import common.model.ParticleType; +import common.tags.TagObject; +import common.util.HitPosition; +import common.vars.Vars; +import common.world.World; public class EntityDynamite extends EntityThrowable implements IObjectData { @@ -36,7 +36,7 @@ public class EntityDynamite extends EntityThrowable implements IObjectData protected void onImpact(HitPosition pos) { - if (pos.entity != null && Config.knockDynamite) + if (pos.entity != null && Vars.knockDynamite) { pos.entity.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()), 0); } @@ -59,15 +59,15 @@ public class EntityDynamite extends EntityThrowable implements IObjectData } } - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); + super.writeEntity(tagCompound); tagCompound.setByte("Power", (byte)this.explosionSize); } - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); + super.readEntity(tagCompund); this.explosionSize = ((int)tagCompund.getByte("Power")) & 7; } diff --git a/java/src/game/entity/projectile/EntityEgg.java b/common/src/main/java/common/entity/projectile/EntityEgg.java similarity index 75% rename from java/src/game/entity/projectile/EntityEgg.java rename to common/src/main/java/common/entity/projectile/EntityEgg.java index c693d74..f010a1b 100755 --- a/java/src/game/entity/projectile/EntityEgg.java +++ b/common/src/main/java/common/entity/projectile/EntityEgg.java @@ -1,15 +1,15 @@ -package game.entity.projectile; +package common.entity.projectile; -import game.entity.DamageSource; -import game.entity.animal.EntityChicken; -import game.entity.types.EntityLiving; -import game.entity.types.EntityThrowable; -import game.init.Config; -import game.init.ItemRegistry; -import game.init.Items; -import game.renderer.particle.ParticleType; -import game.world.HitPosition; -import game.world.World; +import common.entity.DamageSource; +import common.entity.animal.EntityChicken; +import common.entity.types.EntityLiving; +import common.entity.types.EntityThrowable; +import common.init.ItemRegistry; +import common.init.Items; +import common.model.ParticleType; +import common.util.HitPosition; +import common.vars.Vars; +import common.world.World; public class EntityEgg extends EntityThrowable { @@ -33,12 +33,12 @@ public class EntityEgg extends EntityThrowable */ protected void onImpact(HitPosition p_70184_1_) { - if (p_70184_1_.entity != null && Config.knockEgg) + if (p_70184_1_.entity != null && Vars.knockEgg) { p_70184_1_.entity.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()), 0); } - if (!this.worldObj.client && this.rand.chance(8) && Config.mobs && Config.spawnEggChicken) + if (!this.worldObj.client && this.rand.chance(8) && Vars.mobs && Vars.spawnEggChicken) { int i = this.rand.chance(1, 4, 32); diff --git a/java/src/game/entity/projectile/EntityFireCharge.java b/common/src/main/java/common/entity/projectile/EntityFireCharge.java similarity index 87% rename from java/src/game/entity/projectile/EntityFireCharge.java rename to common/src/main/java/common/entity/projectile/EntityFireCharge.java index 4776022..36459ad 100755 --- a/java/src/game/entity/projectile/EntityFireCharge.java +++ b/common/src/main/java/common/entity/projectile/EntityFireCharge.java @@ -1,12 +1,12 @@ -package game.entity.projectile; +package common.entity.projectile; -import game.entity.DamageSource; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.world.BlockPos; -import game.world.HitPosition; -import game.world.World; +import common.entity.DamageSource; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.util.BlockPos; +import common.util.HitPosition; +import common.vars.Vars; +import common.world.World; public class EntityFireCharge extends EntityProjectile { @@ -43,7 +43,7 @@ public class EntityFireCharge extends EntityProjectile { if (movingObject.entity != null) { - boolean flag = Config.damageFireball && + boolean flag = Vars.damageFireball && movingObject.entity.attackEntityFrom(DamageSource.causeFireballDamage(this, this.shootingEntity), 6); if (flag) @@ -62,7 +62,7 @@ public class EntityFireCharge extends EntityProjectile if (this.shootingEntity != null && this.shootingEntity instanceof EntityLiving) // && !(this.shootingEntity.isPlayer())) { - flag1 = Config.mobGrief; + flag1 = Vars.mobGrief; } if (flag1) diff --git a/java/src/game/entity/projectile/EntityFireball.java b/common/src/main/java/common/entity/projectile/EntityFireball.java similarity index 66% rename from java/src/game/entity/projectile/EntityFireball.java rename to common/src/main/java/common/entity/projectile/EntityFireball.java index 93cc5d9..6ea5e9a 100755 --- a/java/src/game/entity/projectile/EntityFireball.java +++ b/common/src/main/java/common/entity/projectile/EntityFireball.java @@ -1,11 +1,11 @@ -package game.entity.projectile; +package common.entity.projectile; -import game.entity.DamageSource; -import game.entity.types.EntityLiving; -import game.init.Config; -import game.nbt.NBTTagCompound; -import game.world.HitPosition; -import game.world.World; +import common.entity.DamageSource; +import common.entity.types.EntityLiving; +import common.tags.TagObject; +import common.util.HitPosition; +import common.vars.Vars; +import common.world.World; public class EntityFireball extends EntityProjectile { @@ -36,13 +36,13 @@ public class EntityFireball extends EntityProjectile { if (!this.worldObj.client) { - if (Config.damageFireball && movingObject.entity != null) + if (Vars.damageFireball && movingObject.entity != null) { movingObject.entity.attackEntityFrom(DamageSource.causeFireballDamage(this, this.shootingEntity), 8); this.applyEnchantments(this.shootingEntity, movingObject.entity); } - boolean flag = Config.mobGrief; + boolean flag = Vars.mobGrief; this.worldObj.newExplosion(this.shootingEntity, this.posX, this.posY, this.posZ, (float)this.explosionPower, flag, false, true); this.setDead(); } @@ -56,22 +56,18 @@ public class EntityFireball extends EntityProjectile /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setInteger("ExplosionPower", this.explosionPower); + super.writeEntity(tagCompound); + tagCompound.setInt("ExplosionPower", this.explosionPower); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - - if (tagCompund.hasKey("ExplosionPower", 99)) - { - this.explosionPower = tagCompund.getInteger("ExplosionPower"); - } + super.readEntity(tagCompund); + this.explosionPower = tagCompund.getInt("ExplosionPower"); } } diff --git a/java/src/game/entity/projectile/EntityHook.java b/common/src/main/java/common/entity/projectile/EntityHook.java similarity index 91% rename from java/src/game/entity/projectile/EntityHook.java rename to common/src/main/java/common/entity/projectile/EntityHook.java index 15fc77f..f01f65e 100755 --- a/java/src/game/entity/projectile/EntityHook.java +++ b/common/src/main/java/common/entity/projectile/EntityHook.java @@ -1,32 +1,31 @@ -package game.entity.projectile; +package common.entity.projectile; import java.util.List; -import game.block.Block; -import game.enchantment.EnchantmentHelper; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.item.EntityItem; -import game.entity.item.EntityXp; -import game.entity.npc.EntityNPC; -import game.entity.types.IObjectData; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.Config; -import game.init.Items; -import game.init.SoundEvent; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.HitPosition; -import game.world.Vec3; -import game.world.World; -import game.world.WorldServer; -import game.worldgen.LootConstants; +import common.block.Block; +import common.enchantment.EnchantmentHelper; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.item.EntityItem; +import common.entity.item.EntityXp; +import common.entity.npc.EntityNPC; +import common.entity.types.IObjectData; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.Items; +import common.init.SoundEvent; +import common.item.ItemStack; +import common.model.ParticleType; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.HitPosition; +import common.util.Vec3; +import common.vars.Vars; +import common.world.World; +import common.world.AWorldServer; public class EntityHook extends Entity implements IObjectData { @@ -122,7 +121,7 @@ public class EntityHook extends Entity implements IObjectData { } - public boolean writeToNBTOptional(NBTTagCompound tagCompund) + public boolean writeOptional(TagObject tagCompund) { return false; } @@ -165,14 +164,14 @@ public class EntityHook extends Entity implements IObjectData this.ticksInGround = 0; } - public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) + public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) { this.fishX = x; this.fishY = y; this.fishZ = z; this.fishYaw = (double)yaw; this.fishPitch = (double)pitch; - this.fishPosRotationIncrements = posRotationIncrements; + this.fishPosRotationIncrements = 3; this.motionX = this.clientMotionX; this.motionY = this.clientMotionY; this.motionZ = this.clientMotionZ; @@ -317,10 +316,10 @@ public class EntityHook extends Entity implements IObjectData { if (movingobjectposition.entity != null) { - if (this.worldObj.client || !Config.knockHook || movingobjectposition.entity.attackEntityFrom( - DamageSource.causeThrownDamage(this, this.angler), 0) || !Config.hookCheckDamage) + if (this.worldObj.client || !Vars.knockHook || movingobjectposition.entity.attackEntityFrom( + DamageSource.causeThrownDamage(this, this.angler), 0) || !Vars.hookCheckDamage) { - if(this.worldObj.client || Config.hookEntity) // && (!(movingobjectposition.entity.isPlayer()) + if(this.worldObj.client || Vars.hookEntity) // && (!(movingobjectposition.entity.isPlayer()) // || !((EntityNPC)movingobjectposition.entity).creative))) this.caughtEntity = movingobjectposition.entity; } @@ -385,7 +384,7 @@ public class EntityHook extends Entity implements IObjectData if (!this.worldObj.client && d10 > 0.0D) { - WorldServer worldserver = (WorldServer)this.worldObj; + AWorldServer worldserver = (AWorldServer)this.worldObj; int l = 1; BlockPos blockpos = (new BlockPos(this)).up(); @@ -518,37 +517,39 @@ public class EntityHook extends Entity implements IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { tagCompound.setShort("xTile", (short)this.xTile); tagCompound.setShort("yTile", (short)this.yTile); tagCompound.setShort("zTile", (short)this.zTile); - String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(this.inTile); - tagCompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); + if(this.inTile != null) { + String id = BlockRegistry.getNameFromBlock(this.inTile); + tagCompound.setString("inTile", id == null ? "" : id.toString()); + } tagCompound.setByte("shake", (byte)this.shake); - tagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0)); + tagCompound.setBool("inGround", this.inGround); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { this.xTile = tagCompund.getShort("xTile"); this.yTile = tagCompund.getShort("yTile"); this.zTile = tagCompund.getShort("zTile"); - if (tagCompund.hasKey("inTile", 8)) + if (tagCompund.hasString("inTile")) { - this.inTile = BlockRegistry.getByIdFallback(tagCompund.getString("inTile")); + this.inTile = BlockRegistry.getRegisteredBlock(tagCompund.getString("inTile")); } else { - this.inTile = BlockRegistry.getBlockById(tagCompund.getByte("inTile") & 255); + this.inTile = null; } this.shake = tagCompund.getByte("shake") & 255; - this.inGround = tagCompund.getByte("inGround") == 1; + this.inGround = tagCompund.getBool("inGround"); } public int handleHookRetraction() @@ -585,7 +586,7 @@ public class EntityHook extends Entity implements IObjectData entityitem.motionY = d3 * d9 + (double)ExtMath.sqrtd(d7) * 0.08D; entityitem.motionZ = d5 * d9; this.worldObj.spawnEntityInWorld(entityitem); - if(Config.fishingXP) + if(Vars.fishingXP) this.angler.worldObj.spawnEntityInWorld(new EntityXp(this.angler.worldObj, this.angler.posX, this.angler.posY + 0.5D, this.angler.posZ + 0.5D, this.rand.roll(6))); i = 1; } @@ -614,7 +615,7 @@ public class EntityHook extends Entity implements IObjectData if (f < f1) { // this.angler.triggerAchievement(StatRegistry.junkFishedStat); - return ((RngFishable)LootConstants.FISHING_JUNK.pick(this.rand)).getItemStack(this.rand); + return ((RngFishable)FishConstants.FISHING_JUNK.pick(this.rand)).getItemStack(this.rand); } else { @@ -623,13 +624,13 @@ public class EntityHook extends Entity implements IObjectData if (f < f2) { // this.angler.triggerAchievement(StatRegistry.treasureFishedStat); - return ((RngFishable)LootConstants.FISHING_TREASURE.pick(this.rand)).getItemStack(this.rand); + return ((RngFishable)FishConstants.FISHING_TREASURE.pick(this.rand)).getItemStack(this.rand); } else { float f3 = f - f2; // this.angler.triggerAchievement(StatRegistry.fishCaughtStat); - return ((RngFishable)LootConstants.FISH_TYPES.pick(this.rand)).getItemStack(this.rand); + return ((RngFishable)FishConstants.FISH_TYPES.pick(this.rand)).getItemStack(this.rand); } } } diff --git a/java/src/game/entity/projectile/EntityPotion.java b/common/src/main/java/common/entity/projectile/EntityPotion.java similarity index 83% rename from java/src/game/entity/projectile/EntityPotion.java rename to common/src/main/java/common/entity/projectile/EntityPotion.java index 21f86b5..bcee549 100755 --- a/java/src/game/entity/projectile/EntityPotion.java +++ b/common/src/main/java/common/entity/projectile/EntityPotion.java @@ -1,19 +1,19 @@ -package game.entity.projectile; +package common.entity.projectile; import java.util.List; -import game.entity.types.EntityLiving; -import game.entity.types.EntityThrowable; -import game.entity.types.IObjectData; -import game.init.Items; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.HitPosition; -import game.world.World; +import common.entity.types.EntityLiving; +import common.entity.types.EntityThrowable; +import common.entity.types.IObjectData; +import common.init.Items; +import common.item.ItemStack; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.HitPosition; +import common.world.World; public class EntityPotion extends EntityThrowable implements IObjectData { @@ -125,7 +125,7 @@ public class EntityPotion extends EntityThrowable implements IObjectData for (PotionEffect potioneffect : list) { Potion i = potioneffect.getPotion(); - if(!entitylivingbase.isPotionApplicable(i)) + if(!entitylivingbase.isPotionApplicable(i, potioneffect.getAmplifier())) continue; if (i.isInstant()) @@ -158,17 +158,17 @@ public class EntityPotion extends EntityThrowable implements IObjectData /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); + super.readEntity(tagCompund); - if (tagCompund.hasKey("Potion", 10)) + if (tagCompund.hasObject("Potion")) { - this.potionDamage = ItemStack.loadItemStackFromNBT(tagCompund.getCompoundTag("Potion")); + this.potionDamage = ItemStack.readFromTag(tagCompund.getObject("Potion")); } else { - this.setPotionDamage(tagCompund.getInteger("potionValue")); + this.setPotionDamage(tagCompund.getInt("potionValue")); } if (this.potionDamage == null) @@ -180,13 +180,13 @@ public class EntityPotion extends EntityThrowable implements IObjectData /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); + super.writeEntity(tagCompound); if (this.potionDamage != null) { - tagCompound.setTag("Potion", this.potionDamage.writeToNBT(new NBTTagCompound())); + tagCompound.setObject("Potion", this.potionDamage.writeTags(new TagObject())); } } diff --git a/java/src/game/entity/projectile/EntityProjectile.java b/common/src/main/java/common/entity/projectile/EntityProjectile.java similarity index 87% rename from java/src/game/entity/projectile/EntityProjectile.java rename to common/src/main/java/common/entity/projectile/EntityProjectile.java index cde6ff9..394801e 100755 --- a/java/src/game/entity/projectile/EntityProjectile.java +++ b/common/src/main/java/common/entity/projectile/EntityProjectile.java @@ -1,22 +1,21 @@ -package game.entity.projectile; +package common.entity.projectile; import java.util.List; -import game.block.Block; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.types.EntityLiving; -import game.init.BlockRegistry; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.HitPosition; -import game.world.Vec3; -import game.world.World; +import common.block.Block; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.types.EntityLiving; +import common.init.BlockRegistry; +import common.model.ParticleType; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.HitPosition; +import common.util.Vec3; +import common.world.World; public abstract class EntityProjectile extends Entity { @@ -254,50 +253,53 @@ public abstract class EntityProjectile extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { tagCompound.setShort("xTile", (short)this.xTile); tagCompound.setShort("yTile", (short)this.yTile); tagCompound.setShort("zTile", (short)this.zTile); - String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(this.inTile); - tagCompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); - tagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0)); - tagCompound.setTag("direction", this.newDoubleNBTList(this.motionX, this.motionY, this.motionZ)); - tagCompound.setInteger("Age", this.age); + if(this.inTile != null) { + String id = BlockRegistry.getNameFromBlock(this.inTile); + tagCompound.setString("inTile", id == null ? "" : id.toString()); + } + tagCompound.setBool("inGround", this.inGround); + tagCompound.setDouble("dirX", this.motionX); + tagCompound.setDouble("dirY", this.motionY); + tagCompound.setDouble("dirZ", this.motionZ); + tagCompound.setInt("Age", this.age); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { this.xTile = tagCompund.getShort("xTile"); this.yTile = tagCompund.getShort("yTile"); this.zTile = tagCompund.getShort("zTile"); - if (tagCompund.hasKey("inTile", 8)) + if (tagCompund.hasString("inTile")) { - this.inTile = BlockRegistry.getByIdFallback(tagCompund.getString("inTile")); + this.inTile = BlockRegistry.getRegisteredBlock(tagCompund.getString("inTile")); } else { - this.inTile = BlockRegistry.getBlockById(tagCompund.getByte("inTile") & 255); + this.inTile = null; } - this.inGround = tagCompund.getByte("inGround") == 1; + this.inGround = tagCompund.getBool("inGround"); - if (tagCompund.hasKey("direction", 9)) + if (tagCompund.hasDouble("dirX") && tagCompund.hasDouble("dirY") && tagCompund.hasDouble("dirZ")) { - NBTTagList nbttaglist = tagCompund.getTagList("direction", 6); - this.motionX = nbttaglist.getDoubleAt(0); - this.motionY = nbttaglist.getDoubleAt(1); - this.motionZ = nbttaglist.getDoubleAt(2); + this.motionX = tagCompund.getDouble("dirX"); + this.motionY = tagCompund.getDouble("dirY"); + this.motionZ = tagCompund.getDouble("dirZ"); } else { this.setDead(); } - this.age = tagCompund.getInteger("Age"); + this.age = tagCompund.getInt("Age"); } /** diff --git a/java/src/game/entity/projectile/EntitySnowball.java b/common/src/main/java/common/entity/projectile/EntitySnowball.java similarity index 78% rename from java/src/game/entity/projectile/EntitySnowball.java rename to common/src/main/java/common/entity/projectile/EntitySnowball.java index 883d290..b2aa02c 100755 --- a/java/src/game/entity/projectile/EntitySnowball.java +++ b/common/src/main/java/common/entity/projectile/EntitySnowball.java @@ -1,12 +1,12 @@ -package game.entity.projectile; +package common.entity.projectile; -import game.entity.DamageSource; -import game.entity.types.EntityLiving; -import game.entity.types.EntityThrowable; -import game.init.Config; -import game.renderer.particle.ParticleType; -import game.world.HitPosition; -import game.world.World; +import common.entity.DamageSource; +import common.entity.types.EntityLiving; +import common.entity.types.EntityThrowable; +import common.model.ParticleType; +import common.util.HitPosition; +import common.vars.Vars; +import common.world.World; public class EntitySnowball extends EntityThrowable { @@ -39,7 +39,7 @@ public class EntitySnowball extends EntityThrowable // i = 3; // } - if(Config.knockSnowball) + if(Vars.knockSnowball) p_70184_1_.entity.attackEntityFrom(DamageSource.causeThrownDamage(this, this.getThrower()), 0); } diff --git a/common/src/main/java/common/entity/projectile/FishConstants.java b/common/src/main/java/common/entity/projectile/FishConstants.java new file mode 100644 index 0000000..890d8c7 --- /dev/null +++ b/common/src/main/java/common/entity/projectile/FishConstants.java @@ -0,0 +1,29 @@ +package common.entity.projectile; + +import common.color.DyeColor; +import common.init.Blocks; +import common.init.Items; +import common.item.ItemFishFood; +import common.item.ItemStack; +import common.rng.WeightedList; + +public abstract class FishConstants { + public static final WeightedList FISHING_JUNK = new WeightedList( + (new RngFishable(new ItemStack(Items.leather_boots), 10)).setMaxDamagePercent(0.9F), new RngFishable(new ItemStack(Items.leather), 10), + new RngFishable(new ItemStack(Items.bone), 10), new RngFishable(new ItemStack(Items.potion), 10), + new RngFishable(new ItemStack(Items.string), 5), (new RngFishable(new ItemStack(Items.fishing_rod), 2)).setMaxDamagePercent(0.9F), + new RngFishable(new ItemStack(Items.bowl), 10), new RngFishable(new ItemStack(Items.stick), 5), + new RngFishable(new ItemStack(Items.dye, 10, DyeColor.BLACK.getDyeDamage()), 1), + new RngFishable(new ItemStack(Blocks.tripwire_hook), 10), new RngFishable(new ItemStack(Items.rotten_flesh), 10)); + public static final WeightedList FISHING_TREASURE = new WeightedList( + new RngFishable(new ItemStack(Blocks.waterlily), 1), new RngFishable(new ItemStack(Items.name_tag), 1), + new RngFishable(new ItemStack(Items.saddle), 1), + (new RngFishable(new ItemStack(Items.bow), 1)).setMaxDamagePercent(0.25F).setEnchantable(), + (new RngFishable(new ItemStack(Items.fishing_rod), 1)).setMaxDamagePercent(0.25F).setEnchantable(), + (new RngFishable(new ItemStack(Items.book), 1)).setEnchantable()); + public static final WeightedList FISH_TYPES = new WeightedList( + new RngFishable(new ItemStack(Items.fish, 1, ItemFishFood.FishType.COD.getMetadata()), 60), + new RngFishable(new ItemStack(Items.fish, 1, ItemFishFood.FishType.SALMON.getMetadata()), 25), + new RngFishable(new ItemStack(Items.fish, 1, ItemFishFood.FishType.CLOWNFISH.getMetadata()), 2), + new RngFishable(new ItemStack(Items.fish, 1, ItemFishFood.FishType.PUFFERFISH.getMetadata()), 13)); +} diff --git a/java/src/game/entity/projectile/RngFishable.java b/common/src/main/java/common/entity/projectile/RngFishable.java similarity index 88% rename from java/src/game/entity/projectile/RngFishable.java rename to common/src/main/java/common/entity/projectile/RngFishable.java index 9d4c6c8..700ec68 100755 --- a/java/src/game/entity/projectile/RngFishable.java +++ b/common/src/main/java/common/entity/projectile/RngFishable.java @@ -1,9 +1,9 @@ -package game.entity.projectile; +package common.entity.projectile; -import game.enchantment.EnchantmentHelper; -import game.item.ItemStack; -import game.rng.Random; -import game.rng.RngItem; +import common.enchantment.EnchantmentHelper; +import common.item.ItemStack; +import common.rng.Random; +import common.rng.RngItem; public class RngFishable extends RngItem { diff --git a/common/src/main/java/common/entity/types/CombatEntry.java b/common/src/main/java/common/entity/types/CombatEntry.java new file mode 100755 index 0000000..9d9b6e7 --- /dev/null +++ b/common/src/main/java/common/entity/types/CombatEntry.java @@ -0,0 +1,6 @@ +package common.entity.types; + +import common.entity.DamageSource; + +public record CombatEntry(DamageSource source, int damage, String blockType, float fallDistance) { +} diff --git a/java/src/game/entity/types/EntityAnimal.java b/common/src/main/java/common/entity/types/EntityAnimal.java similarity index 90% rename from java/src/game/entity/types/EntityAnimal.java rename to common/src/main/java/common/entity/types/EntityAnimal.java index e9f995d..e8a0542 100755 --- a/java/src/game/entity/types/EntityAnimal.java +++ b/common/src/main/java/common/entity/types/EntityAnimal.java @@ -1,22 +1,21 @@ -package game.entity.types; +package common.entity.types; import java.util.Set; -import game.collect.Sets; - -import game.block.Block; -import game.entity.DamageSource; -import game.entity.EntityType; -import game.entity.npc.Alignment; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Items; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.World; +import common.block.Block; +import common.collect.Sets; +import common.entity.DamageSource; +import common.entity.EntityType; +import common.entity.npc.Alignment; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.item.ItemStack; +import common.model.ParticleType; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.World; public abstract class EntityAnimal extends EntityLiving { @@ -101,19 +100,19 @@ public abstract class EntityAnimal extends EntityLiving /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); - tagCompound.setInteger("InLove", this.inLove); + super.writeEntity(tagCompound); + tagCompound.setInt("InLove", this.inLove); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); - this.setInLove(tagCompund.getInteger("InLove"), true); + super.readEntity(tagCompund); + this.setInLove(tagCompund.getInt("InLove"), true); } /** @@ -201,9 +200,9 @@ public abstract class EntityAnimal extends EntityLiving { // if (!player.creative) // { - --stack.stackSize; + --stack.size; - if (stack.stackSize <= 0) + if (stack.size <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } diff --git a/java/src/game/entity/types/EntityBodyHelper.java b/common/src/main/java/common/entity/types/EntityBodyHelper.java similarity index 97% rename from java/src/game/entity/types/EntityBodyHelper.java rename to common/src/main/java/common/entity/types/EntityBodyHelper.java index 0fa1d8c..26160ea 100755 --- a/java/src/game/entity/types/EntityBodyHelper.java +++ b/common/src/main/java/common/entity/types/EntityBodyHelper.java @@ -1,6 +1,6 @@ -package game.entity.types; +package common.entity.types; -import game.util.ExtMath; +import common.util.ExtMath; public class EntityBodyHelper { diff --git a/java/src/game/entity/types/EntityLiving.java b/common/src/main/java/common/entity/types/EntityLiving.java similarity index 86% rename from java/src/game/entity/types/EntityLiving.java rename to common/src/main/java/common/entity/types/EntityLiving.java index 560d5b7..46a66ca 100755 --- a/java/src/game/entity/types/EntityLiving.java +++ b/common/src/main/java/common/entity/types/EntityLiving.java @@ -1,79 +1,73 @@ -package game.entity.types; +package common.entity.types; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; - import java.util.function.Predicate; -import game.collect.Lists; -import game.collect.Maps; -import game.ai.EntityAIBase; -import game.ai.EntityAIMoveTowardsRestriction; -import game.ai.EntityAITasks; -import game.ai.EntityJumpHelper; -import game.ai.EntityLookHelper; -import game.ai.EntityMoveHelper; -import game.ai.EntitySenses; -import game.audio.SoundType; -import game.block.Block; -import game.color.TextColor; -import game.enchantment.EnchantmentHelper; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityDamageSource; -import game.entity.animal.EntityWolf; -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.AttributeMap; -import game.entity.attributes.AttributeModifier; -import game.entity.attributes.Attributes; -import game.entity.item.EntityItem; -import game.entity.item.EntityLeashKnot; -import game.entity.item.EntityXp; -import game.entity.npc.Alignment; -import game.entity.npc.Energy; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityArrow; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.Config; -import game.init.EntityRegistry; -import game.init.ItemRegistry; -import game.init.Items; -import game.init.SoundEvent; -import game.item.Item; -import game.item.ItemArmor; -import game.item.ItemMonsterPlacer; -import game.item.ItemStack; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.network.Player; -import game.packet.S1BPacketEntityAttach; -import game.packet.SPacketAnimation; -import game.packet.SPacketCollectItem; -import game.pathfinding.PathNavigate; -import game.pathfinding.PathNavigateGround; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.potion.PotionHelper; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.State; -import game.world.Vec3; -import game.world.World; -import game.world.WorldServer; +import common.ai.EntityAIBase; +import common.ai.EntityAIMoveTowardsRestriction; +import common.ai.EntityAITasks; +import common.ai.EntityJumpHelper; +import common.ai.EntityLookHelper; +import common.ai.EntityMoveHelper; +import common.ai.EntitySenses; +import common.attributes.Attribute; +import common.attributes.AttributeMap; +import common.block.Block; +import common.block.SoundType; +import common.collect.Lists; +import common.collect.Maps; +import common.color.TextColor; +import common.enchantment.EnchantmentHelper; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityDamageSource; +import common.entity.animal.EntityWolf; +import common.entity.item.EntityItem; +import common.entity.item.EntityLeashKnot; +import common.entity.item.EntityXp; +import common.entity.npc.Alignment; +import common.entity.npc.Energy; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityArrow; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.EntityRegistry; +import common.init.ItemRegistry; +import common.init.Items; +import common.init.SoundEvent; +import common.item.Item; +import common.item.ItemArmor; +import common.item.ItemMonsterPlacer; +import common.item.ItemStack; +import common.model.ParticleType; +import common.network.IPlayer; +import common.packet.SPacketEntityAttach; +import common.packet.SPacketAnimation; +import common.packet.SPacketCollectItem; +import common.pathfinding.PathNavigate; +import common.pathfinding.PathNavigateGround; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.potion.PotionHelper; +import common.rng.Random; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Vec3; +import common.vars.Vars; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public abstract class EntityLiving extends Entity { private static final ItemStack[] EMPTY_INV = new ItemStack[5]; - private AttributeMap attributes; + protected AttributeMap attributes = new AttributeMap(); private final List combat = Lists.newArrayList(); private final Map effects = Maps.newEnumMap(Potion.class); public int soundTimer; @@ -89,7 +83,7 @@ public abstract class EntityLiving extends Entity private EntitySenses senses; private boolean leashed; private Entity leashedTo; - private NBTTagCompound leashTag; + private TagObject leashTag; public float prevCamPitch; public float camPitch; @@ -159,6 +153,8 @@ public abstract class EntityLiving extends Entity private float ageHeight; private EntityAIBase aiBase = new EntityAIMoveTowardsRestriction(this, 1.0D); private boolean isMovementAITaskSet; + private float baseSpeed = 0.7f; + private float modSpeed = 1.0f; public EntityLiving(World worldIn) { @@ -185,23 +181,16 @@ public abstract class EntityLiving extends Entity protected void entityInit() { - this.dataWatcher.addObject(7, Integer.valueOf(0)); - this.dataWatcher.addObject(8, Byte.valueOf((byte)0)); - this.dataWatcher.addObject(9, Byte.valueOf((byte)0)); - this.dataWatcher.addObject(6, Integer.valueOf(1)); - this.dataWatcher.addObject(12, Integer.valueOf(0)); -// this.dataWatcher.addObject(15, Byte.valueOf((byte)0)); + this.dataWatcher.addObject(2, 0); // potion color + this.dataWatcher.addObject(3, (byte)0); // potion ambient + this.dataWatcher.addObject(4, (byte)0); // arrows + this.dataWatcher.addObject(5, 1); // max health + this.dataWatcher.addObject(6, 1); // health + this.dataWatcher.addObject(7, 0); // age } protected void applyEntityAttributes() { - this.getAttributeMap().registerAttribute(Attributes.MAX_HEALTH); - this.getAttributeMap().registerAttribute(Attributes.KNOCKBACK_RESISTANCE); - this.getAttributeMap().registerAttribute(Attributes.MOVEMENT_SPEED); - this.getAttributeMap().registerAttribute(Attributes.RADIATION); - this.getAttributeMap().registerAttribute(Attributes.RADIATION_RESISTANCE); - - this.getAttributeMap().registerAttribute(Attributes.FOLLOW_RANGE).setBaseValue(16.0D); } protected void updateFallState(double y, boolean onGroundIn, Block blockIn, BlockPos pos) @@ -225,7 +214,7 @@ public abstract class EntityLiving extends Entity Block block = iblockstate.getBlock(); float f = (float)ExtMath.ceilf(this.fallDistance - 3.0F); - if (block.getMaterial() != Material.air) + if (block != Blocks.air) { double d0 = (double)Math.min(0.2F + f / 15.0F, 10.0F); @@ -235,7 +224,7 @@ public abstract class EntityLiving extends Entity } int i = (int)(150.0D * d0); - ((WorldServer)this.worldObj).spawnParticle(ParticleType.BLOCK_DUST, this.posX, this.posY, this.posZ, i, 0.0D, 0.0D, 0.0D, 0.15000000596046448D, BlockRegistry.getStateId(iblockstate)); + ((AWorldServer)this.worldObj).spawnParticle(ParticleType.BLOCK_DUST, this.posX, this.posY, this.posZ, i, 0.0D, 0.0D, 0.0D, 0.15000000596046448D, BlockRegistry.getStateId(iblockstate)); } } @@ -256,7 +245,7 @@ public abstract class EntityLiving extends Entity if (this.isEntityAlive()) { - if ((this.worldObj.client || Config.damageWall) && this.isEntityInsideOpaqueBlock()) + if ((this.worldObj.client || Vars.damageWall) && this.isEntityInsideOpaqueBlock()) { this.attackEntityFrom(DamageSource.inWall, 1); } @@ -368,10 +357,10 @@ public abstract class EntityLiving extends Entity } if(!this.worldObj.client) { - if(!this.firstEffectUpdate && Config.radiation) { // && + if(!this.firstEffectUpdate && Vars.radiation) { // && // (!(this.isPlayer()) || !((EntityNPCMP)this).creative)) { - float radiation = this.radiation + (float)this.attributes.getAttributeInstance(Attributes.RADIATION).getAttributeValue(); - radiation -= (float)this.attributes.getAttributeInstance(Attributes.RADIATION_RESISTANCE).getAttributeValue(); + float radiation = this.radiation + this.attributes.get(Attribute.RADIATION); + radiation -= 10.0f + this.attributes.get(Attribute.RADIATION_RESISTANCE); // if(this.isPlayer()) // Log.SERVER.info("rad:" + radiation); if(radiation >= 0.0f) { @@ -430,7 +419,7 @@ public abstract class EntityLiving extends Entity if (this.deathTime == 20) { - if (!this.worldObj.client && (this.recentlyHit > 0 || this.isPlayer()) && this.canDropLoot() && Config.mobXP) + if (!this.worldObj.client && (this.recentlyHit > 0 || this.isPlayer()) && this.canDropLoot() && Vars.mobXP) { int i = this.getExperiencePoints(this.playerAttacker); @@ -541,50 +530,34 @@ public abstract class EntityLiving extends Entity /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - tagCompound.setInteger("Health", this.getHealth()); + tagCompound.setInt("MaxHealth", this.getMaxHealth()); + tagCompound.setInt("Health", this.getHealth()); // tagCompound.setShort("Health", (short)((int)Math.ceil((double)this.getHealth()))); tagCompound.setShort("HurtTime", (short)this.hurtTime); - tagCompound.setInteger("HurtByTimestamp", this.lastAttacked); + tagCompound.setInt("HurtByTimestamp", this.lastAttacked); tagCompound.setFloat("Radiation", this.radiation); tagCompound.setShort("DeathTime", (short)this.deathTime); - tagCompound.setInteger("Absorption", this.getAbsorptionAmount()); - - for (ItemStack itemstack : this.getInventory()) - { - if (itemstack != null) - { - this.attributes.removeAttributeModifiers(itemstack.getAttributeModifiers(1)); - } - } - - tagCompound.setTag("Attributes", Attributes.writeBaseAttributeMapToNBT(this.getAttributeMap())); - - for (ItemStack itemstack1 : this.getInventory()) - { - if (itemstack1 != null) - { - this.attributes.applyAttributeModifiers(itemstack1.getAttributeModifiers(1)); - } - } + tagCompound.setInt("Absorption", this.getAbsorptionAmount()); + tagCompound.setFloat("SpeedBase", this.getSpeedBase()); if (!this.effects.isEmpty()) { - NBTTagList nbttaglist = new NBTTagList(); + List nbttaglist = Lists.newArrayList(); for (PotionEffect potioneffect : this.effects.values()) { - nbttaglist.appendTag(potioneffect.toNbt()); + nbttaglist.add(potioneffect.toTags()); } - tagCompound.setTag("ActiveEffects", nbttaglist); + tagCompound.setList("ActiveEffects", nbttaglist); } - tagCompound.setBoolean("Leashed", this.leashed); + tagCompound.setBool("Leashed", this.leashed); if(this.leashedTo != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + TagObject nbttagcompound1 = new TagObject(); // if(this.leashedTo.isPlayer()) { // nbttagcompound1.setString("PlayerName", ((EntityNPC)this.leashedTo).getUser()); @@ -592,18 +565,18 @@ public abstract class EntityLiving extends Entity // else if(this.leashedTo instanceof EntityLeashKnot) { BlockPos blockpos = ((EntityLeashKnot)this.leashedTo).getHangingPosition(); - nbttagcompound1.setInteger("X", blockpos.getX()); - nbttagcompound1.setInteger("Y", blockpos.getY()); - nbttagcompound1.setInteger("Z", blockpos.getZ()); + nbttagcompound1.setInt("X", blockpos.getX()); + nbttagcompound1.setInt("Y", blockpos.getY()); + nbttagcompound1.setInt("Z", blockpos.getZ()); } - tagCompound.setTag("Leash", nbttagcompound1); + tagCompound.setObject("Leash", nbttagcompound1); } // if(this.isAIDisabled()) { // tagCompound.setBoolean("NoAI", this.isAIDisabled()); // } - tagCompound.setInteger("Age", this.getGrowingAge()); + tagCompound.setInt("Age", this.getGrowingAge()); if(this.description != null) tagCompound.setString("Description", this.description); } @@ -611,23 +584,19 @@ public abstract class EntityLiving extends Entity /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - this.setAbsorptionAmount(tagCompund.getInteger("Absorption")); + this.setAbsorptionAmount(tagCompund.getInt("Absorption")); + this.setSpeedBase(tagCompund.getFloat("SpeedBase")); - if (tagCompund.hasKey("Attributes", 9) && this.worldObj != null && !this.worldObj.client) + if (tagCompund.hasList("ActiveEffects")) { - Attributes.setAttributeModifiers(this.getAttributeMap(), tagCompund.getTagList("Attributes", 10)); - } + List nbttaglist = tagCompund.getList("ActiveEffects"); - if (tagCompund.hasKey("ActiveEffects", 9)) - { - NBTTagList nbttaglist = tagCompund.getTagList("ActiveEffects", 10); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); - PotionEffect potioneffect = PotionEffect.fromNbt(nbttagcompound); + TagObject nbttagcompound = nbttaglist.get(i); + PotionEffect potioneffect = PotionEffect.fromTags(nbttagcompound); if (potioneffect != null && !potioneffect.getPotion().isInstant()) { @@ -636,9 +605,10 @@ public abstract class EntityLiving extends Entity } } - if (tagCompund.hasKey("Health", 3)) + this.setMaxHealth(Math.max(1, tagCompund.getInt("MaxHealth"))); + if (tagCompund.hasInt("Health")) { - this.setHealth(tagCompund.getInteger("Health")); + this.setHealth(tagCompund.getInt("Health")); } else { @@ -660,20 +630,20 @@ public abstract class EntityLiving extends Entity this.hurtTime = tagCompund.getShort("HurtTime"); this.deathTime = tagCompund.getShort("DeathTime"); - this.lastAttacked = tagCompund.getInteger("HurtByTimestamp"); + this.lastAttacked = tagCompund.getInt("HurtByTimestamp"); this.radiation = tagCompund.getFloat("Radiation"); if(!(this.isPlayer())) { - this.leashed = tagCompund.getBoolean("Leashed"); + this.leashed = tagCompund.getBool("Leashed"); - if(this.leashed && tagCompund.hasKey("Leash", 10)) { - this.leashTag = tagCompund.getCompoundTag("Leash"); + if(this.leashed && tagCompund.hasObject("Leash")) { + this.leashTag = tagCompund.getObject("Leash"); } } // this.setNoAI(tagCompund.getBoolean("NoAI")); - this.setGrowingAge(tagCompund.getInteger("Age")); - this.description = tagCompund.hasKey("Description", 8) ? tagCompund.getString("Description") : null; + this.setGrowingAge(tagCompund.getInt("Age")); + this.description = tagCompund.hasString("Description") ? tagCompund.getString("Description") : null; if(this.description != null && this.description.isEmpty()) this.description = null; } @@ -711,8 +681,8 @@ public abstract class EntityLiving extends Entity this.effectsDirty = false; } - int i = this.dataWatcher.getWatchableObjectInt(7); - boolean flag1 = this.dataWatcher.getWatchableObjectByte(8) > 0; + int i = this.dataWatcher.getWatchableObjectInt(2); + boolean flag1 = this.dataWatcher.getWatchableObjectByte(3) > 0; if (i > 0) { @@ -756,8 +726,8 @@ public abstract class EntityLiving extends Entity else { int i = PotionHelper.calcPotionLiquidColor(this.effects.values()); - this.dataWatcher.updateObject(8, Byte.valueOf((byte)(PotionHelper.getAreAmbient(this.effects.values()) ? 1 : 0))); - this.dataWatcher.updateObject(7, Integer.valueOf(i)); + this.dataWatcher.updateObject(3, Byte.valueOf((byte)(PotionHelper.getAreAmbient(this.effects.values()) ? 1 : 0))); + this.dataWatcher.updateObject(2, Integer.valueOf(i)); // this.setInvisible(this.hasEffect(Potion.invisibility.id)); } } @@ -767,8 +737,8 @@ public abstract class EntityLiving extends Entity */ protected void resetPotionEffectMetadata() { - this.dataWatcher.updateObject(8, Byte.valueOf((byte)0)); - this.dataWatcher.updateObject(7, Integer.valueOf(0)); + this.dataWatcher.updateObject(3, Byte.valueOf((byte)0)); + this.dataWatcher.updateObject(2, Integer.valueOf(0)); } public void clearEffects(boolean negative) @@ -816,7 +786,7 @@ public abstract class EntityLiving extends Entity */ public void addEffect(PotionEffect potioneffectIn) { - if (!potioneffectIn.getPotion().isInstant() && this.isPotionApplicable(potioneffectIn.getPotion())) + if (!potioneffectIn.getPotion().isInstant() && this.isPotionApplicable(potioneffectIn.getPotion(), potioneffectIn.getAmplifier())) { if (this.effects.containsKey(potioneffectIn.getPotion())) { @@ -831,20 +801,9 @@ public abstract class EntityLiving extends Entity } } - public boolean isPotionApplicable(Potion potion) - { -// if (this.getCreatureType() == CreatureType.UNDEAD) -// { -// int i = potioneffectIn.getPotionID(); -// -// if (i == Potion.regeneration.id || i == Potion.poison.id) -// { -// return false; -// } -// } - - return true; - } + public boolean isPotionApplicable(Potion potion, int amplifier) { + return potion == Potion.SPEED || potion == Potion.SLOWNESS || potion == Potion.HEAL || potion == Potion.DAMAGE || potion == Potion.POISON || potion == Potion.RADIATION; + } public boolean arePotionsInverted() { @@ -878,7 +837,7 @@ public abstract class EntityLiving extends Entity if (!this.worldObj.client) { - id.getPotion().addModifiers(this, this.getAttributeMap(), id.getAmplifier()); + id.getPotion().addModifiers(this, id.getAmplifier()); } } @@ -888,8 +847,8 @@ public abstract class EntityLiving extends Entity if (added && !this.worldObj.client) { - id.getPotion().removeModifiers(this, this.getAttributeMap(), id.getAmplifier()); - id.getPotion().addModifiers(this, this.getAttributeMap(), id.getAmplifier()); + id.getPotion().removeModifiers(this, id.getAmplifier()); + id.getPotion().addModifiers(this, id.getAmplifier()); } } @@ -899,7 +858,7 @@ public abstract class EntityLiving extends Entity if (!this.worldObj.client) { - effect.getPotion().removeModifiers(this, this.getAttributeMap(), effect.getAmplifier()); + effect.getPotion().removeModifiers(this, effect.getAmplifier()); } } @@ -915,11 +874,6 @@ public abstract class EntityLiving extends Entity this.setHealth(f + healAmount); } } - - public void healMana(int amount) - { - this.setManaPoints(ExtMath.clampi(this.getManaPoints() + amount, 0, this.getMaxMana())); - } public final int getHealth() { @@ -986,7 +940,7 @@ public abstract class EntityLiving extends Entity else { this.lastDamage = amount; - this.hurtResistance = this.hurtCooldown = Config.hurtDelay; + this.hurtResistance = this.hurtCooldown = Vars.hurtDelay; this.damageEntity(source, amount); this.hurtTime = this.maxHurtTime = 10; } @@ -1125,7 +1079,7 @@ public abstract class EntityLiving extends Entity i = EnchantmentHelper.getLootingModifier((EntityLiving)entity); } - if (this.canDropLoot() && Config.dropLoot) + if (this.canDropLoot() && Vars.dropLoot) { this.dropFewItems(this.recentlyHit > 0, i); // this.dropEquipment(this.recentlyHit > 0, i); @@ -1156,11 +1110,11 @@ public abstract class EntityLiving extends Entity */ public void knockBack(Entity source, float damage, double xfactor, double zfactor) { - if (this.rand.doublev() >= this.getEntityAttribute(Attributes.KNOCKBACK_RESISTANCE).getAttributeValue()) + if (!this.hasEffect(Potion.STABILITY) && this.rand.doublev() >= this.getKnockBackResistance()) { this.isAirBorne = true; float div = ExtMath.sqrtd(xfactor * xfactor + zfactor * zfactor); - float mult = 0.4F * Config.knockback; + float mult = 0.4F * Vars.knockback; this.motionX /= 2.0D; this.motionY /= 2.0D; this.motionZ /= 2.0D; @@ -1239,7 +1193,7 @@ public abstract class EntityLiving extends Entity if (i > 0) { - if(Config.damageFall) { + if(Vars.damageFall) { this.playSound(i > 4 ? SoundEvent.FALL_BIG : SoundEvent.FALL_SMALL, 1.0F); this.attackEntityFrom(DamageSource.fall, i); } @@ -1248,7 +1202,7 @@ public abstract class EntityLiving extends Entity int l = ExtMath.floord(this.posZ); Block block = this.worldObj.getState(new BlockPos(j, k, l)).getBlock(); - if (block.getMaterial() != Material.air) + if (block != Blocks.air) { SoundType block$soundtype = block.sound; if(block$soundtype.getStepSound() != null) @@ -1382,21 +1336,12 @@ public abstract class EntityLiving extends Entity public final int getMaxHealth() { - return (int)this.getEntityAttribute(Attributes.MAX_HEALTH).getAttributeValue(); - } - - public final int getRawMaxHealth() - { - return (int)this.getEntityAttribute(Attributes.MAX_HEALTH).getBaseValue(); + return this.dataWatcher.getWatchableObjectInt(5); } public final void setMaxHealth(int max) { - this.getEntityAttribute(Attributes.MAX_HEALTH).setBaseValue((double)max); - } - - public int getMaxMana() { - return 0; + this.dataWatcher.updateObject(5, max); } /** @@ -1404,7 +1349,7 @@ public abstract class EntityLiving extends Entity */ public final int getArrowCountInEntity() { - return this.dataWatcher.getWatchableObjectByte(9); + return this.dataWatcher.getWatchableObjectByte(4); } /** @@ -1412,7 +1357,7 @@ public abstract class EntityLiving extends Entity */ public final void setArrowCountInEntity(int count) { - this.dataWatcher.updateObject(9, Byte.valueOf((byte)count)); + this.dataWatcher.updateObject(4, Byte.valueOf((byte)count)); } /** @@ -1434,9 +1379,9 @@ public abstract class EntityLiving extends Entity this.swingTimer = -1; this.swingingItem = true; - if (this.worldObj instanceof WorldServer) + if (this.worldObj instanceof AWorldServer) { - ((WorldServer)this.worldObj).sendToAllTrackingEntity(this, new SPacketAnimation(this, 0)); + ((AWorldServer)this.worldObj).sendToAllTrackingEntity(this, new SPacketAnimation(this, 0)); } } } @@ -1485,7 +1430,7 @@ public abstract class EntityLiving extends Entity public void kill() { - if(this.worldObj.client || Config.damageVoid) + if(this.worldObj.client || Vars.damageVoid) this.attackEntityFrom(DamageSource.outOfWorld, Integer.MAX_VALUE); } @@ -1514,18 +1459,8 @@ public abstract class EntityLiving extends Entity this.swingFactor = (float)this.swingTimer / (float)i; } - public AttributeInstance getEntityAttribute(Attribute attribute) + public final AttributeMap getAttributeMap() { - return this.getAttributeMap().getAttributeInstance(attribute); - } - - public AttributeMap getAttributeMap() - { - if (this.attributes == null) - { - this.attributes = new AttributeMap(this.worldObj == null || this.worldObj.client); - } - return this.attributes; } @@ -1547,25 +1482,6 @@ public abstract class EntityLiving extends Entity } // public abstract void setItem(int slot, ItemStack stack); - /** - * Set sprinting switch for Entity. - */ - public void setSprinting(boolean sprinting) - { - super.setSprinting(sprinting); - AttributeInstance iattributeinstance = this.getEntityAttribute(Attributes.MOVEMENT_SPEED); - - if (iattributeinstance.getModifier(Attributes.SPRINT_SPEED_ID) != null) - { - iattributeinstance.removeModifier(Attributes.SPRINT_SPEED_MOD); - } - - if (sprinting) - { - iattributeinstance.applyModifier(Attributes.SPRINT_SPEED_MOD); - } - } - /** * returns the inventory of this entity (only used in EntityNPCMP it seems) */ @@ -1747,7 +1663,7 @@ public abstract class EntityLiving extends Entity this.motionY = 0.2D; } - if (this.worldObj.client && (!this.worldObj.isBlockLoaded(new BlockPos((int)this.posX, 0, (int)this.posZ)) || !this.worldObj.getChunk(new BlockPos((int)this.posX, 0, (int)this.posZ)).isLoaded())) + if (this.worldObj.client && (!this.worldObj.isBlockLoaded(new BlockPos((int)this.posX, 0, (int)this.posZ)) || !this.worldObj.getChunk(new BlockPos((int)this.posX, 0, (int)this.posZ)).isLoaded()) && !this.isPlayer()) { if (this.posY > 0.0D) { @@ -1842,6 +1758,27 @@ public abstract class EntityLiving extends Entity { return this.landMovement; } + + public float getSpeedBase() { + return this.baseSpeed; + } + + public void setSpeedBase(float value) { + this.baseSpeed = value; + } + + public final void setSpeedMod(float value) { + this.modSpeed = value; + } + + public float getMovementSpeed() { + float speed = this.getSpeedBase() * (this.isSprinting() ? 1.3f : 1.0f); + if(this.hasEffect(Potion.SPEED)) + speed *= 1.0f + (float)(this.getEffect(Potion.SPEED).getAmplifier() + 1) * 0.2f; + if(this.hasEffect(Potion.SLOWNESS)) + speed *= Math.max(1.0f - (float)(this.getEffect(Potion.SLOWNESS).getAmplifier() + 1) * 0.15f, 0.0f); + return Math.max(this.modSpeed * speed, 0.0f); + } /** * set the movespeed used for the new AI system @@ -1899,7 +1836,7 @@ public abstract class EntityLiving extends Entity // // if (!ItemStack.areItemStacksEqual(itemstack1, itemstack)) // { -// ((WorldServer)this.worldObj).sendToAllTrackingEntity(this, new SPacketEntityEquipment(this.getId(), j, itemstack1)); +// ((IWorldServer)this.worldObj).sendToAllTrackingEntity(this, new SPacketEntityEquipment(this.getId(), j, itemstack1)); // // if (itemstack != null) // { @@ -2198,14 +2135,14 @@ public abstract class EntityLiving extends Entity this.fallDistance = 0.0F; } - public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) + public void setClientPosition(double x, double y, double z, float yaw, float pitch, boolean teleport) { this.newX = x; this.newY = y; this.newZ = z; this.newYaw = (double)yaw; this.newPitch = (double)pitch; - this.moveIncrements = posRotationIncrements; + this.moveIncrements = 3; } public void setJumping(boolean jumping) @@ -2220,7 +2157,7 @@ public abstract class EntityLiving extends Entity { if (!entity.dead && !this.worldObj.client) { - WorldServer world = ((WorldServer)this.worldObj); + AWorldServer world = ((AWorldServer)this.worldObj); if (entity instanceof EntityItem) { @@ -2307,13 +2244,17 @@ public abstract class EntityLiving extends Entity { return !this.dead; } + + public double getKnockBackResistance() { + return 0.0; + } /** * Sets that this entity has been attacked. */ protected void setBeenAttacked() { - this.veloChanged = this.rand.doublev() >= this.getEntityAttribute(Attributes.KNOCKBACK_RESISTANCE).getAttributeValue(); + this.veloChanged = !this.hasEffect(Potion.STABILITY) && this.rand.doublev() >= this.getKnockBackResistance(); } public float getRotationYawHead() @@ -2383,13 +2324,6 @@ public abstract class EntityLiving extends Entity return max >= 2000 ? TextColor.BLACK : (max >= 500 ? TextColor.DMAGENTA : (max >= 120 ? TextColor.MAGENTA : (max >= 40 ? TextColor.CYAN : (max >= 15 ? TextColor.NEON : (max >= 5 ? TextColor.BLUE : TextColor.LGRAY))))); } - - public int getManaPoints() { - return 0; - } - - public void setManaPoints(int pts) { - } public int getEnergy(Energy type) { return 0; @@ -2409,9 +2343,8 @@ public abstract class EntityLiving extends Entity public String formatStats() { return String.format(this.getAlignment().prefix + " " + getHealthColor(this.getHealth(), this.getMaxHealth()) + "%d" + - TextColor.GRAY + "/" + getMaxHpColor(this.getMaxHealth()) + - "%d" + (this.getManaPoints() == 0 ? "" : (TextColor.GRAY + " [" + TextColor.MIDNIGHT + "%d" + TextColor.GRAY + "]")), - this.getHealth(), this.getMaxHealth(), this.getManaPoints()); + TextColor.GRAY + "/" + getMaxHpColor(this.getMaxHealth()) + "%d", + this.getHealth(), this.getMaxHealth()); } public abstract int getColor(); @@ -2446,11 +2379,11 @@ public abstract class EntityLiving extends Entity else if(this.isInLiquid()) { this.blockType = "aus dem Wasser"; } - CombatEntry entry = new CombatEntry(source, amount, this.blockType, this.fallDistance); + CombatEntry entry = new CombatEntry(source, amount, this.blockType, source == DamageSource.outOfWorld ? Float.MAX_VALUE : this.fallDistance); this.combat.add(entry); this.lastDamaged = this.ticksExisted; this.damaged = true; - if(entry.getSource().getEntity() instanceof EntityLiving && !this.attacked && this.isEntityAlive()) + if(entry.source().getEntity() instanceof EntityLiving && !this.attacked && this.isEntityAlive()) this.attacked = true; } @@ -2463,7 +2396,7 @@ public abstract class EntityLiving extends Entity return; String msg; String kill; - Player receiver = null; + IPlayer receiver = null; if(this.combat.size() == 0) { msg = kill = natural ? String.format("%s starb", this.getColoredName(TextColor.LGRAY)) : null; } @@ -2477,8 +2410,8 @@ public abstract class EntityLiving extends Entity CombatEntry entry = (CombatEntry)this.combat.get(z); CombatEntry last = z > 0 ? (CombatEntry)this.combat.get(z - 1) : null; - if((entry.getSource() == DamageSource.fall || entry.getSource() == DamageSource.outOfWorld) && - entry.getFallDistance() > 0.0F && (strong == null || entry.getFallDistance() > max)) { + if((entry.source() == DamageSource.fall || entry.source() == DamageSource.outOfWorld) && + entry.fallDistance() > 0.0F && (strong == null || entry.fallDistance() > max)) { if(z > 0) { strong = last; } @@ -2486,20 +2419,20 @@ public abstract class EntityLiving extends Entity strong = entry; } - max = entry.getFallDistance(); + max = entry.fallDistance(); } - if(entry.getBlockType() != null && (block == null || entry.getDamage() > min)) { + if(entry.blockType() != null && (block == null || entry.damage() > min)) { block = entry; } } CombatEntry fall = max > 5.0F && strong != null ? strong : (min > 5 && block != null ? block : null); CombatEntry last = (CombatEntry)this.combat.get(this.combat.size() - 1); - Entity lastEnt = last.getSource().getEntity(); + Entity lastEnt = last.source().getEntity(); - if(fall != null && last.getSource() == DamageSource.fall) { - if(fall.getSource() != DamageSource.fall && fall.getSource() != DamageSource.outOfWorld) { - Entity fallEnt = fall.getSource().getEntity(); + if(fall != null && last.source() == DamageSource.fall) { + if(fall.source() != DamageSource.fall && fall.source() != DamageSource.outOfWorld) { + Entity fallEnt = fall.source().getEntity(); if(fallEnt != null && (lastEnt == null || fallEnt != lastEnt)) { ItemStack fallItem = fallEnt instanceof EntityLiving ? ((EntityLiving)fallEnt).getHeldItem() : null; receiver = fallEnt.isPlayer() ? ((EntityNPC)fallEnt).connection : null; @@ -2537,14 +2470,14 @@ public abstract class EntityLiving extends Entity } } else { - msg = kill = natural ? String.format("%s fiel " + (fall.getBlockType() == null ? "aus zu großer Höhe" : fall.getBlockType()), + msg = kill = natural ? String.format("%s fiel " + (fall.blockType() == null ? "aus zu großer Höhe" : fall.blockType()), this.getColoredName(TextColor.NEON)) : null; } } else { - receiver = last.getSource().getEntity() != null && last.getSource().getEntity().isPlayer() ? ((EntityNPC)last.getSource().getEntity()).connection : null; - msg = natural || (last.getSource() instanceof EntityDamageSource ? last.getSource().getEntity() != null : this.getAttackingEntity() != null) ? last.getSource().getDeathMessage(this) : null; - kill = msg == null ? null : last.getSource().getKillMessage(this); + receiver = last.source().getEntity() != null && last.source().getEntity().isPlayer() ? ((EntityNPC)last.source().getEntity()).connection : null; + msg = natural || (last.source() instanceof EntityDamageSource ? last.source().getEntity() != null : this.getAttackingEntity() != null) ? last.source().getDeathMessage(this) : null; + kill = msg == null ? null : last.source().getKillMessage(this); } } if(msg == null) @@ -2552,7 +2485,7 @@ public abstract class EntityLiving extends Entity if(receiver != null) receiver.addFeed(kill); if(forAll) - for(Player player : ((WorldServer)this.worldObj).getServer().getPlayers()) { + for(IPlayer player : ((AWorldServer)this.worldObj).getAllPlayers()) { if(player != receiver) player.addFeed(msg); } @@ -2564,13 +2497,13 @@ public abstract class EntityLiving extends Entity int edmg = 0; int pdmg = 0; for(CombatEntry entry : this.combat) { - if(entry.getSource().getEntity() != null && entry.getSource().getEntity().isPlayer() && (player == null || entry.getDamage() > pdmg)) { - pdmg = entry.getDamage(); - player = (EntityNPC)entry.getSource().getEntity(); + if(entry.source().getEntity() != null && entry.source().getEntity().isPlayer() && (player == null || entry.damage() > pdmg)) { + pdmg = entry.damage(); + player = (EntityNPC)entry.source().getEntity(); } - if(entry.getSource().getEntity() instanceof EntityLiving && (entity == null || entry.getDamage() > edmg)) { - edmg = entry.getDamage(); - entity = (EntityLiving)entry.getSource().getEntity(); + if(entry.source().getEntity() instanceof EntityLiving && (entity == null || entry.damage() > edmg)) { + edmg = entry.damage(); + entity = (EntityLiving)entry.source().getEntity(); } } return player != null && pdmg >= edmg / 3 ? player : entity; @@ -2714,10 +2647,12 @@ public abstract class EntityLiving extends Entity // super.setAIMoveSpeed(speedIn); // this.setMoveForward(speedIn); // } + + public int getPathingRange() { + return 16; + } public Object onInitialSpawn(Object livingdata) { - this.getEntityAttribute(Attributes.FOLLOW_RANGE) - .applyModifier(new AttributeModifier("Random spawn bonus", this.rand.gaussian() * 0.05D, true)); return livingdata; } @@ -2738,7 +2673,7 @@ public abstract class EntityLiving extends Entity // } public boolean isTicked() { - return !this.worldObj.client && /* !this.isAIDisabled() && */ Config.mobTick; + return !this.worldObj.client && /* !this.isAIDisabled() && */ Vars.mobTick; } // public void setNoAI(boolean disable) { @@ -2777,13 +2712,13 @@ public abstract class EntityLiving extends Entity if(stack != null && stack.getItem() == Items.lead && this.allowLeashing()) { if(!(this instanceof EntityTameable) || !((EntityTameable)this).isTamed()) { this.setLeashedTo(player, true); - --stack.stackSize; + --stack.size; return true; } if(((EntityTameable)this).isOwner(player)) { this.setLeashedTo(player, true); - --stack.stackSize; + --stack.size; return true; } } @@ -3094,8 +3029,8 @@ public abstract class EntityLiving extends Entity this.dropItem(Items.lead, 1); } - if(!this.worldObj.client && pkt && this.worldObj instanceof WorldServer) { - ((WorldServer)this.worldObj).sendToAllTrackingEntity(this, new S1BPacketEntityAttach(1, this, (Entity)null)); + if(!this.worldObj.client && pkt && this.worldObj instanceof AWorldServer) { + ((AWorldServer)this.worldObj).sendToAllTrackingEntity(this, new SPacketEntityAttach(1, this, (Entity)null)); } } } @@ -3116,14 +3051,14 @@ public abstract class EntityLiving extends Entity this.leashed = true; this.leashedTo = entity; - if(!this.worldObj.client && pkt && this.worldObj instanceof WorldServer) { - ((WorldServer)this.worldObj).sendToAllTrackingEntity(this, new S1BPacketEntityAttach(1, this, this.leashedTo)); + if(!this.worldObj.client && pkt && this.worldObj instanceof AWorldServer) { + ((AWorldServer)this.worldObj).sendToAllTrackingEntity(this, new SPacketEntityAttach(1, this, this.leashedTo)); } } private void recreateLeash() { if(this.leashed && this.leashTag != null) { -// if(this.leashTag.hasKey("PlayerName", 8)) { +// if(this.leashTag.hasString("PlayerName")) { // String id = this.leashTag.getString("PlayerName"); // if(!id.isEmpty()) { // for(EntityNPC entitylivingbase : this.worldObj.getEntitiesWithinAABB(EntityNPC.class, @@ -3136,9 +3071,9 @@ public abstract class EntityLiving extends Entity // } // } // else - if(this.leashTag.hasKey("X", 99) && this.leashTag.hasKey("Y", 99) && this.leashTag.hasKey("Z", 99)) { - BlockPos blockpos = new BlockPos(this.leashTag.getInteger("X"), this.leashTag.getInteger("Y"), - this.leashTag.getInteger("Z")); + if(this.leashTag.hasInt("X") && this.leashTag.hasInt("Y") && this.leashTag.hasInt("Z")) { + BlockPos blockpos = new BlockPos(this.leashTag.getInt("X"), this.leashTag.getInt("Y"), + this.leashTag.getInt("Z")); EntityLeashKnot entityleashknot = EntityLeashKnot.getKnotForPosition(this.worldObj, blockpos); if(entityleashknot == null) { @@ -3224,9 +3159,9 @@ public abstract class EntityLiving extends Entity // if (!player.creative) // { - --itemstack.stackSize; + --itemstack.size; - if (itemstack.stackSize <= 0) + if (itemstack.size <= 0) { player.inventory.setInventorySlotContents(player.inventory.currentItem, (ItemStack)null); } @@ -3245,7 +3180,7 @@ public abstract class EntityLiving extends Entity public int getGrowingAge() { - return this.worldObj.client ? this.dataWatcher.getWatchableObjectInt(12) : this.growingAge; + return this.worldObj.client ? this.dataWatcher.getWatchableObjectInt(7) : this.growingAge; } public void grow(int amount) @@ -3257,7 +3192,7 @@ public abstract class EntityLiving extends Entity public void setGrowingAge(int age) { - this.dataWatcher.updateObject(12, Integer.valueOf(ExtMath.clampi(age, -24000, 1))); + this.dataWatcher.updateObject(7, Integer.valueOf(ExtMath.clampi(age, -24000, 1))); this.growingAge = age; this.setScaleForAge(); } diff --git a/java/src/game/entity/types/EntityTameable.java b/common/src/main/java/common/entity/types/EntityTameable.java similarity index 88% rename from java/src/game/entity/types/EntityTameable.java rename to common/src/main/java/common/entity/types/EntityTameable.java index 3563575..eb6e0c9 100755 --- a/java/src/game/entity/types/EntityTameable.java +++ b/common/src/main/java/common/entity/types/EntityTameable.java @@ -1,9 +1,9 @@ -package game.entity.types; +package common.entity.types; -import game.ai.EntityAISit; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.world.World; +import common.ai.EntityAISit; +import common.model.ParticleType; +import common.tags.TagObject; +import common.world.World; public abstract class EntityTameable extends EntityAnimal implements IEntityOwnable { @@ -25,9 +25,9 @@ public abstract class EntityTameable extends EntityAnimal implements IEntityOwna /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { - super.writeEntityToNBT(tagCompound); + super.writeEntity(tagCompound); // if (this.getOwnerId() == null) // { @@ -38,19 +38,19 @@ public abstract class EntityTameable extends EntityAnimal implements IEntityOwna // tagCompound.setString("Owner", this.getOwnerId()); // } - tagCompound.setBoolean("Tame", this.isTamed()); - tagCompound.setBoolean("Sitting", this.isSitting()); + tagCompound.setBool("Tame", this.isTamed()); + tagCompound.setBool("Sitting", this.isSitting()); } /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { - super.readEntityFromNBT(tagCompund); + super.readEntity(tagCompund); // String s = ""; // -// if (tagCompund.hasKey("Owner", 8)) +// if (tagCompund.hasString("Owner")) // { // s = tagCompund.getString("Owner"); // } @@ -61,9 +61,9 @@ public abstract class EntityTameable extends EntityAnimal implements IEntityOwna // this.setTamed(true); // } - this.setTamed(tagCompund.getBoolean("Tame")); - this.aiSit.setSitting(tagCompund.getBoolean("Sitting")); - this.setSitting(tagCompund.getBoolean("Sitting")); + this.setTamed(tagCompund.getBool("Tame")); + this.aiSit.setSitting(tagCompund.getBool("Sitting")); + this.setSitting(tagCompund.getBool("Sitting")); } /** diff --git a/java/src/game/entity/types/EntityThrowable.java b/common/src/main/java/common/entity/types/EntityThrowable.java similarity index 90% rename from java/src/game/entity/types/EntityThrowable.java rename to common/src/main/java/common/entity/types/EntityThrowable.java index c781e42..a67633e 100755 --- a/java/src/game/entity/types/EntityThrowable.java +++ b/common/src/main/java/common/entity/types/EntityThrowable.java @@ -1,22 +1,22 @@ -package game.entity.types; +package common.entity.types; import java.util.List; -import game.block.Block; -import game.block.BlockPortal; -import game.entity.Entity; -import game.entity.EntityType; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.nbt.NBTTagCompound; -import game.renderer.particle.ParticleType; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.HitPosition; -import game.world.State; -import game.world.Vec3; -import game.world.World; +import common.block.Block; +import common.block.artificial.BlockPortal; +import common.entity.Entity; +import common.entity.EntityType; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.model.ParticleType; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.HitPosition; +import common.util.Vec3; +import common.world.State; +import common.world.World; public abstract class EntityThrowable extends Entity implements IProjectile { @@ -303,15 +303,17 @@ public abstract class EntityThrowable extends Entity implements IProjectile /** * (abstract) Protected helper method to write subclass entity data to NBT. */ - public void writeEntityToNBT(NBTTagCompound tagCompound) + public void writeEntity(TagObject tagCompound) { tagCompound.setShort("xTile", (short)this.xTile); tagCompound.setShort("yTile", (short)this.yTile); tagCompound.setShort("zTile", (short)this.zTile); - String resourcelocation = BlockRegistry.REGISTRY.getNameForObject(this.inTile); - tagCompound.setString("inTile", resourcelocation == null ? "" : resourcelocation.toString()); + if(this.inTile != null) { + String id = BlockRegistry.getNameFromBlock(this.inTile); + tagCompound.setString("inTile", id == null ? "" : id.toString()); + } tagCompound.setByte("shake", (byte)this.throwableShake); - tagCompound.setByte("inGround", (byte)(this.inGround ? 1 : 0)); + tagCompound.setBool("inGround", this.inGround); // if ((this.throwerName == null || this.throwerName.length() == 0) && this.thrower.isPlayer()) // { @@ -324,23 +326,23 @@ public abstract class EntityThrowable extends Entity implements IProjectile /** * (abstract) Protected helper method to read subclass entity data from NBT. */ - public void readEntityFromNBT(NBTTagCompound tagCompund) + public void readEntity(TagObject tagCompund) { this.xTile = tagCompund.getShort("xTile"); this.yTile = tagCompund.getShort("yTile"); this.zTile = tagCompund.getShort("zTile"); - if (tagCompund.hasKey("inTile", 8)) + if (tagCompund.hasString("inTile")) { - this.inTile = BlockRegistry.getByIdFallback(tagCompund.getString("inTile")); + this.inTile = BlockRegistry.getRegisteredBlock(tagCompund.getString("inTile")); } else { - this.inTile = BlockRegistry.getBlockById(tagCompund.getByte("inTile") & 255); + this.inTile = null; } this.throwableShake = tagCompund.getByte("shake") & 255; - this.inGround = tagCompund.getByte("inGround") == 1; + this.inGround = tagCompund.getBool("inGround"); // this.thrower = null; // this.throwerName = tagCompund.getString("ownerName"); // @@ -358,11 +360,11 @@ public abstract class EntityThrowable extends Entity implements IProjectile // { // this.thrower = this.worldObj.getPlayer(this.throwerName); -// if (this.thrower == null && this.worldObj instanceof WorldServer) +// if (this.thrower == null && this.worldObj instanceof IWorldServer) // { // try // { -// Entity entity = ((WorldServer)this.worldObj).getEntityFromUuid(UUID.fromString(this.throwerName)); +// Entity entity = ((IWorldServer)this.worldObj).getEntityFromUuid(UUID.fromString(this.throwerName)); // // if (entity instanceof EntityLivingBase) // { diff --git a/java/src/game/entity/types/EntityWaterMob.java b/common/src/main/java/common/entity/types/EntityWaterMob.java similarity index 88% rename from java/src/game/entity/types/EntityWaterMob.java rename to common/src/main/java/common/entity/types/EntityWaterMob.java index bca942d..ae019b0 100755 --- a/java/src/game/entity/types/EntityWaterMob.java +++ b/common/src/main/java/common/entity/types/EntityWaterMob.java @@ -1,10 +1,10 @@ -package game.entity.types; +package common.entity.types; -import game.entity.DamageSource; -import game.entity.EntityType; -import game.entity.npc.EntityNPC; -import game.init.Config; -import game.world.World; +import common.entity.DamageSource; +import common.entity.EntityType; +import common.entity.npc.EntityNPC; +import common.vars.Vars; +import common.world.World; public abstract class EntityWaterMob extends EntityLiving { @@ -71,7 +71,7 @@ public abstract class EntityWaterMob extends EntityLiving // int i = this.getAir(); super.onEntityUpdate(); - if (this.isEntityAlive() && (this.worldObj.client || Config.waterMobDry) && !this.isInLiquid() && this.rand.chance(30)) + if (this.isEntityAlive() && (this.worldObj.client || Vars.waterMobDry) && !this.isInLiquid() && this.rand.chance(30)) { // --i; // this.setAir(i); diff --git a/java/src/game/entity/types/EntityWeatherEffect.java b/common/src/main/java/common/entity/types/EntityWeatherEffect.java similarity index 63% rename from java/src/game/entity/types/EntityWeatherEffect.java rename to common/src/main/java/common/entity/types/EntityWeatherEffect.java index b958937..315c0a0 100755 --- a/java/src/game/entity/types/EntityWeatherEffect.java +++ b/common/src/main/java/common/entity/types/EntityWeatherEffect.java @@ -1,9 +1,9 @@ -package game.entity.types; +package common.entity.types; -import game.entity.Entity; -import game.entity.EntityType; -import game.nbt.NBTTagCompound; -import game.world.World; +import common.entity.Entity; +import common.entity.EntityType; +import common.tags.TagObject; +import common.world.World; public abstract class EntityWeatherEffect extends Entity { public EntityWeatherEffect(World world) { @@ -25,10 +25,10 @@ public abstract class EntityWeatherEffect extends Entity { protected final void entityInit() { } - protected final void readEntityFromNBT(NBTTagCompound tagCompund) { + protected final void readEntity(TagObject tagCompund) { } - protected final void writeEntityToNBT(NBTTagCompound tagCompound) { + protected final void writeEntity(TagObject tagCompound) { } public final EntityType getType() { diff --git a/java/src/game/entity/types/IEntityMultiPart.java b/common/src/main/java/common/entity/types/IEntityMultiPart.java similarity index 54% rename from java/src/game/entity/types/IEntityMultiPart.java rename to common/src/main/java/common/entity/types/IEntityMultiPart.java index a8b4692..5ad5770 100755 --- a/java/src/game/entity/types/IEntityMultiPart.java +++ b/common/src/main/java/common/entity/types/IEntityMultiPart.java @@ -1,8 +1,8 @@ -package game.entity.types; +package common.entity.types; -import game.entity.DamageSource; -import game.entity.animal.EntityDragonPart; -import game.world.World; +import common.entity.DamageSource; +import common.entity.animal.EntityDragonPart; +import common.world.World; public interface IEntityMultiPart { diff --git a/java/src/game/entity/types/IEntityOwnable.java b/common/src/main/java/common/entity/types/IEntityOwnable.java similarity index 60% rename from java/src/game/entity/types/IEntityOwnable.java rename to common/src/main/java/common/entity/types/IEntityOwnable.java index a048caa..4dd194d 100755 --- a/java/src/game/entity/types/IEntityOwnable.java +++ b/common/src/main/java/common/entity/types/IEntityOwnable.java @@ -1,6 +1,6 @@ -package game.entity.types; +package common.entity.types; -import game.entity.Entity; +import common.entity.Entity; public interface IEntityOwnable { diff --git a/java/src/game/entity/types/IObjectData.java b/common/src/main/java/common/entity/types/IObjectData.java similarity index 65% rename from java/src/game/entity/types/IObjectData.java rename to common/src/main/java/common/entity/types/IObjectData.java index 1e206e9..2174539 100755 --- a/java/src/game/entity/types/IObjectData.java +++ b/common/src/main/java/common/entity/types/IObjectData.java @@ -1,4 +1,4 @@ -package game.entity.types; +package common.entity.types; public interface IObjectData { int getPacketData(); diff --git a/java/src/game/entity/types/IProjectile.java b/common/src/main/java/common/entity/types/IProjectile.java similarity index 81% rename from java/src/game/entity/types/IProjectile.java rename to common/src/main/java/common/entity/types/IProjectile.java index d4d6b9d..3f71083 100755 --- a/java/src/game/entity/types/IProjectile.java +++ b/common/src/main/java/common/entity/types/IProjectile.java @@ -1,4 +1,4 @@ -package game.entity.types; +package common.entity.types; public interface IProjectile { void setThrowableHeading(double x, double y, double z, float velocity, float inaccuracy); diff --git a/java/src/game/future/AbstractFuture.java b/common/src/main/java/common/future/AbstractFuture.java similarity index 99% rename from java/src/game/future/AbstractFuture.java rename to common/src/main/java/common/future/AbstractFuture.java index e63a476..280f3af 100644 --- a/java/src/game/future/AbstractFuture.java +++ b/common/src/main/java/common/future/AbstractFuture.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.future; +package common.future; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; diff --git a/java/src/game/future/ExecutionError.java b/common/src/main/java/common/future/ExecutionError.java similarity index 98% rename from java/src/game/future/ExecutionError.java rename to common/src/main/java/common/future/ExecutionError.java index cf8eae0..73fe3f1 100644 --- a/java/src/game/future/ExecutionError.java +++ b/common/src/main/java/common/future/ExecutionError.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.future; +package common.future; /** * {@link Error} variant of {@link java.util.concurrent.ExecutionException}. As diff --git a/java/src/game/future/ExecutionList.java b/common/src/main/java/common/future/ExecutionList.java similarity index 99% rename from java/src/game/future/ExecutionList.java rename to common/src/main/java/common/future/ExecutionList.java index 79e86cf..46a757c 100644 --- a/java/src/game/future/ExecutionList.java +++ b/common/src/main/java/common/future/ExecutionList.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.future; +package common.future; import java.util.concurrent.Executor; import java.util.logging.Level; diff --git a/java/src/game/future/FutureCallback.java b/common/src/main/java/common/future/FutureCallback.java similarity index 98% rename from java/src/game/future/FutureCallback.java rename to common/src/main/java/common/future/FutureCallback.java index cdb9092..6e5b529 100644 --- a/java/src/game/future/FutureCallback.java +++ b/common/src/main/java/common/future/FutureCallback.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.future; +package common.future; /** * A callback for accepting the results of a {@link java.util.concurrent.Future} diff --git a/java/src/game/future/Futures.java b/common/src/main/java/common/future/Futures.java similarity index 99% rename from java/src/game/future/Futures.java rename to common/src/main/java/common/future/Futures.java index 08fe41f..6dbce5f 100644 --- a/java/src/game/future/Futures.java +++ b/common/src/main/java/common/future/Futures.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.future; +package common.future; import java.util.ArrayList; import java.util.List; @@ -28,8 +28,8 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; -import game.collect.ImmutableList; -import game.collect.Sets; +import common.collect.ImmutableList; +import common.collect.Sets; /** * Static utility methods pertaining to the {@link Future} interface. diff --git a/java/src/game/future/ListenableFuture.java b/common/src/main/java/common/future/ListenableFuture.java similarity index 99% rename from java/src/game/future/ListenableFuture.java rename to common/src/main/java/common/future/ListenableFuture.java index ab19dd2..c841794 100644 --- a/java/src/game/future/ListenableFuture.java +++ b/common/src/main/java/common/future/ListenableFuture.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.future; +package common.future; import java.util.concurrent.Executor; import java.util.concurrent.Future; diff --git a/java/src/game/future/ListenableFutureTask.java b/common/src/main/java/common/future/ListenableFutureTask.java similarity index 99% rename from java/src/game/future/ListenableFutureTask.java rename to common/src/main/java/common/future/ListenableFutureTask.java index 38b0621..e2b9450 100644 --- a/java/src/game/future/ListenableFutureTask.java +++ b/common/src/main/java/common/future/ListenableFutureTask.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.future; +package common.future; import java.util.concurrent.Callable; import java.util.concurrent.Executor; diff --git a/java/src/game/future/MoreExecutors.java b/common/src/main/java/common/future/MoreExecutors.java similarity index 99% rename from java/src/game/future/MoreExecutors.java rename to common/src/main/java/common/future/MoreExecutors.java index 5e3e49a..ad8b8f1 100644 --- a/java/src/game/future/MoreExecutors.java +++ b/common/src/main/java/common/future/MoreExecutors.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.future; +package common.future; import java.util.Collections; import java.util.List; diff --git a/java/src/game/future/ThreadFactoryBuilder.java b/common/src/main/java/common/future/ThreadFactoryBuilder.java similarity index 99% rename from java/src/game/future/ThreadFactoryBuilder.java rename to common/src/main/java/common/future/ThreadFactoryBuilder.java index 611bdf0..a115d0f 100644 --- a/java/src/game/future/ThreadFactoryBuilder.java +++ b/common/src/main/java/common/future/ThreadFactoryBuilder.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.future; +package common.future; import java.lang.Thread.UncaughtExceptionHandler; import java.util.concurrent.Executors; diff --git a/java/src/game/future/UncheckedExecutionException.java b/common/src/main/java/common/future/UncheckedExecutionException.java similarity index 98% rename from java/src/game/future/UncheckedExecutionException.java rename to common/src/main/java/common/future/UncheckedExecutionException.java index 4f25bf8..b080867 100644 --- a/java/src/game/future/UncheckedExecutionException.java +++ b/common/src/main/java/common/future/UncheckedExecutionException.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.future; +package common.future; /** * Unchecked variant of {@link java.util.concurrent.ExecutionException}. As with diff --git a/java/src/game/init/BlockRegistry.java b/common/src/main/java/common/init/BlockRegistry.java similarity index 67% rename from java/src/game/init/BlockRegistry.java rename to common/src/main/java/common/init/BlockRegistry.java index 699ee3b..abb3594 100755 --- a/java/src/game/init/BlockRegistry.java +++ b/common/src/main/java/common/init/BlockRegistry.java @@ -1,16 +1,136 @@ -package game.init; +package common.init; -import game.audio.SoundType; -import game.block.*; -import game.color.DyeColor; -import game.init.FluidRegistry.LiquidType; -import game.item.CheatTab; -import game.material.Material; -import game.renderer.ticked.TextureLavaFX; -import game.renderer.ticked.TextureLavaFlowFX; -import game.renderer.ticked.TextureWaterFX; -import game.renderer.ticked.TextureWaterFlowFX; -import game.world.State; +import common.block.*; +import common.block.artificial.BlockBed; +import common.block.artificial.BlockBookshelf; +import common.block.artificial.BlockCake; +import common.block.artificial.BlockCarpet; +import common.block.artificial.BlockCompressedPowered; +import common.block.artificial.BlockDoor; +import common.block.artificial.BlockDragonEgg; +import common.block.artificial.BlockFence; +import common.block.artificial.BlockFenceGate; +import common.block.artificial.BlockFloorPortal; +import common.block.artificial.BlockFlowerPot; +import common.block.artificial.BlockGlass; +import common.block.artificial.BlockHay; +import common.block.artificial.BlockLadder; +import common.block.artificial.BlockPane; +import common.block.artificial.BlockPortal; +import common.block.artificial.BlockPortalFrame; +import common.block.artificial.BlockQuartz; +import common.block.artificial.BlockSkull; +import common.block.artificial.BlockSlab; +import common.block.artificial.BlockStainedGlass; +import common.block.artificial.BlockStainedGlassPane; +import common.block.artificial.BlockStairs; +import common.block.artificial.BlockStoneBrick; +import common.block.artificial.BlockTrapDoor; +import common.block.artificial.BlockWall; +import common.block.foliage.BlockBaseFlower; +import common.block.foliage.BlockBlackenedSoil; +import common.block.foliage.BlockBlueShroom; +import common.block.foliage.BlockCactus; +import common.block.foliage.BlockCarrot; +import common.block.foliage.BlockCocoa; +import common.block.foliage.BlockCrops; +import common.block.foliage.BlockDeadBush; +import common.block.foliage.BlockDoublePlant; +import common.block.foliage.BlockDryLeaves; +import common.block.foliage.BlockFarmland; +import common.block.foliage.BlockGrass; +import common.block.foliage.BlockHugeMushroom; +import common.block.foliage.BlockLeaves; +import common.block.foliage.BlockLilyPad; +import common.block.foliage.BlockLog; +import common.block.foliage.BlockMelon; +import common.block.foliage.BlockMushroom; +import common.block.foliage.BlockMycelium; +import common.block.foliage.BlockPotato; +import common.block.foliage.BlockPumpkin; +import common.block.foliage.BlockReed; +import common.block.foliage.BlockSapling; +import common.block.foliage.BlockStem; +import common.block.foliage.BlockTallGrass; +import common.block.foliage.BlockTianSoil; +import common.block.foliage.BlockVine; +import common.block.foliage.BlockWart; +import common.block.liquid.BlockDynamicLiquid; +import common.block.liquid.BlockStaticLiquid; +import common.block.natural.BlockBedrock; +import common.block.natural.BlockBlackenedDirt; +import common.block.natural.BlockBlackenedStone; +import common.block.natural.BlockClay; +import common.block.natural.BlockDirt; +import common.block.natural.BlockFire; +import common.block.natural.BlockGlowstone; +import common.block.natural.BlockGravel; +import common.block.natural.BlockHardenedClay; +import common.block.natural.BlockHellRock; +import common.block.natural.BlockIce; +import common.block.natural.BlockObsidian; +import common.block.natural.BlockOre; +import common.block.natural.BlockPackedIce; +import common.block.natural.BlockRedstoneOre; +import common.block.natural.BlockRock; +import common.block.natural.BlockSand; +import common.block.natural.BlockSandStone; +import common.block.natural.BlockSlime; +import common.block.natural.BlockSnow; +import common.block.natural.BlockSnowBlock; +import common.block.natural.BlockSoulFire; +import common.block.natural.BlockSoulSand; +import common.block.natural.BlockStone; +import common.block.natural.BlockTintedFire; +import common.block.natural.BlockWeb; +import common.block.tech.BlockAnvil; +import common.block.tech.BlockBeacon; +import common.block.tech.BlockBrewingStand; +import common.block.tech.BlockButton; +import common.block.tech.BlockCauldron; +import common.block.tech.BlockChest; +import common.block.tech.BlockCore; +import common.block.tech.BlockDaylightDetector; +import common.block.tech.BlockDispenser; +import common.block.tech.BlockDropper; +import common.block.tech.BlockEnchantmentTable; +import common.block.tech.BlockFurnace; +import common.block.tech.BlockHopper; +import common.block.tech.BlockJukebox; +import common.block.tech.BlockLever; +import common.block.tech.BlockMobSpawner; +import common.block.tech.BlockNote; +import common.block.tech.BlockNuke; +import common.block.tech.BlockPistonBase; +import common.block.tech.BlockPistonHead; +import common.block.tech.BlockPistonMoving; +import common.block.tech.BlockPressurePlate; +import common.block.tech.BlockPressurePlateWeighted; +import common.block.tech.BlockRail; +import common.block.tech.BlockRailDetector; +import common.block.tech.BlockRailPowered; +import common.block.tech.BlockRedstoneComparator; +import common.block.tech.BlockRedstoneLight; +import common.block.tech.BlockRedstoneRepeater; +import common.block.tech.BlockRedstoneTorch; +import common.block.tech.BlockRedstoneWire; +import common.block.tech.BlockTNT; +import common.block.tech.BlockTianReactor; +import common.block.tech.BlockTorch; +import common.block.tech.BlockTripWire; +import common.block.tech.BlockTripWireHook; +import common.block.tech.BlockWarpChest; +import common.block.tech.BlockWorkbench; +import common.block.tile.BlockBannerHanging; +import common.block.tile.BlockBannerStanding; +import common.block.tile.BlockStandingSign; +import common.block.tile.BlockWallSign; +import common.color.DyeColor; +import common.init.FluidRegistry.LiquidType; +import common.item.CheatTab; +import common.util.ObjectIntIdentityMap; +import common.util.RegistryNamespacedDefaultedByKey; +import common.world.State; public abstract class BlockRegistry { private static final String AIR_ID = "air"; @@ -21,13 +141,17 @@ public abstract class BlockRegistry { return REGISTRY.getIDForObject(block); } + public static String getNameFromBlock(Block block) { + return REGISTRY.getNameForObject(block); + } + public static int getStateId(State state) { Block block = state.getBlock(); return getIdFromBlock(block) + (block.getMetaFromState(state) << 12); } public static Block getBlockById(int id) { - return (Block)REGISTRY.getObjectById(id); + return REGISTRY.getObjectById(id); } public static State getStateById(int id) { @@ -36,65 +160,21 @@ public abstract class BlockRegistry { return getBlockById(i).getStateFromMeta(j); } - public static Block getByNameOrId(String name) { - Block block = REGISTRY.getObjectExact(name); - if(block == null) { - try { - return REGISTRY.getObjectExact(Integer.parseInt(name)); - } - catch(NumberFormatException e) { - } - } - return block; - } - - public static Block getByIdFallback(String name) { -// String loc = StringUtils.trimColon(name); - if(REGISTRY.containsKey(name)) { - return REGISTRY.getObject(name); - } - else { - try { - return REGISTRY.getObjectById(Integer.parseInt(name)); - } - catch(NumberFormatException e) { - return null; - } - } - } - - public static String toIdName(State block) { - int meta = block.getBlock().getMetaFromState(block); - return REGISTRY.getNameForObject(block.getBlock()).toString() + - ((meta == block.getBlock().getMetaFromState(block.getBlock().getState())) ? "" : (":" + meta)); - } - public static State getFromIdName(String name, State def) { - if(name == null) { + if(name == null) return def; - } String[] tok = name.split(":"); - if(tok.length < 1 || tok.length > 2) { + if(tok.length < 1 || tok.length > 2) return def; - } - Block block = getByNameOrId(tok[0]); -// if(block == null) { -// try { -// block = getBlockById(Integer.parseUnsignedInt(tok[0])); -// } -// catch(NumberFormatException e) { -// } -// } - if(block == null) { + Block block = REGISTRY.getObjectExact(tok[0]); + if(block == null) return def; - } byte data; if(tok.length == 2) { try { - int i = (byte)Integer.parseUnsignedInt(tok[1]); - if(i >= 16) { + int i = Integer.parseUnsignedInt(tok[1]); + if(i >= 16) return def; - } data = (byte)i; } catch(NumberFormatException e) { @@ -117,7 +197,7 @@ public abstract class BlockRegistry { REGISTRY.validateKey(); for(Block block : REGISTRY) { - if(block.getMaterial() != Material.air + if(block != Blocks.air && ((block instanceof BlockStairs) || /* (block instanceof BlockSlab) || */ (block instanceof BlockSlab) || (block instanceof BlockFarmland) || block.isTranslucent() || block.getLightOpacity() == 0)) { block.setSumBrightness(); @@ -152,19 +232,19 @@ public abstract class BlockRegistry { Block stone = (new BlockStone()).setHardness(1.5F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Stein"); registerBlock(1, "stone", stone); registerBlock(2, "bedrock", (new BlockBedrock()).setHardness(1000.0F).setResistance(100000.0F).setStepSound(SoundType.STONE) - .setDisplay("Grundgestein").setTab(CheatTab.tabNature).setMiningLevel(6)); + .setDisplay("Grundgestein").setTab(CheatTab.NATURE).setMiningLevel(6)); registerBlock(3, "rock", (new BlockRock()).setHardness(2.0F).setResistance(15.0F).setStepSound(SoundType.STONE).setDisplay("Felsen")); registerBlock(4, "hellrock", (new BlockHellRock()).setHardness(0.4F).setStepSound(SoundType.STONE).setDisplay("Höllenstein")); - registerBlock(5, "cell_rock", (new Block(Material.clay)).setHardness(1.0F).setResistance(3.0F) - .setStepSound(SoundType.SLIME).setDisplay("Zellstein").setTab(CheatTab.tabNature)); - registerBlock(6, "moon_rock", (new Block(Material.rock)).setHardness(2.5F).setResistance(10.0F) - .setStepSound(SoundType.STONE).setDisplay("Mondgestein").setTab(CheatTab.tabNature)); - Block cobblestone = (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Bruchstein").setTab(CheatTab.tabNature); + registerBlock(5, "cell_rock", (new Block(Material.LOOSE)).setHardness(1.0F).setResistance(3.0F) + .setStepSound(SoundType.SLIME).setDisplay("Zellstein").setTab(CheatTab.NATURE)); + registerBlock(6, "moon_rock", (new Block(Material.SOLID)).setHardness(2.5F).setResistance(10.0F) + .setStepSound(SoundType.STONE).setDisplay("Mondgestein").setTab(CheatTab.NATURE)); + Block cobblestone = (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Bruchstein").setTab(CheatTab.NATURE); registerBlock(7, "cobblestone", cobblestone); - registerBlock(8, "mossy_cobblestone", (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Bemooster Bruchstein").setTab(CheatTab.tabNature)); + registerBlock(8, "mossy_cobblestone", (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Bemooster Bruchstein").setTab(CheatTab.NATURE)); Block sandstone = (new BlockSandStone()).setStepSound(SoundType.STONE).setHardness(0.8F).setDisplay("Sandstein"); registerBlock(9, "sandstone", sandstone); registerBlock(10, "obsidian", (new BlockObsidian()).setHardness(50.0F).setResistance(2000.0F).setStepSound(SoundType.STONE) @@ -173,16 +253,16 @@ public abstract class BlockRegistry { (new BlockClay()).setHardness(0.6F).setStepSound(SoundType.GRAVEL).setDisplay("Ton").setShovelHarvestable()); registerBlock(12, "hardened_clay", (new BlockHardenedClay()).setHardness(1.25F).setResistance(7.0F).setStepSound(SoundType.STONE).setDisplay("Gebrannter Ton")); - registerBlock(13, "stained_hardened_clay", (new BlockColored(Material.rock)).setHardness(1.25F).setResistance(7.0F) - .setStepSound(SoundType.STONE).setDisplay("gefärbter Ton").setTab(CheatTab.tabNature)); - registerBlock(14, "coal_block", (new Block(Material.rock)).setHardness(5.0F).setResistance(10.0F) - .setStepSound(SoundType.STONE).setDisplay("Kohleblock").setTab(CheatTab.tabNature)); + registerBlock(13, "stained_hardened_clay", (new BlockColored(Material.SOLID)).setHardness(1.25F).setResistance(7.0F) + .setStepSound(SoundType.STONE).setDisplay("gefärbter Ton").setTab(CheatTab.NATURE)); + registerBlock(14, "coal_block", (new Block(Material.SOLID)).setHardness(5.0F).setResistance(10.0F) + .setStepSound(SoundType.STONE).setDisplay("Kohleblock").setTab(CheatTab.NATURE)); registerBlock(15, "sand", (new BlockSand()).setHardness(0.5F).setStepSound(SoundType.SAND).setDisplay("Sand").setShovelHarvestable()); registerBlock(16, "gravel", (new BlockGravel()).setHardness(0.6F).setStepSound(SoundType.GRAVEL).setDisplay("Kies").setShovelHarvestable()); registerBlock(17, "ash", - (new Block(Material.sand)).setHardness(0.2F).setStepSound(SoundType.SAND).setDisplay("Asche") - .setTab(CheatTab.tabNature).setShovelHarvestable()); + (new Block(Material.LOOSE)).setHardness(0.2F).setStepSound(SoundType.SAND).setDisplay("Asche") + .setTab(CheatTab.NATURE).setShovelHarvestable()); registerBlock(18, "snow_layer", (new BlockSnow()).setHardness(0.1F).setStepSound(SoundType.SNOW).setDisplay("Schnee").setLightOpacity(0) .setShovelHarvestable()); registerBlock(19, "snow", @@ -193,16 +273,16 @@ public abstract class BlockRegistry { (new BlockPackedIce()).setHardness(0.5F).setStepSound(SoundType.GLASS).setDisplay("Packeis").setMiningLevel(0)); registerBlock(22, "soul_sand", (new BlockSoulSand()).setHardness(0.5F).setStepSound(SoundType.SAND).setDisplay("Seelensand").setShovelHarvestable()); - registerBlock(23, "glowstone", (new BlockGlowstone(Material.glass)).setHardness(0.3F).setStepSound(SoundType.GLASS).setLightLevel(1.0F) + registerBlock(23, "glowstone", (new BlockGlowstone(Material.TRANSLUCENT)).setHardness(0.3F).setStepSound(SoundType.GLASS).setLightLevel(1.0F) .setDisplay("Glowstone")); registerBlock(24, "blackened_stone", (new BlockBlackenedStone()).setHardness(1.5F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Schwarzstein")); - registerBlock(25, "blackened_cobble", (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Schwarzbruchstein").setTab(CheatTab.tabNature)); + registerBlock(25, "blackened_cobble", (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Schwarzbruchstein").setTab(CheatTab.NATURE)); - registerFluid(32, 33, "water", "Wasser", true, LiquidType.WATER, false, 0, 5, 0.0f, TextureWaterFX.class, TextureWaterFlowFX.class); + registerFluid(32, 33, "water", "Wasser", true, LiquidType.WATER, false, 0, 5, 0.0f, "water", "waterflow"); registerFluid(34, 35, "lava", "Lava", false, LiquidType.LAVA, true, 15, -30, 0.0f, 2, 3); - registerFluid(36, 37, "magma", "Magma", false, LiquidType.HOT, true, 15, 40, 0.0f, TextureLavaFX.class, TextureLavaFlowFX.class); + registerFluid(36, 37, "magma", "Magma", false, LiquidType.HOT, true, 15, 40, 0.0f, "lava", "lavaflow"); registerFluid(38, 39, "mercury", "Quecksilber", false, LiquidType.COLD, true, 0, 40, 0.0f, 8, 4); registerFluid(40, 41, "hydrogen", "Wasserstoff", false, LiquidType.COLD, true, 0, 50, 0.0f, 8, 4); registerFluid(42, 43, "acid", "Säure", false, LiquidType.HOT, false, 0, 5, 0.0f, 1, 1); @@ -210,6 +290,7 @@ public abstract class BlockRegistry { registerFluid(46, 47, "goo", "Klebrige Masse", false, LiquidType.COLD, true, 0, 60, 0.0f, 10, 5); registerFluid(48, 49, "nukage", "Radioaktive Masse", false, LiquidType.COLD, true, 10, 10, 4.0f, 2, 2); registerFluid(50, 51, "blood", "Blut", false, LiquidType.COLD, false, 0, 10, 0.0f, 2, 1); + registerFluid(52, 53, "springwater", "Klares Wasser", true, LiquidType.COLD, false, 0, 5, 0.0f, 1, 1); registerBlock(60, "coal_ore", @@ -224,7 +305,7 @@ public abstract class BlockRegistry { .setDisplay("Schwarzes Quarzerz")); registerBlock(68, "redstone_ore", (new BlockRedstoneOre(false)).setHardness(3.0F).setResistance(5.0F).setStepSound(SoundType.STONE) - .setDisplay("Redstone-Erz").setTab(CheatTab.tabGems).setMiningLevel(2)); + .setDisplay("Redstone-Erz").setTab(CheatTab.GEMS).setMiningLevel(2)); registerBlock(69, "lit_redstone_ore", (new BlockRedstoneOre(true)).setLightLevel(0.625F).setHardness(3.0F).setResistance(5.0F) .setStepSound(SoundType.STONE).setDisplay("Redstone-Erz").setMiningLevel(2)); int bid = 70; @@ -250,12 +331,12 @@ public abstract class BlockRegistry { (new BlockGrass()).setHardness(0.6F).setStepSound(SoundType.GRASS).setDisplay("Gras").setShovelHarvestable()); registerBlock(130, "mycelium", (new BlockMycelium()).setHardness(0.6F).setStepSound(SoundType.GRASS).setDisplay("Myzel").setShovelHarvestable()); - registerBlock(131, "tian", (new Block(Material.rock)).setHardness(2.0F).setResistance(15.0F).setStepSound(SoundType.STONE) - .setDisplay("Tian").setTab(CheatTab.tabNature)); + registerBlock(131, "tian", (new Block(Material.SOLID)).setHardness(2.0F).setResistance(15.0F).setStepSound(SoundType.STONE) + .setDisplay("Tian").setTab(CheatTab.NATURE)); registerBlock(132, "tian_soil", (new BlockTianSoil()).setHardness(2.0F).setResistance(15.0F).setStepSound(SoundType.STONE) - .setDisplay("Tianerde").setTab(CheatTab.tabNature)); - registerBlock(133, "moon_cheese", (new BlockTreasure(Material.gourd)).setHardness(1.5F).setResistance(5.0F) - .setStepSound(SoundType.CLOTH).setDisplay("Mondkäse").setTab(CheatTab.tabNature)); + .setDisplay("Tianerde").setTab(CheatTab.NATURE)); + registerBlock(133, "moon_cheese", (new BlockTreasure(Material.SOFT)).setHardness(1.5F).setResistance(5.0F) + .setStepSound(SoundType.CLOTH).setDisplay("Mondkäse").setTab(CheatTab.NATURE)); registerBlock(134, "slime_block", (new BlockSlime()).setDisplay("Schleimblock").setStepSound(SoundType.SLIME)); registerBlock(135, "blackened_dirt", (new BlockBlackenedDirt()).setHardness(0.5F).setStepSound(SoundType.GRAVEL).setDisplay("Schwarzerde").setShovelHarvestable()); @@ -283,12 +364,12 @@ public abstract class BlockRegistry { Block brownMushroom = (new BlockMushroom()).setHardness(0.0F).setStepSound(SoundType.GRASS).setLightLevel(0.125F) .setDisplay("Pilz"); registerBlock(160, "brown_mushroom", brownMushroom); - registerBlock(161, "brown_mushroom_block", (new BlockHugeMushroom(Material.wood, brownMushroom)).setHardness(0.2F) - .setStepSound(SoundType.WOOD).setDisplay("Pilzblock").setTab(CheatTab.tabPlants)); + registerBlock(161, "brown_mushroom_block", (new BlockHugeMushroom(Material.WOOD, brownMushroom)).setHardness(0.2F) + .setStepSound(SoundType.WOOD).setDisplay("Pilzblock").setTab(CheatTab.PLANTS)); Block redMushrooom = (new BlockMushroom()).setHardness(0.0F).setStepSound(SoundType.GRASS).setDisplay("Pilz"); registerBlock(162, "red_mushroom", redMushrooom); - registerBlock(163, "red_mushroom_block", (new BlockHugeMushroom(Material.wood, redMushrooom)).setHardness(0.2F) - .setStepSound(SoundType.WOOD).setDisplay("Pilzblock").setTab(CheatTab.tabPlants)); + registerBlock(163, "red_mushroom_block", (new BlockHugeMushroom(Material.WOOD, redMushrooom)).setHardness(0.2F) + .setStepSound(SoundType.WOOD).setDisplay("Pilzblock").setTab(CheatTab.PLANTS)); registerBlock(164, "blue_mushroom", (new BlockBlueShroom()).setHardness(0.0F).setStepSound(SoundType.GRASS).setLightLevel(0.5F) .setDisplay("Tianpilz")); @@ -309,31 +390,35 @@ public abstract class BlockRegistry { .setDisplay(wood.getDisplay() + "setzling")); } + registerBlock(252, "soul_fire", + (new BlockSoulFire()).setHardness(0.0F).setLightLevel(1.0F).setStepSound(SoundType.CLOTH).setDisplay("Feuer der Seelen")); + registerBlock(253, "black_fire", + (new BlockTintedFire(0x202020)).setHardness(0.0F).setLightLevel(1.0F).setStepSound(SoundType.CLOTH).setDisplay("Dunkles Feuer")); registerBlock(254, "web", (new BlockWeb()).setLightOpacity(1).setHardness(4.0F).setDisplay("Spinnennetz")); registerBlock(255, "fire", (new BlockFire()).setHardness(0.0F).setLightLevel(1.0F).setStepSound(SoundType.CLOTH).setDisplay("Feuer")); - registerBlock(256, "lapis_block", (new Block(Material.iron)).setHardness(3.0F).setResistance(5.0F) - .setStepSound(SoundType.STONE).setDisplay("Lapislazuliblock").setTab(CheatTab.tabGems).setMiningLevel(1)); - registerBlock(257, "emerald_block", (new Block(Material.iron)).setHardness(5.0F).setResistance(10.0F) - .setStepSound(SoundType.STONE).setDisplay("Smaragdblock").setTab(CheatTab.tabGems).setMiningLevel(2)); - registerBlock(258, "redstone_block", (new BlockCompressedPowered(Material.iron)).setHardness(5.0F).setResistance(10.0F) - .setStepSound(SoundType.STONE).setDisplay("Redstone-Block").setTab(CheatTab.tabTech)); + registerBlock(256, "lapis_block", (new Block(Material.SOLID)).setHardness(3.0F).setResistance(5.0F) + .setStepSound(SoundType.STONE).setDisplay("Lapislazuliblock").setTab(CheatTab.GEMS).setMiningLevel(1)); + registerBlock(257, "emerald_block", (new Block(Material.SOLID)).setHardness(5.0F).setResistance(10.0F) + .setStepSound(SoundType.STONE).setDisplay("Smaragdblock").setTab(CheatTab.GEMS).setMiningLevel(2)); + registerBlock(258, "redstone_block", (new BlockCompressedPowered(Material.SOLID)).setHardness(5.0F).setResistance(10.0F) + .setStepSound(SoundType.STONE).setDisplay("Redstone-Block").setTab(CheatTab.TECHNOLOGY)); registerBlock(270, "glass", - (new BlockGlass(Material.glass, false)).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("Glas")); + (new BlockGlass()).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("Glas")); registerBlock(271, "stained_glass", - (new BlockStainedGlass(Material.glass)).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("gefärbtes Glas")); + (new BlockStainedGlass()).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("gefärbtes Glas")); registerBlock(272, "glass_pane", - (new BlockPane(Material.glass, false)).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("Glasscheibe")); + (new BlockPane(Material.TRANSLUCENT, false)).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("Glasscheibe")); registerBlock(273, "stained_glass_pane", (new BlockStainedGlassPane()).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("gefärbte Glasscheibe")); - registerBlock(280, "wool", (new BlockColored(Material.cloth)).setHardness(0.8F).setStepSound(SoundType.CLOTH).setDisplay("Wolle") + registerBlock(280, "wool", (new BlockColored(Material.BURNABLE)).setHardness(0.8F).setStepSound(SoundType.CLOTH).setDisplay("Wolle") .setShearsEfficiency(1)); registerBlock(281, "carpet", (new BlockCarpet()).setHardness(0.1F).setStepSound(SoundType.CLOTH).setDisplay("Teppich").setLightOpacity(0)); @@ -346,37 +431,37 @@ public abstract class BlockRegistry { (new BlockLadder()).setHardness(0.4F).setStepSound(SoundType.LADDER).setDisplay("Leiter").setAxeHarvestable()); registerBlock(301, "torch", (new BlockTorch()).setHardness(0.0F).setLightLevel(0.9375F).setStepSound(SoundType.WOOD).setDisplay("Fackel")); - registerBlock(302, "lamp", (new Block(Material.glass)).setHardness(0.3F).setStepSound(SoundType.GLASS).setLightLevel(1.0F) - .setDisplay("Lampe").setTab(CheatTab.tabTech)); + registerBlock(302, "lamp", (new Block(Material.TRANSLUCENT)).setHardness(0.3F).setStepSound(SoundType.GLASS).setLightLevel(1.0F) + .setDisplay("Lampe").setTab(CheatTab.TECHNOLOGY)); registerBlock(304, "bookshelf", (new BlockBookshelf()).setHardness(1.5F).setStepSound(SoundType.WOOD).setDisplay("Bücherregal")); registerBlock(305, "cake", (new BlockCake()).setHardness(0.5F).setStepSound(SoundType.CLOTH).setDisplay("Kuchen")); registerBlock(306, "dragon_egg", (new BlockDragonEgg()).setHardness(3.0F).setResistance(15.0F).setStepSound(SoundType.STONE) - .setLightLevel(0.125F).setDisplay("Drachenei").setTab(CheatTab.tabDeco)); + .setLightLevel(0.125F).setDisplay("Drachenei").setTab(CheatTab.DECORATION)); registerBlock(307, "flower_pot", (new BlockFlowerPot()).setHardness(0.0F).setStepSound(SoundType.STONE).setDisplay("Blumentopf")); - registerBlock(308, "sponge", (new Block(Material.sponge)).setHardness(0.6F).setStepSound(SoundType.GRASS).setDisplay("Schwamm") - .setTab(CheatTab.tabDeco)); - registerBlock(309, "skull", (new BlockSkull()).setHardness(1.0F).setStepSound(SoundType.STONE).setDisplay("Kopf")); + registerBlock(308, "sponge", (new Block(Material.LOOSE)).setHardness(0.6F).setStepSound(SoundType.GRASS).setDisplay("Schwamm") + .setTab(CheatTab.DECORATION)); + registerBlock(309, "skull", (new BlockSkull()).setHardness(1.0F).setStepSound(SoundType.STONE).setDisplay("Schädel").setTab(CheatTab.DECORATION)); registerBlock(310, "lit_pumpkin", (new BlockPumpkin()).setHardness(1.0F).setStepSound(SoundType.WOOD).setLightLevel(1.0F).setDisplay("Kürbislaterne")); registerBlock(311, "hay_block", (new BlockHay()).setHardness(0.5F).setStepSound(SoundType.GRASS).setDisplay("Strohballen") - .setTab(CheatTab.tabDeco)); + .setTab(CheatTab.DECORATION)); registerBlock(312, "sign", (new BlockStandingSign()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Schild")); registerBlock(313, "wall_sign", (new BlockWallSign()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Schild")); registerBlock(314, "banner", - (new BlockBanner.BlockBannerStanding()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Banner")); + (new BlockBannerStanding()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Banner")); registerBlock(315, "wall_banner", - (new BlockBanner.BlockBannerHanging()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Banner")); + (new BlockBannerHanging()).setHardness(1.0F).setStepSound(SoundType.WOOD).setDisplay("Banner")); registerBlock(390, "portal", (new BlockPortal()).setHardness(0.0F).setStepSound(SoundType.GLASS).setLightLevel(0.75F).setDisplay("Portal")); - registerBlock(391, "floor_portal", (new BlockFloorPortal(Material.portal)).setHardness(0.0F).setDisplay("Portal")); + registerBlock(391, "floor_portal", (new BlockFloorPortal(Material.PORTAL)).setHardness(0.0F).setDisplay("Portal")); registerBlock(392, "portal_frame", (new BlockPortalFrame()).setStepSound(SoundType.GLASS).setLightLevel(0.125F).setHardness(5.0F) - .setDisplay("Portalrahmen").setResistance(2000.0F).setTab(CheatTab.tabTech)); + .setDisplay("Portalrahmen").setResistance(2000.0F).setTab(CheatTab.TECHNOLOGY)); registerBlock(400, "farmland", (new BlockFarmland()).setHardness(0.6F).setStepSound(SoundType.GRAVEL).setDisplay("Ackerboden") - .setShovelHarvestable().setTab(CheatTab.tabPlants)); + .setShovelHarvestable().setTab(CheatTab.PLANTS)); registerBlock(401, "wheat", (new BlockCrops()).setDisplay("Getreide")); registerBlock(402, "carrot", (new BlockCarrot()).setDisplay("Karotten")); registerBlock(403, "potato", (new BlockPotato()).setDisplay("Kartoffeln")); @@ -389,16 +474,16 @@ public abstract class BlockRegistry { for(MetalType metal : MetalType.values()) { // String loc = metal.name.substring(0, 1).toUpperCase() + metal.name.substring(1); registerBlock(bid++, metal.name + "_block", - (new Block(Material.iron)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay(metal.display + "block").setTab(CheatTab.tabGems).setMiningLevel(1) + (new Block(Material.SOLID)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay(metal.display + "block").setTab(CheatTab.GEMS).setMiningLevel(1) .setLightLevel(metal.radioactivity > 0.0F ? 0.25F : 0.0F).setRadiation(metal.radioactivity * 2.0f)); } bid = 540; for(OreType ore : OreType.values()) { // String loc = ore.name.substring(0, 1).toUpperCase() + ore.name.substring(1); registerBlock(bid++, ore.name + "_block", - (new Block(Material.iron)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay(ore.display + "block").setTab(CheatTab.tabGems) + (new Block(Material.SOLID)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay(ore.display + "block").setTab(CheatTab.GEMS) .setMiningLevel(ore.material.getHarvestLevel() - 1)); } @@ -408,18 +493,18 @@ public abstract class BlockRegistry { registerBlock(600, "stone_slab", - (new BlockSlab(Material.rock, "stone_slab_side", "double_stone_top", "double_stone_top")) + (new BlockSlab(Material.SOLID, "stone_slab_side", "double_stone_top", "double_stone_top")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Steinstufe")); registerBlock(601, "stone_stairs", (new BlockStairs(stone.getState())).setDisplay("Steintreppe")); registerBlock(610, "cobblestone_slab", - (new BlockSlab(Material.rock, "cobblestone")) + (new BlockSlab(Material.SOLID, "cobblestone")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Bruchsteinstufe")); registerBlock(611, "cobblestone_stairs", (new BlockStairs(cobblestone.getState())).setDisplay("Bruchsteintreppe")); registerBlock(612, "cobblestone_wall", (new BlockWall(cobblestone)).setDisplay("Bruchsteinmauer")); registerBlock(620, "sandstone_slab", - (new BlockSlab(Material.rock, "sandstone_normal", "sandstone_bottom", "sandstone_all")) + (new BlockSlab(Material.SOLID, "sandstone_normal", "sandstone_bottom", "sandstone_all")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Sandsteinstufe")); registerBlock(621, "sandstone_stairs", (new BlockStairs(sandstone.getState().withProperty(BlockSandStone.TYPE, BlockSandStone.EnumType.DEFAULT), @@ -429,25 +514,25 @@ public abstract class BlockRegistry { Block quartz = (new BlockQuartz("")).setStepSound(SoundType.STONE).setHardness(0.8F).setDisplay("Quarzblock"); registerBlock(630, "quartz_block", quartz); registerBlock(631, "quartz_slab", - (new BlockSlab(Material.rock, "quartz_block_side", "quartz_block_bottom", "quartz_top")) + (new BlockSlab(Material.SOLID, "quartz_block_side", "quartz_block_bottom", "quartz_top")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Quarzstufe")); registerBlock(632, "quartz_stairs", (new BlockStairs(quartz.getState().withProperty(BlockQuartz.VARIANT, BlockQuartz.EnumType.DEFAULT), "quartz_block_bottom", "quartz_top")) .setDisplay("Quarztreppe")); - registerBlock(640, "iron_bars", (new BlockPane(Material.iron, true)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + registerBlock(640, "iron_bars", (new BlockPane(Material.SOLID, true)).setHardness(5.0F).setResistance(10.0F).setStepSound(SoundType.STONE) .setDisplay("Eisengitter")); registerBlock(641, "iron_door", - (new BlockDoor(Material.iron)).setHardness(5.0F).setStepSound(SoundType.STONE).setDisplay("Eisentür")); + (new BlockDoor(Material.SOLID)).setHardness(5.0F).setStepSound(SoundType.STONE).setDisplay("Eisentür")); registerBlock(642, "iron_trapdoor", - (new BlockTrapDoor(Material.iron)).setHardness(5.0F).setStepSound(SoundType.STONE).setDisplay("Eisenfalltür")); + (new BlockTrapDoor(Material.SOLID)).setHardness(5.0F).setStepSound(SoundType.STONE).setDisplay("Eisenfalltür")); - Block brick = (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Ziegelsteine").setTab(CheatTab.tabBlocks); + Block brick = (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Ziegelsteine").setTab(CheatTab.BLOCKS); registerBlock(650, "brick_block", brick); registerBlock(651, "brick_slab", - (new BlockSlab(Material.rock, "brick_block")) + (new BlockSlab(Material.SOLID, "brick_block")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Ziegelstufe")); registerBlock(652, "brick_stairs", (new BlockStairs(brick.getState())).setDisplay("Ziegeltreppe")); @@ -455,38 +540,38 @@ public abstract class BlockRegistry { .setDisplay("Steinziegel"); registerBlock(660, "stonebrick", stonebrick); registerBlock(661, "stonebrick_slab", - (new BlockSlab(Material.rock, "stonebrick_default")) + (new BlockSlab(Material.SOLID, "stonebrick_default")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Steinziegelstufe")); registerBlock(662, "stonebrick_stairs", (new BlockStairs(stonebrick.getState().withProperty(BlockStoneBrick.VARIANT, BlockStoneBrick.EnumType.DEFAULT))) .setDisplay("Steinziegeltreppe")); - Block bloodBrick = (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Blutrote Ziegel").setTab(CheatTab.tabBlocks); + Block bloodBrick = (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Blutrote Ziegel").setTab(CheatTab.BLOCKS); registerBlock(670, "blood_brick", bloodBrick); registerBlock(671, "blood_brick_slab", - (new BlockSlab(Material.rock, "blood_brick")) + (new BlockSlab(Material.SOLID, "blood_brick")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Blutrote Ziegelstufe")); - registerBlock(672, "blood_brick_fence", (new BlockFence(Material.rock, "blood_brick")).setHardness(2.0F).setResistance(10.0F) + registerBlock(672, "blood_brick_fence", (new BlockFence(Material.SOLID, "blood_brick")).setHardness(2.0F).setResistance(10.0F) .setStepSound(SoundType.STONE).setDisplay("Blutroter Ziegelzaun")); registerBlock(673, "blood_brick_stairs", (new BlockStairs(bloodBrick.getState())).setDisplay("Blutrote Ziegeltreppe")); - Block blackBrick = (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) - .setDisplay("Schwarze Ziegel").setTab(CheatTab.tabBlocks); + Block blackBrick = (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE) + .setDisplay("Schwarze Ziegel").setTab(CheatTab.BLOCKS); registerBlock(680, "black_brick", blackBrick); registerBlock(681, "black_brick_slab", - (new BlockSlab(Material.rock, "black_brick")) + (new BlockSlab(Material.SOLID, "black_brick")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Schwarze Ziegelstufe")); registerBlock(682, "black_brick_stairs", (new BlockStairs(blackBrick.getState())).setDisplay("Schwarze Ziegeltreppe")); - registerBlock(683, "black_brick_fence", (new BlockFence(Material.rock, "black_brick")).setHardness(2.0F).setResistance(10.0F) + registerBlock(683, "black_brick_fence", (new BlockFence(Material.SOLID, "black_brick")).setHardness(2.0F).setResistance(10.0F) .setStepSound(SoundType.STONE).setDisplay("Schwarzer Ziegelzaun")); Block bquartz = (new BlockQuartz("black_")).setStepSound(SoundType.STONE).setHardness(0.8F).setDisplay("Schwarzer Quarzblock"); registerBlock(690, "black_quartz_block", bquartz); registerBlock(691, "black_quartz_slab", - (new BlockSlab(Material.rock, "black_quartz_block_side", "black_quartz_block_bottom", "black_quartz_top")) + (new BlockSlab(Material.SOLID, "black_quartz_block_side", "black_quartz_block_bottom", "black_quartz_top")) .setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Schwarze Quarzstufe")); registerBlock(692, "black_quartz_stairs", (new BlockStairs(bquartz.getState().withProperty(BlockQuartz.VARIANT, BlockQuartz.EnumType.DEFAULT), @@ -495,29 +580,29 @@ public abstract class BlockRegistry { bid = 700; for(DecoType deco : DecoType.values()) { - registerBlock(bid++, deco.name, (new Block(Material.rock)).setHardness(2.0F).setResistance(10.0F) - .setStepSound(SoundType.STONE).setDisplay(deco.display).setTab(CheatTab.tabBlocks)); + registerBlock(bid++, deco.name, (new Block(Material.SOLID)).setHardness(2.0F).setResistance(10.0F) + .setStepSound(SoundType.STONE).setDisplay(deco.display).setTab(CheatTab.BLOCKS)); } registerBlock(1000, "trapdoor", - (new BlockTrapDoor(Material.wood)).setHardness(3.0F).setStepSound(SoundType.WOOD).setDisplay("Holzfalltür")); + (new BlockTrapDoor(Material.WOOD)).setHardness(3.0F).setStepSound(SoundType.WOOD).setDisplay("Holzfalltür")); bid = 1100; for(WoodType wood : WoodType.values()) { - Block planks = (new Block(Material.wood)).setHardness(2.0F).setResistance(5.0F).setStepSound(SoundType.WOOD) - .setDisplay(wood.getDisplay() + "holzbretter").setTab(CheatTab.tabWood); + Block planks = (new Block(Material.WOOD)).setHardness(2.0F).setResistance(5.0F).setStepSound(SoundType.WOOD) + .setDisplay(wood.getDisplay() + "holzbretter").setTab(CheatTab.WOOD); registerBlock(bid++, wood.getName() + "_planks", planks); registerBlock(bid++, wood.getName() + "_stairs", (new BlockStairs(planks.getState())) .setDisplay(wood.getDisplay() + "holztreppe")); - registerBlock(bid++, wood.getName() + "_slab", (new BlockSlab(Material.wood, wood.getName() + "_planks")) + registerBlock(bid++, wood.getName() + "_slab", (new BlockSlab(Material.WOOD, wood.getName() + "_planks")) .setHardness(2.0F).setResistance(5.0F).setStepSound(SoundType.WOOD).setDisplay(wood.getDisplay() + "holzstufe")); - registerBlock(bid++, wood.getName() + "_fence", (new BlockFence(Material.wood, wood.getName() + "_planks")) + registerBlock(bid++, wood.getName() + "_fence", (new BlockFence(Material.WOOD, wood.getName() + "_planks")) .setHardness(2.0F).setResistance(5.0F).setStepSound(SoundType.WOOD).setDisplay(wood.getDisplay() + "holzzaun")); registerBlock(bid++, wood.getName() + "_fence_gate", (new BlockFenceGate(wood)).setHardness(2.0F).setResistance(5.0F) .setStepSound(SoundType.WOOD).setDisplay(wood.getDisplay() + "holzzauntor")); - registerBlock(bid++, wood.getName() + "_door", (new BlockDoor(Material.wood)).setHardness(3.0F).setStepSound(SoundType.WOOD) + registerBlock(bid++, wood.getName() + "_door", (new BlockDoor(Material.WOOD)).setHardness(3.0F).setStepSound(SoundType.WOOD) .setDisplay(wood.getDisplay() + "holztür")); } @@ -525,12 +610,12 @@ public abstract class BlockRegistry { registerBlock(2000, "core", new BlockCore().setHardness(1.5F).setResistance(10.0F).setStepSound(SoundType.STONE) .setDisplay("Chunk-Lade-Kern")); registerBlock(2001, "mob_spawner", - (new BlockMobSpawner()).setHardness(5.0F).setStepSound(SoundType.STONE).setDisplay("Monsterspawner")); - registerBlock(2002, "crafting_table", (new BlockWorkbench()).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Werkbank")); + (new BlockMobSpawner()).setHardness(3.0F).setResistance(8.0F).setStepSound(SoundType.STONE).setDisplay("Mob-Spawner")); + registerBlock(2002, "workbench", (new BlockWorkbench(3)).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Werkbank")); registerBlock(2003, "furnace", (new BlockFurnace(false)).setHardness(3.5F).setStepSound(SoundType.STONE).setDisplay("Ofen") - .setTab(CheatTab.tabTech)); + .setTab(CheatTab.TECHNOLOGY)); registerBlock(2004, "lit_furnace", (new BlockFurnace(true)).setHardness(3.5F).setStepSound(SoundType.STONE).setLightLevel(0.875F) - .setDisplay("Ofen (Gefeuert)").setTab(CheatTab.tabTech)); + .setDisplay("Ofen (Gefeuert)").setTab(CheatTab.TECHNOLOGY)); registerBlock(2005, "anvil", (new BlockAnvil()).setHardness(5.0F).setStepSound(SoundType.ANVIL).setResistance(2000.0F).setDisplay("Amboss")); registerBlock(2006, "enchanting_table", @@ -541,6 +626,8 @@ public abstract class BlockRegistry { registerBlock(2010, "noteblock", (new BlockNote()).setHardness(0.8F).setDisplay("Notenblock")); registerBlock(2011, "jukebox", (new BlockJukebox()).setHardness(2.0F).setResistance(10.0F).setStepSound(SoundType.STONE).setDisplay("Plattenspieler")); + registerBlock(2012, "construction_table", (new BlockWorkbench(4)).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Konstruktionstisch")); + registerBlock(2013, "assembly_unit", (new BlockWorkbench(5)).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Fertigungseinheit")); registerBlock(2100, "chest", (new BlockChest(0)).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Truhe")); registerBlock(2101, "trapped_chest", (new BlockChest(1)).setHardness(2.5F).setStepSound(SoundType.WOOD).setDisplay("Redstonetruhe")); @@ -571,13 +658,13 @@ public abstract class BlockRegistry { registerBlock(2500, "lever", (new BlockLever()).setHardness(0.5F).setStepSound(SoundType.WOOD).setDisplay("Hebel")); - registerBlock(2510, "stone_pressure_plate", (new BlockPressurePlate(Material.rock, BlockPressurePlate.Sensitivity.MOBS)).setHardness(0.5F) + registerBlock(2510, "stone_pressure_plate", (new BlockPressurePlate(Material.SOLID, BlockPressurePlate.Sensitivity.MOBS)).setHardness(0.5F) .setStepSound(SoundType.STONE).setDisplay("Steindruckplatte")); - registerBlock(2511, "wooden_pressure_plate", (new BlockPressurePlate(Material.wood, BlockPressurePlate.Sensitivity.EVERYTHING)) + registerBlock(2511, "wooden_pressure_plate", (new BlockPressurePlate(Material.WOOD, BlockPressurePlate.Sensitivity.EVERYTHING)) .setHardness(0.5F).setStepSound(SoundType.WOOD).setDisplay("Holzdruckplatte")); - registerBlock(2512, "light_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.iron, 15)).setHardness(0.5F) + registerBlock(2512, "light_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.SOLID, 15)).setHardness(0.5F) .setStepSound(SoundType.WOOD).setDisplay("Wägeplatte (niedrige Gewichte)")); - registerBlock(2513, "heavy_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.iron, 150)).setHardness(0.5F) + registerBlock(2513, "heavy_weighted_pressure_plate", (new BlockPressurePlateWeighted(Material.SOLID, 150)).setHardness(0.5F) .setStepSound(SoundType.WOOD).setDisplay("Wägeplatte (hohe Gewichte)")); registerBlock(2520, "stone_button", (new BlockButton(false, 20, "stone")).setHardness(0.5F).setStepSound(SoundType.STONE).setDisplay("Knopf")); @@ -589,7 +676,7 @@ public abstract class BlockRegistry { registerBlock(2601, "unlit_redstone_torch", (new BlockRedstoneTorch(false)).setHardness(0.0F).setStepSound(SoundType.WOOD).setDisplay("Redstone-Fackel")); registerBlock(2602, "redstone_torch", (new BlockRedstoneTorch(true)).setHardness(0.0F).setLightLevel(0.5F).setStepSound(SoundType.WOOD) - .setDisplay("Redstone-Fackel").setTab(CheatTab.tabTech)); + .setDisplay("Redstone-Fackel").setTab(CheatTab.TECHNOLOGY)); registerBlock(2603, "repeater", (new BlockRedstoneRepeater(false)).setHardness(0.0F).setStepSound(SoundType.WOOD).setDisplay("Redstone-Verstärker")); registerBlock(2604, "powered_repeater", @@ -599,7 +686,7 @@ public abstract class BlockRegistry { registerBlock(2606, "powered_comparator", (new BlockRedstoneComparator(true)).setHardness(0.0F).setLightLevel(0.625F) .setStepSound(SoundType.WOOD).setDisplay("Redstone-Komparator")); registerBlock(2607, "redstone_lamp", (new BlockRedstoneLight(false)).setHardness(0.3F).setStepSound(SoundType.GLASS) - .setDisplay("Redstone-Lampe").setTab(CheatTab.tabTech)); + .setDisplay("Redstone-Lampe").setTab(CheatTab.TECHNOLOGY)); registerBlock(2608, "lit_redstone_lamp", (new BlockRedstoneLight(true)).setHardness(0.3F).setStepSound(SoundType.GLASS).setDisplay("Redstone-Lampe")); registerBlock(2609, "daylight_detector", new BlockDaylightDetector(false).setDisplay("Tageslichtsensor")); diff --git a/common/src/main/java/common/init/Blocks.java b/common/src/main/java/common/init/Blocks.java new file mode 100755 index 0000000..0b163e0 --- /dev/null +++ b/common/src/main/java/common/init/Blocks.java @@ -0,0 +1,444 @@ +package common.init; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Set; + +import common.block.*; +import common.block.artificial.*; +import common.block.foliage.*; +import common.block.liquid.*; +import common.block.natural.*; +import common.block.tech.*; +import common.block.tile.*; +import common.collect.Lists; +import common.collect.Sets; +import common.util.Util; + + +public abstract class Blocks { + public static final BlockDoor acacia_door = get("acacia_door"); + public static final BlockFence acacia_fence = get("acacia_fence"); + public static final BlockFenceGate acacia_fence_gate = get("acacia_fence_gate"); + public static final BlockLeaves acacia_leaves = get("acacia_leaves"); + public static final BlockLog acacia_log = get("acacia_log"); + public static final Block acacia_planks = get("acacia_planks"); + public static final BlockSapling acacia_sapling = get("acacia_sapling"); + public static final BlockSlab acacia_slab = get("acacia_slab"); + public static final BlockStairs acacia_stairs = get("acacia_stairs"); + public static final BlockStaticLiquid acid = get("acid"); + public static final BlockRailPowered activator_rail = get("activator_rail"); + public static final BlockAir air = get("air"); + public static final Block aluminium_block = get("aluminium_block"); + public static final BlockOre aluminium_ore = get("aluminium_ore"); + public static final Block antimony_block = get("antimony_block"); + public static final BlockOre antimony_ore = get("antimony_ore"); + public static final BlockAnvil anvil = get("anvil"); + public static final Block ardite_block = get("ardite_block"); + public static final BlockOre ardite_ore = get("ardite_ore"); + public static final Block arsenic_block = get("arsenic_block"); + public static final BlockOre arsenic_ore = get("arsenic_ore"); + public static final Block ash = get("ash"); + public static final BlockWorkbench assembly_unit = get("assembly_unit"); + public static final BlockBannerStanding banner = get("banner"); + public static final BlockBeacon beacon = get("beacon"); + public static final BlockBedrock bedrock = get("bedrock"); + public static final BlockDoor birch_door = get("birch_door"); + public static final BlockFence birch_fence = get("birch_fence"); + public static final BlockFenceGate birch_fence_gate = get("birch_fence_gate"); + public static final BlockLeaves birch_leaves = get("birch_leaves"); + public static final BlockLog birch_log = get("birch_log"); + public static final Block birch_planks = get("birch_planks"); + public static final BlockSapling birch_sapling = get("birch_sapling"); + public static final BlockSlab birch_slab = get("birch_slab"); + public static final BlockStairs birch_stairs = get("birch_stairs"); + public static final Block bismuth_block = get("bismuth_block"); + public static final BlockOre bismuth_ore = get("bismuth_ore"); + public static final BlockBed black_bed = get("black_bed"); + public static final Block black_brick = get("black_brick"); + public static final BlockFence black_brick_fence = get("black_brick_fence"); + public static final BlockSlab black_brick_slab = get("black_brick_slab"); + public static final BlockStairs black_brick_stairs = get("black_brick_stairs"); + public static final BlockTintedFire black_fire = get("black_fire"); + public static final Block black_metal_block = get("black_metal_block"); + public static final BlockOre black_metal_ore = get("black_metal_ore"); + public static final BlockQuartz black_quartz_block = get("black_quartz_block"); + public static final BlockOre black_quartz_ore = get("black_quartz_ore"); + public static final BlockSlab black_quartz_slab = get("black_quartz_slab"); + public static final BlockStairs black_quartz_stairs = get("black_quartz_stairs"); + public static final Block blackened_cobble = get("blackened_cobble"); + public static final BlockBlackenedDirt blackened_dirt = get("blackened_dirt"); + public static final BlockBlackenedSoil blackened_soil = get("blackened_soil"); + public static final BlockBlackenedStone blackened_stone = get("blackened_stone"); + public static final BlockDoor blackwood_door = get("blackwood_door"); + public static final BlockFence blackwood_fence = get("blackwood_fence"); + public static final BlockFenceGate blackwood_fence_gate = get("blackwood_fence_gate"); + public static final BlockLeaves blackwood_leaves = get("blackwood_leaves"); + public static final BlockLog blackwood_log = get("blackwood_log"); + public static final Block blackwood_planks = get("blackwood_planks"); + public static final BlockSapling blackwood_sapling = get("blackwood_sapling"); + public static final BlockSlab blackwood_slab = get("blackwood_slab"); + public static final BlockStairs blackwood_stairs = get("blackwood_stairs"); + public static final BlockStaticLiquid blood = get("blood"); + public static final Block blood_brick = get("blood_brick"); + public static final BlockFence blood_brick_fence = get("blood_brick_fence"); + public static final BlockSlab blood_brick_slab = get("blood_brick_slab"); + public static final BlockStairs blood_brick_stairs = get("blood_brick_stairs"); + public static final BlockBlueShroom blue_mushroom = get("blue_mushroom"); + public static final BlockBookshelf bookshelf = get("bookshelf"); + public static final BlockBrewingStand brewing_stand = get("brewing_stand"); + public static final Block brick_block = get("brick_block"); + public static final BlockSlab brick_slab = get("brick_slab"); + public static final BlockStairs brick_stairs = get("brick_stairs"); + public static final BlockMushroom brown_mushroom = get("brown_mushroom"); + public static final BlockHugeMushroom brown_mushroom_block = get("brown_mushroom_block"); + public static final BlockCactus cactus = get("cactus"); + public static final BlockCake cake = get("cake"); + public static final Block calcium_block = get("calcium_block"); + public static final BlockOre calcium_ore = get("calcium_ore"); + public static final BlockCarpet carpet = get("carpet"); + public static final BlockCarrot carrot = get("carrot"); + public static final BlockCauldron cauldron = get("cauldron"); + public static final Block cell_rock = get("cell_rock"); + public static final BlockDoor cherry_door = get("cherry_door"); + public static final BlockFence cherry_fence = get("cherry_fence"); + public static final BlockFenceGate cherry_fence_gate = get("cherry_fence_gate"); + public static final BlockLeaves cherry_leaves = get("cherry_leaves"); + public static final BlockLog cherry_log = get("cherry_log"); + public static final Block cherry_planks = get("cherry_planks"); + public static final BlockSapling cherry_sapling = get("cherry_sapling"); + public static final BlockSlab cherry_slab = get("cherry_slab"); + public static final BlockStairs cherry_stairs = get("cherry_stairs"); + public static final BlockChest chest = get("chest"); + public static final Block chrome_block = get("chrome_block"); + public static final BlockOre chrome_ore = get("chrome_ore"); + public static final Block cinnabar_block = get("cinnabar_block"); + public static final BlockOre cinnabar_ore = get("cinnabar_ore"); + public static final BlockClay clay = get("clay"); + public static final Block coal_block = get("coal_block"); + public static final BlockOre coal_ore = get("coal_ore"); + public static final Block cobalt_block = get("cobalt_block"); + public static final BlockOre cobalt_ore = get("cobalt_ore"); + public static final Block cobblestone = get("cobblestone"); + public static final BlockSlab cobblestone_slab = get("cobblestone_slab"); + public static final BlockStairs cobblestone_stairs = get("cobblestone_stairs"); + public static final BlockWall cobblestone_wall = get("cobblestone_wall"); + public static final BlockCocoa cocoa = get("cocoa"); + public static final BlockRedstoneComparator comparator = get("comparator"); + public static final BlockWorkbench construction_table = get("construction_table"); + public static final Block copper_block = get("copper_block"); + public static final BlockOre copper_ore = get("copper_ore"); + public static final BlockCore core = get("core"); + public static final BlockDoor dark_oak_door = get("dark_oak_door"); + public static final BlockFence dark_oak_fence = get("dark_oak_fence"); + public static final BlockFenceGate dark_oak_fence_gate = get("dark_oak_fence_gate"); + public static final BlockLeaves dark_oak_leaves = get("dark_oak_leaves"); + public static final BlockLog dark_oak_log = get("dark_oak_log"); + public static final Block dark_oak_planks = get("dark_oak_planks"); + public static final BlockSapling dark_oak_sapling = get("dark_oak_sapling"); + public static final BlockSlab dark_oak_slab = get("dark_oak_slab"); + public static final BlockStairs dark_oak_stairs = get("dark_oak_stairs"); + public static final BlockDaylightDetector daylight_detector = get("daylight_detector"); + public static final BlockDaylightDetector daylight_detector_inverted = get("daylight_detector_inverted"); + public static final BlockDeadBush deadbush = get("deadbush"); + public static final BlockRailDetector detector_rail = get("detector_rail"); + public static final Block diamond_block = get("diamond_block"); + public static final BlockOre diamond_ore = get("diamond_ore"); + public static final BlockDirt dirt = get("dirt"); + public static final BlockDispenser dispenser = get("dispenser"); + public static final BlockDoublePlant double_plant = get("double_plant"); + public static final BlockDragonEgg dragon_egg = get("dragon_egg"); + public static final BlockDropper dropper = get("dropper"); + public static final BlockDryLeaves dry_leaves = get("dry_leaves"); + public static final Block emerald_block = get("emerald_block"); + public static final BlockOre emerald_ore = get("emerald_ore"); + public static final BlockEnchantmentTable enchanting_table = get("enchanting_table"); + public static final BlockFarmland farmland = get("farmland"); + public static final BlockFire fire = get("fire"); + public static final BlockFloorPortal floor_portal = get("floor_portal"); + public static final Block floor_tiles = get("floor_tiles"); + public static final Block floor_tiles_black = get("floor_tiles_black"); + public static final Block floor_tiles_red = get("floor_tiles_red"); + public static final Block floor_tiles_white = get("floor_tiles_white"); + public static final BlockBaseFlower flower = get("flower"); + public static final BlockFlowerPot flower_pot = get("flower_pot"); + public static final BlockDynamicLiquid flowing_acid = get("flowing_acid"); + public static final BlockDynamicLiquid flowing_blood = get("flowing_blood"); + public static final BlockDynamicLiquid flowing_goo = get("flowing_goo"); + public static final BlockDynamicLiquid flowing_hydrogen = get("flowing_hydrogen"); + public static final BlockDynamicLiquid flowing_lava = get("flowing_lava"); + public static final BlockDynamicLiquid flowing_magma = get("flowing_magma"); + public static final BlockDynamicLiquid flowing_mercury = get("flowing_mercury"); + public static final BlockDynamicLiquid flowing_nukage = get("flowing_nukage"); + public static final BlockDynamicLiquid flowing_slime = get("flowing_slime"); + public static final BlockDynamicLiquid flowing_water = get("flowing_water"); + public static final BlockFurnace furnace = get("furnace"); + public static final BlockGlass glass = get("glass"); + public static final BlockPane glass_pane = get("glass_pane"); + public static final BlockGlowstone glowstone = get("glowstone"); + public static final Block gold_block = get("gold_block"); + public static final BlockOre gold_ore = get("gold_ore"); + public static final BlockRailPowered golden_rail = get("golden_rail"); + public static final BlockStaticLiquid goo = get("goo"); + public static final BlockGrass grass = get("grass"); + public static final BlockGravel gravel = get("gravel"); + public static final Block gyriyn_block = get("gyriyn_block"); + public static final BlockOre gyriyn_ore = get("gyriyn_ore"); + public static final BlockHardenedClay hardened_clay = get("hardened_clay"); + public static final BlockHay hay_block = get("hay_block"); + public static final BlockPressurePlateWeighted heavy_weighted_pressure_plate = get("heavy_weighted_pressure_plate"); + public static final BlockHellRock hellrock = get("hellrock"); + public static final BlockHopper hopper = get("hopper"); + public static final BlockStaticLiquid hydrogen = get("hydrogen"); + public static final BlockIce ice = get("ice"); + public static final Block iodine_block = get("iodine_block"); + public static final BlockOre iodine_ore = get("iodine_ore"); + public static final BlockPane iron_bars = get("iron_bars"); + public static final Block iron_block = get("iron_block"); + public static final BlockDoor iron_door = get("iron_door"); + public static final BlockOre iron_ore = get("iron_ore"); + public static final BlockTrapDoor iron_trapdoor = get("iron_trapdoor"); + public static final BlockJukebox jukebox = get("jukebox"); + public static final BlockDoor jungle_door = get("jungle_door"); + public static final BlockFence jungle_fence = get("jungle_fence"); + public static final BlockFenceGate jungle_fence_gate = get("jungle_fence_gate"); + public static final BlockLeaves jungle_leaves = get("jungle_leaves"); + public static final BlockLog jungle_log = get("jungle_log"); + public static final Block jungle_planks = get("jungle_planks"); + public static final BlockSapling jungle_sapling = get("jungle_sapling"); + public static final BlockSlab jungle_slab = get("jungle_slab"); + public static final BlockStairs jungle_stairs = get("jungle_stairs"); + public static final BlockLadder ladder = get("ladder"); + public static final Block lamp = get("lamp"); + public static final Block lapis_block = get("lapis_block"); + public static final BlockOre lapis_ore = get("lapis_ore"); + public static final BlockStaticLiquid lava = get("lava"); + public static final Block lead_block = get("lead_block"); + public static final BlockOre lead_ore = get("lead_ore"); + public static final BlockLever lever = get("lever"); + public static final BlockPressurePlateWeighted light_weighted_pressure_plate = get("light_weighted_pressure_plate"); + public static final BlockFurnace lit_furnace = get("lit_furnace"); + public static final BlockPumpkin lit_pumpkin = get("lit_pumpkin"); + public static final BlockRedstoneLight lit_redstone_lamp = get("lit_redstone_lamp"); + public static final BlockRedstoneOre lit_redstone_ore = get("lit_redstone_ore"); + public static final Block lithium_block = get("lithium_block"); + public static final BlockOre lithium_ore = get("lithium_ore"); + public static final BlockStaticLiquid magma = get("magma"); + public static final Block magnesium_block = get("magnesium_block"); + public static final BlockOre magnesium_ore = get("magnesium_ore"); + public static final Block manganese_block = get("manganese_block"); + public static final BlockOre manganese_ore = get("manganese_ore"); + public static final BlockDoor maple_door = get("maple_door"); + public static final BlockFence maple_fence = get("maple_fence"); + public static final BlockFenceGate maple_fence_gate = get("maple_fence_gate"); + public static final BlockLeaves maple_leaves = get("maple_leaves"); + public static final BlockLog maple_log = get("maple_log"); + public static final Block maple_planks = get("maple_planks"); + public static final BlockSapling maple_sapling = get("maple_sapling"); + public static final BlockSlab maple_slab = get("maple_slab"); + public static final BlockStairs maple_stairs = get("maple_stairs"); + public static final BlockMelon melon_block = get("melon_block"); + public static final BlockStem melon_stem = get("melon_stem"); + public static final BlockStaticLiquid mercury = get("mercury"); + public static final BlockMobSpawner mob_spawner = get("mob_spawner"); + public static final BlockTreasure moon_cheese = get("moon_cheese"); + public static final Block moon_rock = get("moon_rock"); + public static final Block mossy_cobblestone = get("mossy_cobblestone"); + public static final BlockMycelium mycelium = get("mycelium"); + public static final Block neodymium_block = get("neodymium_block"); + public static final BlockOre neodymium_ore = get("neodymium_ore"); + public static final Block neptunium_block = get("neptunium_block"); + public static final BlockOre neptunium_ore = get("neptunium_ore"); + public static final Block nichun_block = get("nichun_block"); + public static final BlockOre nichun_ore = get("nichun_ore"); + public static final Block nickel_block = get("nickel_block"); + public static final BlockOre nickel_ore = get("nickel_ore"); + public static final BlockNote noteblock = get("noteblock"); + public static final BlockStaticLiquid nukage = get("nukage"); + public static final BlockNuke nuke = get("nuke"); + public static final BlockDoor oak_door = get("oak_door"); + public static final BlockFence oak_fence = get("oak_fence"); + public static final BlockFenceGate oak_fence_gate = get("oak_fence_gate"); + public static final BlockLeaves oak_leaves = get("oak_leaves"); + public static final BlockLog oak_log = get("oak_log"); + public static final Block oak_planks = get("oak_planks"); + public static final BlockSapling oak_sapling = get("oak_sapling"); + public static final BlockSlab oak_slab = get("oak_slab"); + public static final BlockStairs oak_stairs = get("oak_stairs"); + public static final BlockObsidian obsidian = get("obsidian"); + public static final BlockPackedIce packed_ice = get("packed_ice"); + public static final Block palladium_block = get("palladium_block"); + public static final BlockOre palladium_ore = get("palladium_ore"); + public static final Block pentagram = get("pentagram"); + public static final Block phosphor_block = get("phosphor_block"); + public static final BlockOre phosphor_ore = get("phosphor_ore"); + public static final BlockPistonBase piston = get("piston"); + public static final BlockPistonMoving piston_extension = get("piston_extension"); + public static final BlockPistonHead piston_head = get("piston_head"); + public static final Block platinum_block = get("platinum_block"); + public static final BlockOre platinum_ore = get("platinum_ore"); + public static final Block plutonium_block = get("plutonium_block"); + public static final BlockOre plutonium_ore = get("plutonium_ore"); + public static final BlockPortal portal = get("portal"); + public static final BlockPortalFrame portal_frame = get("portal_frame"); + public static final Block potassium_block = get("potassium_block"); + public static final BlockOre potassium_ore = get("potassium_ore"); + public static final BlockPotato potato = get("potato"); + public static final BlockRedstoneComparator powered_comparator = get("powered_comparator"); + public static final BlockRedstoneRepeater powered_repeater = get("powered_repeater"); + public static final Block praseodymium_block = get("praseodymium_block"); + public static final BlockOre praseodymium_ore = get("praseodymium_ore"); + public static final BlockPumpkin pumpkin = get("pumpkin"); + public static final BlockStem pumpkin_stem = get("pumpkin_stem"); + public static final BlockBed purple_bed = get("purple_bed"); + public static final BlockQuartz quartz_block = get("quartz_block"); + public static final BlockOre quartz_ore = get("quartz_ore"); + public static final BlockSlab quartz_slab = get("quartz_slab"); + public static final BlockStairs quartz_stairs = get("quartz_stairs"); + public static final Block radium_block = get("radium_block"); + public static final BlockOre radium_ore = get("radium_ore"); + public static final BlockRail rail = get("rail"); + public static final BlockBed red_bed = get("red_bed"); + public static final BlockButton red_button = get("red_button"); + public static final BlockMushroom red_mushroom = get("red_mushroom"); + public static final BlockHugeMushroom red_mushroom_block = get("red_mushroom_block"); + public static final BlockRedstoneWire redstone = get("redstone"); + public static final BlockCompressedPowered redstone_block = get("redstone_block"); + public static final BlockRedstoneLight redstone_lamp = get("redstone_lamp"); + public static final BlockRedstoneOre redstone_ore = get("redstone_ore"); + public static final BlockRedstoneTorch redstone_torch = get("redstone_torch"); + public static final BlockReed reeds = get("reeds"); + public static final BlockRedstoneRepeater repeater = get("repeater"); + public static final BlockRock rock = get("rock"); + public static final Block ruby_block = get("ruby_block"); + public static final BlockOre ruby_ore = get("ruby_ore"); + public static final BlockSand sand = get("sand"); + public static final BlockSandStone sandstone = get("sandstone"); + public static final BlockSlab sandstone_slab = get("sandstone_slab"); + public static final BlockStairs sandstone_stairs = get("sandstone_stairs"); + public static final Block selenium_block = get("selenium_block"); + public static final BlockOre selenium_ore = get("selenium_ore"); + public static final BlockStandingSign sign = get("sign"); + public static final Block silicon_block = get("silicon_block"); + public static final BlockOre silicon_ore = get("silicon_ore"); + public static final Block silver_block = get("silver_block"); + public static final BlockOre silver_ore = get("silver_ore"); + public static final BlockSkull skull = get("skull"); + public static final BlockStaticLiquid slime = get("slime"); + public static final BlockSlime slime_block = get("slime_block"); + public static final BlockSnowBlock snow = get("snow"); + public static final BlockSnow snow_layer = get("snow_layer"); + public static final Block sodium_block = get("sodium_block"); + public static final BlockOre sodium_ore = get("sodium_ore"); + public static final BlockSoulFire soul_fire = get("soul_fire"); + public static final BlockSoulSand soul_sand = get("soul_sand"); + public static final BlockWart soul_wart = get("soul_wart"); + public static final Block sponge = get("sponge"); + public static final BlockDoor spruce_door = get("spruce_door"); + public static final BlockFence spruce_fence = get("spruce_fence"); + public static final BlockFenceGate spruce_fence_gate = get("spruce_fence_gate"); + public static final BlockLeaves spruce_leaves = get("spruce_leaves"); + public static final BlockLog spruce_log = get("spruce_log"); + public static final Block spruce_planks = get("spruce_planks"); + public static final BlockSapling spruce_sapling = get("spruce_sapling"); + public static final BlockSlab spruce_slab = get("spruce_slab"); + public static final BlockStairs spruce_stairs = get("spruce_stairs"); + public static final BlockStainedGlass stained_glass = get("stained_glass"); + public static final BlockStainedGlassPane stained_glass_pane = get("stained_glass_pane"); + public static final BlockColored stained_hardened_clay = get("stained_hardened_clay"); + public static final BlockPistonBase sticky_piston = get("sticky_piston"); + public static final BlockStone stone = get("stone"); + public static final BlockButton stone_button = get("stone_button"); + public static final BlockPressurePlate stone_pressure_plate = get("stone_pressure_plate"); + public static final BlockSlab stone_slab = get("stone_slab"); + public static final BlockStairs stone_stairs = get("stone_stairs"); + public static final BlockStoneBrick stonebrick = get("stonebrick"); + public static final BlockSlab stonebrick_slab = get("stonebrick_slab"); + public static final BlockStairs stonebrick_stairs = get("stonebrick_stairs"); + public static final BlockTripWire string = get("string"); + public static final Block sulfur_block = get("sulfur_block"); + public static final BlockOre sulfur_ore = get("sulfur_ore"); + public static final BlockTallGrass tallgrass = get("tallgrass"); + public static final Block thetium_block = get("thetium_block"); + public static final BlockOre thetium_ore = get("thetium_ore"); + public static final Block tian = get("tian"); + public static final BlockDoor tian_door = get("tian_door"); + public static final BlockFence tian_fence = get("tian_fence"); + public static final BlockFenceGate tian_fence_gate = get("tian_fence_gate"); + public static final BlockLeaves tian_leaves = get("tian_leaves"); + public static final BlockLog tian_log = get("tian_log"); + public static final Block tian_planks = get("tian_planks"); + public static final BlockTianReactor tian_reactor = get("tian_reactor"); + public static final BlockSapling tian_sapling = get("tian_sapling"); + public static final BlockSlab tian_slab = get("tian_slab"); + public static final BlockTianSoil tian_soil = get("tian_soil"); + public static final BlockStairs tian_stairs = get("tian_stairs"); + public static final Block tin_block = get("tin_block"); + public static final BlockOre tin_ore = get("tin_ore"); + public static final Block titanium_block = get("titanium_block"); + public static final BlockOre titanium_ore = get("titanium_ore"); + public static final BlockTNT tnt = get("tnt"); + public static final BlockTorch torch = get("torch"); + public static final BlockTrapDoor trapdoor = get("trapdoor"); + public static final BlockChest trapped_chest = get("trapped_chest"); + public static final BlockTripWireHook tripwire_hook = get("tripwire_hook"); + public static final Block tungsten_block = get("tungsten_block"); + public static final BlockOre tungsten_ore = get("tungsten_ore"); + public static final BlockRedstoneTorch unlit_redstone_torch = get("unlit_redstone_torch"); + public static final Block uranium_block = get("uranium_block"); + public static final BlockOre uranium_ore = get("uranium_ore"); + public static final Block vanadium_block = get("vanadium_block"); + public static final BlockOre vanadium_ore = get("vanadium_ore"); + public static final BlockVine vine = get("vine"); + public static final BlockBannerHanging wall_banner = get("wall_banner"); + public static final BlockWallSign wall_sign = get("wall_sign"); + public static final BlockWarpChest warp_chest = get("warp_chest"); + public static final BlockStaticLiquid water = get("water"); + public static final BlockLilyPad waterlily = get("waterlily"); + public static final BlockWeb web = get("web"); + public static final BlockCrops wheat = get("wheat"); + public static final BlockBed white_bed = get("white_bed"); + public static final BlockButton wooden_button = get("wooden_button"); + public static final BlockPressurePlate wooden_pressure_plate = get("wooden_pressure_plate"); + public static final BlockColored wool = get("wool"); + public static final BlockWorkbench workbench = get("workbench"); + public static final Block zinc_block = get("zinc_block"); + public static final BlockOre zinc_ore = get("zinc_ore"); + public static final BlockDynamicLiquid flowing_springwater = get("flowing_springwater"); + public static final BlockStaticLiquid springwater = get("springwater"); + + private static T get(String id) { + if(!BlockRegistry.REGISTRY.containsKey(id)) + throw new RuntimeException("Block " + id + " existiert nicht"); + return (T)BlockRegistry.REGISTRY.getObject(id); + } + + static { + if(Util.DEVMODE) { + Set blocks = Sets.newHashSet(BlockRegistry.REGISTRY); + for(Field field : Blocks.class.getDeclaredFields()) { + if(Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers()) && Block.class.isAssignableFrom(field.getType())) + try { + blocks.remove(field.get(null)); + } + catch(IllegalArgumentException | IllegalAccessException e) { + Util.throwUnchecked(e); + } + } + if(!blocks.isEmpty()) { + List list = Lists.newArrayList(blocks); + Collections.sort(list, Comparator.comparing(block -> BlockRegistry.getNameFromBlock(block))); + System.err.printf("\n*** -------------------------------------------------------------- ***\n\n"); + for(Block block : list) { + String name = BlockRegistry.getNameFromBlock(block); + System.err.printf("\tpublic static final %s %s = get(\"%s\");\n", block.getClass().getSimpleName(), name, name); + } + System.err.printf("\n^^^ " + Blocks.class.getCanonicalName() + ": Blockliste ist unvollständig, Bitte neuen Quellcode einfügen ^^^\n"); + System.exit(1); + } + } + } +} diff --git a/java/src/game/init/CraftingRegistry.java b/common/src/main/java/common/init/CraftingRegistry.java similarity index 82% rename from java/src/game/init/CraftingRegistry.java rename to common/src/main/java/common/init/CraftingRegistry.java index 930d644..d5d491f 100755 --- a/java/src/game/init/CraftingRegistry.java +++ b/common/src/main/java/common/init/CraftingRegistry.java @@ -1,4 +1,4 @@ -package game.init; +package common.init; import java.util.Collections; import java.util.Comparator; @@ -6,55 +6,39 @@ import java.util.List; import java.util.Map; import java.util.Set; -import game.collect.Lists; -import game.collect.Maps; - -import game.block.Block; -import game.block.BlockBed; -import game.block.BlockDirt; -import game.block.BlockDoublePlant; -import game.block.BlockFlower; -import game.block.BlockQuartz; -import game.block.BlockSand; -import game.block.BlockSandStone; -import game.block.BlockStoneBrick; -import game.block.BlockWall; -import game.color.DyeColor; -import game.entity.animal.EntitySheep; -import game.inventory.InventoryCrafting; -import game.item.Item; -import game.item.ItemArmor; -import game.item.ItemDye; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.tileentity.TileEntityBanner; -import game.world.World; +import common.block.Block; +import common.block.artificial.BlockBed; +import common.block.artificial.BlockQuartz; +import common.block.artificial.BlockStoneBrick; +import common.block.artificial.BlockWall; +import common.block.foliage.BlockDoublePlant; +import common.block.foliage.BlockFlower; +import common.block.natural.BlockDirt; +import common.block.natural.BlockSand; +import common.block.natural.BlockSandStone; +import common.collect.Lists; +import common.collect.Maps; +import common.color.DyeColor; +import common.entity.animal.EntitySheep; +import common.inventory.InventoryCrafting; +import common.item.Item; +import common.item.ItemArmor; +import common.item.ItemDye; +import common.item.ItemStack; +import common.tags.TagObject; +import common.tileentity.TileEntityBanner; +import common.world.World; public abstract class CraftingRegistry { private static final String[][] TOOLS = new String[][] { {"XXX", " # ", " # "}, {"X", "#", "#"}, {"XX", "X#", " #"}, {"XX", " #", " #"} }; -// private static final Object[][] toolItems = new Object[][] { -// {Blocks.planks, Blocks.cobblestone}, // Items.iron_ingot, Items.diamond, Items.gold_ingot}, -// {Items.wooden_pickaxe, Items.stone_pickaxe}, // Items.iron_pickaxe, Items.diamond_pickaxe, Items.golden_pickaxe}, -// {Items.wooden_shovel, Items.stone_shovel}, // Items.iron_shovel, Items.diamond_shovel, Items.golden_shovel}, -// {Items.wooden_axe, Items.stone_axe}, // Items.iron_axe, Items.diamond_axe, Items.golden_axe}, -// {Items.wooden_hoe, Items.stone_hoe}, // Items.iron_hoe, Items.diamond_hoe, Items.golden_hoe} -// }; private static final String[][] WEAPONS = new String[][] {{"X", "X", "#"}}; -// private static final Object[][] weaponItems = new Object[][] { -// {Blocks.planks, Blocks.cobblestone}, // Items.iron_ingot, Items.diamond, Items.gold_ingot}, -// {Items.wooden_sword, Items.stone_sword}, // Items.iron_sword, Items.diamond_sword, Items.golden_sword} -// }; private static final String[][] ARMOR = new String[][] { {"XXX", "X X"}, {"X X", "XXX", "XXX"}, {"XXX", "X X", "X X"}, {"X X", "X X"} }; private static final Object[][] COMPRESSED = new Object[][] { - /* {Blocks.gold_block, new ItemStack(Items.gold_ingot, 9)}, - {Blocks.iron_block, new ItemStack(Items.iron_ingot, 9)}, */ -// {Blocks.diamond_block, new ItemStack(Items.diamond, 9)}, {Blocks.emerald_block, new ItemStack(Items.emerald, 9)}, {Blocks.lapis_block, new ItemStack(Items.dye, 9, DyeColor.BLUE.getDyeDamage())}, {Blocks.redstone_block, new ItemStack(Items.redstone, 9)}, @@ -62,33 +46,12 @@ public abstract class CraftingRegistry {Blocks.hay_block, new ItemStack(Items.wheats, 9)}, {Blocks.slime_block, new ItemStack(Items.slime_ball, 9)} }; -// private static final Item[][] armorItems = new Item[][] { -// {Items.leather}, // /* Items.iron_ingot, */ Items.diamond /* , Items.gold_ingot */}, -// {Items.leather_helmet}, // /* Items.iron_helmet, */ Items.diamond_helmet /* , Items.golden_helmet */}, -// {Items.leather_chestplate}, // /* Items.iron_chestplate, */ Items.diamond_chestplate /* , Items.golden_chestplate */}, -// {Items.leather_leggings}, // /* Items.iron_leggings, */ Items.diamond_leggings /* , Items.golden_leggings */}, -// {Items.leather_boots}, // /* Items.iron_boots, */ Items.diamond_boots /* , Items.golden_boots */} -// }; private static final List recipes = Lists.newArrayList(); private static final List base = Lists.newArrayList(); static void register() { -// for (int i = 0; i < toolItems[0].length; ++i) -// { -// Object object = toolItems[0][i]; -// -// for (int j = 0; j < toolItems.length - 1; ++j) -// { -// Item item = (Item)toolItems[j + 1][i]; -// add(new ItemStack(item), toolPatterns[j], '#', Items.stick, 'X', object); -// } -// } - -// add(new ItemStack(Items.shears), " #", "# ", '#', Items.iron_ingot); -// add(new ItemStack(Items.diamond_shears), " #", "# ", '#', Items.diamond); - for(OreType ore : OreType.values()) { Item item = ItemRegistry.getRegisteredItem(ore.item); ore.material.addRepairItem(item); @@ -165,17 +128,6 @@ public abstract class CraftingRegistry } } -// for (int i = 0; i < weaponItems[0].length; ++i) -// { -// Object object = weaponItems[0][i]; -// -// for (int j = 0; j < weaponItems.length - 1; ++j) -// { -// Item item = (Item)weaponItems[j + 1][i]; -// add(new ItemStack(item), weaponPatterns[j], '#', Items.stick, 'X', object); -// } -// } - add(new ItemStack(Items.bow, 1), " #X", "# X", " #X", 'X', Items.string, '#', Items.stick); add(new ItemStack(Items.arrow, 4), "X", "#", "Y", 'Y', Items.feather, 'X', Items.flint, '#', Items.stick); @@ -192,8 +144,6 @@ public abstract class CraftingRegistry addShapeless(new ItemStack(Items.mushroom_stew), Blocks.brown_mushroom, Blocks.red_mushroom, Items.bowl); add(new ItemStack(Items.cookie, 8), "#X#", 'X', new ItemStack(Items.dye, 1, DyeColor.BROWN.getDyeDamage()), '#', Items.wheats); -// addRecipe(new ItemStack(Items.rabbit_stew), " R ", "CPM", " B ", 'R', new ItemStack(Items.cooked_rabbit), 'C', Items.carrot, 'P', Items.baked_potato, 'M', Blocks.brown_mushroom, 'B', Items.bowl); -// addRecipe(new ItemStack(Items.rabbit_stew), " R ", "CPD", " B ", 'R', new ItemStack(Items.cooked_rabbit), 'C', Items.carrot, 'P', Items.baked_potato, 'D', Blocks.red_mushroom, 'B', Items.bowl); add(new ItemStack(Blocks.melon_block), "MMM", "MMM", "MMM", 'M', Items.melon); add(new ItemStack(Items.melon_stem), "M", 'M', Items.melon); add(new ItemStack(Items.pumpkin_stem, 4), "M", 'M', Blocks.pumpkin); @@ -206,10 +156,7 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.warp_chest), "###", "#E#", "###", '#', Blocks.obsidian, 'E', Items.charged_orb); add(new ItemStack(Blocks.furnace), "###", "# #", "###", '#', Blocks.cobblestone); add(new ItemStack(Blocks.sandstone), "##", "##", '#', new ItemStack(Blocks.sand, 1, BlockSand.EnumType.SAND.getMetadata())); -// addRecipe(new ItemStack(Blocks.red_sandstone), "##", "##", '#', new ItemStack(Blocks.sand, 1, BlockSand.EnumType.RED_SAND.getMetadata())); add(new ItemStack(Blocks.sandstone, 4, BlockSandStone.EnumType.SMOOTH.getMetadata()), "##", "##", '#', new ItemStack(Blocks.sandstone, 1, BlockSandStone.EnumType.DEFAULT.getMetadata())); -// addRecipe(new ItemStack(Blocks.red_sandstone, 4, BlockRedSandstone.EnumType.SMOOTH.getMetadata()), "##", "##", '#', new ItemStack(Blocks.red_sandstone, 1, BlockRedSandstone.EnumType.DEFAULT.getMetadata())); -// addRecipe(new ItemStack(Blocks.red_sandstone, 1, BlockRedSandstone.EnumType.CHISELED.getMetadata()), "#", "#", '#', new ItemStack(Blocks.stone_slab2, 1, BlockStoneSlabNew.EnumType.RED_SANDSTONE.getMetadata())); add(new ItemStack(Blocks.quartz_block, 2, BlockQuartz.EnumType.LINES_Y.getMetadata()), "#", "#", '#', new ItemStack(Blocks.quartz_block, 1, BlockQuartz.EnumType.DEFAULT.getMetadata())); add(new ItemStack(Blocks.stonebrick, 4), "##", "##", '#', Blocks.stone); addShapeless(new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.MOSSY_META), Blocks.stonebrick, Blocks.vine); @@ -219,31 +166,10 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.redstone_lamp, 1), " R ", "RGR", " R ", 'R', Items.redstone, 'G', Blocks.glowstone); add(new ItemStack(Blocks.beacon, 1), "GGG", "GSG", "OOO", 'G', Blocks.glass, 'S', Items.charge_crystal, 'O', Blocks.obsidian); add(new ItemStack(Blocks.blood_brick, 1), "NN", "NN", 'N', Items.bloodbrick); -// addRecipe(new ItemStack(Blocks.stone, 2, BlockStone.EnumType.DIORITE.getMetadata()), "CQ", "QC", 'C', Blocks.cobblestone, 'Q', Items.quartz); -// addShapelessRecipe(new ItemStack(Blocks.stone, 1, BlockStone.EnumType.GRANITE.getMetadata()), new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata()), Items.quartz); -// addShapelessRecipe(new ItemStack(Blocks.stone, 2, BlockStone.EnumType.ANDESITE.getMetadata()), new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata()), Blocks.cobblestone); add(new ItemStack(Blocks.dirt, 4, BlockDirt.DirtType.COARSE_DIRT.getMetadata()), "DG", "GD", 'D', new ItemStack(Blocks.dirt, 1, BlockDirt.DirtType.DIRT.getMetadata()), 'G', Blocks.gravel); -// addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.DIORITE_SMOOTH.getMetadata()), "SS", "SS", 'S', new ItemStack(Blocks.stone, 1, BlockStone.EnumType.DIORITE.getMetadata())); -// addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.GRANITE_SMOOTH.getMetadata()), "SS", "SS", 'S', new ItemStack(Blocks.stone, 1, BlockStone.EnumType.GRANITE.getMetadata())); -// addRecipe(new ItemStack(Blocks.stone, 4, BlockStone.EnumType.ANDESITE_SMOOTH.getMetadata()), "SS", "SS", 'S', new ItemStack(Blocks.stone, 1, BlockStone.EnumType.ANDESITE.getMetadata())); -// addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.ROUGH_META), "SS", "SS", 'S', Items.prismarine_shard); -// addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.BRICKS_META), "SSS", "SSS", "SSS", 'S', Items.prismarine_shard); -// addRecipe(new ItemStack(Blocks.prismarine, 1, BlockPrismarine.DARK_META), "SSS", "SIS", "SSS", 'S', Items.prismarine_shard, 'I', new ItemStack(Items.dye, 1, EnumDyeColor.BLACK.getDyeDamage())); -// addRecipe(new ItemStack(Blocks.sea_lantern, 1, 0), "SCS", "CCC", "SCS", 'S', Items.prismarine_shard, 'C', Items.prismarine_crystals); add(new ItemStack(Blocks.lamp, 1), " R ", "RGR", " R ", 'R', Blocks.glass, 'G', Blocks.glowstone); -// for (int i = 0; i < armorItems[0].length; ++i) -// { -// Item item = armorItems[0][i]; -// -// for (int j = 0; j < armorItems.length - 1; ++j) -// { -// Item item1 = armorItems[j + 1][i]; -// add(new ItemStack(item1), armorPatterns[j], 'X', item); -// } -// } - for (int i = 0; i < 16; ++i) { addShapeless(new ItemStack(Blocks.wool, 1, i), new ItemStack(Items.dye, 1, 15 - i), new ItemStack(Blocks.wool, 1, 0)); @@ -287,9 +213,6 @@ public abstract class CraftingRegistry } recipes.add(new RecipesArmorDyes()); -// this.recipes.add(new RecipeBookCloning()); -// recipes.add(new RecipesMapCloning()); -// recipes.add(new RecipesMapExtending()); recipes.add(new RecipeFireworks()); recipes.add(new RecipeRepairItem()); @@ -316,7 +239,8 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.daylight_detector), "GGG", "QQQ", "WWW", 'G', Blocks.glass, 'Q', Items.quartz, 'W', slab); add(new ItemStack(Blocks.chest), "###", "# #", "###", '#', planks); - addBasic(new ItemStack(Blocks.crafting_table), "##", "##", '#', planks); + addBasic(new ItemStack(Blocks.workbench), "##", "##", '#', planks); + add(new ItemStack(Blocks.assembly_unit), "----", "XXXX", "X##X", '#', Blocks.construction_table, '-', Items.titanium_ingot, 'X', planks); add(new ItemStack(Blocks.jukebox, 1), "###", "#X#", "###", '#', planks, 'X', Items.diamond); @@ -358,17 +282,6 @@ public abstract class CraftingRegistry addShapeless(new ItemStack(Blocks.tnt, 1, 6), new ItemStack(Blocks.tnt, 1, 5), new ItemStack(Blocks.tnt, 1, 5)); addShapeless(new ItemStack(Blocks.tnt, 1, 7), new ItemStack(Blocks.tnt, 1, 6), new ItemStack(Blocks.tnt, 1, 6)); add(new ItemStack(Blocks.nuke, 1), "###", "###", "###", '#', new ItemStack(Blocks.tnt, 1, 7)); - -// add(new ItemStack(Blocks.sandstone, 1, BlockSandStone.EnumType.CHISELED.getMetadata()), "#", "#", '#', new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.SAND.getMetadata())); -// add(new ItemStack(Blocks.quartz_block, 1, BlockQuartz.EnumType.CHISELED.getMetadata()), "#", "#", '#', new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.QUARTZ.getMetadata())); -// add(new ItemStack(Blocks.stonebrick, 1, BlockStoneBrick.CHISELED_META), "#", "#", '#', new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.SMOOTHBRICK.getMetadata())); -// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.COBBLESTONE.getMetadata()), "###", '#', Blocks.cobblestone); -// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.STONE.getMetadata()), "###", '#', Blocks.stone); -// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.SAND.getMetadata()), "###", '#', Blocks.sandstone); -// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.BRICK.getMetadata()), "###", '#', Blocks.brick_block); -// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.SMOOTHBRICK.getMetadata()), "###", '#', Blocks.stonebrick); -// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.BLOODBRICK.getMetadata()), "###", '#', Blocks.blood_brick); -// add(new ItemStack(Blocks.stone_slab, 6, BlockStoneSlab.EnumType.QUARTZ.getMetadata()), "###", '#', Blocks.quartz_block); add(new ItemStack(Blocks.ladder, 3), "# #", "###", "# #", '#', Items.stick); @@ -389,7 +302,6 @@ public abstract class CraftingRegistry add(new ItemStack(Items.brewing_stand, 1), " B ", "###", '#', Blocks.cobblestone, 'B', Items.blaze_rod); add(new ItemStack(Blocks.lit_pumpkin, 1), "A", "B", 'A', Blocks.pumpkin, 'B', Blocks.torch); add(new ItemStack(Items.chest_minecart, 1), "A", "B", 'A', Blocks.chest, 'B', Items.minecart); -// add(new ItemStack(Items.furnace_minecart, 1), "A", "B", 'A', Blocks.furnace, 'B', Items.minecart); add(new ItemStack(Items.tnt_minecart, 1), "A", "B", 'A', new ItemStack(Blocks.tnt, 1, 0), 'B', Items.minecart); add(new ItemStack(Items.hopper_minecart, 1), "A", "B", 'A', Blocks.hopper, 'B', Items.minecart); add(new ItemStack(Items.bucket, 1), "# #", " # ", '#', Items.iron_ingot); @@ -404,10 +316,7 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.stonebrick_stairs, 4), "# ", "## ", "###", '#', Blocks.stonebrick); add(new ItemStack(Blocks.blood_brick_stairs, 4), "# ", "## ", "###", '#', Blocks.blood_brick); add(new ItemStack(Blocks.sandstone_stairs, 4), "# ", "## ", "###", '#', Blocks.sandstone); -// addRecipe(new ItemStack(Blocks.red_sandstone_stairs, 4), "# ", "## ", "###", '#', Blocks.red_sandstone); add(new ItemStack(Blocks.quartz_stairs, 4), "# ", "## ", "###", '#', Blocks.quartz_block); -// add(new ItemStack(Items.painting, 1), "###", "#X#", "###", '#', Items.stick, 'X', Blocks.wool); -// add(new ItemStack(Items.item_frame, 1), "###", "#X#", "###", '#', Items.stick, 'X', Items.leather); add(new ItemStack(Items.golden_apple, 1, 0), "###", "#X#", "###", '#', Items.gold_ingot, 'X', Items.apple); add(new ItemStack(Items.golden_apple, 1, 1), "###", "#X#", "###", '#', Blocks.gold_block, 'X', Items.apple); add(new ItemStack(Items.golden_carrot, 1, 0), "###", "#X#", "###", '#', Items.gold_nugget, 'X', Items.carrot); @@ -416,9 +325,7 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.redstone_torch, 1), "X", "#", '#', Items.stick, 'X', Items.redstone); add(new ItemStack(Items.repeater, 1), "#X#", "III", '#', Blocks.redstone_torch, 'X', Items.redstone, 'I', Blocks.stone); add(new ItemStack(Items.comparator, 1), " # ", "#X#", "III", '#', Blocks.redstone_torch, 'X', Items.quartz, 'I', Blocks.stone); -// add(new ItemStack(Items.clock, 1), " # ", "#X#", " # ", '#', Items.gold_ingot, 'X', Items.redstone); add(new ItemStack(Items.navigator, 1), " # ", "#X#", " # ", '#', Items.iron_ingot, 'X', Items.redstone); -// add(new ItemStack(Items.map, 1), "###", "#X#", "###", '#', Items.paper, 'X', Items.compass); add(new ItemStack(Blocks.stone_button, 1), "#", '#', Blocks.stone); add(new ItemStack(Blocks.stone_pressure_plate, 1), "##", '#', Blocks.stone); add(new ItemStack(Blocks.heavy_weighted_pressure_plate, 1), "##", '#', Items.iron_ingot); @@ -428,12 +335,10 @@ public abstract class CraftingRegistry add(new ItemStack(Blocks.sticky_piston, 1), "S", "P", 'S', Items.slime_ball, 'P', Blocks.piston); add(new ItemStack(Blocks.enchanting_table, 1), " B ", "D#D", "###", '#', Blocks.obsidian, 'B', Items.book, 'D', Items.diamond); add(new ItemStack(Blocks.anvil, 1), "III", " i ", "iii", 'I', Blocks.iron_block, 'i', Items.iron_ingot); -// addRecipe(new ItemStack(Items.leather), "##", "##", '#', Items.rabbit_hide); addShapeless(new ItemStack(Items.charged_orb, 1), Items.orb, Items.blaze_powder); addShapeless(new ItemStack(Items.fire_charge, 3), Items.gunpowder, Items.blaze_powder, Items.coal); addShapeless(new ItemStack(Items.fire_charge, 3), Items.gunpowder, Items.blaze_powder, new ItemStack(Items.coal, 1, 1)); add(new ItemStack(Blocks.hopper), "I I", "ICI", " I ", 'I', Items.iron_ingot, 'C', Blocks.chest); -// addRecipe(new ItemStack(Items.armor_stand, 1), "///", " / ", "/_/", '/', Items.stick, '_', new ItemStack(Blocks.stone_slab, 1, BlockStoneSlab.EnumType.STONE.getMetadata())); add(new ItemStack(Items.dynamite, 1), "X#X", "#X#", "X#X", 'X', Items.gunpowder, '#', Items.clay_ball); @@ -446,27 +351,18 @@ public abstract class CraftingRegistry addShapeless(new ItemStack(Items.dynamite, 1, 7), new ItemStack(Items.dynamite, 1, 6), new ItemStack(Items.dynamite, 1, 6)); add(new ItemStack(Items.portal_frame, 1), "XYX", "X#X", "XXX", 'X', Blocks.obsidian, 'Y', Items.orb, '#', Items.charged_orb); -// add(new ItemStack(Blocks.monster_egg, 1, 0), "XXX", "X#X", "XXX", 'X', new ItemStack(Blocks.stone, 1, 0), '#', new ItemStack(Items.spawn_egg, 1, 60)); -// add(new ItemStack(Blocks.monster_egg, 1, 1), "XXX", "X#X", "XXX", 'X', Blocks.cobblestone, '#', new ItemStack(Items.spawn_egg, 1, 60)); -// for(int z = 0; z < 4; z++) { -// add(new ItemStack(Blocks.monster_egg, 1, z + 2), "XXX", "X#X", "XXX", 'X', new ItemStack(Blocks.stonebrick, 1, z), '#', new ItemStack(Items.spawn_egg, 1, 60)); -// } add(new ItemStack(Items.experience_bottle, 1), "YXY", "X#X", "YXY", 'X', Blocks.glass_pane, 'Y', Blocks.glowstone, '#', Items.emerald); add(new ItemStack(Blocks.mob_spawner, 1), "###", "#X#", "###", 'X', Items.charge_crystal, '#', Blocks.iron_bars); add(new ItemStack(Blocks.dragon_egg, 1), "###", "#X#", "#D#", 'X', Items.charge_crystal, 'D', Items.diamond, '#', Blocks.obsidian); -// addRecipe(new ItemStack(Blocks.command_block, 1), "###", "#X#", "###", 'X', Items.redstone, '#', Items.quartz); -// addShapeless(new ItemStack(Items.spawn_egg, 1, 51), new ItemStack(Items.skull, 1, 0)); -// addShapeless(new ItemStack(Items.spawn_egg, 1, 51), new ItemStack(Items.skull, 1, 1)); -// addShapeless(new ItemStack(Items.spawn_egg, 1, 54), new ItemStack(Items.skull, 1, 2)); -// addShapeless(new ItemStack(Items.spawn_egg, 1, 50), new ItemStack(Items.skull, 1, 4)); -// addShapeless(new ItemStack(Items.spawn_egg, 1, 124), Items.flint, Items.egg, Blocks.cobblestone, Items.slime_ball); -// addRecipe(new ItemStack(Items.command_block_minecart, 1), "A", "B", 'A', Blocks.command_block, 'B', Items.minecart); add(new ItemStack(Blocks.red_button, 1), "#", '#', Items.redstone); add(new ItemStack(Items.chick_magnet, 1), "A A", "N N", " C ", 'A', Items.aluminium_ingot, 'N', Items.nickel_ingot, 'C', Items.cobalt_ingot); add(new ItemStack(Items.magnet, 1), "I I", "N N", " R ", 'I', Items.iron_ingot, 'N', Items.neodymium_ingot, 'R', Items.redstone); addShapeless(new ItemStack(Items.potion, 1, 16384), new ItemStack(Items.potion, 1, 0), Items.gunpowder); + + add(new ItemStack(Blocks.construction_table), "---", "-#-", "---", '#', Blocks.workbench, '-', Items.iron_ingot); + add(new ItemStack(Blocks.bedrock), "#####", "#####", "#####", "#####", "#####", '#', Blocks.obsidian); Collections.sort(recipes, new Comparator() { @@ -697,14 +593,14 @@ public abstract class CraftingRegistry if (itemstack1 != null && itemstack1.getItem() == Items.banner) { itemstack = itemstack1.copy(); - itemstack.stackSize = 1; + itemstack.size = 1; break; } } - TileEntityBanner.EnumBannerPattern tileentitybanner$enumbannerpattern = this.getBannerPattern(inv); + TileEntityBanner.EnumBannerPattern type = this.getBannerPattern(inv); - if (tileentitybanner$enumbannerpattern != null) + if (type != null) { int k = 0; @@ -719,23 +615,23 @@ public abstract class CraftingRegistry } } - NBTTagCompound nbttagcompound1 = itemstack.getSubCompound("BlockEntityTag", true); - NBTTagList nbttaglist = null; + TagObject tag = itemstack.getSubCompound("BlockEntityTag", true); + List list = null; - if (nbttagcompound1.hasKey("Patterns", 9)) + if (tag.hasList("Patterns")) { - nbttaglist = nbttagcompound1.getTagList("Patterns", 10); + list = tag.getList("Patterns"); } else { - nbttaglist = new NBTTagList(); - nbttagcompound1.setTag("Patterns", nbttaglist); + list = Lists.newArrayList(); + tag.setList("Patterns", list); } - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setString("Pattern", tileentitybanner$enumbannerpattern.getPatternID()); - nbttagcompound.setInteger("Color", k); - nbttaglist.appendTag(nbttagcompound); + TagObject pattern = new TagObject(); + pattern.setString("Pattern", type.getPatternID()); + pattern.setInt("Color", k); + list.add(pattern); } return itemstack; @@ -947,7 +843,7 @@ public abstract class CraftingRegistry if (itemstack != null && TileEntityBanner.getPatterns(itemstack) > 0) { ItemStack itemstack1 = itemstack.copy(); - itemstack1.stackSize = 1; + itemstack1.size = 1; return itemstack1; } } @@ -982,7 +878,7 @@ public abstract class CraftingRegistry else if (itemstack.hasTagCompound() && TileEntityBanner.getPatterns(itemstack) > 0) { aitemstack[i] = itemstack.copy(); - aitemstack[i].stackSize = 1; + aitemstack[i].size = 1; } } } @@ -1072,24 +968,24 @@ public abstract class CraftingRegistry if (l > 0) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - NBTTagCompound nbttagcompound3 = new NBTTagCompound(); - NBTTagList nbttaglist = new NBTTagList(); + TagObject tag = new TagObject(); + TagObject data = new TagObject(); + List list = Lists.newArrayList(); for (int k2 = 0; k2 < inv.getSizeInventory(); ++k2) { ItemStack itemstack3 = inv.getStackInSlot(k2); - if (itemstack3 != null && itemstack3.getItem() == Items.firework_charge && itemstack3.hasTagCompound() && itemstack3.getTagCompound().hasKey("Explosion", 10)) + if (itemstack3 != null && itemstack3.getItem() == Items.firework_charge && itemstack3.hasTagCompound() && itemstack3.getTagCompound().hasObject("Explosion")) { - nbttaglist.appendTag(itemstack3.getTagCompound().getCompoundTag("Explosion")); + list.add(itemstack3.getTagCompound().getObject("Explosion")); } } - nbttagcompound3.setTag("Explosions", nbttaglist); - nbttagcompound3.setByte("Flight", (byte)j); - nbttagcompound1.setTag("Fireworks", nbttagcompound3); - this.field_92102_a.setTagCompound(nbttagcompound1); + data.setList("Explosions", list); + data.setByte("Flight", (byte)j); + tag.setObject("Fireworks", data); + this.field_92102_a.setTagCompound(tag); } return true; @@ -1097,8 +993,8 @@ public abstract class CraftingRegistry else if (j == 1 && i == 0 && l == 0 && k > 0 && j1 <= 1) { this.field_92102_a = new ItemStack(Items.firework_charge); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagCompound nbttagcompound2 = new NBTTagCompound(); + TagObject tag = new TagObject(); + TagObject data = new TagObject(); byte b0 = 0; List list = Lists.newArrayList(); @@ -1114,11 +1010,11 @@ public abstract class CraftingRegistry } else if (itemstack2.getItem() == Items.glowstone_dust) { - nbttagcompound2.setBoolean("Flicker", true); + data.setBool("Flicker", true); } else if (itemstack2.getItem() == Items.diamond) { - nbttagcompound2.setBoolean("Trail", true); + data.setBool("Trail", true); } else if (itemstack2.getItem() == Items.fire_charge) { @@ -1146,10 +1042,10 @@ public abstract class CraftingRegistry aint1[l2] = ((Integer)list.get(l2)).intValue(); } - nbttagcompound2.setIntArray("Colors", aint1); - nbttagcompound2.setByte("Type", b0); - nbttagcompound.setTag("Explosion", nbttagcompound2); - this.field_92102_a.setTagCompound(nbttagcompound); + data.setIntArray("Colors", aint1); + data.setByte("Type", b0); + tag.setObject("Explosion", data); + this.field_92102_a.setTagCompound(tag); return true; } else if (j == 0 && i == 0 && l == 1 && k > 0 && k == i1) @@ -1169,7 +1065,7 @@ public abstract class CraftingRegistry else if (itemstack1.getItem() == Items.firework_charge) { this.field_92102_a = itemstack1.copy(); - this.field_92102_a.stackSize = 1; + this.field_92102_a.size = 1; } } } @@ -1183,15 +1079,15 @@ public abstract class CraftingRegistry if (this.field_92102_a != null && this.field_92102_a.hasTagCompound()) { - NBTTagCompound nbttagcompound4 = this.field_92102_a.getTagCompound().getCompoundTag("Explosion"); + TagObject tag = this.field_92102_a.getTagCompound().getObject("Explosion"); - if (nbttagcompound4 == null) + if (tag == null) { return false; } else { - nbttagcompound4.setIntArray("FadeColors", aint); + tag.setIntArray("FadeColors", aint); return true; } } @@ -1271,7 +1167,7 @@ public abstract class CraftingRegistry { ItemStack itemstack1 = (ItemStack)list.get(0); - if (itemstack.getItem() != itemstack1.getItem() || itemstack1.stackSize != 1 || itemstack.stackSize != 1 || !itemstack1.getItem().isDamageable()) + if (itemstack.getItem() != itemstack1.getItem() || itemstack1.size != 1 || itemstack.size != 1 || !itemstack1.getItem().isDamageable()) { return false; } @@ -1301,7 +1197,7 @@ public abstract class CraftingRegistry { ItemStack itemstack1 = (ItemStack)list.get(0); - if (itemstack.getItem() != itemstack1.getItem() || itemstack1.stackSize != 1 || itemstack.stackSize != 1 || !itemstack1.getItem().isDamageable()) + if (itemstack.getItem() != itemstack1.getItem() || itemstack1.size != 1 || itemstack.size != 1 || !itemstack1.getItem().isDamageable()) { return null; } @@ -1314,7 +1210,7 @@ public abstract class CraftingRegistry ItemStack itemstack2 = (ItemStack)list.get(0); ItemStack itemstack3 = (ItemStack)list.get(1); - if (itemstack2.getItem() == itemstack3.getItem() && itemstack2.stackSize == 1 && itemstack3.stackSize == 1 && itemstack2.getItem().isDamageable()) + if (itemstack2.getItem() == itemstack3.getItem() && itemstack2.size == 1 && itemstack3.size == 1 && itemstack2.getItem().isDamageable()) { Item item = itemstack2.getItem(); int j = item.getMaxDamage() - itemstack2.getItemDamage(); @@ -1434,7 +1330,7 @@ public abstract class CraftingRegistry } itemstack = itemstack1.copy(); - itemstack.stackSize = 1; + itemstack.size = 1; if (itemarmor.hasColor(itemstack1)) { @@ -1534,7 +1430,7 @@ public abstract class CraftingRegistry /** Is the ItemStack that you get when craft the recipe. */ private final ItemStack recipeOutput; - private boolean copyIngredientNBT; + private boolean copyIngredientTag; public ShapedRecipes(int width, int height, ItemStack[] p_i1917_3_, ItemStack output) { @@ -1571,9 +1467,9 @@ public abstract class CraftingRegistry */ public boolean matches(InventoryCrafting inv, World worldIn) { - for (int i = 0; i <= 3 - this.recipeWidth; ++i) + for (int i = 0; i <= inv.getWidth() - this.recipeWidth; ++i) { - for (int j = 0; j <= 3 - this.recipeHeight; ++j) + for (int j = 0; j <= inv.getHeight() - this.recipeHeight; ++j) { if (this.checkMatch(inv, i, j, true)) { @@ -1593,43 +1489,43 @@ public abstract class CraftingRegistry /** * Checks if the region of a crafting inventory is match for the recipe. */ - private boolean checkMatch(InventoryCrafting p_77573_1_, int p_77573_2_, int p_77573_3_, boolean p_77573_4_) + private boolean checkMatch(InventoryCrafting inv, int xPos, int yPos, boolean mirror) { - for (int i = 0; i < 3; ++i) + for (int x = 0; x < inv.getWidth(); ++x) { - for (int j = 0; j < 3; ++j) + for (int y = 0; y < inv.getHeight(); ++y) { - int k = i - p_77573_2_; - int l = j - p_77573_3_; - ItemStack itemstack = null; + int rx = x - xPos; + int ry = y - yPos; + ItemStack stack = null; - if (k >= 0 && l >= 0 && k < this.recipeWidth && l < this.recipeHeight) + if (rx >= 0 && ry >= 0 && rx < this.recipeWidth && ry < this.recipeHeight) { - if (p_77573_4_) + if (mirror) { - itemstack = this.recipeItems[this.recipeWidth - k - 1 + l * this.recipeWidth]; + stack = this.recipeItems[this.recipeWidth - rx - 1 + ry * this.recipeWidth]; } else { - itemstack = this.recipeItems[k + l * this.recipeWidth]; + stack = this.recipeItems[rx + ry * this.recipeWidth]; } } - ItemStack itemstack1 = p_77573_1_.getStackInRowAndColumn(i, j); + ItemStack ingredient = inv.getStackInRowAndColumn(x, y); - if (itemstack1 != null || itemstack != null) + if (ingredient != null || stack != null) { - if (itemstack1 == null && itemstack != null || itemstack1 != null && itemstack == null) + if (ingredient == null && stack != null || ingredient != null && stack == null) { return false; } - if (itemstack.getItem() != itemstack1.getItem()) + if (stack.getItem() != ingredient.getItem()) { return false; } - if (itemstack.getMetadata() != 32767 && itemstack.getMetadata() != itemstack1.getMetadata()) + if (stack.getMetadata() != 32767 && stack.getMetadata() != ingredient.getMetadata()) { return false; } @@ -1647,7 +1543,7 @@ public abstract class CraftingRegistry { ItemStack itemstack = this.getRecipeOutput().copy(); - if (this.copyIngredientNBT) + if (this.copyIngredientTag) { for (int i = 0; i < inv.getSizeInventory(); ++i) { @@ -1655,7 +1551,7 @@ public abstract class CraftingRegistry if (itemstack1 != null && itemstack1.hasTagCompound()) { - itemstack.setTagCompound((NBTTagCompound)itemstack1.getTagCompound().copy()); + itemstack.setTagCompound(itemstack1.getTagCompound().copy()); } } } diff --git a/java/src/game/init/DecoType.java b/common/src/main/java/common/init/DecoType.java similarity index 95% rename from java/src/game/init/DecoType.java rename to common/src/main/java/common/init/DecoType.java index 1765119..2ae9779 100755 --- a/java/src/game/init/DecoType.java +++ b/common/src/main/java/common/init/DecoType.java @@ -1,4 +1,4 @@ -package game.init; +package common.init; public enum DecoType { FLOOR("floor_tiles", "Schwarz-weiße Bodenfliesen"), diff --git a/java/src/game/init/DispenserRegistry.java b/common/src/main/java/common/init/DispenserRegistry.java similarity index 69% rename from java/src/game/init/DispenserRegistry.java rename to common/src/main/java/common/init/DispenserRegistry.java index eef268e..db74a2a 100755 --- a/java/src/game/init/DispenserRegistry.java +++ b/common/src/main/java/common/init/DispenserRegistry.java @@ -1,45 +1,46 @@ -package game.init; +package common.init; -import game.block.Block; -import game.block.BlockDispenser; -import game.block.BlockDynamicLiquid; -import game.block.BlockLiquid; -import game.block.BlockTNT; -import game.color.DyeColor; -import game.dispenser.BehaviorDefaultDispenseItem; -import game.dispenser.BehaviorProjectileDispense; -import game.dispenser.IBehaviorDispenseItem; -import game.dispenser.IBlockSource; -import game.dispenser.IPosition; -import game.entity.Entity; -import game.entity.item.EntityBoat; -import game.entity.item.EntityFireworks; -import game.entity.item.EntityTnt; -import game.entity.item.EntityXpBottle; -import game.entity.projectile.EntityArrow; -import game.entity.projectile.EntityDie; -import game.entity.projectile.EntityDynamite; -import game.entity.projectile.EntityEgg; -import game.entity.projectile.EntityFireCharge; -import game.entity.projectile.EntityPotion; -import game.entity.projectile.EntitySnowball; -import game.entity.types.EntityLiving; -import game.entity.types.IProjectile; -import game.item.Item; -import game.item.ItemBucket; -import game.item.ItemDie; -import game.item.ItemDye; -import game.item.ItemMonsterPlacer; -import game.item.ItemPotion; -import game.item.ItemStack; -import game.material.Material; -import game.rng.Random; -import game.tileentity.TileEntityDispenser; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.block.liquid.BlockDynamicLiquid; +import common.block.liquid.BlockLiquid; +import common.block.tech.BlockDispenser; +import common.block.tech.BlockTNT; +import common.color.DyeColor; +import common.dispenser.BehaviorDefaultDispenseItem; +import common.dispenser.BehaviorProjectileDispense; +import common.dispenser.IBehaviorDispenseItem; +import common.dispenser.IBlockSource; +import common.dispenser.IPosition; +import common.entity.Entity; +import common.entity.item.EntityBoat; +import common.entity.item.EntityFireworks; +import common.entity.item.EntityTnt; +import common.entity.item.EntityXpBottle; +import common.entity.projectile.EntityArrow; +import common.entity.projectile.EntityDie; +import common.entity.projectile.EntityDynamite; +import common.entity.projectile.EntityEgg; +import common.entity.projectile.EntityFireCharge; +import common.entity.projectile.EntityPotion; +import common.entity.projectile.EntitySnowball; +import common.entity.types.EntityLiving; +import common.entity.types.IProjectile; +import common.item.Item; +import common.item.ItemBucket; +import common.item.ItemDie; +import common.item.ItemDye; +import common.item.ItemMonsterPlacer; +import common.item.ItemPotion; +import common.item.ItemStack; +import common.rng.Random; +import common.tileentity.TileEntityDispenser; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.util.RegistryDefaulted; +import common.world.State; +import common.world.World; public abstract class DispenserRegistry { public static final RegistryDefaulted REGISTRY = new RegistryDefaulted(new BehaviorDefaultDispenseItem()); @@ -137,7 +138,7 @@ public abstract class DispenserRegistry { double d1 = (double)((float)source.getBlockPos().getY() + 0.2F); double d2 = source.getZ() + (double)enumfacing.getFrontOffsetZ(); Entity entity = ItemMonsterPlacer.spawnCreature(source.getWorld(), ((ItemMonsterPlacer)stack.getItem()).getSpawnedId(), - d0, d1, d2); + d0, d1, d2, false); if (entity instanceof EntityLiving && stack.hasDisplayName()) { @@ -148,8 +149,8 @@ public abstract class DispenserRegistry { return stack; } }; - for(EntityEggInfo egg : EntityRegistry.SPAWN_EGGS.values()) { - REGISTRY.putObject(ItemRegistry.getRegisteredItem(egg.spawnedID.toLowerCase() + "_spawner"), + for(EntityInfo egg : EntityRegistry.SPAWN_EGGS.values()) { + REGISTRY.putObject(ItemRegistry.getRegisteredItem(egg.id().toLowerCase() + "_spawner"), disp); } REGISTRY.putObject(Items.fireworks, new BehaviorDefaultDispenseItem() @@ -204,16 +205,16 @@ public abstract class DispenserRegistry { double d1 = source.getY() + (double)((float)enumfacing.getFrontOffsetY() * 1.125F); double d2 = source.getZ() + (double)((float)enumfacing.getFrontOffsetZ() * 1.125F); BlockPos blockpos = source.getBlockPos().offset(enumfacing); - Material material = world.getState(blockpos).getBlock().getMaterial(); + Block block = world.getState(blockpos).getBlock(); double d3; - if (material.isColdLiquid()) + if (block.getMaterial().isColdLiquid()) { d3 = 1.0D; } else { - if (!Material.air.equals(material) || !world.getState(blockpos.down()).getBlock().getMaterial().isColdLiquid()) + if (block != Blocks.air || !world.getState(blockpos.down()).getBlock().getMaterial().isColdLiquid()) { return this.field_150842_b.dispense(source, stack); } @@ -242,7 +243,7 @@ public abstract class DispenserRegistry { if (itembucket.tryPlaceContainedLiquid(source.getWorld(), blockpos)) { stack.setItem(Items.bucket); - stack.stackSize = 1; + stack.size = 1; return stack; } else @@ -255,7 +256,7 @@ public abstract class DispenserRegistry { // REGISTRY.putObject(Items.water_bucket, ibehaviordispenseitem); // REGISTRY.putObject(Items.fluid_bucket, ibehaviordispenseitem); for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { - REGISTRY.putObject(ItemRegistry.getRegisteredItem(BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)) + + REGISTRY.putObject(ItemRegistry.getRegisteredItem(BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)) + "_bucket"), ibehaviordispenseitem); } REGISTRY.putObject(Items.bucket, new BehaviorDefaultDispenseItem() @@ -282,7 +283,7 @@ public abstract class DispenserRegistry { // else if (material.isLiquid() && block instanceof BlockLiquid && ((Integer)iblockstate.getValue(BlockLiquid.LEVEL)).intValue() == 0) { - item = ItemRegistry.getRegisteredItem(BlockRegistry.REGISTRY.getNameForObject(block instanceof BlockDynamicLiquid + item = ItemRegistry.getRegisteredItem(BlockRegistry.getNameFromBlock(block instanceof BlockDynamicLiquid ? FluidRegistry.getStaticBlock((BlockDynamicLiquid)block) : block) + "_bucket"); // Items.fluid_bucket; // meta = FluidRegistry.getFluidMeta((BlockLiquid)iblockstate.getBlock()); @@ -299,10 +300,10 @@ public abstract class DispenserRegistry { world.setBlockToAir(blockpos); - if (--stack.stackSize == 0) + if (--stack.size == 0) { stack.setItem(item); - stack.stackSize = 1; + stack.size = 1; } else if (((TileEntityDispenser)source.getBlockTileEntity()).addItemStack(new ItemStack(item)) < 0) { @@ -326,7 +327,7 @@ public abstract class DispenserRegistry { if (stack.attemptDamageItem(1, world.rand)) { - stack.stackSize = 0; + stack.size = 0; } } else if (world.getState(blockpos).getBlock() == Blocks.tnt) @@ -403,112 +404,9 @@ public abstract class DispenserRegistry { EntityTnt entitytntprimed = new EntityTnt(world, (double)blockpos.getX() + 0.5D, (double)blockpos.getY(), (double)blockpos.getZ() + 0.5D, (EntityLiving)null, stack.getMetadata()); world.spawnEntityInWorld(entitytntprimed); world.playSoundAtEntity(entitytntprimed, SoundEvent.FUSE, 1.0F); - --stack.stackSize; + --stack.size; return stack; } }); -// REGISTRY.putObject(Items.skull, new BehaviorDefaultDispenseItem() -// { -// private boolean field_179240_b = true; -// protected ItemStack dispenseStack(IBlockSource source, ItemStack stack) -// { -// World world = source.getWorld(); -// EnumFacing enumfacing = BlockDispenser.getFacing(source.getBlockMetadata()); -// BlockPos blockpos = source.getBlockPos().offset(enumfacing); -// BlockSkull blockskull = Blocks.skull; -// -// if (world.isAirBlock(blockpos) && blockskull.canDispenserPlace(world, blockpos, stack)) -// { -// if (!world.client) -// { -// world.setBlockState(blockpos, blockskull.getDefaultState().withProperty(BlockSkull.FACING, EnumFacing.UP), 3); -// TileEntity tileentity = world.getTileEntity(blockpos); -// -// if (tileentity instanceof TileEntitySkull) -// { -// if (stack.getMetadata() == 3) -// { -// String user = null; -// -// if (stack.hasTagCompound()) -// { -// NBTTagCompound nbttagcompound = stack.getTagCompound(); -// -// if (nbttagcompound.hasKey("SkullOwner", 8) && nbttagcompound.getString("SkullOwner").length() > 0) -// { -// user = nbttagcompound.getString("SkullOwner"); -// } -// } -// -// ((TileEntitySkull)tileentity).setUser(user); -// } -// else -// { -// ((TileEntitySkull)tileentity).setType(stack.getMetadata()); -// } -// -// ((TileEntitySkull)tileentity).setSkullRotation(enumfacing.getOpposite().getHorizontalIndex() * 4); -//// Blocks.skull.checkWitherSpawn(world, blockpos, (TileEntitySkull)tileentity); -// } -// -// --stack.stackSize; -// } -// } -// else -// { -// this.field_179240_b = false; -// } -// -// return stack; -// } -// protected void playDispenseSound(IBlockSource source) -// { -// if (this.field_179240_b) -// { -// source.getWorld().playAuxSFX(1000, source.getBlockPos(), 0); -// } -// else -// { -// source.getWorld().playAuxSFX(1001, source.getBlockPos(), 0); -// } -// } -// }); -// REGISTRY.putObject(ItemRegistry.getItemFromBlock(Blocks.pumpkin), new BehaviorDefaultDispenseItem() -// { -// private boolean field_179241_b = true; -// protected ItemStack dispenseStack(IBlockSource source, ItemStack stack) -// { -// World world = source.getWorld(); -// BlockPos blockpos = source.getBlockPos().offset(BlockDispenser.getFacing(source.getBlockMetadata())); -// BlockPumpkin blockpumpkin = (BlockPumpkin)Blocks.pumpkin; -// -// if (world.isAirBlock(blockpos) && blockpumpkin.canDispenserPlace(world, blockpos)) -// { -// if (!world.client) -// { -// world.setBlockState(blockpos, blockpumpkin.getDefaultState(), 3); -// } -// -// --stack.stackSize; -// } -// else -// { -// this.field_179241_b = false; -// } -// -// return stack; -// } -// protected void playDispenseSound(IBlockSource source) -// { -// if (this.field_179241_b) -// { -// source.getWorld().playAuxSFX(1000, source.getBlockPos(), 0); -// } -// else -// { -// source.getWorld().playAuxSFX(1001, source.getBlockPos(), 0); -// } -// } -// }); } } diff --git a/common/src/main/java/common/init/EntityInfo.java b/common/src/main/java/common/init/EntityInfo.java new file mode 100755 index 0000000..6ea464e --- /dev/null +++ b/common/src/main/java/common/init/EntityInfo.java @@ -0,0 +1,4 @@ +package common.init; + +public record EntityInfo(String id, String origin, int color1, int color2) { +} diff --git a/java/src/game/init/EntityRegistry.java b/common/src/main/java/common/init/EntityRegistry.java similarity index 53% rename from java/src/game/init/EntityRegistry.java rename to common/src/main/java/common/init/EntityRegistry.java index d43d4d4..e0c9b95 100755 --- a/java/src/game/init/EntityRegistry.java +++ b/common/src/main/java/common/init/EntityRegistry.java @@ -1,112 +1,57 @@ -package game.init; +package common.init; import java.util.Map; import java.util.Set; -import game.collect.Maps; - -import game.entity.Entity; -import game.entity.animal.EntityBat; -import game.entity.animal.EntityChicken; -import game.entity.animal.EntityCow; -import game.entity.animal.EntityDragon; -import game.entity.animal.EntityHorse; -import game.entity.animal.EntityMooshroom; -import game.entity.animal.EntityMouse; -import game.entity.animal.EntityOcelot; -import game.entity.animal.EntityPig; -import game.entity.animal.EntityRabbit; -import game.entity.animal.EntitySheep; -import game.entity.animal.EntitySquid; -import game.entity.animal.EntityWolf; -import game.entity.effect.EntityLightning; -import game.entity.item.EntityBoat; -import game.entity.item.EntityCart; -import game.entity.item.EntityChestCart; -import game.entity.item.EntityCrystal; -import game.entity.item.EntityExplosion; -import game.entity.item.EntityFalling; -import game.entity.item.EntityFireworks; -import game.entity.item.EntityHopperCart; -import game.entity.item.EntityItem; -import game.entity.item.EntityLeashKnot; -import game.entity.item.EntityMinecart; -import game.entity.item.EntityNuke; -import game.entity.item.EntityOrb; -import game.entity.item.EntityTnt; -import game.entity.item.EntityTntCart; -import game.entity.item.EntityXp; -import game.entity.item.EntityXpBottle; -import game.entity.npc.SpeciesInfo; -import game.entity.projectile.EntityArrow; -import game.entity.projectile.EntityBox; -import game.entity.projectile.EntityBullet; -import game.entity.projectile.EntityDie; -import game.entity.projectile.EntityDynamite; -import game.entity.projectile.EntityEgg; -import game.entity.projectile.EntityFireCharge; -import game.entity.projectile.EntityFireball; -import game.entity.projectile.EntityHook; -import game.entity.projectile.EntityPotion; -import game.entity.projectile.EntitySnowball; -import game.entity.types.EntityLiving; -import game.entity.types.IObjectData; -import game.init.SpeciesRegistry.ModelType; -import game.log.Log; -import game.nbt.NBTTagCompound; -import game.renderer.entity.Render; -import game.renderer.entity.RenderArachnoid; -import game.renderer.entity.RenderArrow; -import game.renderer.entity.RenderBat; -import game.renderer.entity.RenderBlockEntity; -import game.renderer.entity.RenderBoat; -import game.renderer.entity.RenderBullet; -import game.renderer.entity.RenderChicken; -import game.renderer.entity.RenderCow; -import game.renderer.entity.RenderCrystal; -import game.renderer.entity.RenderDie; -import game.renderer.entity.RenderDragon; -import game.renderer.entity.RenderDynamite; -import game.renderer.entity.RenderEntity; -import game.renderer.entity.RenderEntityItem; -import game.renderer.entity.RenderFallingBlock; -import game.renderer.entity.RenderFireball; -import game.renderer.entity.RenderFish; -import game.renderer.entity.RenderFlyingBox; -import game.renderer.entity.RenderHorse; -import game.renderer.entity.RenderHumanoid; -import game.renderer.entity.RenderItem; -import game.renderer.entity.RenderItemEntity; -import game.renderer.entity.RenderLeashKnot; -import game.renderer.entity.RenderLightning; -import game.renderer.entity.RenderManager; -import game.renderer.entity.RenderMinecart; -import game.renderer.entity.RenderMooshroom; -import game.renderer.entity.RenderMouse; -import game.renderer.entity.RenderNpc; -import game.renderer.entity.RenderOcelot; -import game.renderer.entity.RenderPig; -import game.renderer.entity.RenderPotion; -import game.renderer.entity.RenderRabbit; -import game.renderer.entity.RenderSheep; -import game.renderer.entity.RenderSlime; -import game.renderer.entity.RenderSpaceMarine; -import game.renderer.entity.RenderSquid; -import game.renderer.entity.RenderTntMinecart; -import game.renderer.entity.RenderTntPrimed; -import game.renderer.entity.RenderWolf; -import game.renderer.entity.RenderXpOrb; -import game.renderer.model.ModelChicken; -import game.renderer.model.ModelCow; -import game.renderer.model.ModelHorse; -import game.renderer.model.ModelMouse; -import game.renderer.model.ModelOcelot; -import game.renderer.model.ModelPig; -import game.renderer.model.ModelRabbit; -import game.renderer.model.ModelSheep2; -import game.renderer.model.ModelSquid; -import game.renderer.model.ModelWolf; -import game.world.World; +import common.collect.Maps; +import common.entity.Entity; +import common.entity.animal.EntityBat; +import common.entity.animal.EntityChicken; +import common.entity.animal.EntityCow; +import common.entity.animal.EntityDragon; +import common.entity.animal.EntityFox; +import common.entity.animal.EntityHorse; +import common.entity.animal.EntityMooshroom; +import common.entity.animal.EntityMouse; +import common.entity.animal.EntityOcelot; +import common.entity.animal.EntityPig; +import common.entity.animal.EntityRabbit; +import common.entity.animal.EntitySheep; +import common.entity.animal.EntitySquid; +import common.entity.animal.EntityWolf; +import common.entity.item.EntityBoat; +import common.entity.item.EntityChestCart; +import common.entity.item.EntityCrystal; +import common.entity.item.EntityExplosion; +import common.entity.item.EntityFalling; +import common.entity.item.EntityFireworks; +import common.entity.item.EntityHopperCart; +import common.entity.item.EntityItem; +import common.entity.item.EntityLeashKnot; +import common.entity.item.EntityMinecart; +import common.entity.item.EntityNuke; +import common.entity.item.EntityOrb; +import common.entity.item.EntityTnt; +import common.entity.item.EntityTntCart; +import common.entity.item.EntityXp; +import common.entity.item.EntityXpBottle; +import common.entity.npc.SpeciesInfo; +import common.entity.projectile.EntityArrow; +import common.entity.projectile.EntityBox; +import common.entity.projectile.EntityBullet; +import common.entity.projectile.EntityDie; +import common.entity.projectile.EntityDynamite; +import common.entity.projectile.EntityEgg; +import common.entity.projectile.EntityFireCharge; +import common.entity.projectile.EntityFireball; +import common.entity.projectile.EntityHook; +import common.entity.projectile.EntityPotion; +import common.entity.projectile.EntitySnowball; +import common.entity.types.EntityLiving; +import common.entity.types.IObjectData; +import common.log.Log; +import common.tags.TagObject; +import common.world.World; public abstract class EntityRegistry { private static final Map> STRING_TO_CLASS = Maps.>newHashMap(); @@ -114,7 +59,7 @@ public abstract class EntityRegistry { private static final Map> ID_TO_CLASS = Maps.>newHashMap(); private static final Map, Integer> CLASS_TO_ID = Maps., Integer>newHashMap(); // private static final Map STRING_TO_ID = Maps.newHashMap(); - public static final Map SPAWN_EGGS = Maps.newLinkedHashMap(); + public static final Map SPAWN_EGGS = Maps.newLinkedHashMap(); private static final Map STRING_TO_NAME = Maps.newHashMap(); private static boolean register; @@ -145,7 +90,7 @@ public abstract class EntityRegistry { } else { // String name = clazz.getSimpleName().substring(6); - SPAWN_EGGS.put(name, new EntityEggInfo(name, origin, eggColor, spotColor)); + SPAWN_EGGS.put(name, new EntityInfo(name, origin, eggColor, spotColor)); } } @@ -173,19 +118,14 @@ public abstract class EntityRegistry { return entity; } - public static Entity createEntityFromNBT(NBTTagCompound nbt, World worldIn) { + public static Entity createFromTags(TagObject tag, World world) { Entity entity = null; -// if("Minecart".equals(nbt.getString("id"))) { -// nbt.setString("id", EntityMinecart.EnumMinecartType.byNetworkID(nbt.getInteger("Type")).getName()); -// nbt.removeTag("Type"); -// } - try { - Class oclass = (Class)STRING_TO_CLASS.get(nbt.getString("id")); + Class oclass = (Class)STRING_TO_CLASS.get(tag.getString("id")); if(oclass != null) { - entity = (Entity)oclass.getConstructor(World.class).newInstance(worldIn); + entity = (Entity)oclass.getConstructor(World.class).newInstance(world); } } catch(Exception exception) { @@ -193,10 +133,10 @@ public abstract class EntityRegistry { } if(entity != null) { - entity.readFromNBT(nbt); + entity.readTags(tag); } else { - Log.JNI.warn("Ignoriere Objekt mit Name " + nbt.getString("id")); + Log.TICK.warn("Ignoriere Objekt mit Name " + tag.getString("id")); } return entity; @@ -217,7 +157,7 @@ public abstract class EntityRegistry { } if(entity == null) { - Log.JNI.warn("Ignoriere Objekt mit ID " + entityID); + Log.TICK.warn("Ignoriere Objekt mit ID " + entityID); } return entity; @@ -251,7 +191,7 @@ public abstract class EntityRegistry { } if(entity == null) { - Log.JNI.warn("Ignoriere Objekt mit ID " + entityID); + Log.TICK.warn("Ignoriere Objekt mit ID " + entityID); } return entity; @@ -323,6 +263,7 @@ public abstract class EntityRegistry { registerEntity("Horse", EntityHorse.class, "terra", "Pferd", 12623485, 15656192); registerEntity("Rabbit", EntityRabbit.class, "terra", "Kaninchen", 10051392, 7555121); registerEntity("Mouse", EntityMouse.class, "terra", "Maus", 0x606060, 0xb0b0b0); + registerEntity("Fox", EntityFox.class, "terra", "Fuchs", 0xae5300, 0x622f00); for(int z = 0; z < SpeciesRegistry.SPECIMEN.size(); z++) { SpeciesInfo info = SpeciesRegistry.SPECIMEN.get(z); @@ -385,59 +326,4 @@ public abstract class EntityRegistry { // } registerEggs(); } - - public static void registerRenderers(Map, Render> map, - Map models, RenderManager mgr, RenderItem ritem) { - map.put(EntityPig.class, new RenderPig(mgr, new ModelPig())); - map.put(EntitySheep.class, new RenderSheep(mgr, new ModelSheep2())); - map.put(EntityCow.class, new RenderCow(mgr, new ModelCow())); - map.put(EntityMooshroom.class, new RenderMooshroom(mgr, new ModelCow())); - map.put(EntityWolf.class, new RenderWolf(mgr, new ModelWolf())); - map.put(EntityChicken.class, new RenderChicken(mgr, new ModelChicken())); - map.put(EntityOcelot.class, new RenderOcelot(mgr, new ModelOcelot())); - map.put(EntityRabbit.class, new RenderRabbit(mgr, new ModelRabbit())); - map.put(EntitySquid.class, new RenderSquid(mgr, new ModelSquid())); - map.put(EntityBat.class, new RenderBat(mgr)); - map.put(EntityDragon.class, new RenderDragon(mgr)); - map.put(EntityCrystal.class, new RenderCrystal(mgr)); - map.put(Entity.class, new RenderEntity(mgr)); -// map.put(EntityPainting.class, new RenderPainting(mgr)); -// map.put(EntityFrame.class, new RenderItemFrame(mgr, ritem)); - map.put(EntityLeashKnot.class, new RenderLeashKnot(mgr)); - map.put(EntityArrow.class, new RenderArrow(mgr)); - map.put(EntitySnowball.class, new RenderItemEntity(mgr, Items.snowball, ritem)); - map.put(EntityOrb.class, new RenderItemEntity(mgr, Items.charged_orb, ritem)); - map.put(EntityEgg.class, new RenderItemEntity(mgr, Items.egg, ritem)); - map.put(EntityPotion.class, new RenderPotion(mgr, ritem)); - map.put(EntityXpBottle.class, new RenderItemEntity(mgr, Items.experience_bottle, ritem)); - map.put(EntityFireworks.class, new RenderItemEntity(mgr, Items.fireworks, ritem)); - map.put(EntityFireball.class, new RenderFireball(mgr, 0.75F)); - map.put(EntityFireCharge.class, new RenderFireball(mgr, 0.5F)); - map.put(EntityBox.class, new RenderFlyingBox(mgr)); - map.put(EntityItem.class, new RenderEntityItem(mgr, ritem)); - map.put(EntityXp.class, new RenderXpOrb(mgr)); - map.put(EntityTnt.class, new RenderTntPrimed(mgr)); - map.put(EntityFalling.class, new RenderFallingBlock(mgr)); - map.put(EntityTntCart.class, new RenderTntMinecart(mgr)); - map.put(EntityCart.class, new RenderMinecart(mgr)); - map.put(EntityBoat.class, new RenderBoat(mgr)); - map.put(EntityHook.class, new RenderFish(mgr)); - map.put(EntityHorse.class, new RenderHorse(mgr, new ModelHorse())); - map.put(EntityDynamite.class, new RenderDynamite(mgr, Items.dynamite, ritem)); - map.put(EntityNuke.class, new RenderBlockEntity(mgr, Blocks.nuke.getState())); - map.put(EntityMouse.class, new RenderMouse(mgr, new ModelMouse())); - map.put(EntityDie.class, new RenderDie(mgr)); - map.put(EntityBullet.class, new RenderBullet(mgr)); - map.put(EntityLightning.class, new RenderLightning(mgr)); - models.put(ModelType.HUMANOID, new RenderHumanoid(mgr, 12, 12, "textures/entity/char.png")); - models.put(ModelType.ARACHNOID, new RenderArachnoid(mgr)); - models.put(ModelType.SLIME, new RenderSlime(mgr)); - models.put(ModelType.DWARF, new RenderHumanoid(mgr, 10, 10, "textures/entity/dwarf.png")); - models.put(ModelType.HALFLING, new RenderHumanoid(mgr, 8, 8, "textures/entity/goblin.png")); - models.put(ModelType.SPACE_MARINE, new RenderSpaceMarine(mgr)); - for(int z = 0; z < SpeciesRegistry.SPECIMEN.size(); z++) { - SpeciesInfo info = SpeciesRegistry.SPECIMEN.get(z); - map.put(info.clazz, models.get(info.renderer)); - } - } } diff --git a/common/src/main/java/common/init/FlammabilityRegistry.java b/common/src/main/java/common/init/FlammabilityRegistry.java new file mode 100755 index 0000000..0d0a632 --- /dev/null +++ b/common/src/main/java/common/init/FlammabilityRegistry.java @@ -0,0 +1,51 @@ +package common.init; + +import java.util.Map; + +import common.block.Block; +import common.collect.Maps; + +public abstract class FlammabilityRegistry { + private static final Map ENCOURAGEMENT = Maps.newIdentityHashMap(); + private static final Map FLAMMABILITY = Maps.newIdentityHashMap(); + + private static void setFlammable(Block block, int encouragement, int flammability) { + ENCOURAGEMENT.put(block, encouragement); + FLAMMABILITY.put(block, flammability); + } + + static void register() { + for(WoodType wood : WoodType.values()) { + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_planks"), 5, 20); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_slab"), 5, 20); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_stairs"), 5, 20); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_fence"), 5, 20); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_fence_gate"), 5, 20); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_log"), 5, 5); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_leaves"), 30, 60); + setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_sapling"), 15, 100); + } + setFlammable(Blocks.bookshelf, 30, 20); + setFlammable(Blocks.tnt, 15, 100); + setFlammable(Blocks.tallgrass, 60, 100); + setFlammable(Blocks.double_plant, 60, 100); + setFlammable(Blocks.flower, 60, 100); + setFlammable(Blocks.deadbush, 60, 100); + setFlammable(Blocks.dry_leaves, 60, 100); + setFlammable(Blocks.wool, 30, 60); + setFlammable(Blocks.vine, 15, 100); + setFlammable(Blocks.coal_block, 5, 5); + setFlammable(Blocks.hay_block, 60, 20); + setFlammable(Blocks.carpet, 60, 20); + } + + public static int getFlammability(Block block) { + Integer value = FLAMMABILITY.get(block); + return value == null ? 0 : value.intValue(); + } + + public static int getEncouragement(Block block) { + Integer value = ENCOURAGEMENT.get(block); + return value == null ? 0 : value.intValue(); + } +} diff --git a/java/src/game/init/FluidRegistry.java b/common/src/main/java/common/init/FluidRegistry.java similarity index 85% rename from java/src/game/init/FluidRegistry.java rename to common/src/main/java/common/init/FluidRegistry.java index 429adcf..ad5b6ac 100755 --- a/java/src/game/init/FluidRegistry.java +++ b/common/src/main/java/common/init/FluidRegistry.java @@ -1,20 +1,19 @@ -package game.init; +package common.init; import java.util.List; import java.util.Map; -import game.collect.Lists; -import game.collect.Maps; - -import game.block.Block; -import game.block.BlockDynamicLiquid; -import game.block.BlockLiquid; -import game.block.BlockStaticLiquid; -import game.material.Material; +import common.block.Block; +import common.block.Material; +import common.block.liquid.BlockDynamicLiquid; +import common.block.liquid.BlockLiquid; +import common.block.liquid.BlockStaticLiquid; +import common.collect.Lists; +import common.collect.Maps; public abstract class FluidRegistry { public static enum LiquidType { - COLD(Material.coldFluid), HOT(Material.hotFluid), WATER(Material.water), LAVA(Material.lava); + COLD(Material.COLD), HOT(Material.HOT), WATER(Material.WATER), LAVA(Material.LAVA); public final Material material; diff --git a/java/src/game/init/ItemRegistry.java b/common/src/main/java/common/init/ItemRegistry.java similarity index 75% rename from java/src/game/init/ItemRegistry.java rename to common/src/main/java/common/init/ItemRegistry.java index 27b52e3..83b991e 100755 --- a/java/src/game/init/ItemRegistry.java +++ b/common/src/main/java/common/init/ItemRegistry.java @@ -1,130 +1,130 @@ -package game.init; +package common.init; import java.util.Map; import java.util.Set; import java.util.function.Function; -import game.collect.Maps; -import game.collect.Sets; - -import game.block.Block; -import game.block.BlockBed; -import game.block.BlockButton; -import game.block.BlockDirt; -import game.block.BlockDoor; -import game.block.BlockDoublePlant; -import game.block.BlockFence; -import game.block.BlockFlower; -import game.block.BlockLeaves; -import game.block.BlockOre; -import game.block.BlockSand; -import game.block.BlockSandStone; -import game.block.BlockSapling; -import game.block.BlockSlab; -import game.block.BlockStoneBrick; -import game.block.BlockWall; -import game.color.DyeColor; -import game.color.TextColor; -import game.entity.item.EntityCart; -import game.entity.npc.CharacterInfo; -import game.entity.npc.SpeciesInfo; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemAmmo; -import game.item.ItemAnvilBlock; -import game.item.ItemAppleGold; -import game.item.ItemArmor; -import game.item.ItemAxe; -import game.item.ItemBanHammer; -import game.item.ItemBanner; -import game.item.ItemBed; -import game.item.ItemBlock; -import game.item.ItemBoat; -import game.item.ItemBoltgun; -import game.item.ItemBook; -import game.item.ItemBow; -import game.item.ItemBucket; -import game.item.ItemBucketMilk; -import game.item.ItemButton; -import game.item.ItemCamera; -import game.item.ItemCarrotOnAStick; -import game.item.ItemChargedOrb; -import game.item.ItemChest; -import game.item.ItemCloth; -import game.item.ItemCoal; -import game.item.ItemColored; -import game.item.ItemDie; -import game.item.ItemDispenser; -import game.item.ItemDoor; -import game.item.ItemDoublePlant; -import game.item.ItemDye; -import game.item.ItemDynamite; -import game.item.ItemEditWand; -import game.item.ItemEffect; -import game.item.ItemEgg; -import game.item.ItemEnchantedBook; -import game.item.ItemExpBottle; -import game.item.ItemExterminator; -import game.item.ItemFence; -import game.item.ItemFireball; -import game.item.ItemFirework; -import game.item.ItemFireworkCharge; -import game.item.ItemFishFood; -import game.item.ItemFishingRod; -import game.item.ItemFlintAndSteel; -import game.item.ItemFood; -import game.item.ItemFragile; -import game.item.ItemGlassBottle; -import game.item.ItemHoe; -import game.item.ItemHorseArmor; -import game.item.ItemHugeMushroom; -import game.item.ItemInfoWand; -import game.item.ItemKey; -import game.item.ItemLead; -import game.item.ItemLeaves; -import game.item.ItemLightning; -import game.item.ItemLilyPad; -import game.item.ItemMagnet; -import game.item.ItemMagnetic; -import game.item.ItemMetal; -import game.item.ItemMetalBlock; -import game.item.ItemMinecart; -import game.item.ItemMonsterPlacer; -import game.item.ItemMultiTexture; -import game.item.ItemNameTag; -import game.item.ItemNpcSpawner; -import game.item.ItemNugget; -import game.item.ItemPickaxe; -import game.item.ItemPiston; -import game.item.ItemPotion; -import game.item.ItemPressurePlate; -import game.item.ItemRecord; -import game.item.ItemRedstone; -import game.item.ItemReed; -import game.item.ItemRod; -import game.item.ItemSaddle; -import game.item.ItemSeedFood; -import game.item.ItemSeeds; -import game.item.ItemShears; -import game.item.ItemSign; -import game.item.ItemSkull; -import game.item.ItemSlab; -import game.item.ItemSmall; -import game.item.ItemSnow; -import game.item.ItemSnowball; -import game.item.ItemSoup; -import game.item.ItemSpaceNavigator; -import game.item.ItemSpade; -import game.item.ItemStack; -import game.item.ItemStick; -import game.item.ItemSword; -import game.item.ItemTNT; -import game.item.ItemTiny; -import game.item.ItemWall; -import game.item.ItemWeatherToken; -import game.potion.Potion; -import game.potion.PotionHelper; -import game.world.Weather; +import common.attributes.UsageSlot; +import common.block.Block; +import common.block.artificial.BlockBed; +import common.block.artificial.BlockDoor; +import common.block.artificial.BlockFence; +import common.block.artificial.BlockSlab; +import common.block.artificial.BlockStoneBrick; +import common.block.artificial.BlockWall; +import common.block.foliage.BlockDoublePlant; +import common.block.foliage.BlockFlower; +import common.block.foliage.BlockLeaves; +import common.block.foliage.BlockSapling; +import common.block.natural.BlockDirt; +import common.block.natural.BlockOre; +import common.block.natural.BlockSand; +import common.block.natural.BlockSandStone; +import common.block.tech.BlockButton; +import common.collect.Maps; +import common.collect.Sets; +import common.color.DyeColor; +import common.color.TextColor; +import common.entity.item.EntityCart; +import common.entity.npc.CharacterInfo; +import common.entity.npc.SpeciesInfo; +import common.item.CheatTab; +import common.item.Item; +import common.item.ItemAmmo; +import common.item.ItemAnvilBlock; +import common.item.ItemAppleGold; +import common.item.ItemArmor; +import common.item.ItemAxe; +import common.item.ItemBanHammer; +import common.item.ItemBanner; +import common.item.ItemBed; +import common.item.ItemBlock; +import common.item.ItemBoat; +import common.item.ItemBoltgun; +import common.item.ItemBook; +import common.item.ItemBow; +import common.item.ItemBucket; +import common.item.ItemBucketMilk; +import common.item.ItemButton; +import common.item.ItemCamera; +import common.item.ItemCarrotOnAStick; +import common.item.ItemChargedOrb; +import common.item.ItemChest; +import common.item.ItemCloth; +import common.item.ItemCoal; +import common.item.ItemColored; +import common.item.ItemDie; +import common.item.ItemDispenser; +import common.item.ItemDoor; +import common.item.ItemDoublePlant; +import common.item.ItemDye; +import common.item.ItemDynamite; +import common.item.ItemEditWand; +import common.item.ItemEffect; +import common.item.ItemEgg; +import common.item.ItemEnchantedBook; +import common.item.ItemExpBottle; +import common.item.ItemExterminator; +import common.item.ItemFence; +import common.item.ItemFireball; +import common.item.ItemFirework; +import common.item.ItemFireworkCharge; +import common.item.ItemFishFood; +import common.item.ItemFishingRod; +import common.item.ItemFlintAndSteel; +import common.item.ItemFood; +import common.item.ItemFragile; +import common.item.ItemGlassBottle; +import common.item.ItemHoe; +import common.item.ItemHorseArmor; +import common.item.ItemHugeMushroom; +import common.item.ItemInfoWand; +import common.item.ItemKey; +import common.item.ItemLead; +import common.item.ItemLeaves; +import common.item.ItemLightning; +import common.item.ItemLilyPad; +import common.item.ItemMagnet; +import common.item.ItemMagnetic; +import common.item.ItemMetal; +import common.item.ItemMetalBlock; +import common.item.ItemMinecart; +import common.item.ItemMonsterPlacer; +import common.item.ItemMultiTexture; +import common.item.ItemNameTag; +import common.item.ItemNpcSpawner; +import common.item.ItemNugget; +import common.item.ItemPickaxe; +import common.item.ItemPiston; +import common.item.ItemPotion; +import common.item.ItemPressurePlate; +import common.item.ItemRecord; +import common.item.ItemRedstone; +import common.item.ItemSmallBlock; +import common.item.ItemRod; +import common.item.ItemSaddle; +import common.item.ItemSeedFood; +import common.item.ItemSeeds; +import common.item.ItemShears; +import common.item.ItemSign; +import common.item.ItemSlab; +import common.item.ItemSmall; +import common.item.ItemSnow; +import common.item.ItemSnowball; +import common.item.ItemSoup; +import common.item.ItemSpaceNavigator; +import common.item.ItemShovel; +import common.item.ItemStack; +import common.item.ItemStick; +import common.item.ItemSword; +import common.item.ItemTNT; +import common.item.ItemTiny; +import common.item.ItemWall; +import common.item.ItemWeatherToken; +import common.potion.Potion; +import common.potion.PotionHelper; +import common.util.RegistryNamespaced; +import common.world.Weather; public abstract class ItemRegistry { public static final RegistryNamespaced REGISTRY = new RegistryNamespaced(); @@ -137,6 +137,10 @@ public abstract class ItemRegistry { return item == null ? 0 : REGISTRY.getIDForObject(item); } + public static String getNameFromItem(Item item) { + return REGISTRY.getNameForObject(item); + } + public static Item getItemById(int id) { return REGISTRY.getObjectById(id); } @@ -149,6 +153,30 @@ public abstract class ItemRegistry { return REGISTRY.getObject(name); } + public static ItemStack getFromIdName(String name, ItemStack def) { + if(name == null) + return def; + String[] tok = name.split(":"); + if(tok.length < 1 || tok.length > 2) + return def; + Item item = REGISTRY.getObject(tok[0]); + if(item == null) + return def; + short data = 0; + if(tok.length == 2) { + try { + int i = Integer.parseUnsignedInt(tok[1]); + if(i >= 32768) + return def; + data = (short)i; + } + catch(NumberFormatException e) { + return def; + } + } + return new ItemStack(item, 1, data); + } + private static ItemBlock registerFlat(Block block) { ItemBlock item = new ItemBlock(block, ""); registerBlock(block, item); @@ -162,13 +190,13 @@ public abstract class ItemRegistry { } private static void registerBlock(Block block, ItemBlock item) { - REGISTRY.register(BlockRegistry.getIdFromBlock(block), BlockRegistry.REGISTRY.getNameForObject(block), item); + REGISTRY.register(BlockRegistry.getIdFromBlock(block), BlockRegistry.getNameFromBlock(block), item); BLOCKMAP.put(block, item); } private static void registerSpecial(Block block) { if(BLOCKMAP.containsKey(block) || SPECIALIZED.contains(block)) - throw new IllegalArgumentException("Block " + BlockRegistry.REGISTRY.getNameForObject(block) + " ist bereits registriert"); + throw new IllegalArgumentException("Block " + BlockRegistry.getNameFromBlock(block) + " ist bereits registriert"); SPECIALIZED.add(block); } @@ -182,13 +210,13 @@ public abstract class ItemRegistry { if(item.getBlock() == null) throw new IllegalArgumentException("Unbenanntes Item benötigt einen Block"); registerSpecial(item.getBlock()); - REGISTRY.register(BlockRegistry.getIdFromBlock(item.getBlock()), BlockRegistry.REGISTRY.getNameForObject(item.getBlock()), item); + REGISTRY.register(BlockRegistry.getIdFromBlock(item.getBlock()), BlockRegistry.getNameFromBlock(item.getBlock()), item); } private static void registerTools(ToolMaterial material, String name, String prefix) { // String loc = name.substring(0, 1).toUpperCase() + name.substring(1); if(material.hasTools()) { - registerItem(name + "_shovel", (new ItemSpade(material)).setDisplay(prefix + "schaufel")); + registerItem(name + "_shovel", (new ItemShovel(material)).setDisplay(prefix + "schaufel")); registerItem(name + "_pickaxe", (new ItemPickaxe(material)).setDisplay(prefix + "spitzhacke")); registerItem(name + "_axe", (new ItemAxe(material)).setDisplay(prefix + "axt")); registerItem(name + "_hoe", (new ItemHoe(material)).setDisplay(prefix + "hacke")); @@ -201,10 +229,10 @@ public abstract class ItemRegistry { registerItem(name + "_sword", (new ItemSword(material)).setDisplay(prefix + "schwert")); } if(material.hasArmor()) { - registerItem(name + "_helmet", (new ItemArmor(material, name, 0)).setDisplay(prefix == null ? "Kappe" : prefix + "helm")); - registerItem(name + "_chestplate", (new ItemArmor(material, name, 1)).setDisplay(prefix == null ? "Jacke" : prefix + "brustpanzer")); - registerItem(name + "_leggings", (new ItemArmor(material, name, 2)).setDisplay(prefix == null ? "Hose" : prefix + "beinschutz")); - registerItem(name + "_boots", (new ItemArmor(material, name, 3)).setDisplay(prefix == null ? "Stiefel" : prefix + "stiefel")); + registerItem(name + "_helmet", (new ItemArmor(material, name, UsageSlot.HEAD)).setDisplay(prefix == null ? "Kappe" : prefix + "helm")); + registerItem(name + "_chestplate", (new ItemArmor(material, name, UsageSlot.BODY)).setDisplay(prefix == null ? "Jacke" : prefix + "brustpanzer")); + registerItem(name + "_leggings", (new ItemArmor(material, name, UsageSlot.LEGS)).setDisplay(prefix == null ? "Hose" : prefix + "beinschutz")); + registerItem(name + "_boots", (new ItemArmor(material, name, UsageSlot.FEET)).setDisplay(prefix == null ? "Stiefel" : prefix + "stiefel")); } } @@ -333,7 +361,7 @@ public abstract class ItemRegistry { })).setDisplay("Felsen")); for(BlockLeaves leaves : BlockLeaves.LEAVES) { - registerBlock(leaves, new ItemLeaves(leaves)); // .setDisplay(BlockRegistry.REGISTRY.getNameForObject(leaves))); + registerBlock(leaves, new ItemLeaves(leaves)); // .setDisplay(BlockRegistry.getNameFromBlock(leaves))); } for(BlockSlab slab : BlockSlab.SLABS) { registerBlock(slab, new ItemSlab(slab)); @@ -352,13 +380,13 @@ public abstract class ItemRegistry { Item bucket = (new ItemBucket(null, false)).setDisplay("Eimer"); registerItem("bucket", bucket); for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { - registerItem(BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)) + + registerItem(BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)) + "_bucket", new ItemBucket(FluidRegistry.getFluidBlock(z), false).setDisplay("Eimer") .setContainerItem(bucket)); } registerItem("recursive_bucket", (new ItemBucket(null, true)).setDisplay("Unendlicher Eimer")); for(int z = 0; z < FluidRegistry.getNumFluids(); z++) { - registerItem("recursive_" + BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(z)) + + registerItem("recursive_" + BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(z)) + "_bucket", new ItemBucket(FluidRegistry.getFluidBlock(z), true).setDisplay("Flutender Eimer")); } registerItem("milk_bucket", (new ItemBucketMilk()).setDisplay("Milch").setContainerItem(bucket)); @@ -371,8 +399,8 @@ public abstract class ItemRegistry { registerItem("hopper_minecart", (new ItemMinecart(EntityCart.EnumMinecartType.HOPPER)).setDisplay("Trichterlore")); registerItem("tnt_minecart", (new ItemMinecart(EntityCart.EnumMinecartType.TNT)).setDisplay("TNT-Lore") .setColor(TextColor.RED)); - for(EntityEggInfo egg : EntityRegistry.SPAWN_EGGS.values()) { - registerItem(egg.spawnedID.toLowerCase() + "_spawner", (new ItemMonsterPlacer(egg.spawnedID)) + for(EntityInfo egg : EntityRegistry.SPAWN_EGGS.values()) { + registerItem(egg.id().toLowerCase() + "_spawner", (new ItemMonsterPlacer(egg.id())) .setDisplay("Spawner").setMaxStackSize(ItemStack.MAX_SIZE)); } for(SpeciesInfo species : SpeciesRegistry.SPECIMEN) { @@ -386,35 +414,37 @@ public abstract class ItemRegistry { registerItem("wand", (new ItemEditWand()).setDisplay("Bearbeitungswerkzeug")); registerItem("info_wand", (new ItemInfoWand()).setDisplay("Infowerkzeug")); registerItem("lightning_wand", (new ItemLightning()).setDisplay("Geladenes Zepter")); - registerItem("banhammer", (new ItemBanHammer()).setDisplay("Hammer der Verbannung").setTab(CheatTab.tabTools)); - registerItem("key", (new ItemKey()).setDisplay("Schlüssel").setTab(CheatTab.tabTools).setMaxStackSize(128)); + registerItem("banhammer", (new ItemBanHammer()).setDisplay("Hammer der Verbannung").setTab(CheatTab.TOOLS)); + registerItem("key", (new ItemKey()).setDisplay("Schlüssel").setTab(CheatTab.TOOLS).setMaxStackSize(128)); registerItem("die", (new ItemDie()).setDisplay("Würfel").setMaxStackSize(128)); registerItem("chick_magnet", (new ItemMagnet(true)).setDisplay("Kükenmagnet")); registerItem("magnet", (new ItemMagnet(false)).setDisplay("Magnet")); - registerItem("camera", (new ItemCamera()).setDisplay("Kamera").setTab(CheatTab.tabTools)); + registerItem("camera", (new ItemCamera()).setDisplay("Kamera").setTab(CheatTab.TOOLS)); for(Weather weather : Weather.values()) { - registerItem("weather_token_" + weather.getName(), new ItemWeatherToken(weather).setDisplay("Wetterkristall").setTab(CheatTab.tabTools)); + registerItem("weather_token_" + weather.getName(), new ItemWeatherToken(weather).setDisplay("Wetterkristall").setTab(CheatTab.TOOLS)); } - - registerItem("flint_and_steel", (new ItemFlintAndSteel()).setDisplay("Feuerzeug")); + + registerItem("flint_and_steel", (new ItemFlintAndSteel(Blocks.fire)).setDisplay("Feuerzeug")); + registerItem("burning_soul", (new ItemFlintAndSteel(Blocks.soul_fire)).setDisplay("Brennende Seele")); + registerItem("dark_lighter", (new ItemFlintAndSteel(Blocks.black_fire)).setDisplay("Verdunkelndes Feuerzeug")); registerItem("apple", (new ItemFood(4, false)).setDisplay("Apfel").setMaxStackSize(128)); registerItem("bow", (new ItemBow()).setDisplay("Bogen")); registerItem("boltgun", (new ItemBoltgun()).setDisplay("Bolter")); registerItem("bolt", (new ItemAmmo(5, 1.0f, 128)).setDisplay("Bolter-Munition")); - registerItem("arrow", (new Item()).setDisplay("Pfeil").setTab(CheatTab.tabCombat).setMaxStackSize(128)); + registerItem("arrow", (new Item()).setDisplay("Pfeil").setTab(CheatTab.COMBAT).setMaxStackSize(128)); Item coal = (new ItemCoal()).setDisplay("Kohle"); registerItem("coal", coal); - registerItem("stick", (new ItemStick()).setDisplay("Stock").setTab(CheatTab.tabMaterials).setMaxStackSize(256)); - registerItem("bowl", (new ItemSmall()).setDisplay("Schüssel").setTab(CheatTab.tabMisc)); + registerItem("stick", (new ItemStick()).setDisplay("Stock").setTab(CheatTab.MATERIALS).setMaxStackSize(256)); + registerItem("bowl", (new ItemSmall()).setDisplay("Schüssel").setTab(CheatTab.MISC)); registerItem("mushroom_stew", (new ItemSoup(6)).setDisplay("Pilzsuppe")); - registerItem((new ItemReed(Blocks.string)).setDisplay("Faden").setTab(CheatTab.tabTech).setMaxStackSize(1024)); - registerItem("feather", (new Item()).setDisplay("Feder").setTab(CheatTab.tabMaterials).setMaxStackSize(512)); - registerItem("gunpowder", (new Item()).setDisplay("Schwarzpulver").setPotionEffect(PotionHelper.gunpowderEffect).setTab(CheatTab.tabMaterials).setMaxStackSize(256)); + registerItem((new ItemSmallBlock(Blocks.string)).setDisplay("Faden").setTab(CheatTab.TECHNOLOGY).setMaxStackSize(1024)); + registerItem("feather", (new Item()).setDisplay("Feder").setTab(CheatTab.MATERIALS).setMaxStackSize(512)); + registerItem("gunpowder", (new Item()).setDisplay("Schwarzpulver").setPotionEffect(PotionHelper.gunpowderEffect).setTab(CheatTab.MATERIALS).setMaxStackSize(256)); registerItem((new ItemSeeds(Blocks.wheat, Blocks.farmland)).setDisplay("Weizenkörner").setMaxStackSize(256)); - registerItem("wheats", (new Item()).setDisplay("Weizen").setTab(CheatTab.tabMaterials).setMaxStackSize(128)); + registerItem("wheats", (new Item()).setDisplay("Weizen").setTab(CheatTab.MATERIALS).setMaxStackSize(128)); registerItem("bread", (new ItemFood(5, false)).setDisplay("Brot")); - registerItem("flint", (new Item()).setDisplay("Feuerstein").setTab(CheatTab.tabMaterials).setMaxStackSize(128)); + registerItem("flint", (new Item()).setDisplay("Feuerstein").setTab(CheatTab.MATERIALS).setMaxStackSize(128)); registerItem("porkchop", (new ItemFood(3, true)).setDisplay("Rohes Schweinefleisch")); registerItem("cooked_porkchop", (new ItemFood(8, true)).setDisplay("Gebratenes Schweinefleisch")); registerItem("golden_apple", (new ItemAppleGold(4, false)).setPotionEffect(Potion.REGENERATION, 5, 1, 1.0F) @@ -427,27 +457,27 @@ public abstract class ItemRegistry { // registerItem("iron_door", (new ItemDoor(Blocks.iron_door)).setUnlocalizedName("doorIron")); registerItem((new ItemRedstone()).setDisplay("Redstone").setPotionEffect(PotionHelper.redstoneEffect).setMaxStackSize(256)); registerItem("snowball", (new ItemSnowball()).setDisplay("Schneeball").setMaxStackSize(128)); - registerItem("leather", (new Item()).setDisplay("Leder").setTab(CheatTab.tabMaterials)); - registerItem("brick", (new Item()).setDisplay("Ziegel").setTab(CheatTab.tabMaterials)); - registerItem("clay_ball", (new Item()).setDisplay("Ton").setTab(CheatTab.tabMaterials).setMaxStackSize(128)); - registerItem((new ItemReed(Blocks.reeds)).setDisplay("Zuckerrohr").setTab(CheatTab.tabPlants).setMaxStackSize(128)); - registerItem("paper", (new Item()).setDisplay("Papier").setTab(CheatTab.tabMaterials).setMaxStackSize(256)); - registerItem("book", (new ItemBook()).setDisplay("Buch").setTab(CheatTab.tabMisc)); - registerItem("slime_ball", (new Item()).setDisplay("Schleimball").setTab(CheatTab.tabMaterials).setMaxStackSize(128)); + registerItem("leather", (new Item()).setDisplay("Leder").setTab(CheatTab.MATERIALS)); + registerItem("brick", (new Item()).setDisplay("Ziegel").setTab(CheatTab.MATERIALS)); + registerItem("clay_ball", (new Item()).setDisplay("Ton").setTab(CheatTab.MATERIALS).setMaxStackSize(128)); + registerItem((new ItemSmallBlock(Blocks.reeds)).setDisplay("Zuckerrohr").setTab(CheatTab.PLANTS).setMaxStackSize(128)); + registerItem("paper", (new Item()).setDisplay("Papier").setTab(CheatTab.MATERIALS).setMaxStackSize(256)); + registerItem("book", (new ItemBook()).setDisplay("Buch").setTab(CheatTab.MISC)); + registerItem("slime_ball", (new Item()).setDisplay("Schleimball").setTab(CheatTab.MATERIALS).setMaxStackSize(128)); registerItem("egg", (new ItemEgg()).setDisplay("Ei").setMaxStackSize(128)); - registerItem("navigator", (new ItemSpaceNavigator()).setDisplay("Elektronischer Navigator").setTab(CheatTab.tabTools)); - registerItem("exterminator", (new ItemExterminator()).setDisplay("Weltenzerstörer").setTab(CheatTab.tabTools)); + registerItem("navigator", (new ItemSpaceNavigator()).setDisplay("Elektronischer Navigator").setTab(CheatTab.TOOLS)); + registerItem("exterminator", (new ItemExterminator()).setDisplay("Weltenzerstörer").setTab(CheatTab.TOOLS)); registerItem("fishing_rod", (new ItemFishingRod()).setDisplay("Angel")); registerItem("glowstone_dust", (new Item()).setDisplay("Glowstonestaub").setPotionEffect(PotionHelper.glowstoneEffect) - .setTab(CheatTab.tabMaterials).setMaxStackSize(256)); + .setTab(CheatTab.MATERIALS).setMaxStackSize(256)); registerItem("fish", (new ItemFishFood(false)).setDisplay("Fisch").setHasSubtypes(true)); registerItem("cooked_fish", (new ItemFishFood(true)).setDisplay("Fisch").setHasSubtypes(true)); Item dye = (new ItemDye()).setDisplay("Farbstoff").setMaxStackSize(512); registerItem("dye", dye); - registerItem("bone", (new ItemStick()).setDisplay("Knochen").setTab(CheatTab.tabMaterials).setMaxStackSize(128)); - registerItem("sugar", (new Item()).setDisplay("Zucker").setPotionEffect(PotionHelper.sugarEffect).setTab(CheatTab.tabMaterials).setMaxStackSize(512)); - registerItem((new ItemReed(Blocks.cake)).setMaxStackSize(1).setDisplay("Kuchen").setTab(CheatTab.tabDeco)); - registerItem((new ItemReed(Blocks.repeater)).setDisplay("Redstone-Verstärker").setTab(CheatTab.tabTech)); + registerItem("bone", (new ItemStick()).setDisplay("Knochen").setTab(CheatTab.MATERIALS).setMaxStackSize(128)); + registerItem("sugar", (new Item()).setDisplay("Zucker").setPotionEffect(PotionHelper.sugarEffect).setTab(CheatTab.MATERIALS).setMaxStackSize(512)); + registerItem((new ItemSmallBlock(Blocks.cake)).setMaxStackSize(1).setDisplay("Kuchen").setTab(CheatTab.DECORATION)); + registerItem((new ItemSmallBlock(Blocks.repeater)).setDisplay("Redstone-Verstärker").setTab(CheatTab.TECHNOLOGY)); registerItem("cookie", (new ItemFood(2, false)).setDisplay("Keks").setMaxStackSize(128)); registerItem("melon", (new ItemFood(2, false)).setDisplay("Melone")); registerItem((new ItemSeeds(Blocks.pumpkin_stem, Blocks.farmland)).setDisplay("Kürbiskerne").setMaxStackSize(256)); @@ -457,51 +487,51 @@ public abstract class ItemRegistry { registerItem("chicken", (new ItemFood(2, true)).setDisplay("Rohes Hühnchen")); registerItem("cooked_chicken", (new ItemFood(6, true)).setDisplay("Gebratenes Hühnchen")); registerItem("rotten_flesh", (new ItemFood(4, true)).setDisplay("Verrottetes Fleisch")); - registerItem("orb", (new ItemFragile()).setDisplay("Kugel").setTab(CheatTab.tabTools)); - registerItem("blaze_rod", (new ItemRod()).setDisplay("Lohenrute").setTab(CheatTab.tabMaterials).setMaxStackSize(256)); - registerItem("ghast_tear", (new ItemTiny()).setDisplay("Ghastträne").setPotionEffect(PotionHelper.ghastTearEffect).setTab(CheatTab.tabMaterials).setMaxStackSize(256)); - registerItem("gold_nugget", (new ItemNugget()).setDisplay("Goldnugget").setTab(CheatTab.tabMetals).setMaxStackSize(256)); + registerItem("orb", (new ItemFragile()).setDisplay("Kugel").setTab(CheatTab.TOOLS)); + registerItem("blaze_rod", (new ItemRod()).setDisplay("Lohenrute").setTab(CheatTab.MATERIALS).setMaxStackSize(256)); + registerItem("ghast_tear", (new ItemTiny()).setDisplay("Ghastträne").setPotionEffect(PotionHelper.ghastTearEffect).setTab(CheatTab.MATERIALS).setMaxStackSize(256)); + registerItem("gold_nugget", (new ItemNugget()).setDisplay("Goldnugget").setTab(CheatTab.METALS).setMaxStackSize(256)); registerItem((new ItemSeeds(Blocks.soul_wart, Blocks.soul_sand)).setDisplay("Seelenwarze").setPotionEffect("+4").setMaxStackSize(128)); registerItem("potion", (new ItemPotion()).setDisplay("Trank")); registerItem("glass_bottle", (new ItemGlassBottle()).setDisplay("Glasflasche")); registerItem("spider_eye", (new ItemFood(2, false)).setPotionEffect(Potion.POISON, 5, 0, 1.0F).setDisplay("Spinnenauge") .setPotionEffect(PotionHelper.spiderEyeEffect).setMaxStackSize(128)); registerItem("fermented_spider_eye", (new Item()).setDisplay("Fermentiertes Spinnenauge") - .setPotionEffect(PotionHelper.fermentedSpiderEyeEffect).setTab(CheatTab.tabMisc).setMaxStackSize(128)); + .setPotionEffect(PotionHelper.fermentedSpiderEyeEffect).setTab(CheatTab.MISC).setMaxStackSize(128)); registerItem("blaze_powder", (new Item()).setDisplay("Lohenstaub").setPotionEffect(PotionHelper.blazePowderEffect) - .setTab(CheatTab.tabMaterials).setMaxStackSize(256)); - registerItem("magma_cream", (new Item()).setDisplay("Magmacreme").setPotionEffect(PotionHelper.magmaCreamEffect).setTab(CheatTab.tabMaterials).setMaxStackSize(128)); - registerItem((new ItemReed(Blocks.brewing_stand)).setDisplay("Braustand").setTab(CheatTab.tabTech)); - registerItem((new ItemReed(Blocks.cauldron)).setDisplay("Kessel").setTab(CheatTab.tabTech)); + .setTab(CheatTab.MATERIALS).setMaxStackSize(256)); + registerItem("magma_cream", (new Item()).setDisplay("Magmacreme").setPotionEffect(PotionHelper.magmaCreamEffect).setTab(CheatTab.MATERIALS).setMaxStackSize(128)); + registerItem((new ItemSmallBlock(Blocks.brewing_stand)).setDisplay("Braustand").setTab(CheatTab.TECHNOLOGY)); + registerItem((new ItemSmallBlock(Blocks.cauldron)).setDisplay("Kessel").setTab(CheatTab.TECHNOLOGY)); registerItem("charged_orb", (new ItemChargedOrb()).setDisplay("Geladene Kugel")); registerItem("speckled_melon", (new Item()).setDisplay("Glitzernde Melone").setPotionEffect(PotionHelper.speckledMelonEffect) - .setTab(CheatTab.tabMisc)); + .setTab(CheatTab.MISC)); registerItem("experience_bottle", (new ItemExpBottle()).setDisplay("Erfahrungsfläschchen")); registerItem("fire_charge", (new ItemFireball()).setDisplay("Feuerkugel")); - registerItem("writable_book", (new Item()).setDisplay("Buch und Feder").setTab(CheatTab.tabTools)); - registerItem("written_book", (new Item()).setDisplay("Beschriebenes Buch").setTab(CheatTab.tabMisc)); - Item emerald = (new Item()).setDisplay("Smaragd").setTab(CheatTab.tabMetals); + registerItem("writable_book", (new Item()).setDisplay("Buch und Feder").setTab(CheatTab.TOOLS)); + registerItem("written_book", (new Item()).setDisplay("Beschriebenes Buch").setTab(CheatTab.MISC)); + Item emerald = (new Item()).setDisplay("Smaragd").setTab(CheatTab.METALS); registerItem("emerald", emerald); - registerItem((new ItemReed(Blocks.flower_pot)).setDisplay("Blumentopf").setTab(CheatTab.tabDeco)); + registerItem((new ItemSmallBlock(Blocks.flower_pot)).setDisplay("Blumentopf").setTab(CheatTab.DECORATION)); registerItem((new ItemSeedFood(3, Blocks.carrot, Blocks.farmland)).setDisplay("Karotte").setMaxStackSize(128)); registerItem((new ItemSeedFood(1, Blocks.potato, Blocks.farmland)).setDisplay("Kartoffel").setMaxStackSize(128)); registerItem("baked_potato", (new ItemFood(5, false)).setDisplay("Ofenkartoffel").setMaxStackSize(128)); registerItem("poisonous_potato", (new ItemFood(2, false)).setPotionEffect(Potion.POISON, 5, 0, 0.6F).setDisplay("Giftige Kartoffel").setMaxStackSize(128)); registerItem("golden_carrot", (new ItemFood(6, false)).setDisplay("Goldene Karotte") - .setPotionEffect(PotionHelper.goldenCarrotEffect).setTab(CheatTab.tabMisc)); - registerItem((new ItemSkull()).setDisplay("Kopf")); + .setPotionEffect(PotionHelper.goldenCarrotEffect).setTab(CheatTab.MISC)); + registerItem((new ItemSmallBlock(Blocks.skull)).setDisplay("Schädel").setTab(CheatTab.DECORATION)); registerItem("carrot_on_a_stick", (new ItemCarrotOnAStick()).setDisplay("Karottenrute")); - registerItem("charge_crystal", (new ItemEffect()).setDisplay("Energiekristall").setTab(CheatTab.tabMisc).setColor(TextColor.DMAGENTA)); - registerItem("pumpkin_pie", (new ItemFood(8, false)).setDisplay("Kürbiskuchen").setTab(CheatTab.tabMisc)); + registerItem("charge_crystal", (new ItemEffect()).setDisplay("Energiekristall").setTab(CheatTab.MISC).setColor(TextColor.DMAGENTA)); + registerItem("pumpkin_pie", (new ItemFood(8, false)).setDisplay("Kürbiskuchen").setTab(CheatTab.MISC)); registerItem("fireworks", (new ItemFirework()).setDisplay("Feuerwerksrakete")); - registerItem("firework_charge", (new ItemFireworkCharge()).setDisplay("Feuerwerksstern").setTab(CheatTab.tabMaterials)); - registerItem("enchanted_book", (new ItemEnchantedBook()).setMaxStackSize(1).setDisplay("Verzaubertes Buch").setTab(CheatTab.tabMagic)); - registerItem((new ItemReed(Blocks.comparator)).setDisplay("Redstone-Komparator").setTab(CheatTab.tabTech)); - registerItem("bloodbrick", (new Item()).setDisplay("Blutroter Ziegel").setTab(CheatTab.tabMaterials)); - registerItem("blackbrick", (new Item()).setDisplay("Schwarzer Ziegel").setTab(CheatTab.tabMaterials)); - Item quartz = (new Item()).setDisplay("Quarz").setTab(CheatTab.tabMetals); + registerItem("firework_charge", (new ItemFireworkCharge()).setDisplay("Feuerwerksstern").setTab(CheatTab.MATERIALS)); + registerItem("enchanted_book", (new ItemEnchantedBook()).setMaxStackSize(1).setDisplay("Verzaubertes Buch").setTab(CheatTab.MAGIC)); + registerItem((new ItemSmallBlock(Blocks.comparator)).setDisplay("Redstone-Komparator").setTab(CheatTab.TECHNOLOGY)); + registerItem("bloodbrick", (new Item()).setDisplay("Blutroter Ziegel").setTab(CheatTab.MATERIALS)); + registerItem("blackbrick", (new Item()).setDisplay("Schwarzer Ziegel").setTab(CheatTab.MATERIALS)); + Item quartz = (new Item()).setDisplay("Quarz").setTab(CheatTab.METALS); registerItem("quartz", quartz); - Item bquartz = (new Item()).setDisplay("Schwarzes Quarz").setTab(CheatTab.tabMetals); + Item bquartz = (new Item()).setDisplay("Schwarzes Quarz").setTab(CheatTab.METALS); registerItem("black_quartz", bquartz); registerItem("lead", (new ItemLead()).setDisplay("Leine").setMaxStackSize(128)); registerItem("name_tag", (new ItemNameTag()).setDisplay("Namensschild")); @@ -514,14 +544,14 @@ public abstract class ItemRegistry { registerItem("dynamite", (new ItemDynamite()).setDisplay("Dynamit").setColor(TextColor.RED)); // registerItem("cherry_door", (new ItemDoor(Blocks.cherry_door)).setUnlocalizedName("doorCherry")); // registerItem("maple_door", (new ItemDoor(Blocks.maple_door)).setUnlocalizedName("doorMaple")); - registerItem("chain", (new ItemMagnetic()).setDisplay("Kette").setTab(CheatTab.tabMaterials)); + registerItem("chain", (new ItemMagnetic()).setDisplay("Kette").setTab(CheatTab.MATERIALS)); for(OreType ore : OreType.values()) { // String loc = ore.name.substring(0, 1).toUpperCase() + ore.name.substring(1); // registerItemBlock(BlockRegistry.getRegisteredBlock(ore.name + "_ore")); // registerItemBlock(BlockRegistry.getRegisteredBlock(ore.name + "_block")); // if(ore.gem != null) { - Item itm = (new Item()).setDisplay(ore.itemDisplay).setTab(CheatTab.tabMetals); + Item itm = (new Item()).setDisplay(ore.itemDisplay).setTab(CheatTab.METALS); registerItem(ore.item, itm); ((BlockOre)BlockRegistry.getRegisteredBlock(ore.name + "_ore")).setDropItem(new ItemStack(itm, ore.dropQuantity), ore.bonusChance, ore.experience); @@ -542,12 +572,12 @@ public abstract class ItemRegistry { ItemBlock block = new ItemMetalBlock(fullBlock, metal, false); registerBlock(fullBlock, block); if(metal.isPowder) { - Item itm = (new ItemMetal(metal)).setDisplay(metal.display + "pulver").setTab(CheatTab.tabMetals); + Item itm = (new ItemMetal(metal)).setDisplay(metal.display + "pulver").setTab(CheatTab.METALS); registerItem(metal.name + "_powder", itm); ((BlockOre)BlockRegistry.getRegisteredBlock(metal.name + "_ore")).setDropItem(new ItemStack(itm), 0, 2); } else { - Item itm = (new ItemMetal(metal)).setDisplay(metal.display + "barren").setTab(CheatTab.tabMetals); + Item itm = (new ItemMetal(metal)).setDisplay(metal.display + "barren").setTab(CheatTab.METALS); registerItem(metal.name + "_ingot", itm); ((BlockOre)BlockRegistry.getRegisteredBlock(metal.name + "_ore")).setSmeltItem(new ItemStack(itm)); } @@ -614,6 +644,8 @@ public abstract class ItemRegistry { // registerSpecial(Blocks.reeds); registerSpecial(Blocks.fire); + registerSpecial(Blocks.soul_fire); + registerSpecial(Blocks.black_fire); registerSpecial(Blocks.portal); registerSpecial(Blocks.floor_portal); // registerSpecial(Blocks.standing_sign); @@ -642,7 +674,7 @@ public abstract class ItemRegistry { for(Block block : BlockRegistry.REGISTRY) { if(!BLOCKMAP.containsKey(block) && !SPECIALIZED.contains(block)) registerBlock(block, new ItemBlock(block)); -// Log.info("Block " + BlockRegistry.REGISTRY.getNameForObject(block) + " hat kein Item"); +// Log.info("Block " + BlockRegistry.getNameFromBlock(block) + " hat kein Item"); } } } diff --git a/common/src/main/java/common/init/Items.java b/common/src/main/java/common/init/Items.java new file mode 100755 index 0000000..ecd134e --- /dev/null +++ b/common/src/main/java/common/init/Items.java @@ -0,0 +1,680 @@ +package common.init; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.Collections; +import java.util.Comparator; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import common.collect.Lists; +import common.collect.Sets; +import common.item.*; +import common.util.Util; + + +public abstract class Items { + public static final ItemDoor acacia_door = get("acacia_door"); + public static final ItemFence acacia_fence = get("acacia_fence"); + public static final ItemBlock acacia_fence_gate = get("acacia_fence_gate"); + public static final ItemLeaves acacia_leaves = get("acacia_leaves"); + public static final ItemBlock acacia_log = get("acacia_log"); + public static final ItemBlock acacia_planks = get("acacia_planks"); + public static final ItemBlock acacia_sapling = get("acacia_sapling"); + public static final ItemSlab acacia_slab = get("acacia_slab"); + public static final ItemBlock acacia_stairs = get("acacia_stairs"); + public static final ItemBucket acid_bucket = get("acid_bucket"); + public static final ItemBlock activator_rail = get("activator_rail"); + public static final Item ahrd_fragment = get("ahrd_fragment"); + public static final ItemMetalBlock aluminium_block = get("aluminium_block"); + public static final ItemMetal aluminium_ingot = get("aluminium_ingot"); + public static final ItemMetalBlock aluminium_ore = get("aluminium_ore"); + public static final ItemMetalBlock antimony_block = get("antimony_block"); + public static final ItemMetalBlock antimony_ore = get("antimony_ore"); + public static final ItemMetal antimony_powder = get("antimony_powder"); + public static final ItemAnvilBlock anvil = get("anvil"); + public static final ItemFood apple = get("apple"); + public static final ItemBlock ardite_block = get("ardite_block"); + public static final ItemArmor ardite_boots = get("ardite_boots"); + public static final ItemArmor ardite_chestplate = get("ardite_chestplate"); + public static final ItemArmor ardite_helmet = get("ardite_helmet"); + public static final ItemArmor ardite_leggings = get("ardite_leggings"); + public static final ItemBlock ardite_ore = get("ardite_ore"); + public static final ItemSword ardite_sword = get("ardite_sword"); + public static final Item arrow = get("arrow"); + public static final ItemMetalBlock arsenic_block = get("arsenic_block"); + public static final ItemMetalBlock arsenic_ore = get("arsenic_ore"); + public static final ItemMetal arsenic_powder = get("arsenic_powder"); + public static final ItemBlock ash = get("ash"); + public static final ItemBlock assembly_unit = get("assembly_unit"); + public static final ItemFood baked_potato = get("baked_potato"); + public static final ItemBanHammer banhammer = get("banhammer"); + public static final ItemBanner banner = get("banner"); + public static final ItemBlock beacon = get("beacon"); + public static final ItemBlock bedrock = get("bedrock"); + public static final ItemFood beef = get("beef"); + public static final ItemDoor birch_door = get("birch_door"); + public static final ItemFence birch_fence = get("birch_fence"); + public static final ItemBlock birch_fence_gate = get("birch_fence_gate"); + public static final ItemLeaves birch_leaves = get("birch_leaves"); + public static final ItemBlock birch_log = get("birch_log"); + public static final ItemBlock birch_planks = get("birch_planks"); + public static final ItemBlock birch_sapling = get("birch_sapling"); + public static final ItemSlab birch_slab = get("birch_slab"); + public static final ItemBlock birch_stairs = get("birch_stairs"); + public static final ItemMetalBlock bismuth_block = get("bismuth_block"); + public static final ItemMetal bismuth_ingot = get("bismuth_ingot"); + public static final ItemMetalBlock bismuth_ore = get("bismuth_ore"); + public static final ItemBed black_bed = get("black_bed"); + public static final ItemBlock black_brick = get("black_brick"); + public static final ItemFence black_brick_fence = get("black_brick_fence"); + public static final ItemSlab black_brick_slab = get("black_brick_slab"); + public static final ItemBlock black_brick_stairs = get("black_brick_stairs"); + public static final ItemMetalBlock black_metal_block = get("black_metal_block"); + public static final ItemMetal black_metal_ingot = get("black_metal_ingot"); + public static final ItemMetalBlock black_metal_ore = get("black_metal_ore"); + public static final Item black_quartz = get("black_quartz"); + public static final ItemMultiTexture black_quartz_block = get("black_quartz_block"); + public static final ItemBlock black_quartz_ore = get("black_quartz_ore"); + public static final ItemSlab black_quartz_slab = get("black_quartz_slab"); + public static final ItemBlock black_quartz_stairs = get("black_quartz_stairs"); + public static final Item blackbrick = get("blackbrick"); + public static final ItemBlock blackened_cobble = get("blackened_cobble"); + public static final ItemBlock blackened_dirt = get("blackened_dirt"); + public static final ItemBlock blackened_soil = get("blackened_soil"); + public static final ItemBlock blackened_stone = get("blackened_stone"); + public static final ItemDoor blackwood_door = get("blackwood_door"); + public static final ItemFence blackwood_fence = get("blackwood_fence"); + public static final ItemBlock blackwood_fence_gate = get("blackwood_fence_gate"); + public static final ItemLeaves blackwood_leaves = get("blackwood_leaves"); + public static final ItemBlock blackwood_log = get("blackwood_log"); + public static final ItemBlock blackwood_planks = get("blackwood_planks"); + public static final ItemBlock blackwood_sapling = get("blackwood_sapling"); + public static final ItemSlab blackwood_slab = get("blackwood_slab"); + public static final ItemBlock blackwood_stairs = get("blackwood_stairs"); + public static final Item blaze_powder = get("blaze_powder"); + public static final ItemRod blaze_rod = get("blaze_rod"); + public static final ItemBlock blood_brick = get("blood_brick"); + public static final ItemFence blood_brick_fence = get("blood_brick_fence"); + public static final ItemSlab blood_brick_slab = get("blood_brick_slab"); + public static final ItemBlock blood_brick_stairs = get("blood_brick_stairs"); + public static final ItemBucket blood_bucket = get("blood_bucket"); + public static final Item bloodbrick = get("bloodbrick"); + public static final ItemBlock blue_mushroom = get("blue_mushroom"); + public static final ItemBoat boat = get("boat"); + public static final ItemAmmo bolt = get("bolt"); + public static final ItemBoltgun boltgun = get("boltgun"); + public static final ItemStick bone = get("bone"); + public static final ItemBook book = get("book"); + public static final ItemBlock bookshelf = get("bookshelf"); + public static final ItemBow bow = get("bow"); + public static final ItemSmall bowl = get("bowl"); + public static final ItemFood bread = get("bread"); + public static final ItemSmallBlock brewing_stand = get("brewing_stand"); + public static final Item brick = get("brick"); + public static final ItemBlock brick_block = get("brick_block"); + public static final ItemSlab brick_slab = get("brick_slab"); + public static final ItemBlock brick_stairs = get("brick_stairs"); + public static final ItemBlock brown_mushroom = get("brown_mushroom"); + public static final ItemHugeMushroom brown_mushroom_block = get("brown_mushroom_block"); + public static final ItemBucket bucket = get("bucket"); + public static final ItemFlintAndSteel burning_soul = get("burning_soul"); + public static final ItemBlock cactus = get("cactus"); + public static final ItemSmallBlock cake = get("cake"); + public static final ItemMetalBlock calcium_block = get("calcium_block"); + public static final ItemMetalBlock calcium_ore = get("calcium_ore"); + public static final ItemMetal calcium_powder = get("calcium_powder"); + public static final ItemCamera camera = get("camera"); + public static final ItemCloth carpet = get("carpet"); + public static final ItemSeedFood carrot = get("carrot"); + public static final ItemCarrotOnAStick carrot_on_a_stick = get("carrot_on_a_stick"); + public static final ItemSmallBlock cauldron = get("cauldron"); + public static final ItemBlock cell_rock = get("cell_rock"); + public static final ItemMagnetic chain = get("chain"); + public static final ItemArmor chain_boots = get("chain_boots"); + public static final ItemArmor chain_chestplate = get("chain_chestplate"); + public static final ItemArmor chain_helmet = get("chain_helmet"); + public static final ItemArmor chain_leggings = get("chain_leggings"); + public static final ItemEffect charge_crystal = get("charge_crystal"); + public static final ItemChargedOrb charged_orb = get("charged_orb"); + public static final ItemDoor cherry_door = get("cherry_door"); + public static final ItemFence cherry_fence = get("cherry_fence"); + public static final ItemBlock cherry_fence_gate = get("cherry_fence_gate"); + public static final ItemLeaves cherry_leaves = get("cherry_leaves"); + public static final ItemBlock cherry_log = get("cherry_log"); + public static final ItemBlock cherry_planks = get("cherry_planks"); + public static final ItemBlock cherry_sapling = get("cherry_sapling"); + public static final ItemSlab cherry_slab = get("cherry_slab"); + public static final ItemBlock cherry_stairs = get("cherry_stairs"); + public static final ItemChest chest = get("chest"); + public static final ItemMinecart chest_minecart = get("chest_minecart"); + public static final ItemMagnet chick_magnet = get("chick_magnet"); + public static final ItemFood chicken = get("chicken"); + public static final ItemMetalBlock chrome_block = get("chrome_block"); + public static final ItemMetal chrome_ingot = get("chrome_ingot"); + public static final ItemMetalBlock chrome_ore = get("chrome_ore"); + public static final Item cinnabar = get("cinnabar"); + public static final ItemBlock cinnabar_block = get("cinnabar_block"); + public static final ItemBlock cinnabar_ore = get("cinnabar_ore"); + public static final ItemBlock clay = get("clay"); + public static final Item clay_ball = get("clay_ball"); + public static final ItemArmor cloth_boots = get("cloth_boots"); + public static final ItemArmor cloth_chestplate = get("cloth_chestplate"); + public static final ItemArmor cloth_helmet = get("cloth_helmet"); + public static final ItemArmor cloth_leggings = get("cloth_leggings"); + public static final ItemCoal coal = get("coal"); + public static final ItemBlock coal_block = get("coal_block"); + public static final ItemBlock coal_ore = get("coal_ore"); + public static final ItemMetalBlock cobalt_block = get("cobalt_block"); + public static final ItemMetal cobalt_ingot = get("cobalt_ingot"); + public static final ItemMetalBlock cobalt_ore = get("cobalt_ore"); + public static final ItemBlock cobblestone = get("cobblestone"); + public static final ItemSlab cobblestone_slab = get("cobblestone_slab"); + public static final ItemBlock cobblestone_stairs = get("cobblestone_stairs"); + public static final ItemWall cobblestone_wall = get("cobblestone_wall"); + public static final ItemSmallBlock comparator = get("comparator"); + public static final ItemBlock construction_table = get("construction_table"); + public static final ItemFood cooked_beef = get("cooked_beef"); + public static final ItemFood cooked_chicken = get("cooked_chicken"); + public static final ItemFishFood cooked_fish = get("cooked_fish"); + public static final ItemFood cooked_porkchop = get("cooked_porkchop"); + public static final ItemFood cookie = get("cookie"); + public static final ItemMetalBlock copper_block = get("copper_block"); + public static final ItemMetal copper_ingot = get("copper_ingot"); + public static final ItemMetalBlock copper_ore = get("copper_ore"); + public static final ItemBlock core = get("core"); + public static final ItemFlintAndSteel dark_lighter = get("dark_lighter"); + public static final ItemDoor dark_oak_door = get("dark_oak_door"); + public static final ItemFence dark_oak_fence = get("dark_oak_fence"); + public static final ItemBlock dark_oak_fence_gate = get("dark_oak_fence_gate"); + public static final ItemLeaves dark_oak_leaves = get("dark_oak_leaves"); + public static final ItemBlock dark_oak_log = get("dark_oak_log"); + public static final ItemBlock dark_oak_planks = get("dark_oak_planks"); + public static final ItemBlock dark_oak_sapling = get("dark_oak_sapling"); + public static final ItemSlab dark_oak_slab = get("dark_oak_slab"); + public static final ItemBlock dark_oak_stairs = get("dark_oak_stairs"); + public static final ItemBlock daylight_detector = get("daylight_detector"); + public static final ItemBlock deadbush = get("deadbush"); + public static final ItemBlock detector_rail = get("detector_rail"); + public static final Item diamond = get("diamond"); + public static final ItemAxe diamond_axe = get("diamond_axe"); + public static final ItemBlock diamond_block = get("diamond_block"); + public static final ItemArmor diamond_boots = get("diamond_boots"); + public static final ItemArmor diamond_chestplate = get("diamond_chestplate"); + public static final ItemArmor diamond_helmet = get("diamond_helmet"); + public static final ItemHoe diamond_hoe = get("diamond_hoe"); + public static final ItemHorseArmor diamond_horse_armor = get("diamond_horse_armor"); + public static final ItemArmor diamond_leggings = get("diamond_leggings"); + public static final ItemBlock diamond_ore = get("diamond_ore"); + public static final ItemPickaxe diamond_pickaxe = get("diamond_pickaxe"); + public static final ItemShears diamond_shears = get("diamond_shears"); + public static final ItemShovel diamond_shovel = get("diamond_shovel"); + public static final ItemSword diamond_sword = get("diamond_sword"); + public static final ItemDie die = get("die"); + public static final ItemMultiTexture dirt = get("dirt"); + public static final ItemDispenser dispenser = get("dispenser"); + public static final ItemDoublePlant double_plant = get("double_plant"); + public static final ItemBlock dragon_egg = get("dragon_egg"); + public static final ItemDispenser dropper = get("dropper"); + public static final ItemBlock dry_leaves = get("dry_leaves"); + public static final ItemDye dye = get("dye"); + public static final ItemDynamite dynamite = get("dynamite"); + public static final ItemEgg egg = get("egg"); + public static final Item emerald = get("emerald"); + public static final ItemBlock emerald_block = get("emerald_block"); + public static final ItemBlock emerald_ore = get("emerald_ore"); + public static final ItemEnchantedBook enchanted_book = get("enchanted_book"); + public static final ItemBlock enchanting_table = get("enchanting_table"); + public static final ItemExpBottle experience_bottle = get("experience_bottle"); + public static final ItemExterminator exterminator = get("exterminator"); + public static final ItemBlock farmland = get("farmland"); + public static final Item feather = get("feather"); + public static final Item fermented_spider_eye = get("fermented_spider_eye"); + public static final ItemFireball fire_charge = get("fire_charge"); + public static final ItemFireworkCharge firework_charge = get("firework_charge"); + public static final ItemFirework fireworks = get("fireworks"); + public static final ItemFishFood fish = get("fish"); + public static final ItemFishingRod fishing_rod = get("fishing_rod"); + public static final Item flint = get("flint"); + public static final ItemFlintAndSteel flint_and_steel = get("flint_and_steel"); + public static final ItemBlock floor_tiles = get("floor_tiles"); + public static final ItemBlock floor_tiles_black = get("floor_tiles_black"); + public static final ItemBlock floor_tiles_red = get("floor_tiles_red"); + public static final ItemBlock floor_tiles_white = get("floor_tiles_white"); + public static final ItemMultiTexture flower = get("flower"); + public static final ItemSmallBlock flower_pot = get("flower_pot"); + public static final ItemBlock furnace = get("furnace"); + public static final ItemTiny ghast_tear = get("ghast_tear"); + public static final Item ghi_fragment = get("ghi_fragment"); + public static final ItemBlock glass = get("glass"); + public static final ItemGlassBottle glass_bottle = get("glass_bottle"); + public static final ItemBlock glass_pane = get("glass_pane"); + public static final ItemBlock glowstone = get("glowstone"); + public static final Item glowstone_dust = get("glowstone_dust"); + public static final ItemAxe gold_axe = get("gold_axe"); + public static final ItemMetalBlock gold_block = get("gold_block"); + public static final ItemArmor gold_boots = get("gold_boots"); + public static final ItemArmor gold_chestplate = get("gold_chestplate"); + public static final ItemArmor gold_helmet = get("gold_helmet"); + public static final ItemHoe gold_hoe = get("gold_hoe"); + public static final ItemHorseArmor gold_horse_armor = get("gold_horse_armor"); + public static final ItemMetal gold_ingot = get("gold_ingot"); + public static final ItemArmor gold_leggings = get("gold_leggings"); + public static final ItemNugget gold_nugget = get("gold_nugget"); + public static final ItemMetalBlock gold_ore = get("gold_ore"); + public static final ItemPickaxe gold_pickaxe = get("gold_pickaxe"); + public static final ItemShears gold_shears = get("gold_shears"); + public static final ItemShovel gold_shovel = get("gold_shovel"); + public static final ItemSword gold_sword = get("gold_sword"); + public static final ItemAppleGold golden_apple = get("golden_apple"); + public static final ItemFood golden_carrot = get("golden_carrot"); + public static final ItemBlock golden_rail = get("golden_rail"); + public static final ItemBucket goo_bucket = get("goo_bucket"); + public static final ItemColored grass = get("grass"); + public static final ItemBlock gravel = get("gravel"); + public static final Item gunpowder = get("gunpowder"); + public static final ItemAxe gyriyn_axe = get("gyriyn_axe"); + public static final ItemBlock gyriyn_block = get("gyriyn_block"); + public static final ItemHoe gyriyn_hoe = get("gyriyn_hoe"); + public static final ItemBlock gyriyn_ore = get("gyriyn_ore"); + public static final ItemPickaxe gyriyn_pickaxe = get("gyriyn_pickaxe"); + public static final ItemShovel gyriyn_shovel = get("gyriyn_shovel"); + public static final ItemBlock hardened_clay = get("hardened_clay"); + public static final ItemBlock hay_block = get("hay_block"); + public static final ItemPressurePlate heavy_weighted_pressure_plate = get("heavy_weighted_pressure_plate"); + public static final ItemBlock hellrock = get("hellrock"); + public static final ItemBlock hopper = get("hopper"); + public static final ItemMinecart hopper_minecart = get("hopper_minecart"); + public static final ItemBucket hydrogen_bucket = get("hydrogen_bucket"); + public static final ItemBlock ice = get("ice"); + public static final ItemInfoWand info_wand = get("info_wand"); + public static final ItemMetalBlock iodine_block = get("iodine_block"); + public static final ItemMetalBlock iodine_ore = get("iodine_ore"); + public static final ItemMetal iodine_powder = get("iodine_powder"); + public static final ItemAxe iron_axe = get("iron_axe"); + public static final ItemBlock iron_bars = get("iron_bars"); + public static final ItemMetalBlock iron_block = get("iron_block"); + public static final ItemArmor iron_boots = get("iron_boots"); + public static final ItemArmor iron_chestplate = get("iron_chestplate"); + public static final ItemDoor iron_door = get("iron_door"); + public static final ItemArmor iron_helmet = get("iron_helmet"); + public static final ItemHoe iron_hoe = get("iron_hoe"); + public static final ItemHorseArmor iron_horse_armor = get("iron_horse_armor"); + public static final ItemMetal iron_ingot = get("iron_ingot"); + public static final ItemArmor iron_leggings = get("iron_leggings"); + public static final ItemMetalBlock iron_ore = get("iron_ore"); + public static final ItemPickaxe iron_pickaxe = get("iron_pickaxe"); + public static final ItemShears iron_shears = get("iron_shears"); + public static final ItemShovel iron_shovel = get("iron_shovel"); + public static final ItemSword iron_sword = get("iron_sword"); + public static final ItemBlock iron_trapdoor = get("iron_trapdoor"); + public static final ItemBlock jukebox = get("jukebox"); + public static final ItemDoor jungle_door = get("jungle_door"); + public static final ItemFence jungle_fence = get("jungle_fence"); + public static final ItemBlock jungle_fence_gate = get("jungle_fence_gate"); + public static final ItemLeaves jungle_leaves = get("jungle_leaves"); + public static final ItemBlock jungle_log = get("jungle_log"); + public static final ItemBlock jungle_planks = get("jungle_planks"); + public static final ItemBlock jungle_sapling = get("jungle_sapling"); + public static final ItemSlab jungle_slab = get("jungle_slab"); + public static final ItemBlock jungle_stairs = get("jungle_stairs"); + public static final ItemKey key = get("key"); + public static final ItemBlock ladder = get("ladder"); + public static final ItemBlock lamp = get("lamp"); + public static final ItemBlock lapis_block = get("lapis_block"); + public static final ItemBlock lapis_ore = get("lapis_ore"); + public static final ItemBucket lava_bucket = get("lava_bucket"); + public static final ItemLead lead = get("lead"); + public static final ItemMetalBlock lead_block = get("lead_block"); + public static final ItemMetal lead_ingot = get("lead_ingot"); + public static final ItemMetalBlock lead_ore = get("lead_ore"); + public static final Item leather = get("leather"); + public static final ItemArmor leather_boots = get("leather_boots"); + public static final ItemArmor leather_chestplate = get("leather_chestplate"); + public static final ItemArmor leather_helmet = get("leather_helmet"); + public static final ItemArmor leather_leggings = get("leather_leggings"); + public static final ItemBlock lever = get("lever"); + public static final ItemPressurePlate light_weighted_pressure_plate = get("light_weighted_pressure_plate"); + public static final ItemLightning lightning_wand = get("lightning_wand"); + public static final ItemBlock lit_furnace = get("lit_furnace"); + public static final ItemBlock lit_pumpkin = get("lit_pumpkin"); + public static final ItemMetalBlock lithium_block = get("lithium_block"); + public static final ItemMetal lithium_ingot = get("lithium_ingot"); + public static final ItemMetalBlock lithium_ore = get("lithium_ore"); + public static final ItemBucket magma_bucket = get("magma_bucket"); + public static final Item magma_cream = get("magma_cream"); + public static final ItemMetalBlock magnesium_block = get("magnesium_block"); + public static final ItemMetalBlock magnesium_ore = get("magnesium_ore"); + public static final ItemMetal magnesium_powder = get("magnesium_powder"); + public static final ItemMagnet magnet = get("magnet"); + public static final ItemMetalBlock manganese_block = get("manganese_block"); + public static final ItemMetal manganese_ingot = get("manganese_ingot"); + public static final ItemMetalBlock manganese_ore = get("manganese_ore"); + public static final ItemDoor maple_door = get("maple_door"); + public static final ItemFence maple_fence = get("maple_fence"); + public static final ItemBlock maple_fence_gate = get("maple_fence_gate"); + public static final ItemLeaves maple_leaves = get("maple_leaves"); + public static final ItemBlock maple_log = get("maple_log"); + public static final ItemBlock maple_planks = get("maple_planks"); + public static final ItemBlock maple_sapling = get("maple_sapling"); + public static final ItemSlab maple_slab = get("maple_slab"); + public static final ItemBlock maple_stairs = get("maple_stairs"); + public static final ItemFood melon = get("melon"); + public static final ItemBlock melon_block = get("melon_block"); + public static final ItemSeeds melon_stem = get("melon_stem"); + public static final ItemBucket mercury_bucket = get("mercury_bucket"); + public static final ItemBucketMilk milk_bucket = get("milk_bucket"); + public static final ItemMinecart minecart = get("minecart"); + public static final ItemBlock mob_spawner = get("mob_spawner"); + public static final ItemBlock moon_cheese = get("moon_cheese"); + public static final ItemBlock moon_rock = get("moon_rock"); + public static final ItemBlock mossy_cobblestone = get("mossy_cobblestone"); + public static final ItemSoup mushroom_stew = get("mushroom_stew"); + public static final ItemBlock mycelium = get("mycelium"); + public static final ItemNameTag name_tag = get("name_tag"); + public static final ItemSpaceNavigator navigator = get("navigator"); + public static final ItemMetalBlock neodymium_block = get("neodymium_block"); + public static final ItemMetal neodymium_ingot = get("neodymium_ingot"); + public static final ItemMetalBlock neodymium_ore = get("neodymium_ore"); + public static final ItemMetalBlock neptunium_block = get("neptunium_block"); + public static final ItemMetal neptunium_ingot = get("neptunium_ingot"); + public static final ItemMetalBlock neptunium_ore = get("neptunium_ore"); + public static final ItemAxe nichun_axe = get("nichun_axe"); + public static final ItemBlock nichun_block = get("nichun_block"); + public static final ItemArmor nichun_boots = get("nichun_boots"); + public static final ItemArmor nichun_chestplate = get("nichun_chestplate"); + public static final ItemArmor nichun_helmet = get("nichun_helmet"); + public static final ItemHoe nichun_hoe = get("nichun_hoe"); + public static final ItemArmor nichun_leggings = get("nichun_leggings"); + public static final ItemBlock nichun_ore = get("nichun_ore"); + public static final ItemPickaxe nichun_pickaxe = get("nichun_pickaxe"); + public static final ItemShovel nichun_shovel = get("nichun_shovel"); + public static final ItemSword nichun_sword = get("nichun_sword"); + public static final ItemMetalBlock nickel_block = get("nickel_block"); + public static final ItemMetal nickel_ingot = get("nickel_ingot"); + public static final ItemMetalBlock nickel_ore = get("nickel_ore"); + public static final Item nieh_fragment = get("nieh_fragment"); + public static final ItemBlock noteblock = get("noteblock"); + public static final ItemBucket nukage_bucket = get("nukage_bucket"); + public static final ItemBlock nuke = get("nuke"); + public static final ItemDoor oak_door = get("oak_door"); + public static final ItemFence oak_fence = get("oak_fence"); + public static final ItemBlock oak_fence_gate = get("oak_fence_gate"); + public static final ItemLeaves oak_leaves = get("oak_leaves"); + public static final ItemBlock oak_log = get("oak_log"); + public static final ItemBlock oak_planks = get("oak_planks"); + public static final ItemBlock oak_sapling = get("oak_sapling"); + public static final ItemSlab oak_slab = get("oak_slab"); + public static final ItemBlock oak_stairs = get("oak_stairs"); + public static final ItemBlock obsidian = get("obsidian"); + public static final ItemFragile orb = get("orb"); + public static final ItemBlock packed_ice = get("packed_ice"); + public static final ItemMetalBlock palladium_block = get("palladium_block"); + public static final ItemMetal palladium_ingot = get("palladium_ingot"); + public static final ItemMetalBlock palladium_ore = get("palladium_ore"); + public static final Item paper = get("paper"); + public static final ItemBlock pentagram = get("pentagram"); + public static final ItemMetalBlock phosphor_block = get("phosphor_block"); + public static final ItemMetalBlock phosphor_ore = get("phosphor_ore"); + public static final ItemMetal phosphor_powder = get("phosphor_powder"); + public static final ItemPiston piston = get("piston"); + public static final ItemMetalBlock platinum_block = get("platinum_block"); + public static final ItemMetal platinum_ingot = get("platinum_ingot"); + public static final ItemMetalBlock platinum_ore = get("platinum_ore"); + public static final ItemMetalBlock plutonium_block = get("plutonium_block"); + public static final ItemMetal plutonium_ingot = get("plutonium_ingot"); + public static final ItemMetalBlock plutonium_ore = get("plutonium_ore"); + public static final ItemFood poisonous_potato = get("poisonous_potato"); + public static final ItemFood porkchop = get("porkchop"); + public static final ItemBlock portal_frame = get("portal_frame"); + public static final ItemMetalBlock potassium_block = get("potassium_block"); + public static final ItemMetalBlock potassium_ore = get("potassium_ore"); + public static final ItemMetal potassium_powder = get("potassium_powder"); + public static final ItemSeedFood potato = get("potato"); + public static final ItemPotion potion = get("potion"); + public static final ItemMetalBlock praseodymium_block = get("praseodymium_block"); + public static final ItemMetal praseodymium_ingot = get("praseodymium_ingot"); + public static final ItemMetalBlock praseodymium_ore = get("praseodymium_ore"); + public static final ItemBlock pumpkin = get("pumpkin"); + public static final ItemFood pumpkin_pie = get("pumpkin_pie"); + public static final ItemSeeds pumpkin_stem = get("pumpkin_stem"); + public static final ItemBed purple_bed = get("purple_bed"); + public static final Item quartz = get("quartz"); + public static final ItemMultiTexture quartz_block = get("quartz_block"); + public static final ItemBlock quartz_ore = get("quartz_ore"); + public static final ItemSlab quartz_slab = get("quartz_slab"); + public static final ItemBlock quartz_stairs = get("quartz_stairs"); + public static final ItemMetalBlock radium_block = get("radium_block"); + public static final ItemMetal radium_ingot = get("radium_ingot"); + public static final ItemMetalBlock radium_ore = get("radium_ore"); + public static final ItemBlock rail = get("rail"); + public static final ItemRecord record_11 = get("record_11"); + public static final ItemRecord record_13 = get("record_13"); + public static final ItemRecord record_blocks = get("record_blocks"); + public static final ItemRecord record_cat = get("record_cat"); + public static final ItemRecord record_chirp = get("record_chirp"); + public static final ItemRecord record_delay = get("record_delay"); + public static final ItemRecord record_extend = get("record_extend"); + public static final ItemRecord record_far = get("record_far"); + public static final ItemRecord record_mall = get("record_mall"); + public static final ItemRecord record_mellohi = get("record_mellohi"); + public static final ItemRecord record_stal = get("record_stal"); + public static final ItemRecord record_strad = get("record_strad"); + public static final ItemRecord record_wait = get("record_wait"); + public static final ItemRecord record_ward = get("record_ward"); + public static final ItemBucket recursive_acid_bucket = get("recursive_acid_bucket"); + public static final ItemBucket recursive_blood_bucket = get("recursive_blood_bucket"); + public static final ItemBucket recursive_bucket = get("recursive_bucket"); + public static final ItemBucket recursive_goo_bucket = get("recursive_goo_bucket"); + public static final ItemBucket recursive_hydrogen_bucket = get("recursive_hydrogen_bucket"); + public static final ItemBucket recursive_lava_bucket = get("recursive_lava_bucket"); + public static final ItemBucket recursive_magma_bucket = get("recursive_magma_bucket"); + public static final ItemBucket recursive_mercury_bucket = get("recursive_mercury_bucket"); + public static final ItemBucket recursive_nukage_bucket = get("recursive_nukage_bucket"); + public static final ItemBucket recursive_slime_bucket = get("recursive_slime_bucket"); + public static final ItemBucket recursive_water_bucket = get("recursive_water_bucket"); + public static final ItemBed red_bed = get("red_bed"); + public static final ItemButton red_button = get("red_button"); + public static final ItemBlock red_mushroom = get("red_mushroom"); + public static final ItemHugeMushroom red_mushroom_block = get("red_mushroom_block"); + public static final ItemRedstone redstone = get("redstone"); + public static final ItemBlock redstone_block = get("redstone_block"); + public static final ItemBlock redstone_lamp = get("redstone_lamp"); + public static final ItemBlock redstone_ore = get("redstone_ore"); + public static final ItemBlock redstone_torch = get("redstone_torch"); + public static final ItemSmallBlock reeds = get("reeds"); + public static final ItemSmallBlock repeater = get("repeater"); + public static final ItemMultiTexture rock = get("rock"); + public static final ItemFood rotten_flesh = get("rotten_flesh"); + public static final Item ruby = get("ruby"); + public static final ItemBlock ruby_block = get("ruby_block"); + public static final ItemBlock ruby_ore = get("ruby_ore"); + public static final ItemSaddle saddle = get("saddle"); + public static final ItemMultiTexture sand = get("sand"); + public static final ItemMultiTexture sandstone = get("sandstone"); + public static final ItemSlab sandstone_slab = get("sandstone_slab"); + public static final ItemBlock sandstone_stairs = get("sandstone_stairs"); + public static final ItemMetalBlock selenium_block = get("selenium_block"); + public static final ItemMetalBlock selenium_ore = get("selenium_ore"); + public static final ItemMetal selenium_powder = get("selenium_powder"); + public static final ItemSign sign = get("sign"); + public static final ItemMetalBlock silicon_block = get("silicon_block"); + public static final ItemMetal silicon_ingot = get("silicon_ingot"); + public static final ItemMetalBlock silicon_ore = get("silicon_ore"); + public static final ItemMetalBlock silver_block = get("silver_block"); + public static final ItemMetal silver_ingot = get("silver_ingot"); + public static final ItemMetalBlock silver_ore = get("silver_ore"); + public static final ItemSmallBlock skull = get("skull"); + public static final Item slime_ball = get("slime_ball"); + public static final ItemBlock slime_block = get("slime_block"); + public static final ItemBucket slime_bucket = get("slime_bucket"); + public static final ItemBlock snow = get("snow"); + public static final ItemSnow snow_layer = get("snow_layer"); + public static final ItemSnowball snowball = get("snowball"); + public static final ItemMetalBlock sodium_block = get("sodium_block"); + public static final ItemMetalBlock sodium_ore = get("sodium_ore"); + public static final ItemMetal sodium_powder = get("sodium_powder"); + public static final ItemBlock soul_sand = get("soul_sand"); + public static final ItemSeeds soul_wart = get("soul_wart"); + public static final Item speckled_melon = get("speckled_melon"); + public static final ItemFood spider_eye = get("spider_eye"); + public static final ItemBlock sponge = get("sponge"); + public static final ItemDoor spruce_door = get("spruce_door"); + public static final ItemFence spruce_fence = get("spruce_fence"); + public static final ItemBlock spruce_fence_gate = get("spruce_fence_gate"); + public static final ItemLeaves spruce_leaves = get("spruce_leaves"); + public static final ItemBlock spruce_log = get("spruce_log"); + public static final ItemBlock spruce_planks = get("spruce_planks"); + public static final ItemBlock spruce_sapling = get("spruce_sapling"); + public static final ItemSlab spruce_slab = get("spruce_slab"); + public static final ItemBlock spruce_stairs = get("spruce_stairs"); + public static final ItemCloth stained_glass = get("stained_glass"); + public static final ItemCloth stained_glass_pane = get("stained_glass_pane"); + public static final ItemCloth stained_hardened_clay = get("stained_hardened_clay"); + public static final ItemStick stick = get("stick"); + public static final ItemPiston sticky_piston = get("sticky_piston"); + public static final ItemBlock stone = get("stone"); + public static final ItemAxe stone_axe = get("stone_axe"); + public static final ItemButton stone_button = get("stone_button"); + public static final ItemHoe stone_hoe = get("stone_hoe"); + public static final ItemPickaxe stone_pickaxe = get("stone_pickaxe"); + public static final ItemPressurePlate stone_pressure_plate = get("stone_pressure_plate"); + public static final ItemShovel stone_shovel = get("stone_shovel"); + public static final ItemSlab stone_slab = get("stone_slab"); + public static final ItemBlock stone_stairs = get("stone_stairs"); + public static final ItemSword stone_sword = get("stone_sword"); + public static final ItemMultiTexture stonebrick = get("stonebrick"); + public static final ItemSlab stonebrick_slab = get("stonebrick_slab"); + public static final ItemBlock stonebrick_stairs = get("stonebrick_stairs"); + public static final ItemSmallBlock string = get("string"); + public static final Item sugar = get("sugar"); + public static final ItemMetalBlock sulfur_block = get("sulfur_block"); + public static final ItemMetalBlock sulfur_ore = get("sulfur_ore"); + public static final ItemMetal sulfur_powder = get("sulfur_powder"); + public static final ItemColored tallgrass = get("tallgrass"); + public static final ItemAxe thetium_axe = get("thetium_axe"); + public static final ItemBlock thetium_block = get("thetium_block"); + public static final ItemArmor thetium_boots = get("thetium_boots"); + public static final ItemArmor thetium_chestplate = get("thetium_chestplate"); + public static final ItemArmor thetium_helmet = get("thetium_helmet"); + public static final ItemHoe thetium_hoe = get("thetium_hoe"); + public static final ItemArmor thetium_leggings = get("thetium_leggings"); + public static final ItemBlock thetium_ore = get("thetium_ore"); + public static final ItemPickaxe thetium_pickaxe = get("thetium_pickaxe"); + public static final ItemShovel thetium_shovel = get("thetium_shovel"); + public static final ItemSword thetium_sword = get("thetium_sword"); + public static final Item thi_fragment = get("thi_fragment"); + public static final ItemBlock tian = get("tian"); + public static final ItemDoor tian_door = get("tian_door"); + public static final ItemFence tian_fence = get("tian_fence"); + public static final ItemBlock tian_fence_gate = get("tian_fence_gate"); + public static final ItemLeaves tian_leaves = get("tian_leaves"); + public static final ItemBlock tian_log = get("tian_log"); + public static final ItemBlock tian_planks = get("tian_planks"); + public static final ItemBlock tian_reactor = get("tian_reactor"); + public static final ItemBlock tian_sapling = get("tian_sapling"); + public static final ItemSlab tian_slab = get("tian_slab"); + public static final ItemBlock tian_soil = get("tian_soil"); + public static final ItemBlock tian_stairs = get("tian_stairs"); + public static final ItemMetalBlock tin_block = get("tin_block"); + public static final ItemMetal tin_ingot = get("tin_ingot"); + public static final ItemMetalBlock tin_ore = get("tin_ore"); + public static final ItemMetalBlock titanium_block = get("titanium_block"); + public static final ItemMetal titanium_ingot = get("titanium_ingot"); + public static final ItemMetalBlock titanium_ore = get("titanium_ore"); + public static final ItemTNT tnt = get("tnt"); + public static final ItemMinecart tnt_minecart = get("tnt_minecart"); + public static final ItemBlock torch = get("torch"); + public static final ItemBlock trapdoor = get("trapdoor"); + public static final ItemChest trapped_chest = get("trapped_chest"); + public static final ItemBlock tripwire_hook = get("tripwire_hook"); + public static final ItemMetalBlock tungsten_block = get("tungsten_block"); + public static final ItemMetal tungsten_ingot = get("tungsten_ingot"); + public static final ItemMetalBlock tungsten_ore = get("tungsten_ore"); + public static final ItemMetalBlock uranium_block = get("uranium_block"); + public static final ItemMetal uranium_ingot = get("uranium_ingot"); + public static final ItemMetalBlock uranium_ore = get("uranium_ore"); + public static final ItemMetalBlock vanadium_block = get("vanadium_block"); + public static final ItemMetal vanadium_ingot = get("vanadium_ingot"); + public static final ItemMetalBlock vanadium_ore = get("vanadium_ore"); + public static final ItemColored vine = get("vine"); + public static final ItemEditWand wand = get("wand"); + public static final ItemBlock warp_chest = get("warp_chest"); + public static final ItemBucket water_bucket = get("water_bucket"); + public static final ItemLilyPad waterlily = get("waterlily"); + public static final ItemWeatherToken weather_token_chilled = get("weather_token_chilled"); + public static final ItemWeatherToken weather_token_clear = get("weather_token_clear"); + public static final ItemWeatherToken weather_token_cold = get("weather_token_cold"); + public static final ItemWeatherToken weather_token_fire = get("weather_token_fire"); + public static final ItemWeatherToken weather_token_fog = get("weather_token_fog"); + public static final ItemWeatherToken weather_token_frost = get("weather_token_frost"); + public static final ItemWeatherToken weather_token_hail = get("weather_token_hail"); + public static final ItemWeatherToken weather_token_hailstorm = get("weather_token_hailstorm"); + public static final ItemWeatherToken weather_token_hot = get("weather_token_hot"); + public static final ItemWeatherToken weather_token_ice = get("weather_token_ice"); + public static final ItemWeatherToken weather_token_iceage = get("weather_token_iceage"); + public static final ItemWeatherToken weather_token_inferno = get("weather_token_inferno"); + public static final ItemWeatherToken weather_token_rain = get("weather_token_rain"); + public static final ItemWeatherToken weather_token_snow = get("weather_token_snow"); + public static final ItemWeatherToken weather_token_snowstorm = get("weather_token_snowstorm"); + public static final ItemWeatherToken weather_token_storm = get("weather_token_storm"); + public static final ItemWeatherToken weather_token_thunder = get("weather_token_thunder"); + public static final ItemBlock web = get("web"); + public static final ItemSeeds wheat = get("wheat"); + public static final Item wheats = get("wheats"); + public static final ItemBed white_bed = get("white_bed"); + public static final ItemAxe wood_axe = get("wood_axe"); + public static final ItemHoe wood_hoe = get("wood_hoe"); + public static final ItemPickaxe wood_pickaxe = get("wood_pickaxe"); + public static final ItemShovel wood_shovel = get("wood_shovel"); + public static final ItemSword wood_sword = get("wood_sword"); + public static final ItemButton wooden_button = get("wooden_button"); + public static final ItemPressurePlate wooden_pressure_plate = get("wooden_pressure_plate"); + public static final ItemCloth wool = get("wool"); + public static final ItemBlock workbench = get("workbench"); + public static final Item writable_book = get("writable_book"); + public static final Item written_book = get("written_book"); + public static final ItemMetalBlock zinc_block = get("zinc_block"); + public static final ItemMetal zinc_ingot = get("zinc_ingot"); + public static final ItemMetalBlock zinc_ore = get("zinc_ore"); + public static final ItemBucket recursive_springwater_bucket = get("recursive_springwater_bucket"); + public static final ItemBucket springwater_bucket = get("springwater_bucket"); + + private static T get(String id) { + if(!ItemRegistry.REGISTRY.containsKey(id)) + throw new RuntimeException("Gegenstand " + id + " existiert nicht"); + return (T)ItemRegistry.REGISTRY.getObject(id); + } + + static { + if(Util.DEVMODE) { + Set items = Sets.newHashSet(ItemRegistry.REGISTRY); + for(Field field : Items.class.getDeclaredFields()) { + if(Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers()) && Item.class.isAssignableFrom(field.getType())) + try { + items.remove(field.get(null)); + } + catch(IllegalArgumentException | IllegalAccessException e) { + Util.throwUnchecked(e); + } + } + for(Iterator iter = items.iterator(); iter.hasNext();) { + Item item = iter.next(); + if(item instanceof ItemNpcSpawner || item instanceof ItemMonsterPlacer) + iter.remove(); + } + if(!items.isEmpty()) { + List list = Lists.newArrayList(items); + Collections.sort(list, Comparator.comparing(item -> ItemRegistry.getNameFromItem(item))); + System.err.printf("\n*** -------------------------------------------------------------- ***\n\n"); + for(Item item : list) { + String name = ItemRegistry.getNameFromItem(item); + System.err.printf("\tpublic static final %s %s = get(\"%s\");\n", item.getClass().getSimpleName(), name, name); + } + System.err.printf("\n^^^ " + Items.class.getCanonicalName() + ": Gegenstandsliste ist unvollständig, Bitte neuen Quellcode einfügen ^^^\n"); + System.exit(1); + } + } + } +} diff --git a/java/src/game/init/MetalType.java b/common/src/main/java/common/init/MetalType.java similarity index 98% rename from java/src/game/init/MetalType.java rename to common/src/main/java/common/init/MetalType.java index 3b6ea86..77b63bf 100755 --- a/java/src/game/init/MetalType.java +++ b/common/src/main/java/common/init/MetalType.java @@ -1,6 +1,6 @@ -package game.init; +package common.init; -import game.color.TextColor; +import common.color.TextColor; public enum MetalType { IRON("iron", 26, "Fe", "Eisen", 0, new ToolMaterial(2, 8.0f, 0.0f, 250, 6.0F, 2, 14, true, 15, 9, 2, 6, 5, 2).setMagnetic()), diff --git a/java/src/game/init/NameRegistry.java b/common/src/main/java/common/init/NameRegistry.java similarity index 99% rename from java/src/game/init/NameRegistry.java rename to common/src/main/java/common/init/NameRegistry.java index fcd8d2f..5b9583e 100755 --- a/java/src/game/init/NameRegistry.java +++ b/common/src/main/java/common/init/NameRegistry.java @@ -1,6 +1,6 @@ -package game.init; +package common.init; -import game.rng.Random; +import common.rng.Random; /** * This class is released under the GNU general public license (GPL) diff --git a/java/src/game/init/OreType.java b/common/src/main/java/common/init/OreType.java similarity index 98% rename from java/src/game/init/OreType.java rename to common/src/main/java/common/init/OreType.java index 95b80ff..764b288 100755 --- a/java/src/game/init/OreType.java +++ b/common/src/main/java/common/init/OreType.java @@ -1,4 +1,4 @@ -package game.init; +package common.init; public enum OreType { DIAMOND("diamond", "Diamant", new ToolMaterial(3, 12.0f, 2.0f, 1561, 8.0F, 3, 10, true, 33, 10, 3, 8, 6, 3), "diamond", 3, 1, 0), diff --git a/common/src/main/java/common/init/Registry.java b/common/src/main/java/common/init/Registry.java new file mode 100755 index 0000000..fecbfde --- /dev/null +++ b/common/src/main/java/common/init/Registry.java @@ -0,0 +1,17 @@ +package common.init; + +public abstract class Registry { + public static void register() { + NameRegistry.register(); + BlockRegistry.register(); + FlammabilityRegistry.register(); + SpeciesRegistry.register(); + EntityRegistry.registerEggs(); + ItemRegistry.register(); + TileRegistry.register(); + CraftingRegistry.register(); + SmeltingRegistry.register(); + EntityRegistry.register(); + DispenserRegistry.register(); + } +} diff --git a/java/src/game/init/SmeltingRegistry.java b/common/src/main/java/common/init/SmeltingRegistry.java similarity index 95% rename from java/src/game/init/SmeltingRegistry.java rename to common/src/main/java/common/init/SmeltingRegistry.java index b8e3e6f..4a316bc 100755 --- a/java/src/game/init/SmeltingRegistry.java +++ b/common/src/main/java/common/init/SmeltingRegistry.java @@ -1,18 +1,18 @@ -package game.init; +package common.init; import java.util.Map; import java.util.Map.Entry; + +import common.block.Block; +import common.block.artificial.BlockStoneBrick; +import common.collect.Maps; +import common.color.DyeColor; +import common.item.Item; +import common.item.ItemFishFood; +import common.item.ItemStack; + import java.util.Set; -import game.collect.Maps; - -import game.block.Block; -import game.block.BlockStoneBrick; -import game.color.DyeColor; -import game.item.Item; -import game.item.ItemFishFood; -import game.item.ItemStack; - public abstract class SmeltingRegistry { private static final Map smeltingList = Maps.newHashMap(); diff --git a/java/src/game/init/SoundEvent.java b/common/src/main/java/common/init/SoundEvent.java similarity index 75% rename from java/src/game/init/SoundEvent.java rename to common/src/main/java/common/init/SoundEvent.java index 716f5d2..4ab1d86 100755 --- a/java/src/game/init/SoundEvent.java +++ b/common/src/main/java/common/init/SoundEvent.java @@ -1,13 +1,4 @@ -package game.init; - -import java.io.BufferedInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import game.audio.CodecJOrbis; -import game.log.Log; -import game.rng.Random; -import game.util.FileUtils; +package common.init; public enum SoundEvent { CLOTH("cloth1", "cloth2", "cloth3", "cloth4"), @@ -118,57 +109,21 @@ public enum SoundEvent { WOLF_PANTING("wolf_panting"), WOLF_SHAKE("wolf_shake"), WOLF_WHINE("wolf_whine"), + + FOX_DEATH("fox_death"), + FOX_HURT("fox_hurt1", "fox_hurt2"), SLIME_ATTACK("slime_attack1", "slime_attack2"), SLIME_BIG("slime_big1", "slime_big2", "slime_big3", "slime_big4"), SLIME_SMALL("slime_small1", "slime_small2", "slime_small3", "slime_small4", "slime_small5"); - - private static final Random RANDOM = new Random(); private final String[] sounds; - private final short[][] buffers; - - public static void loadSounds() { - int n = 0; - for(SoundEvent entry : SoundEvent.values()) { - for(int z = 0; z < entry.sounds.length; z++) { - String sound = entry.sounds[z]; - Log.SOUND.trace("Lade Sound %s", sound); - entry.buffers[z] = readOgg("sounds/" + sound + ".ogg"); - } - } - } - - private static short[] readOgg(String filename) { - InputStream in = null; - try { - in = new BufferedInputStream(FileUtils.getResource(filename)); - return CodecJOrbis.readAll(in); - } - catch(FileNotFoundException e) { - Log.IO.error("Fehler beim Lesen von OPUS-Datei '%s': Datei nicht gefunden", filename); - return null; - } - catch(Exception e) { - Log.IO.error("Fehler beim Lesen von OPUS-Datei '%s': %s", filename, e.getMessage()); - return null; - } - finally { - try { - if(in != null) - in.close(); - } - catch(IOException e) { - } - } - } private SoundEvent(String ... sounds) { this.sounds = sounds; - this.buffers = new short[sounds.length][]; } - public short[] getBuffer() { - return RANDOM.pick(this.buffers); + public String[] getSounds() { + return this.sounds; } } diff --git a/java/src/game/init/SpeciesRegistry.java b/common/src/main/java/common/init/SpeciesRegistry.java similarity index 85% rename from java/src/game/init/SpeciesRegistry.java rename to common/src/main/java/common/init/SpeciesRegistry.java index e6df5e4..9126171 100755 --- a/java/src/game/init/SpeciesRegistry.java +++ b/common/src/main/java/common/init/SpeciesRegistry.java @@ -1,41 +1,40 @@ -package game.init; +package common.init; import java.util.List; import java.util.Map; import java.util.Set; -import game.collect.Lists; -import game.collect.Maps; -import game.collect.Sets; - -import game.entity.npc.EntityArachnoid; -import game.entity.npc.EntityBloodElf; -import game.entity.npc.EntityChaosMarine; -import game.entity.npc.EntityCpu; -import game.entity.npc.EntityCultivator; -import game.entity.npc.EntityDarkMage; -import game.entity.npc.EntityDwarf; -import game.entity.npc.EntityElf; -import game.entity.npc.EntityFireDemon; -import game.entity.npc.EntityGargoyle; -import game.entity.npc.EntityGoblin; -import game.entity.npc.EntityHaunter; -import game.entity.npc.EntityHuman; -import game.entity.npc.EntityMage; -import game.entity.npc.EntityMagma; -import game.entity.npc.EntityMetalhead; -import game.entity.npc.EntityNPC; -import game.entity.npc.EntityOrc; -import game.entity.npc.EntityPrimarch; -import game.entity.npc.EntitySlime; -import game.entity.npc.EntitySpaceMarine; -import game.entity.npc.EntitySpirit; -import game.entity.npc.EntityTiefling; -import game.entity.npc.EntityUndead; -import game.entity.npc.EntityVampire; -import game.entity.npc.EntityWoodElf; -import game.entity.npc.EntityZombie; -import game.entity.npc.SpeciesInfo; +import common.collect.Lists; +import common.collect.Maps; +import common.collect.Sets; +import common.entity.npc.EntityArachnoid; +import common.entity.npc.EntityBloodElf; +import common.entity.npc.EntityChaosMarine; +import common.entity.npc.EntityCpu; +import common.entity.npc.EntityCultivator; +import common.entity.npc.EntityDarkMage; +import common.entity.npc.EntityDwarf; +import common.entity.npc.EntityElf; +import common.entity.npc.EntityFireDemon; +import common.entity.npc.EntityGargoyle; +import common.entity.npc.EntityGoblin; +import common.entity.npc.EntityHaunter; +import common.entity.npc.EntityHuman; +import common.entity.npc.EntityMage; +import common.entity.npc.EntityMagma; +import common.entity.npc.EntityMetalhead; +import common.entity.npc.EntityNPC; +import common.entity.npc.EntityOrc; +import common.entity.npc.EntityPrimarch; +import common.entity.npc.EntitySlime; +import common.entity.npc.EntitySpaceMarine; +import common.entity.npc.EntitySpirit; +import common.entity.npc.EntityTiefling; +import common.entity.npc.EntityUndead; +import common.entity.npc.EntityVampire; +import common.entity.npc.EntityWoodElf; +import common.entity.npc.EntityZombie; +import common.entity.npc.SpeciesInfo; public abstract class SpeciesRegistry { public static enum ModelType { diff --git a/common/src/main/java/common/init/TileRegistry.java b/common/src/main/java/common/init/TileRegistry.java new file mode 100755 index 0000000..4ebcac4 --- /dev/null +++ b/common/src/main/java/common/init/TileRegistry.java @@ -0,0 +1,55 @@ +package common.init; + +import java.util.Map; + +import common.collect.Maps; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityBanner; +import common.tileentity.TileEntityBeacon; +import common.tileentity.TileEntityBrewingStand; +import common.tileentity.TileEntityChest; +import common.tileentity.TileEntityComparator; +import common.tileentity.TileEntityDaylightDetector; +import common.tileentity.TileEntityDispenser; +import common.tileentity.TileEntityDropper; +import common.tileentity.TileEntityEnchantmentTable; +import common.tileentity.TileEntityFurnace; +import common.tileentity.TileEntityHopper; +import common.tileentity.TileEntityMobSpawner; +import common.tileentity.TileEntityPiston; +import common.tileentity.TileEntitySign; +import common.tileentity.TileEntityTianReactor; + +public abstract class TileRegistry { + public static final Map> NAME_TO_CLASS = Maps.>newHashMap(); + public static final Map, String> CLASS_TO_NAME = Maps., String>newHashMap(); + public static final Map, Integer> CLASS_TO_ID = Maps., Integer>newHashMap(); + + private static int nextId; + + private static void addMapping(Class cl, String id) { + if(NAME_TO_CLASS.containsKey(id)) + throw new IllegalArgumentException("Duplicate id: " + id); + NAME_TO_CLASS.put(id, cl); + CLASS_TO_NAME.put(cl, id); + CLASS_TO_ID.put(cl, ++nextId); + } + + static void register() { + addMapping(TileEntityFurnace.class, "Furnace"); + addMapping(TileEntityChest.class, "Chest"); + addMapping(TileEntityDispenser.class, "Trap"); + addMapping(TileEntityDropper.class, "Dropper"); + addMapping(TileEntitySign.class, "Sign"); + addMapping(TileEntityPiston.class, "Piston"); + addMapping(TileEntityBrewingStand.class, "Cauldron"); + addMapping(TileEntityEnchantmentTable.class, "EnchantTable"); + addMapping(TileEntityBeacon.class, "Beacon"); + addMapping(TileEntityDaylightDetector.class, "DLDetector"); + addMapping(TileEntityHopper.class, "Hopper"); + addMapping(TileEntityComparator.class, "Comparator"); + addMapping(TileEntityBanner.class, "Banner"); + addMapping(TileEntityTianReactor.class, "TianReactor"); + addMapping(TileEntityMobSpawner.class, "MobSpawner"); + } +} diff --git a/common/src/main/java/common/init/ToolMaterial.java b/common/src/main/java/common/init/ToolMaterial.java new file mode 100755 index 0000000..5cf8dd3 --- /dev/null +++ b/common/src/main/java/common/init/ToolMaterial.java @@ -0,0 +1,155 @@ +package common.init; + +import java.util.Set; + +import common.attributes.UsageSlot; +import common.collect.Sets; +import common.item.Item; + +public class ToolMaterial { + private static final int[] MAX_DAMAGE = new int[] {11, 16, 15, 13}; + private static final float[] RAD_REDUCE = new float[] {1.0f, 1.7f, 1.6f, 1.4f}; + private static final float[] MAG_REDUCE = new float[] {1.0f, 1.2f, 1.1f, 1.0f}; + + private final int harvestLevel; + private final int durability; + private final float efficiency; + private final int damage; + private final float radiationResistance; + private final float magicResistance; + private final int enchantability; + private final int maxDamageFactor; + private final int[] damageReduction; + private final int armorEnchantability; + private final boolean tools; + private final boolean weapons; + private final boolean extras; + private final Set repair = Sets.newHashSet(); + + private boolean magnetic; + private int defColor = 0xffffffff; + + private ToolMaterial(float rad, float mag, int level, int uses, float efficiency, int damage, int ench, boolean tools, boolean weapons, + boolean extras, int auses, int aench, int r1, int r2, int r3, int r4) { + this.harvestLevel = level; + this.durability = uses; + this.efficiency = efficiency; + this.damage = damage; + this.enchantability = ench; + this.maxDamageFactor = auses; + this.damageReduction = new int[] {r1, r2, r3, r4}; + this.armorEnchantability = aench; + this.radiationResistance = rad; + this.magicResistance = mag; + this.tools = tools; + this.weapons = weapons; + this.extras = extras; + } + + protected ToolMaterial(int level) { + this(0.0f, 0.0f, level, 0, 0.0f, 0, 0, false, false, false, 0, 0, 0, 0, 0, 0); + } + + protected ToolMaterial(int level, int uses, float efficiency, int damage, int ench, boolean weapons) { + this(0.0f, 0.0f, level, uses, efficiency, damage, ench, true, weapons, false, 0, ench, 0, 0, 0, 0); + } + + protected ToolMaterial(int level, float rad, float mag, int uses, int damage, int ench, int auses, int aench, int r1, int r2, int r3, int r4) { + this(rad, mag, level, uses, 0.0F, damage, ench, false, true, false, auses, aench, r1, r2, r3, r4); + } + + protected ToolMaterial(int level, float rad, float mag, int auses, int aench, int r1, int r2, int r3, int r4) { + this(rad, mag, 0, 0, 0.0F, 0, 0, false, false, false, auses, aench, r1, r2, r3, r4); + } + + protected ToolMaterial(int level, float rad, float mag, int uses, float efficiency, int damage, int ench, boolean extras, int auses, int aench, + int r1, int r2, int r3, int r4) { + this(rad, mag, level, uses, efficiency, damage, ench, true, true, extras, auses, aench, r1, r2, r3, r4); + } + + protected ToolMaterial setDyeable(int defColor) { + this.defColor = defColor; + return this; + } + + protected ToolMaterial setMagnetic() { + this.magnetic = true; + return this; + } + + protected void addRepairItem(Item item) { + this.repair.add(item); + } + + public boolean hasArmor() { + return this.maxDamageFactor > 0; + } + + public boolean hasTools() { + return this.tools; + } + + public boolean hasWeapons() { + return this.weapons; + } + + public boolean hasExtras() { + return this.extras; + } + + public int getDurability() { + return this.durability; + } + + public float getEfficiency() { + return this.efficiency; + } + + public int getDamage() { + return this.damage; + } + + public int getHarvestLevel() { + return this.harvestLevel; + } + + public int getEnchantability() { + return this.enchantability; + } + + public boolean isRepairItem(Item item) { + return this.repair.contains(item); + } + + public int getDurability(UsageSlot armorType) { + return armorType.getArmorSlot() < 0 ? 0 : MAX_DAMAGE[armorType.getArmorSlot()] * this.maxDamageFactor; + } + + public float getRadiationReduction(UsageSlot armorType) { + return armorType.getArmorSlot() < 0 ? 0.0f : RAD_REDUCE[armorType.getArmorSlot()] * this.radiationResistance; + } + + public float getMagicReduction(UsageSlot armorType) { + return armorType.getArmorSlot() < 0 ? 0.0f : MAG_REDUCE[armorType.getArmorSlot()] * this.magicResistance; + } + + public int getDamageReduction(UsageSlot armorType) { + return armorType.getArmorSlot() < 0 ? 0 : this.damageReduction[armorType.getArmorSlot()]; + } + + public int getArmorEnchantability() { + return this.armorEnchantability; + } + + public boolean canBeDyed() { + return this.defColor != 0xffffffff; + } + + public int getDefaultColor() { + return this.defColor; + } + + public boolean isMagnetic() { + return this.magnetic; + } +} \ No newline at end of file diff --git a/java/src/game/init/ToolType.java b/common/src/main/java/common/init/ToolType.java similarity index 97% rename from java/src/game/init/ToolType.java rename to common/src/main/java/common/init/ToolType.java index 94cff02..893269f 100755 --- a/java/src/game/init/ToolType.java +++ b/common/src/main/java/common/init/ToolType.java @@ -1,4 +1,4 @@ -package game.init; +package common.init; public enum ToolType { WOOD("wood", "Holz", new ToolMaterial(0, 59, 2.0F, 0, 15, true), WoodType.getNames("planks")), diff --git a/java/src/game/init/TradeRegistry.java b/common/src/main/java/common/init/TradeRegistry.java similarity index 96% rename from java/src/game/init/TradeRegistry.java rename to common/src/main/java/common/init/TradeRegistry.java index 5ff6029..c9d1356 100755 --- a/java/src/game/init/TradeRegistry.java +++ b/common/src/main/java/common/init/TradeRegistry.java @@ -1,14 +1,14 @@ -package game.init; +package common.init; -import game.color.DyeColor; -import game.enchantment.Enchantment; -import game.enchantment.EnchantmentHelper; -import game.enchantment.RngEnchantment; -import game.item.Item; -import game.item.ItemStack; -import game.rng.Random; -import game.village.MerchantRecipe; -import game.village.MerchantRecipeList; +import common.color.DyeColor; +import common.enchantment.Enchantment; +import common.enchantment.EnchantmentHelper; +import common.enchantment.RngEnchantment; +import common.item.Item; +import common.item.ItemStack; +import common.rng.Random; +import common.village.MerchantRecipe; +import common.village.MerchantRecipeList; public abstract class TradeRegistry { public interface ITradeList { @@ -179,7 +179,7 @@ public abstract class TradeRegistry { static class BookForGem implements ITradeList { public void modifyMerchantRecipeList(MerchantRecipeList recipeList, Random random) { - Enchantment enchantment = random.pick(Enchantment.enchantmentsBookList); + Enchantment enchantment = random.pick(Enchantment.values()); int i = random.range(enchantment.getMinLevel(), enchantment.getMaxLevel()); ItemStack itemstack = Items.enchanted_book.getEnchantedItemStack(new RngEnchantment(enchantment, i)); int j = 2 + random.zrange(5 + i * 10) + 3 * i; diff --git a/java/src/game/init/UniverseRegistry.java b/common/src/main/java/common/init/UniverseRegistry.java similarity index 78% rename from java/src/game/init/UniverseRegistry.java rename to common/src/main/java/common/init/UniverseRegistry.java index e42c48c..3c894be 100755 --- a/java/src/game/init/UniverseRegistry.java +++ b/common/src/main/java/common/init/UniverseRegistry.java @@ -1,42 +1,40 @@ -package game.init; +package common.init; import java.util.List; import java.util.Map; import java.util.Map.Entry; + +import common.biome.Biome; +import common.block.BlockColored; +import common.block.foliage.LeavesType; +import common.block.natural.BlockSand; +import common.collect.Lists; +import common.collect.Maps; +import common.collect.Sets; +import common.color.DyeColor; +import common.dimension.Area; +import common.dimension.CloudType; +import common.dimension.DimType; +import common.dimension.Dimension; +import common.dimension.Domain; +import common.dimension.Galaxy; +import common.dimension.Moon; +import common.dimension.Planet; +import common.dimension.Sector; +import common.dimension.Semi; +import common.dimension.Space; +import common.dimension.Star; +import common.dimension.Dimension.GeneratorType; +import common.dimension.Dimension.ReplacerType; +import common.log.Log; +import common.rng.Random; +import common.tags.TagObject; +import common.util.PortalType; +import common.world.State; +import common.world.Weather; + import java.util.Set; -import game.collect.Lists; -import game.collect.Maps; -import game.collect.Sets; - -import game.biome.Biome; -import game.block.BlockColored; -import game.block.BlockSand; -import game.block.LeavesType; -import game.color.DyeColor; -import game.dimension.Area; -import game.dimension.DimType; -import game.dimension.Dimension; -import game.dimension.Dimension.GeneratorType; -import game.dimension.Dimension.ReplacerType; -import game.dimension.Domain; -import game.dimension.Galaxy; -import game.dimension.Moon; -import game.dimension.Planet; -import game.dimension.Sector; -import game.dimension.Semi; -import game.dimension.Space; -import game.dimension.Star; -import game.log.Log; -import game.nbt.NBTException; -import game.nbt.NBTParser; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.rng.Random; -import game.world.PortalType; -import game.world.State; -import game.world.Weather; - public abstract class UniverseRegistry { public static final int MORE_DIM_ID = 1000; public static final long EARTH_YEAR = 8766144L; @@ -91,167 +89,167 @@ public abstract class UniverseRegistry { } } - public static void loadNbt(NBTTagCompound tag) { - NBTTagList list = tag.getTagList("Dimensions", 10); - for(int z = 0; z < list.tagCount(); z++) { - Dimension dim = Dimension.getByNbt(list.getCompoundTagAt(z)); + public static void fromTags(TagObject tag) { + List list = tag.getList("Dimensions"); + for(int z = 0; z < list.size(); z++) { + Dimension dim = Dimension.getByTag(list.get(z)); if(!REGISTRY.containsKey(dim.getDimensionId()) && !ALIASES.containsKey(dim.getDimensionName())) register(dim); } - list = tag.getTagList("Names", 10); - for(int z = 0; z < list.tagCount(); z++) { - NBTTagCompound data = list.getCompoundTagAt(z); + list = tag.getList("Names"); + for(int z = 0; z < list.size(); z++) { + TagObject data = list.get(z); String id = data.getString("ID"); // if(BASE_ALIASES.containsKey(id)) { Dimension dim = ALIASES.get(id); if(dim != null && dim != Space.INSTANCE) - dim.readNbt(data); + dim.readTags(data); // } } - list = tag.getTagList("Sectors", 10); - for(int z = 0; z < list.tagCount(); z++) { - NBTTagCompound data = list.getCompoundTagAt(z); + list = tag.getList("Sectors"); + for(int z = 0; z < list.size(); z++) { + TagObject data = list.get(z); String id = data.getString("ID"); Sector sector = SECTORS.get(id); if(sector == null) SECTORS.put(id, sector = new Sector(id)); - sector.readNbt(data); + sector.readTags(data); } - list = tag.getTagList("Galaxies", 10); - for(int z = 0; z < list.tagCount(); z++) { - NBTTagCompound data = list.getCompoundTagAt(z); + list = tag.getList("Galaxies"); + for(int z = 0; z < list.size(); z++) { + TagObject data = list.get(z); String id = data.getString("ID"); Galaxy galaxy = GALAXIES.get(id); if(galaxy == null) GALAXIES.put(id, galaxy = new Galaxy(id)); - galaxy.readNbt(data); + galaxy.readTags(data); } - list = tag.getTagList("Domains", 10); - for(int z = 0; z < list.tagCount(); z++) { - NBTTagCompound data = list.getCompoundTagAt(z); + list = tag.getList("Domains"); + for(int z = 0; z < list.size(); z++) { + TagObject data = list.get(z); String id = data.getString("ID"); Domain domain = DOMAINS.get(id); if(domain == null) DOMAINS.put(id, domain = new Domain(id)); - domain.readNbt(data); + domain.readTags(data); } - list = tag.getTagList("Barycenters", 10); - for(int z = 0; z < list.tagCount(); z++) { - NBTTagCompound link = list.getCompoundTagAt(z); + list = tag.getList("Barycenters"); + for(int z = 0; z < list.size(); z++) { + TagObject link = list.get(z); if(!assign(link.getString("Celestial"), link.getString("Center"))) - Log.JNI.warn("Konnte '" + link.getString("Celestial") + "' nicht zu '" + link.getString("Center") + "' zuweisen"); + Log.TICK.warn("Konnte '" + link.getString("Celestial") + "' nicht zu '" + link.getString("Center") + "' zuweisen"); } } - public static NBTTagCompound saveNbt() { - NBTTagCompound tag = new NBTTagCompound(); + public static TagObject toTags() { + TagObject tag = new TagObject(); - NBTTagList list = new NBTTagList(); + List list = Lists.newArrayList(); for(Dimension dim : DIMENSIONS) { if(!BASE_REGISTRY.containsKey(dim.getDimensionId()) && dim != Space.INSTANCE) - list.appendTag(dim.toNbt()); + list.add(dim.toTags()); } - if(!list.hasNoTags()) - tag.setTag("Dimensions", list); + if(!list.isEmpty()) + tag.setList("Dimensions", list); - list = new NBTTagList(); + list = Lists.newArrayList(); for(Dimension dim : DIMENSIONS) { if(/* BASE_REGISTRY.containsKey(dim.getDimensionId()) */ dim != Space.INSTANCE) { - NBTTagCompound data = new NBTTagCompound(); - dim.writeNbt(data); - if(!data.hasNoTags()) { + TagObject data = new TagObject(); + dim.writeTags(data); + if(!data.isEmpty()) { data.setString("ID", dim.getDimensionName()); - list.appendTag(data); + list.add(data); } } } - if(!list.hasNoTags()) - tag.setTag("Names", list); + if(!list.isEmpty()) + tag.setList("Names", list); - list = new NBTTagList(); + list = Lists.newArrayList(); for(Sector sector : SECTORS.values()) { - NBTTagCompound data = new NBTTagCompound(); - sector.writeNbt(data); - if(!data.hasNoTags()) { + TagObject data = new TagObject(); + sector.writeTags(data); + if(!data.isEmpty()) { data.setString("ID", sector.id); - list.appendTag(data); + list.add(data); } } - if(!list.hasNoTags()) - tag.setTag("Sectors", list); + if(!list.isEmpty()) + tag.setList("Sectors", list); - list = new NBTTagList(); + list = Lists.newArrayList(); for(Galaxy galaxy : GALAXIES.values()) { - NBTTagCompound data = new NBTTagCompound(); - galaxy.writeNbt(data); - if(!data.hasNoTags()) { + TagObject data = new TagObject(); + galaxy.writeTags(data); + if(!data.isEmpty()) { data.setString("ID", galaxy.id); - list.appendTag(data); + list.add(data); } } - if(!list.hasNoTags()) - tag.setTag("Galaxies", list); + if(!list.isEmpty()) + tag.setList("Galaxies", list); - list = new NBTTagList(); + list = Lists.newArrayList(); for(Domain domain : DOMAINS.values()) { - NBTTagCompound data = new NBTTagCompound(); - domain.writeNbt(data); - if(!data.hasNoTags()) { + TagObject data = new TagObject(); + domain.writeTags(data); + if(!data.isEmpty()) { data.setString("ID", domain.id); - list.appendTag(data); + list.add(data); } } - if(!list.hasNoTags()) - tag.setTag("Domains", list); + if(!list.isEmpty()) + tag.setList("Domains", list); - list = new NBTTagList(); + list = Lists.newArrayList(); for(Entry entry : MOON_MAP.entrySet()) { if(BASE_REGISTRY.containsKey(entry.getKey().getDimensionId())) continue; - NBTTagCompound link = new NBTTagCompound(); + TagObject link = new TagObject(); link.setString("Celestial", entry.getKey().getDimensionName()); link.setString("Center", entry.getValue().getDimensionName()); - list.appendTag(link); + list.add(link); } for(Entry entry : PLANET_MAP.entrySet()) { if(BASE_REGISTRY.containsKey(entry.getKey().getDimensionId())) continue; - NBTTagCompound link = new NBTTagCompound(); + TagObject link = new TagObject(); link.setString("Celestial", entry.getKey().getDimensionName()); link.setString("Center", entry.getValue().getDimensionName()); - list.appendTag(link); + list.add(link); } for(Entry entry : STAR_MAP.entrySet()) { if(BASE_REGISTRY.containsKey(entry.getKey().getDimensionId())) continue; - NBTTagCompound link = new NBTTagCompound(); + TagObject link = new TagObject(); link.setString("Celestial", entry.getKey().getDimensionName()); link.setString("Center", entry.getValue().id); - list.appendTag(link); + list.add(link); } for(Entry entry : SECTOR_MAP.entrySet()) { if(BASE_MAP.containsKey(entry.getKey().id)) continue; - NBTTagCompound link = new NBTTagCompound(); + TagObject link = new TagObject(); link.setString("Celestial", entry.getKey().id); link.setString("Center", entry.getValue().id); - list.appendTag(link); + list.add(link); } for(Entry entry : AREA_MAP.entrySet()) { if(BASE_REGISTRY.containsKey(entry.getKey().getDimensionId())) continue; - NBTTagCompound link = new NBTTagCompound(); + TagObject link = new TagObject(); link.setString("Celestial", entry.getKey().getDimensionName()); link.setString("Center", entry.getValue().id); - list.appendTag(link); + list.add(link); } - if(!list.hasNoTags()) - tag.setTag("Barycenters", list); + if(!list.isEmpty()) + tag.setList("Barycenters", list); return tag; } @@ -518,7 +516,7 @@ public abstract class UniverseRegistry { PORTALS.put(portal.ordinal() | 0x7ff00000, BASE_ALIASES.get(dest).getDimensionId()); } - static void register() { + public static void register() { registerGalaxy("Milchstraße", "milkyway"); registerSector("Solar", "solar", "milkyway"); registerDimension("Sol", new Star(2, "sol", 0xff7f00, 274.0f, 5778.0f, Blocks.lava.getState(), 128).setTimeQualifier(1), "solar"); @@ -526,13 +524,13 @@ public abstract class UniverseRegistry { 259.15f).setTimeQualifier(0) .setPerlinGen(Blocks.stone.getState(), Blocks.water.getState(), 63) .setBiomeReplacer(Blocks.gravel.getState()) - .setBiomeGen(Biome.forest, false, 4, 4, 6, 50, 50, Biome.mushroomPlains).enableMobs().enableSnow() - .setFrostBiomes(Biome.icePlains, Biome.icePlains, Biome.icePlains, Biome.coldTaiga, Biome.megaTaiga) - .setColdBiomes(Biome.forest, Biome.extremeHills, Biome.taiga, Biome.plains, Biome.blackened) - .setMediumBiomes(Biome.forest, Biome.roofedForest, Biome.extremeHills, Biome.plains, Biome.birchForest, - Biome.swampland, Biome.jungle, Biome.blackened) - .setHotBiomes(Biome.desert, Biome.desert, Biome.desert, Biome.savanna, Biome.savanna, Biome.plains) - .enableCavesRavines(Blocks.lava.getState()).setDungeons(8).setWorldFloor(Blocks.bedrock.getState()) + .setBiomeGen(Biome.FOREST, false, 4, 4, 6, 50, 50, Biome.MUSHROOMPLAINS).enableMobs().enableSnow() + .setFrostBiomes(Biome.ICEPLAINS, Biome.ICEPLAINS, Biome.ICEPLAINS, Biome.COLDTAIGA, Biome.MEGATAIGA) + .setColdBiomes(Biome.FOREST, Biome.EXTREMEHILLS, Biome.TAIGA, Biome.PLAINS) + .setMediumBiomes(Biome.FOREST, Biome.ROOFEDFOREST, Biome.EXTREMEHILLS, Biome.PLAINS, Biome.BIRCHFOREST, + Biome.SWAMPLAND, Biome.JUNGLE) + .setHotBiomes(Biome.DESERT, Biome.DESERT, Biome.DESERT, Biome.SAVANNA, Biome.SAVANNA, Biome.PLAINS) + .enableCavesRavines(Blocks.lava.getState()).setDungeons(8) .addLake(Blocks.water.getState(), null, Blocks.grass.getState(), 4, 0, 255, false) .addLake(Blocks.lava.getState(), Blocks.stone.getState(), null, 8, 8, 255, true) .addLiquid(Blocks.flowing_water.getState(), 50, 8, 255, false) @@ -549,7 +547,7 @@ public abstract class UniverseRegistry { .addOre(Blocks.cinnabar_ore.getState(), 1, 0, 11, 0, 24, false) .enableVillages().enableMineshafts().enableScattered().enableStrongholds(), "sol"); registerDimension("Luna", new Moon(3, "luna", 0x333333, 0x333333, 655728L, 655728L, 1.62f, 210.0f, 8) - .setPerlinGen(Blocks.moon_rock.getState(), Blocks.air.getState(), 63).setBiome(Biome.moon) + .setPerlinGen(Blocks.moon_rock.getState(), Blocks.air.getState(), 63).setBiome(Biome.MOON) .setTimeQualifier(1), "terra"); registerDimension("Merkur", new Planet(4, "mercury", 0x666666, 0x535353, 0x858585, 2111297L, 1407509L, 3.7f, 440.0f) @@ -592,9 +590,8 @@ public abstract class UniverseRegistry { registerDimension("Gi'rok", new Star(100, "girok", 0xff8f00, 232.0f, 5220.0f, Blocks.lava.getState(), 112).setTimeQualifier(2), "solar"); registerDimension("'Elbenplanet Gharoth'", new Planet(101, "gharoth", 0xffffffff, 0xc0d8ff, 0xffffff, 4837386L, 52960L, 30.0f, 10.0f, 257.3f) .setTimeQualifier(2).setSimpleGen(Blocks.dirt.getState(), Blocks.water.getState(), 64) - .setSimpleReplacer(Blocks.gravel.getState(), Blocks.sand.getState()).setBiome(Biome.elvenForest) + .setSimpleReplacer(Blocks.gravel.getState(), Blocks.sand.getState()).setBiome(Biome.ELVENFOREST) .enableCaves(Blocks.air.getState()).setDungeons(4).enableMobs().enableSnow() - .setWorldFloor(Blocks.bedrock.getState()) .addLake(Blocks.water.getState(), null, Blocks.grass.getState(), 4, 0, 255, false) .addLake(Blocks.lava.getState(), null, null, 8, 8, 255, true) .addLiquid(Blocks.flowing_water.getState(), 50, 8, 255, false) @@ -603,9 +600,8 @@ public abstract class UniverseRegistry { .addOre(Blocks.gyriyn_ore.getState(), 0, 2, 3, 0, 12, false), "girok"); registerDimension("'Vampirplanet Transsylvanien'", new Planet(102, "transylvania", 0xffffffff, 0xc0d8ff, 0xffffff, 33850466L, 49760L, 20.0f, 10.0f, 255.5f) .setTimeQualifier(5).setPerlinGen(Blocks.rock.getState(), Blocks.water.getState(), 63) - .setBiomeReplacer(Blocks.gravel.getState()).setBiomeGen(Biome.forest, true, 5, 3, 3, 30) + .setBiomeReplacer(Blocks.gravel.getState()).setBiomeGen(Biome.FOREST, true, 5, 3, 3, 30) .enableCavesRavines(Blocks.lava.getState()).setDungeons(10).enableMobs().enableSnow() - .setWorldFloor(Blocks.bedrock.getState()) .addLake(Blocks.water.getState(), null, Blocks.grass.getState(), 4, 0, 255, false) .addLake(Blocks.lava.getState(), null, null, 8, 8, 255, true) .addLiquid(Blocks.flowing_water.getState(), 50, 8, 255, false) @@ -615,14 +611,13 @@ public abstract class UniverseRegistry { .addOre(Blocks.ardite_ore.getState(), 0, 2, 3, 0, 12, false) .addOre(Blocks.nichun_ore.getState(), 0, 10, 1, 0, 10, false), "girok"); registerDimension("'Eismond Yrdinath'", new Moon(103, "yrdinath", 0xccccff, 0xccccff, 46743637L, 17460L, 2.5f, 239.15f, 8).setTimeQualifier(4) - .setPerlinGen(Blocks.snow.getState(), Blocks.ice.getState(), 63).setBiome(Biome.snowLand) - .setWorldFloor(Blocks.air.getState()).enableMobs().enableSnow().setWeather(Weather.SNOW), "transylvania"); + .setPerlinGen(Blocks.snow.getState(), Blocks.ice.getState(), 63).setBiome(Biome.SNOWLAND) + .enableMobs().enableSnow().setWeather(Weather.SNOW), "transylvania"); registerDimension("'Wüstenplanet Me'sar'", new Planet(104, "mesar", 0xff7f3f, 0xff6022, 0xff6f00, 56643366L, 87340L, 11.0f, 333.15f) .setTimeQualifier(5).setPerlinGen(Blocks.rock.getState(), Blocks.air.getState(), 63) .setBiomeReplacer(Blocks.sand.getState().withProperty(BlockSand.VARIANT, BlockSand.EnumType.RED_SAND)) - .setBiomeGen(Biome.mesa, true, 3, 1000, 100000, 100000) + .setBiomeGen(Biome.MESA, true, 3, 1000, 100000, 100000) .enableCavesRavines(Blocks.lava.getState()).enableMobs() - .setWorldFloor(Blocks.bedrock.getState()) .addLake(Blocks.lava.getState(), null, null, 8, 8, 255, true) .addLiquid(Blocks.flowing_lava.getState(), 20, 8, 255, true) .addOre(Blocks.iron_ore.getState(), 6, 2, 24, 0, 64, false) @@ -637,16 +632,15 @@ public abstract class UniverseRegistry { registerDimension("Ov'rol", new Star(120, "ovrol", 0x000000, 302.0f, 12666.0f, Blocks.goo.getState(), 192), "blvck"); registerDimension("'Schwarzplanet'", new Planet(121, "blackplanet", 0x000000, 0x000000, 0x000000, 4632918508L, 204556L, 12.0f, 0.0f) .setPerlinGen(Blocks.blackened_stone.getState(), Blocks.goo.getState(), 63) - .setBiomeReplacer(Blocks.blackened_cobble.getState()).setBiome(Biome.blackened) + .setBiomeReplacer(Blocks.blackened_cobble.getState()).setBiome(Biome.BLACKENED) .enableCaves(Blocks.air.getState()).setDungeons(4).enableMobs() - .setWorldFloor(Blocks.bedrock.getState()) .addLake(Blocks.goo.getState(), null, null, 8, 8, 255, true) // .addOre(Blocks.PLACEHOLDER_ore.getState(), 0, 2, 3, 0, 12, false) , "ovrol"); - registerDimension("Der Warp", new Semi(-1, "warp", 0x0c001f, 0x0c001f, 0x190033, 285.0f, 3).setCloudTexture("clouds_dense").setCloudHeight(238.0f) + registerDimension("Der Warp", new Semi(-1, "warp", 0x0c001f, 0x0c001f, 0x190033, 285.0f, 3).setCloudTexture(CloudType.DENSE).setCloudHeight(238.0f) .setPerlinGen(Blocks.obsidian.getState(), Blocks.lava.getState(), 63) - .setBiome(Biome.chaos).enableCavesRavines(Blocks.air.getState()).enableLongCaves().enableMobs().enableSnow() + .setBiome(Biome.CHAOS).enableCavesRavines(Blocks.air.getState()).enableLongCaves().enableMobs().enableSnow() .addLake(Blocks.water.getState(), null, Blocks.obsidian.getState(), 8, 0, 255, false) .addLake(Blocks.lava.getState(), null, null, 1, 8, 255, false) .addLiquid(Blocks.flowing_water.getState(), 1, 8, 255, false) @@ -656,10 +650,10 @@ public abstract class UniverseRegistry { registerDomain("Tian'Xin", "tianxin"); registerDimension("Ni'enrath", new Area(-2, "nienrath", 0x7f00ff, 0x7f00ff, 276.15f, 1) - .setPerlinGen(Blocks.tian.getState(), Blocks.water.getState(), 63).setBiome(Biome.tian) + .setPerlinGen(Blocks.tian.getState(), Blocks.springwater.getState(), 63).setBiome(Biome.TIAN) .setBiomeReplacer(Blocks.tian.getState()).enableLongCaves().enableMobs().enableSnow() - .addLake(Blocks.water.getState(), Blocks.tian.getState(), Blocks.tian.getState(), 4, 0, 255, false) - .addLiquid(Blocks.flowing_water.getState(), 50, 8, 255, false), "tianxin"); + .addLake(Blocks.springwater.getState(), Blocks.tian.getState(), Blocks.tian.getState(), 4, 0, 255, false) + .addLiquid(Blocks.flowing_springwater.getState(), 50, 8, 255, false), "tianxin"); registerDimension("Cyberspace", new Area(-3, "cyberspace", 0x000000, 0x000000, 293.15f, 15) .setFlatGen(Blocks.stained_hardened_clay.getState().withProperty(BlockColored.COLOR, DyeColor.GREEN), 2) @@ -667,35 +661,30 @@ public abstract class UniverseRegistry { registerDomain("Hölle", "hell"); registerDimension("Kreis Thedric", new Area(-1001, "thedric", 0x330707, 0x330707, 347.15f, 2).enableLongCaves().enableMobs().enableFortresses() - .setWorldFloor(Blocks.air.getState()).setWorldCeiling(Blocks.bedrock.getState()).enableDenseFog() + .enableWorldCeiling().enableDenseFog() .setCavernGen(Blocks.hellrock.getState(), Blocks.lava.getState(), 63) .setSurfaceReplacer(Blocks.gravel.getState(), Blocks.soul_sand.getState()) - .setBiome(Biome.upperHell), "hell"); + .setBiome(Biome.UPPERHELL), "hell"); registerDimension("Kreis Kyroth", new Area(-1002, "kyroth", 0x990000, 0x990000, 387.15f, 3).enableLongCaves().enableMobs() - .setWorldFloor(Blocks.air.getState()) .setSimpleGen(Blocks.hellrock.getState(), Blocks.lava.getState(), 64) .setSimpleReplacer(Blocks.obsidian.getState(), Blocks.soul_sand.getState()) - .setBiome(Biome.lowerHell) + .setBiome(Biome.LOWERHELL) .addLake(Blocks.lava.getState(), null, null, 4, 8, 255, false) .addLiquid(Blocks.flowing_lava.getState(), 40, 8, 255, true), "hell"); registerDimension("Kreis Ahrd", new Area(-1003, "ahrd", 0xcc0000, 0xcc0000, 467.15f, 15).enableLongCaves().enableMobs() - .setWorldFloor(Blocks.air.getState()) .setPerlinGen(Blocks.hellrock.getState(), Blocks.lava.getState(), 63) - .setBiomeReplacer(Blocks.soul_sand.getState()).setBiome(Biome.hellHills) + .setBiomeReplacer(Blocks.soul_sand.getState()).setBiome(Biome.HELLHILLS) .addLake(Blocks.lava.getState(), Blocks.soul_sand.getState(), Blocks.soul_sand.getState(), 2, 8, 255, false).addLiquid(Blocks.flowing_lava.getState(), 80, 8, 255, true), "hell"); registerDimension("Kreis Mizorath", new Area(-1004, "mizorath", 0xff0000, 0xff0000, 1067.15f, 15).enableMobs() - .setWorldFloor(Blocks.air.getState()) .setPerlinGen(Blocks.hellrock.getState(), Blocks.blood.getState(), 63) - .setBiomeReplacer(Blocks.soul_sand.getState()).setBiome(Biome.soulPlains), "hell"); + .setBiomeReplacer(Blocks.soul_sand.getState()).setBiome(Biome.SOULPLAINS), "hell"); registerDimension("Kreis Dargoth", new Area(-1005, "dargoth", 0xff3f0c, 0xff3f0c, 1707.15f, 15).enableMobs() - .setWorldFloor(Blocks.air.getState()) .setPerlinGen(Blocks.hellrock.getState(), Blocks.magma.getState(), 63) - .setBiomeReplacer(Blocks.soul_sand.getState()).setBiome(Biome.soulPlains), "hell"); + .setBiomeReplacer(Blocks.soul_sand.getState()).setBiome(Biome.SOULPLAINS), "hell"); registerDimension("Kreis Aasirith", new Area(-1006, "aasirith", 0x191919, 0x191919, 2482.0f, 1).enableLongCaves().enableMobs() - .setWorldFloor(Blocks.air.getState()) .setPerlinGen(Blocks.rock.getState(), Blocks.magma.getState(), 63) - .setBiomeReplacer(Blocks.ash.getState()).setBiome(Biome.ashLand) + .setBiomeReplacer(Blocks.ash.getState()).setBiome(Biome.ASHLAND) .addLake(Blocks.lava.getState(), Blocks.rock.getState(), Blocks.rock.getState(), 2, 8, 255, false).addLiquid(Blocks.flowing_lava.getState(), 80, 8, 255, true), "hell"); @@ -709,60 +698,60 @@ public abstract class UniverseRegistry { private static Dimension addPreset(String name, String base, String data) { Dimension dim = BASE_ALIASES.get(base).copy(UniverseRegistry.MORE_DIM_ID, "preset"); - NBTTagCompound ptag; + TagObject ptag; try { - ptag = NBTParser.parseTag("{" + data + "}"); + ptag = TagObject.parse("{" + data + "}"); } - catch(NBTException e) { + catch(IllegalArgumentException e) { throw new RuntimeException(e); } - NBTTagCompound dtag = dim.toNbt(true); - if(ptag.getBoolean("ClearGenerator")) { - ptag.removeTag("ClearGenerator"); - dtag.removeTag("FloorBlock"); - dtag.removeTag("CeilingBlock"); - dtag.removeTag("Layers"); - dtag.removeTag("AddBiomes"); - dtag.removeTag("FrostBiomes"); - dtag.removeTag("ColdBiomes"); - dtag.removeTag("MediumBiomes"); - dtag.removeTag("HotBiomes"); - dtag.removeTag("Ores"); - dtag.removeTag("Lakes"); - dtag.removeTag("Liquids"); + TagObject dtag = dim.toTags(true); + if(ptag.getBool("ClearGenerator")) { + ptag.remove("ClearGenerator"); + dtag.remove("FloorBlock"); + dtag.remove("CeilingBlock"); + dtag.remove("Layers"); + dtag.remove("AddBiomes"); + dtag.remove("FrostBiomes"); + dtag.remove("ColdBiomes"); + dtag.remove("MediumBiomes"); + dtag.remove("HotBiomes"); + dtag.remove("Ores"); + dtag.remove("Lakes"); + dtag.remove("Liquids"); dtag.setString("Generator", GeneratorType.FLAT.getName()); dtag.setString("Replacer", ReplacerType.NONE.getName()); // dtag.setBoolean("MobGen", false); // dtag.setBoolean("SnowGen", false); - dtag.setBoolean("Caves", false); - dtag.setBoolean("Ravines", false); - dtag.setBoolean("AltCaves", false); - dtag.setBoolean("Strongholds", false); - dtag.setBoolean("Villages", false); - dtag.setBoolean("Mineshafts", false); - dtag.setBoolean("Scattered", false); - dtag.setBoolean("Fortresses", false); - dtag.setInteger("Dungeons", 0); - dtag.setInteger("BiomeSize", 0); - dtag.setInteger("RiverSize", 4); - dtag.setInteger("SnowRarity", 6); - dtag.setInteger("SeaRarity", 50); - dtag.setInteger("AddRarity", 50); - dtag.setInteger("SeaLevel", 0); - dtag.setString("DefaultBiome", Biome.none.name.toLowerCase()); - dtag.setBoolean("SemiFixed", false); + dtag.setBool("Caves", false); + dtag.setBool("Ravines", false); + dtag.setBool("AltCaves", false); + dtag.setBool("Strongholds", false); + dtag.setBool("Villages", false); + dtag.setBool("Mineshafts", false); + dtag.setBool("Scattered", false); + dtag.setBool("Fortresses", false); + dtag.setInt("Dungeons", 0); + dtag.setInt("BiomeSize", 0); + dtag.setInt("RiverSize", 4); + dtag.setInt("SnowRarity", 6); + dtag.setInt("SeaRarity", 50); + dtag.setInt("AddRarity", 50); + dtag.setInt("SeaLevel", 0); + dtag.setString("DefaultBiome", Biome.NONE.name.toLowerCase()); + dtag.setBool("SemiFixed", false); // dtag.setString("DefaultWeather", Weather.CLEAR.getName()); dtag.setString("DefaultLeaves", LeavesType.SPRING.getName()); - dtag.setString("FillerBlock", BlockRegistry.toIdName(Blocks.air.getState())); - dtag.setString("TopBlock", BlockRegistry.toIdName(Blocks.air.getState())); - dtag.setString("SurfaceBlock", BlockRegistry.toIdName(Blocks.air.getState())); - dtag.setString("AltBlock1", BlockRegistry.toIdName(Blocks.air.getState())); - dtag.setString("AltBlock2", BlockRegistry.toIdName(Blocks.air.getState())); - dtag.setString("LiquidBlock", BlockRegistry.toIdName(Blocks.air.getState())); - dtag.setString("CaveFillBlock", BlockRegistry.toIdName(Blocks.air.getState())); + Dimension.writeState(dtag, "FillerBlock", Blocks.air.getState()); + Dimension.writeState(dtag, "TopBlock", Blocks.air.getState()); + Dimension.writeState(dtag, "SurfaceBlock", Blocks.air.getState()); + Dimension.writeState(dtag, "AltBlock1", Blocks.air.getState()); + Dimension.writeState(dtag, "AltBlock2", Blocks.air.getState()); + Dimension.writeState(dtag, "LiquidBlock", Blocks.air.getState()); + Dimension.writeState(dtag, "CaveFillBlock", Blocks.air.getState()); } dtag.merge(ptag); - dim.fromNbt(dtag); + dim.fromTags(dtag); dim.setCustomName(name); // BASE_DIMS.add(dim); return dim; @@ -795,33 +784,33 @@ public abstract class UniverseRegistry { addPreset("Chaotische Höhlen", "UpperLmtScale:2.0,LowerLmtScale:64.0,SeaLevel:6"); addPreset("Viel Glück", "LiquidBlock:lava,SeaLevel:40"); - addFlatPreset("Klassisch", Biome.plains, false, Blocks.dirt.getState(), Blocks.bedrock.getState(), 2, Blocks.dirt.getState(), + addFlatPreset("Klassisch", Biome.PLAINS, false, Blocks.dirt.getState(), Blocks.bedrock.getState(), 2, Blocks.dirt.getState(), Blocks.grass.getState()).enableVillages(); - addFlatPreset("Abbauwelt", Biome.extremeHills, true, Blocks.stone.getState(), Blocks.bedrock.getState(), 230, Blocks.stone.getState(), + addFlatPreset("Abbauwelt", Biome.EXTREMEHILLS, true, Blocks.stone.getState(), Blocks.bedrock.getState(), 230, Blocks.stone.getState(), 5, Blocks.dirt.getState(), Blocks.grass.getState()).enableStrongholds().enableMineshafts().setDungeons(8); - addFlatPreset("Wasserwelt", Biome.sea, false, Blocks.stone.getState(), Blocks.bedrock.getState(), 5, Blocks.stone.getState(), + addFlatPreset("Wasserwelt", Biome.SEA, false, Blocks.stone.getState(), Blocks.bedrock.getState(), 5, Blocks.stone.getState(), 52, Blocks.dirt.getState(), 5, Blocks.sand.getState(), 90, Blocks.water.getState()); - addFlatPreset("Oberfläche", Biome.plains, true, Blocks.stone.getState(), Blocks.bedrock.getState(), 59, Blocks.stone.getState(), + addFlatPreset("Oberfläche", Biome.PLAINS, true, Blocks.stone.getState(), Blocks.bedrock.getState(), 59, Blocks.stone.getState(), 3, Blocks.dirt.getState(), Blocks.grass.getState()).setBiomeReplacer(Blocks.gravel.getState()).enableVillages().enableStrongholds().enableMineshafts().setDungeons(8) .addLake(Blocks.water.getState(), null, Blocks.grass.getState(), 4, 0, 255, false).addLake(Blocks.lava.getState(), Blocks.stone.getState(), null, 8, 8, 255, true); - addFlatPreset("Verschneites Königreich", Biome.icePlains, false, Blocks.stone.getState(), Blocks.bedrock.getState(), 59, Blocks.stone.getState(), + addFlatPreset("Verschneites Königreich", Biome.ICEPLAINS, false, Blocks.stone.getState(), Blocks.bedrock.getState(), 59, Blocks.stone.getState(), 3, Blocks.dirt.getState(), Blocks.grass.getState(), Blocks.snow_layer.getState()).enableVillages(); - addFlatPreset("Verschneites Königreich +", Biome.icePlains, true, Blocks.stone.getState(), Blocks.bedrock.getState(), 59, Blocks.stone.getState(), + addFlatPreset("Verschneites Königreich +", Biome.ICEPLAINS, true, Blocks.stone.getState(), Blocks.bedrock.getState(), 59, Blocks.stone.getState(), 3, Blocks.dirt.getState(), Blocks.grass.getState(), Blocks.snow_layer.getState()).setBiomeReplacer(Blocks.gravel.getState()).enableVillages() .addLake(Blocks.water.getState(), null, Blocks.grass.getState(), 4, 0, 255, false); - addFlatPreset("Unendliche Grube", Biome.plains, false, Blocks.dirt.getState(), 2, Blocks.cobblestone.getState(), 3, Blocks.dirt.getState(), Blocks.grass.getState()) + addFlatPreset("Unendliche Grube", Biome.PLAINS, false, Blocks.dirt.getState(), 2, Blocks.cobblestone.getState(), 3, Blocks.dirt.getState(), Blocks.grass.getState()) .setBiomeReplacer(Blocks.gravel.getState()).enableVillages(); - addFlatPreset("Wüste", Biome.desert, false, Blocks.stone.getState(), Blocks.bedrock.getState(), 3, Blocks.stone.getState(), 52, Blocks.sandstone.getState()) + addFlatPreset("Wüste", Biome.DESERT, false, Blocks.stone.getState(), Blocks.bedrock.getState(), 3, Blocks.stone.getState(), 52, Blocks.sandstone.getState()) .enableVillages().enableScattered(); - addFlatPreset("Redstonewelt", Biome.desert, false, Blocks.sandstone.getState(), Blocks.bedrock.getState(), 3, Blocks.stone.getState(), + addFlatPreset("Redstonewelt", Biome.DESERT, false, Blocks.sandstone.getState(), Blocks.bedrock.getState(), 3, Blocks.stone.getState(), 52, Blocks.sandstone.getState()); addPreset("Leer", "ClearGenerator:1b"); diff --git a/java/src/game/init/WoodType.java b/common/src/main/java/common/init/WoodType.java similarity index 96% rename from java/src/game/init/WoodType.java rename to common/src/main/java/common/init/WoodType.java index 53105c9..aa76f8d 100755 --- a/java/src/game/init/WoodType.java +++ b/common/src/main/java/common/init/WoodType.java @@ -1,6 +1,6 @@ -package game.init; +package common.init; -import game.color.Colorizer; +import common.color.Colorizer; public enum WoodType { OAK("oak", "Eichen", null, 20, "apple"), diff --git a/java/src/game/inventory/AnimalChest.java b/common/src/main/java/common/inventory/AnimalChest.java similarity index 92% rename from java/src/game/inventory/AnimalChest.java rename to common/src/main/java/common/inventory/AnimalChest.java index 1e3edb9..8823e5c 100755 --- a/java/src/game/inventory/AnimalChest.java +++ b/common/src/main/java/common/inventory/AnimalChest.java @@ -1,4 +1,4 @@ -package game.inventory; +package common.inventory; public class AnimalChest extends InventoryBasic { diff --git a/java/src/game/inventory/Container.java b/common/src/main/java/common/inventory/Container.java similarity index 86% rename from java/src/game/inventory/Container.java rename to common/src/main/java/common/inventory/Container.java index 34fa6fb..59197f1 100755 --- a/java/src/game/inventory/Container.java +++ b/common/src/main/java/common/inventory/Container.java @@ -1,16 +1,15 @@ -package game.inventory; +package common.inventory; import java.util.List; import java.util.Set; -import game.collect.Lists; -import game.collect.Sets; - -import game.entity.npc.EntityNPC; -import game.item.Item; -import game.item.ItemStack; -import game.tileentity.TileEntity; -import game.util.ExtMath; +import common.collect.Lists; +import common.collect.Sets; +import common.entity.npc.EntityNPC; +import common.item.Item; +import common.item.ItemStack; +import common.tileentity.TileEntity; +import common.util.ExtMath; public abstract class Container { @@ -98,14 +97,6 @@ public abstract class Container } } - /** - * Handles the given Button-click on the server, currently only used by enchanting. Name is for legacy. - */ - public boolean enchantItem(EntityNPC playerIn, int id) - { - return false; - } - public Slot getSlotFromInventory(IInventory inv, int slotIn) { for (int i = 0; i < this.inventorySlots.size(); ++i) @@ -174,7 +165,7 @@ public abstract class Container { Slot slot = (Slot)this.inventorySlots.get(slotId); - if (slot != null && canAddItemToSlot(slot, inventoryplayer.getItemStack(), true) && slot.isItemValid(inventoryplayer.getItemStack()) && inventoryplayer.getItemStack().stackSize > this.dragSlots.size() && this.canDragIntoSlot(slot)) + if (slot != null && canAddItemToSlot(slot, inventoryplayer.getItemStack(), true) && slot.isItemValid(inventoryplayer.getItemStack()) && inventoryplayer.getItemStack().size > this.dragSlots.size() && this.canDragIntoSlot(slot)) { this.dragSlots.add(slot); } @@ -184,34 +175,34 @@ public abstract class Container if (!this.dragSlots.isEmpty()) { ItemStack itemstack3 = inventoryplayer.getItemStack().copy(); - int j = inventoryplayer.getItemStack().stackSize; + int j = inventoryplayer.getItemStack().size; for (Slot slot1 : this.dragSlots) { - if (slot1 != null && canAddItemToSlot(slot1, inventoryplayer.getItemStack(), true) && slot1.isItemValid(inventoryplayer.getItemStack()) && inventoryplayer.getItemStack().stackSize >= this.dragSlots.size() && this.canDragIntoSlot(slot1)) + if (slot1 != null && canAddItemToSlot(slot1, inventoryplayer.getItemStack(), true) && slot1.isItemValid(inventoryplayer.getItemStack()) && inventoryplayer.getItemStack().size >= this.dragSlots.size() && this.canDragIntoSlot(slot1)) { ItemStack itemstack1 = itemstack3.copy(); - int k = slot1.getHasStack() ? slot1.getStack().stackSize : 0; + int k = slot1.getHasStack() ? slot1.getStack().size : 0; computeStackSize(this.dragSlots, this.dragMode, itemstack1, k); - if (itemstack1.stackSize > itemstack1.getMaxStackSize()) + if (itemstack1.size > itemstack1.getMaxStackSize()) { - itemstack1.stackSize = itemstack1.getMaxStackSize(); + itemstack1.size = itemstack1.getMaxStackSize(); } - if (itemstack1.stackSize > slot1.getItemStackLimit(itemstack1)) + if (itemstack1.size > slot1.getItemStackLimit(itemstack1)) { - itemstack1.stackSize = slot1.getItemStackLimit(itemstack1); + itemstack1.size = slot1.getItemStackLimit(itemstack1); } - j -= itemstack1.stackSize - k; + j -= itemstack1.size - k; slot1.putStack(itemstack1); } } - itemstack3.stackSize = j; + itemstack3.size = j; - if (itemstack3.stackSize <= 0) + if (itemstack3.size <= 0) { itemstack3 = null; } @@ -246,7 +237,7 @@ public abstract class Container { playerIn.dropPlayerItemWithRandomChoice(inventoryplayer.getItemStack().splitStack(1), true); - if (inventoryplayer.getItemStack().stackSize == 0) + if (inventoryplayer.getItemStack().size == 0) { inventoryplayer.setItemStack((ItemStack)null); } @@ -301,19 +292,19 @@ public abstract class Container { if (itemstack10 != null && slot7.isItemValid(itemstack10)) { - int k2 = clickedButton == 0 ? itemstack10.stackSize : 1; + int k2 = clickedButton == 0 ? itemstack10.size : 1; if (k2 > slot7.getItemStackLimit(itemstack10)) { k2 = slot7.getItemStackLimit(itemstack10); } - if (itemstack10.stackSize >= k2) + if (itemstack10.size >= k2) { slot7.putStack(itemstack10.splitStack(k2)); } - if (itemstack10.stackSize == 0) + if (itemstack10.size == 0) { inventoryplayer.setItemStack((ItemStack)null); } @@ -323,11 +314,11 @@ public abstract class Container { if (itemstack10 == null) { - int j2 = clickedButton == 0 ? itemstack9.stackSize : (itemstack9.stackSize + 1) / 2; + int j2 = clickedButton == 0 ? itemstack9.size : (itemstack9.size + 1) / 2; ItemStack itemstack12 = slot7.decrStackSize(j2); inventoryplayer.setItemStack(itemstack12); - if (itemstack9.stackSize == 0) + if (itemstack9.size == 0) { slot7.putStack((ItemStack)null); } @@ -338,28 +329,28 @@ public abstract class Container { if (itemstack9.getItem() == itemstack10.getItem() && itemstack9.getMetadata() == itemstack10.getMetadata() && ItemStack.areItemStackTagsEqual(itemstack9, itemstack10)) { - int i2 = clickedButton == 0 ? itemstack10.stackSize : 1; + int i2 = clickedButton == 0 ? itemstack10.size : 1; - if (i2 > slot7.getItemStackLimit(itemstack10) - itemstack9.stackSize) + if (i2 > slot7.getItemStackLimit(itemstack10) - itemstack9.size) { - i2 = slot7.getItemStackLimit(itemstack10) - itemstack9.stackSize; + i2 = slot7.getItemStackLimit(itemstack10) - itemstack9.size; } - if (i2 > itemstack10.getMaxStackSize() - itemstack9.stackSize) + if (i2 > itemstack10.getMaxStackSize() - itemstack9.size) { - i2 = itemstack10.getMaxStackSize() - itemstack9.stackSize; + i2 = itemstack10.getMaxStackSize() - itemstack9.size; } itemstack10.splitStack(i2); - if (itemstack10.stackSize == 0) + if (itemstack10.size == 0) { inventoryplayer.setItemStack((ItemStack)null); } - itemstack9.stackSize += i2; + itemstack9.size += i2; } - else if (itemstack10.stackSize <= slot7.getItemStackLimit(itemstack10)) + else if (itemstack10.size <= slot7.getItemStackLimit(itemstack10)) { slot7.putStack(itemstack10); inventoryplayer.setItemStack(itemstack9); @@ -367,14 +358,14 @@ public abstract class Container } else if (itemstack9.getItem() == itemstack10.getItem() && itemstack10.getMaxStackSize() > 1 && (!itemstack9.getHasSubtypes() || itemstack9.getMetadata() == itemstack10.getMetadata()) && ItemStack.areItemStackTagsEqual(itemstack9, itemstack10)) { - int l1 = itemstack9.stackSize; + int l1 = itemstack9.size; - if (l1 > 0 && l1 + itemstack10.stackSize <= itemstack10.getMaxStackSize()) + if (l1 > 0 && l1 + itemstack10.size <= itemstack10.getMaxStackSize()) { - itemstack10.stackSize += l1; + itemstack10.size += l1; itemstack9 = slot7.decrStackSize(l1); - if (itemstack9.stackSize == 0) + if (itemstack9.size == 0) { slot7.putStack((ItemStack)null); } @@ -414,14 +405,14 @@ public abstract class Container if (k1 > -1) { inventoryplayer.addItemStackToInventory(itemstack7); - slot5.decrStackSize(itemstack11.stackSize); + slot5.decrStackSize(itemstack11.size); slot5.putStack((ItemStack)null); slot5.onPickupFromSlot(playerIn, itemstack11); } } else { - slot5.decrStackSize(itemstack11.stackSize); + slot5.decrStackSize(itemstack11.size); slot5.putStack(itemstack7); slot5.onPickupFromSlot(playerIn, itemstack11); } @@ -450,7 +441,7 @@ public abstract class Container if (slot3 != null && slot3.getHasStack() && slot3.canTakeStack(playerIn)) { - ItemStack itemstack5 = slot3.decrStackSize(clickedButton == 0 ? 1 : slot3.getStack().stackSize); + ItemStack itemstack5 = slot3.decrStackSize(clickedButton == 0 ? 1 : slot3.getStack().size); slot3.onPickupFromSlot(playerIn, itemstack5); playerIn.dropPlayerItemWithRandomChoice(itemstack5, true); } @@ -467,17 +458,17 @@ public abstract class Container for (int l2 = 0; l2 < 2; ++l2) { - for (int i3 = i1; i3 >= 0 && i3 < this.inventorySlots.size() && itemstack4.stackSize < itemstack4.getMaxStackSize(); i3 += j1) + for (int i3 = i1; i3 >= 0 && i3 < this.inventorySlots.size() && itemstack4.size < itemstack4.getMaxStackSize(); i3 += j1) { Slot slot8 = (Slot)this.inventorySlots.get(i3); - if (slot8.getHasStack() && canAddItemToSlot(slot8, itemstack4, true) && slot8.canTakeStack(playerIn) && this.canMergeSlot(itemstack4, slot8) && (l2 != 0 || slot8.getStack().stackSize != slot8.getStack().getMaxStackSize())) + if (slot8.getHasStack() && canAddItemToSlot(slot8, itemstack4, true) && slot8.canTakeStack(playerIn) && this.canMergeSlot(itemstack4, slot8) && (l2 != 0 || slot8.getStack().size != slot8.getStack().getMaxStackSize())) { - int l = Math.min(itemstack4.getMaxStackSize() - itemstack4.stackSize, slot8.getStack().stackSize); + int l = Math.min(itemstack4.getMaxStackSize() - itemstack4.size, slot8.getStack().size); ItemStack itemstack2 = slot8.decrStackSize(l); - itemstack4.stackSize += l; + itemstack4.size += l; - if (itemstack2.stackSize <= 0) + if (itemstack2.size <= 0) { slot8.putStack((ItemStack)null); } @@ -607,26 +598,26 @@ public abstract class Container if (stack.isStackable()) { - while (stack.stackSize > 0 && (!reverseDirection && i < endIndex || reverseDirection && i >= startIndex)) + while (stack.size > 0 && (!reverseDirection && i < endIndex || reverseDirection && i >= startIndex)) { Slot slot = (Slot)this.inventorySlots.get(i); ItemStack itemstack = slot.getStack(); if (itemstack != null && itemstack.getItem() == stack.getItem() && (!stack.getHasSubtypes() || stack.getMetadata() == itemstack.getMetadata()) && ItemStack.areItemStackTagsEqual(stack, itemstack)) { - int j = itemstack.stackSize + stack.stackSize; + int j = itemstack.size + stack.size; if (j <= stack.getMaxStackSize()) { - stack.stackSize = 0; - itemstack.stackSize = j; + stack.size = 0; + itemstack.size = j; slot.onSlotChanged(); flag = true; } - else if (itemstack.stackSize < stack.getMaxStackSize()) + else if (itemstack.size < stack.getMaxStackSize()) { - stack.stackSize -= stack.getMaxStackSize() - itemstack.stackSize; - itemstack.stackSize = stack.getMaxStackSize(); + stack.size -= stack.getMaxStackSize() - itemstack.size; + itemstack.size = stack.getMaxStackSize(); slot.onSlotChanged(); flag = true; } @@ -643,7 +634,7 @@ public abstract class Container } } - if (stack.stackSize > 0) + if (stack.size > 0) { if (reverseDirection) { @@ -663,7 +654,7 @@ public abstract class Container { slot1.putStack(stack.copy()); slot1.onSlotChanged(); - stack.stackSize = 0; + stack.size = 0; flag = true; break; } @@ -730,7 +721,7 @@ public abstract class Container if (slotIn != null && slotIn.getHasStack() && stack != null && stack.isItemEqual(slotIn.getStack()) && ItemStack.areItemStackTagsEqual(slotIn.getStack(), stack)) { - flag |= slotIn.getStack().stackSize + (stackSizeMatters ? 0 : stack.stackSize) <= stack.getMaxStackSize(); + flag |= slotIn.getStack().size + (stackSizeMatters ? 0 : stack.size) <= stack.getMaxStackSize(); } return flag; @@ -745,18 +736,18 @@ public abstract class Container switch (p_94525_1_) { case 0: - p_94525_2_.stackSize = ExtMath.floorf((float)p_94525_2_.stackSize / (float)p_94525_0_.size()); + p_94525_2_.size = ExtMath.floorf((float)p_94525_2_.size / (float)p_94525_0_.size()); break; case 1: - p_94525_2_.stackSize = 1; + p_94525_2_.size = 1; break; case 2: - p_94525_2_.stackSize = p_94525_2_.getItem().getItemStackLimit(); + p_94525_2_.size = p_94525_2_.getItem().getItemStackLimit(); } - p_94525_2_.stackSize += p_94525_3_; + p_94525_2_.size += p_94525_3_; } /** @@ -793,7 +784,7 @@ public abstract class Container if (itemstack != null) { - f += (float)itemstack.stackSize / (float)Math.min(inv.getInventoryStackLimit(), itemstack.getMaxStackSize()); + f += (float)itemstack.size / (float)Math.min(inv.getInventoryStackLimit(), itemstack.getMaxStackSize()); ++i; } } diff --git a/java/src/game/inventory/ContainerBrewingStand.java b/common/src/main/java/common/inventory/ContainerBrewingStand.java similarity index 96% rename from java/src/game/inventory/ContainerBrewingStand.java rename to common/src/main/java/common/inventory/ContainerBrewingStand.java index 79b09a4..cd28bb7 100755 --- a/java/src/game/inventory/ContainerBrewingStand.java +++ b/common/src/main/java/common/inventory/ContainerBrewingStand.java @@ -1,8 +1,8 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.item.ItemStack; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.item.ItemStack; public class ContainerBrewingStand extends Container { @@ -128,7 +128,7 @@ public class ContainerBrewingStand extends Container slot.onSlotChange(itemstack1, itemstack); } - if (itemstack1.stackSize == 0) + if (itemstack1.size == 0) { slot.putStack((ItemStack)null); } @@ -137,7 +137,7 @@ public class ContainerBrewingStand extends Container slot.onSlotChanged(); } - if (itemstack1.stackSize == itemstack.stackSize) + if (itemstack1.size == itemstack.size) { return null; } diff --git a/java/src/game/inventory/ContainerChest.java b/common/src/main/java/common/inventory/ContainerChest.java similarity index 95% rename from java/src/game/inventory/ContainerChest.java rename to common/src/main/java/common/inventory/ContainerChest.java index ed12ad5..c20fb4d 100755 --- a/java/src/game/inventory/ContainerChest.java +++ b/common/src/main/java/common/inventory/ContainerChest.java @@ -1,7 +1,7 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; public class ContainerChest extends Container { @@ -67,7 +67,7 @@ public class ContainerChest extends Container return null; } - if (itemstack1.stackSize == 0) + if (itemstack1.size == 0) { slot.putStack((ItemStack)null); } diff --git a/java/src/game/inventory/ContainerDispenser.java b/common/src/main/java/common/inventory/ContainerDispenser.java similarity index 91% rename from java/src/game/inventory/ContainerDispenser.java rename to common/src/main/java/common/inventory/ContainerDispenser.java index 34a52c8..5ed17e5 100755 --- a/java/src/game/inventory/ContainerDispenser.java +++ b/common/src/main/java/common/inventory/ContainerDispenser.java @@ -1,7 +1,7 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; public class ContainerDispenser extends Container { @@ -63,7 +63,7 @@ public class ContainerDispenser extends Container return null; } - if (itemstack1.stackSize == 0) + if (itemstack1.size == 0) { slot.putStack((ItemStack)null); } @@ -72,7 +72,7 @@ public class ContainerDispenser extends Container slot.onSlotChanged(); } - if (itemstack1.stackSize == itemstack.stackSize) + if (itemstack1.size == itemstack.size) { return null; } diff --git a/common/src/main/java/common/inventory/ContainerEnchantment.java b/common/src/main/java/common/inventory/ContainerEnchantment.java new file mode 100755 index 0000000..32e26de --- /dev/null +++ b/common/src/main/java/common/inventory/ContainerEnchantment.java @@ -0,0 +1,359 @@ +package common.inventory; + +import java.util.List; + +import common.enchantment.Enchantment; +import common.enchantment.EnchantmentHelper; +import common.enchantment.RngEnchantment; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.item.ItemStack; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Pair; +import common.world.World; + +public class ContainerEnchantment extends Container +{ + public IInventory table; + private World world; + private BlockPos position; + private Random rand; + public int seed; + public int[] mana; + public Pair[] ench; + + public ContainerEnchantment(InventoryPlayer playerInv, World worldIn) + { + this(playerInv, worldIn, BlockPos.ORIGIN); + } + + public ContainerEnchantment(InventoryPlayer playerInv, World worldIn, BlockPos pos) + { + this.table = new InventoryBasic("Enchant", true, 1) + { + public int getInventoryStackLimit() + { + return ItemStack.MAX_SIZE; + } + public void markDirty() + { + super.markDirty(); + ContainerEnchantment.this.onCraftMatrixChanged(this); + } + }; + this.rand = new Random(); + this.mana = new int[3]; + this.ench = new Pair[] {null, null, null}; + this.world = worldIn; + this.position = pos; + this.seed = playerInv.player.getEnchSeed(); + this.addSlotToContainer(new Slot(this.table, 0, 25, 47) + { + public boolean isItemValid(ItemStack stack) + { + return true; + } + public int getSlotStackLimit() + { + return 1; + } + }); + + for (int i = 0; i < 3; ++i) + { + for (int j = 0; j < 9; ++j) + { + this.addSlotToContainer(new Slot(playerInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); + } + } + + for (int k = 0; k < 9; ++k) + { + this.addSlotToContainer(new Slot(playerInv, k, 8 + k * 18, 142)); + } + } + + public static int encodeData(Pair data) { + return data == null ? -1 : data.first().ordinal() | data.second() << 8; + } + + public static Pair decodeData(int data) { + return data < 0 ? null : new Pair(Enchantment.values()[(data & 0xff) % Enchantment.values().length], data >> 8); + } + + public void onCraftGuiOpened(ICrafting listener) + { + super.onCraftGuiOpened(listener); + listener.sendProgressBarUpdate(this, 0, this.mana[0]); + listener.sendProgressBarUpdate(this, 1, this.mana[1]); + listener.sendProgressBarUpdate(this, 2, this.mana[2]); + listener.sendProgressBarUpdate(this, 3, this.seed & -16); + listener.sendProgressBarUpdate(this, 4, encodeData(this.ench[0])); + listener.sendProgressBarUpdate(this, 5, encodeData(this.ench[1])); + listener.sendProgressBarUpdate(this, 6, encodeData(this.ench[2])); + } + + public void detectAndSendChanges() + { + super.detectAndSendChanges(); + + for (int i = 0; i < this.crafters.size(); ++i) + { + ICrafting icrafting = (ICrafting)this.crafters.get(i); + icrafting.sendProgressBarUpdate(this, 0, this.mana[0]); + icrafting.sendProgressBarUpdate(this, 1, this.mana[1]); + icrafting.sendProgressBarUpdate(this, 2, this.mana[2]); + icrafting.sendProgressBarUpdate(this, 3, this.seed & -16); + icrafting.sendProgressBarUpdate(this, 4, encodeData(this.ench[0])); + icrafting.sendProgressBarUpdate(this, 5, encodeData(this.ench[1])); + icrafting.sendProgressBarUpdate(this, 6, encodeData(this.ench[2])); + } + } + + public void updateProgressBar(int id, int data) + { + if (id >= 0 && id <= 2) + { + this.mana[id] = data; + } + else if (id == 3) + { + this.seed = data; + } + else if (id >= 4 && id <= 6) + { + this.ench[id - 4] = decodeData(data); + } + else + { + super.updateProgressBar(id, data); + } + } + + public void onCraftMatrixChanged(IInventory inventoryIn) + { + if (inventoryIn == this.table) + { + ItemStack itemstack = inventoryIn.getStackInSlot(0); + + if (itemstack != null && itemstack.isItemEnchantable()) + { + if (!this.world.client) + { + int l = 0; + + for (int j = -1; j <= 1; ++j) + { + for (int k = -1; k <= 1; ++k) + { + if ((j != 0 || k != 0) && this.world.isAirBlock(this.position.add(k, 0, j)) && this.world.isAirBlock(this.position.add(k, 1, j))) + { + if (this.world.getState(this.position.add(k * 2, 0, j * 2)).getBlock() == Blocks.bookshelf) + { + ++l; + } + + if (this.world.getState(this.position.add(k * 2, 1, j * 2)).getBlock() == Blocks.bookshelf) + { + ++l; + } + + if (k != 0 && j != 0) + { + if (this.world.getState(this.position.add(k * 2, 0, j)).getBlock() == Blocks.bookshelf) + { + ++l; + } + + if (this.world.getState(this.position.add(k * 2, 1, j)).getBlock() == Blocks.bookshelf) + { + ++l; + } + + if (this.world.getState(this.position.add(k, 0, j * 2)).getBlock() == Blocks.bookshelf) + { + ++l; + } + + if (this.world.getState(this.position.add(k, 1, j * 2)).getBlock() == Blocks.bookshelf) + { + ++l; + } + } + } + } + } + + this.rand.setSeed((long)this.seed); + + for (int i1 = 0; i1 < 3; ++i1) + { + this.mana[i1] = EnchantmentHelper.calcItemStackEnchantability(this.rand, i1, l, itemstack); + this.ench[i1] = null; + + if (this.mana[i1] < i1 + 1) + { + this.mana[i1] = 0; + } + } + + for (int j1 = 0; j1 < 3; ++j1) + { + if (this.mana[j1] > 0) + { + List list = this.getRandomEnchantments(itemstack, j1, this.mana[j1]); + + if (list != null && !list.isEmpty()) + { + RngEnchantment enchantmentdata = (RngEnchantment)list.get(this.rand.zrange(list.size())); + this.ench[j1] = new Pair(enchantmentdata.enchantment, enchantmentdata.level); + } + } + } + + this.detectAndSendChanges(); + } + } + else + { + for (int i = 0; i < 3; ++i) + { + this.mana[i] = 0; + this.ench[i] = null; + } + } + } + } + + public boolean enchantItem(EntityNPC player, int id) { + ItemStack stack = this.table.getStackInSlot(0); + int cost = id + 1; + + if(this.mana[id] > 0 && stack != null && player.getManaPoints() >= cost && player.getManaPoints() >= this.mana[id]) { + if(!this.world.client) { + List ench = this.getRandomEnchantments(stack, id, this.mana[id]); + boolean book = stack.getItem() == Items.book; + + if(ench != null) { + player.useMana(cost); + player.updateEnchSeed(); + + if(book) + stack.setItem(Items.enchanted_book); + + for(int z = 0; z < ench.size(); z++) { + RngEnchantment itm = ench.get(z); + + if(book) + Items.enchanted_book.addEnchantment(stack, itm); + else + stack.addEnchantment(itm.enchantment, itm.level); + } + + this.table.markDirty(); + this.seed = player.getEnchSeed(); + this.onCraftMatrixChanged(this.table); + } + } + + return true; + } + else { + return false; + } + } + + private List getRandomEnchantments(ItemStack stack, int id, int level) + { + this.rand.setSeed((long)(this.seed + id)); + List list = EnchantmentHelper.buildEnchantmentList(this.rand, stack, level); + + if (stack.getItem() == Items.book && list != null && list.size() > 1) + { + list.remove(this.rand.zrange(list.size())); + } + + return list; + } + + public void onContainerClosed(EntityNPC playerIn) + { + super.onContainerClosed(playerIn); + + if (!this.world.client) + { + for (int i = 0; i < this.table.getSizeInventory(); ++i) + { + ItemStack itemstack = this.table.removeStackFromSlot(i); + + if (itemstack != null) + { + playerIn.dropPlayerItemWithRandomChoice(itemstack, false); + } + } + } + } + + public boolean canInteractWith(EntityNPC playerIn) + { + return this.world.getState(this.position).getBlock() != Blocks.enchanting_table ? false : playerIn.getDistanceSq((double)this.position.getX() + 0.5D, (double)this.position.getY() + 0.5D, (double)this.position.getZ() + 0.5D) <= 64.0D; + } + + public ItemStack transferStackInSlot(EntityNPC playerIn, int index) + { + ItemStack itemstack = null; + Slot slot = (Slot)this.inventorySlots.get(index); + + if (slot != null && slot.getHasStack()) + { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + + if (index == 0) + { + if (!this.mergeItemStack(itemstack1, 1, 37, true)) + { + return null; + } + } + else + { + if (((Slot)this.inventorySlots.get(0)).getHasStack() || !((Slot)this.inventorySlots.get(0)).isItemValid(itemstack1)) + { + return null; + } + + if (itemstack1.hasTagCompound() && itemstack1.size == 1) + { + ((Slot)this.inventorySlots.get(0)).putStack(itemstack1.copy()); + itemstack1.size = 0; + } + else if (itemstack1.size >= 1) + { + ((Slot)this.inventorySlots.get(0)).putStack(new ItemStack(itemstack1.getItem(), 1, itemstack1.getMetadata())); + --itemstack1.size; + } + } + + if (itemstack1.size == 0) + { + slot.putStack((ItemStack)null); + } + else + { + slot.onSlotChanged(); + } + + if (itemstack1.size == itemstack.size) + { + return null; + } + + slot.onPickupFromSlot(playerIn, itemstack1); + } + + return itemstack; + } +} diff --git a/common/src/main/java/common/inventory/ContainerEntityInventory.java b/common/src/main/java/common/inventory/ContainerEntityInventory.java new file mode 100755 index 0000000..32ba225 --- /dev/null +++ b/common/src/main/java/common/inventory/ContainerEntityInventory.java @@ -0,0 +1,132 @@ +package common.inventory; + +import common.entity.Entity; +import common.entity.animal.EntityHorse; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.item.ItemStack; + +public class ContainerEntityInventory extends Container +{ + private IInventory entityInventory; + private Entity entity; + + public ContainerEntityInventory(IInventory playerInventory, final IInventory entityInv, final Entity entity, EntityNPC player) + { + this.entityInventory = entityInv; + this.entity = entity; + int i = 3; + entityInv.openInventory(player); + int j = (i - 4) * 18; + if(this.entity instanceof EntityHorse) { + final EntityHorse horse = (EntityHorse)this.entity; + this.addSlotToContainer(new Slot(entityInv, 0, 8, 18) + { + public boolean isItemValid(ItemStack stack) + { + return super.isItemValid(stack) && stack.getItem() == Items.saddle && !this.getHasStack(); + } + }); + this.addSlotToContainer(new Slot(entityInv, 1, 8, 36) + { + public boolean isItemValid(ItemStack stack) + { + return super.isItemValid(stack) && horse.canWearArmor() && EntityHorse.isArmorItem(stack.getItem()); + } + public boolean canBeHovered() + { + return horse.canWearArmor(); + } + }); + if (horse.isChested()) + { + for (int k = 0; k < i; ++k) + { + for (int l = 0; l < 5; ++l) + { + this.addSlotToContainer(new Slot(entityInv, 2 + l + k * 5, 80 + l * 18, 18 + k * 18)); + } + } + } + } + + for (int i1 = 0; i1 < 3; ++i1) + { + for (int k1 = 0; k1 < 9; ++k1) + { + this.addSlotToContainer(new Slot(playerInventory, k1 + i1 * 9 + 9, 8 + k1 * 18, 102 + i1 * 18 + j)); + } + } + + for (int j1 = 0; j1 < 9; ++j1) + { + this.addSlotToContainer(new Slot(playerInventory, j1, 8 + j1 * 18, 160 + j)); + } + } + + public boolean canInteractWith(EntityNPC playerIn) + { + return this.entityInventory.isUseableByPlayer(playerIn) && this.entity.isEntityAlive() && this.entity.getDistanceToEntity(playerIn) < 8.0F; + } + + /** + * Take a stack from the specified inventory slot. + */ + public ItemStack transferStackInSlot(EntityNPC playerIn, int index) + { + ItemStack itemstack = null; + Slot slot = (Slot)this.inventorySlots.get(index); + + if (slot != null && slot.getHasStack()) + { + ItemStack itemstack1 = slot.getStack(); + itemstack = itemstack1.copy(); + + if (index < this.entityInventory.getSizeInventory()) + { + if (!this.mergeItemStack(itemstack1, this.entityInventory.getSizeInventory(), this.inventorySlots.size(), true)) + { + return null; + } + } + else if (this.entity instanceof EntityHorse && this.getSlot(1).isItemValid(itemstack1) && !this.getSlot(1).getHasStack()) + { + if (!this.mergeItemStack(itemstack1, 1, 2, false)) + { + return null; + } + } + else if (this.entity instanceof EntityHorse && this.getSlot(0).isItemValid(itemstack1)) + { + if (!this.mergeItemStack(itemstack1, 0, 1, false)) + { + return null; + } + } + else if (this.entity instanceof EntityHorse && (this.entityInventory.getSizeInventory() <= 2 || !this.mergeItemStack(itemstack1, 2, this.entityInventory.getSizeInventory(), false))) + { + return null; + } + + if (itemstack1.size == 0) + { + slot.putStack((ItemStack)null); + } + else + { + slot.onSlotChanged(); + } + } + + return itemstack; + } + + /** + * Called when the container is closed. + */ + public void onContainerClosed(EntityNPC playerIn) + { + super.onContainerClosed(playerIn); + this.entityInventory.closeInventory(playerIn); + } +} diff --git a/java/src/game/inventory/ContainerFurnace.java b/common/src/main/java/common/inventory/ContainerFurnace.java similarity index 94% rename from java/src/game/inventory/ContainerFurnace.java rename to common/src/main/java/common/inventory/ContainerFurnace.java index 860c51b..a4c67ff 100755 --- a/java/src/game/inventory/ContainerFurnace.java +++ b/common/src/main/java/common/inventory/ContainerFurnace.java @@ -1,9 +1,9 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.init.SmeltingRegistry; -import game.item.ItemStack; -import game.tileentity.TileEntityFurnace; +import common.entity.npc.EntityNPC; +import common.init.SmeltingRegistry; +import common.item.ItemStack; +import common.tileentity.TileEntityFurnace; public class ContainerFurnace extends Container { @@ -143,7 +143,7 @@ public class ContainerFurnace extends Container return null; } - if (itemstack1.stackSize == 0) + if (itemstack1.size == 0) { slot.putStack((ItemStack)null); } @@ -152,7 +152,7 @@ public class ContainerFurnace extends Container slot.onSlotChanged(); } - if (itemstack1.stackSize == itemstack.stackSize) + if (itemstack1.size == itemstack.size) { return null; } diff --git a/java/src/game/inventory/ContainerHopper.java b/common/src/main/java/common/inventory/ContainerHopper.java similarity index 94% rename from java/src/game/inventory/ContainerHopper.java rename to common/src/main/java/common/inventory/ContainerHopper.java index e3b0a09..9b8326b 100755 --- a/java/src/game/inventory/ContainerHopper.java +++ b/common/src/main/java/common/inventory/ContainerHopper.java @@ -1,7 +1,7 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; public class ContainerHopper extends Container { @@ -62,7 +62,7 @@ public class ContainerHopper extends Container return null; } - if (itemstack1.stackSize == 0) + if (itemstack1.size == 0) { slot.putStack((ItemStack)null); } diff --git a/java/src/game/inventory/ContainerMerchant.java b/common/src/main/java/common/inventory/ContainerMerchant.java similarity index 95% rename from java/src/game/inventory/ContainerMerchant.java rename to common/src/main/java/common/inventory/ContainerMerchant.java index 44ae587..96c4a4b 100755 --- a/java/src/game/inventory/ContainerMerchant.java +++ b/common/src/main/java/common/inventory/ContainerMerchant.java @@ -1,8 +1,8 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; -import game.world.World; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; +import common.world.World; public class ContainerMerchant extends Container { @@ -115,7 +115,7 @@ public class ContainerMerchant extends Container return null; } - if (itemstack1.stackSize == 0) + if (itemstack1.size == 0) { slot.putStack((ItemStack)null); } @@ -124,7 +124,7 @@ public class ContainerMerchant extends Container slot.onSlotChanged(); } - if (itemstack1.stackSize == itemstack.stackSize) + if (itemstack1.size == itemstack.size) { return null; } diff --git a/java/src/game/inventory/ContainerPlayer.java b/common/src/main/java/common/inventory/ContainerPlayer.java similarity index 88% rename from java/src/game/inventory/ContainerPlayer.java rename to common/src/main/java/common/inventory/ContainerPlayer.java index 24f9857..7db091b 100755 --- a/java/src/game/inventory/ContainerPlayer.java +++ b/common/src/main/java/common/inventory/ContainerPlayer.java @@ -1,14 +1,14 @@ -package game.inventory; +package common.inventory; import java.util.List; -import game.collect.Lists; - -import game.entity.attributes.AttributeMap; -import game.entity.npc.EntityNPC; -import game.init.CraftingRegistry; -import game.item.ItemArmor; -import game.item.ItemStack; +import common.attributes.AttributeMap; +import common.attributes.UsageSlot; +import common.collect.Lists; +import common.entity.npc.EntityNPC; +import common.init.CraftingRegistry; +import common.item.ItemArmor; +import common.item.ItemStack; public class ContainerPlayer extends Container { @@ -45,7 +45,7 @@ public class ContainerPlayer extends Container } public boolean isItemValid(ItemStack stack) { - return stack != null && stack.getItem() instanceof ItemArmor && ((ItemArmor)stack.getItem()).armorType == k_f; // : (stack.getItem() != ItemRegistry.getItemFromBlock(Blocks.pumpkin) && stack.getItem() != Items.skull ? false : k_f == 0)); + return stack != null && stack.getItem() instanceof ItemArmor && ((ItemArmor)stack.getItem()).armorType.getArmorSlot() == k_f; // : (stack.getItem() != ItemRegistry.getItemFromBlock(Blocks.pumpkin) && stack.getItem() != Items.skull ? false : k_f == 0)); } // public String getSlotTexture() // { @@ -91,12 +91,12 @@ public class ContainerPlayer extends Container { if (last != null) { - this.attributes.removeAttributeModifiers(last.getAttributeModifiers(2), slot.getIndex(), last.stackSize); + this.attributes.remove(last.getAttributeModifiers(UsageSlot.INVENTORY), slot.getIndex()); } if (current != null) { - this.attributes.applyAttributeModifiers(current.getAttributeModifiers(2), slot.getIndex(), current.stackSize); + this.attributes.add(current.getAttributeModifiers(UsageSlot.INVENTORY), slot.getIndex(), current.size); } last = current == null ? null : current.copy(); @@ -175,9 +175,9 @@ public class ContainerPlayer extends Container return null; } } - else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType)).getHasStack()) + else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType.getArmorSlot())).getHasStack()) { - int i = 5 + ((ItemArmor)itemstack.getItem()).armorType; + int i = 5 + ((ItemArmor)itemstack.getItem()).armorType.getArmorSlot(); if (!this.mergeItemStack(itemstack1, i, i + 1, false)) { @@ -203,7 +203,7 @@ public class ContainerPlayer extends Container return null; } - if (itemstack1.stackSize == 0) + if (itemstack1.size == 0) { slot.putStack((ItemStack)null); } @@ -212,7 +212,7 @@ public class ContainerPlayer extends Container slot.onSlotChanged(); } - if (itemstack1.stackSize == itemstack.stackSize) + if (itemstack1.size == itemstack.size) { return null; } diff --git a/java/src/game/inventory/ContainerRepair.java b/common/src/main/java/common/inventory/ContainerRepair.java similarity index 88% rename from java/src/game/inventory/ContainerRepair.java rename to common/src/main/java/common/inventory/ContainerRepair.java index 50e25f0..522df45 100755 --- a/java/src/game/inventory/ContainerRepair.java +++ b/common/src/main/java/common/inventory/ContainerRepair.java @@ -1,19 +1,19 @@ -package game.inventory; +package common.inventory; import java.util.Iterator; import java.util.Map; -import game.block.BlockAnvil; -import game.enchantment.Enchantment; -import game.enchantment.EnchantmentHelper; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Config; -import game.init.Items; -import game.item.ItemStack; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.tech.BlockAnvil; +import common.enchantment.Enchantment; +import common.enchantment.EnchantmentHelper; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.item.ItemStack; +import common.util.BlockPos; +import common.vars.Vars; +import common.world.State; +import common.world.World; public class ContainerRepair extends Container { @@ -66,13 +66,14 @@ public class ContainerRepair extends Container } public boolean canTakeStack(EntityNPC playerIn) { - return /* (playerIn.creative || */ playerIn.experienceLevel >= ContainerRepair.this.maximumCost /* ) */ && ContainerRepair.this.maximumCost > 0 && this.getHasStack(); + return /* (playerIn.creative || */ playerIn.getManaPoints() >= ContainerRepair.this.maximumCost /* ) */ && ContainerRepair.this.maximumCost > 0 && this.getHasStack(); } public void onPickupFromSlot(EntityNPC playerIn, ItemStack stack) { // if (!playerIn.creative) // { - playerIn.addExperienceLevel(-ContainerRepair.this.maximumCost); + if(!playerIn.worldObj.client) + playerIn.useMana(ContainerRepair.this.maximumCost); // } ContainerRepair.this.inputSlots.setInventorySlotContents(0, (ItemStack)null); @@ -81,9 +82,9 @@ public class ContainerRepair extends Container { ItemStack itemstack = ContainerRepair.this.inputSlots.getStackInSlot(1); - if (itemstack != null && itemstack.stackSize > ContainerRepair.this.materialCost) + if (itemstack != null && itemstack.size > ContainerRepair.this.materialCost) { - itemstack.stackSize -= ContainerRepair.this.materialCost; + itemstack.size -= ContainerRepair.this.materialCost; ContainerRepair.this.inputSlots.setInventorySlotContents(1, itemstack); } else @@ -99,7 +100,7 @@ public class ContainerRepair extends Container ContainerRepair.this.maximumCost = 0; State iblockstate = worldIn.getState(blockPosIn); - if (/* !playerIn.creative && */ !worldIn.client && Config.anvilRepairDecay && iblockstate.getBlock() == Blocks.anvil && playerIn.getRNG().floatv() < 0.12F) + if (/* !playerIn.creative && */ !worldIn.client && Vars.anvilRepairDecay && iblockstate.getBlock() == Blocks.anvil && playerIn.getRNG().floatv() < 0.12F) { int l = ((Integer)iblockstate.getValue(BlockAnvil.DAMAGE)).intValue(); ++l; @@ -176,14 +177,14 @@ public class ContainerRepair extends Container { ItemStack newStack = stack.copy(); ItemStack repStack = this.inputSlots.getStackInSlot(1); - Map newEnch = EnchantmentHelper.getEnchantments(newStack); + Map newEnch = EnchantmentHelper.getEnchantments(newStack); boolean isBook = false; repairCost = repairCost + stack.getRepairCost() + (repStack == null ? 0 : repStack.getRepairCost()); this.materialCost = 0; if (repStack != null) { - isBook = repStack.getItem() == Items.enchanted_book && Items.enchanted_book.getEnchantments(repStack).tagCount() > 0; + isBook = repStack.getItem() == Items.enchanted_book && Items.enchanted_book.getEnchantments(repStack).size() > 0; if (newStack.isItemStackDamageable() && newStack.getItem().getIsRepairable(stack, repStack)) { @@ -198,7 +199,7 @@ public class ContainerRepair extends Container int cost; - for (cost = 0; damage > 0 && cost < repStack.stackSize; ++cost) + for (cost = 0; damage > 0 && cost < repStack.size; ++cost) { int j5 = newStack.getItemDamage() - damage; newStack.setItemDamage(j5); @@ -237,18 +238,17 @@ public class ContainerRepair extends Container } } - Map ench = EnchantmentHelper.getEnchantments(repStack); - Iterator enchs = ench.keySet().iterator(); + Map ench = EnchantmentHelper.getEnchantments(repStack); + Iterator enchs = ench.keySet().iterator(); while (enchs.hasNext()) { - int eid = ((Integer)enchs.next()).intValue(); - Enchantment enchantment = Enchantment.getEnchantmentById(eid); + Enchantment enchantment = enchs.next(); if (enchantment != null) { - int newLevel = newEnch.containsKey(Integer.valueOf(eid)) ? ((Integer)newEnch.get(Integer.valueOf(eid))).intValue() : 0; - int level = ((Integer)ench.get(Integer.valueOf(eid))).intValue(); + int newLevel = newEnch.containsKey(enchantment) ? newEnch.get(enchantment) : 0; + int level = ench.get(enchantment); int diff; if (newLevel == level) @@ -269,13 +269,13 @@ public class ContainerRepair extends Container applies = true; } - Iterator newEnchs = newEnch.keySet().iterator(); + Iterator newEnchs = newEnch.keySet().iterator(); while (newEnchs.hasNext()) { - int nEid = ((Integer)newEnchs.next()).intValue(); + Enchantment nEid = newEnchs.next(); - if (nEid != eid && !enchantment.canApplyTogether(Enchantment.getEnchantmentById(nEid))) + if (nEid != enchantment && !enchantment.canApplyTogether(nEid)) { applies = false; ++totalCost; @@ -289,7 +289,7 @@ public class ContainerRepair extends Container level = enchantment.getMaxLevel(); } - newEnch.put(Integer.valueOf(eid), Integer.valueOf(level)); + newEnch.put(enchantment, level); int cost = 0; switch (enchantment.getWeight()) @@ -365,7 +365,7 @@ public class ContainerRepair extends Container if (newStack != null) { - if(!this.theWorld.client && Config.repairXP) { + if(!this.theWorld.client && Vars.repairXP) { int cost = newStack.getRepairCost(); if (repStack != null && cost < repStack.getRepairCost()) @@ -458,7 +458,7 @@ public class ContainerRepair extends Container return null; } - if (itemstack1.stackSize == 0) + if (itemstack1.size == 0) { slot.putStack((ItemStack)null); } @@ -467,7 +467,7 @@ public class ContainerRepair extends Container slot.onSlotChanged(); } - if (itemstack1.stackSize == itemstack.stackSize) + if (itemstack1.size == itemstack.size) { return null; } diff --git a/java/src/game/inventory/ContainerMachine.java b/common/src/main/java/common/inventory/ContainerTile.java similarity index 61% rename from java/src/game/inventory/ContainerMachine.java rename to common/src/main/java/common/inventory/ContainerTile.java index 1b7085b..e697fff 100755 --- a/java/src/game/inventory/ContainerMachine.java +++ b/common/src/main/java/common/inventory/ContainerTile.java @@ -1,33 +1,33 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; -import game.tileentity.TileEntityMachine; -import game.tileentity.TileEntityMachine.Status; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; +import common.tileentity.TileEntityDevice; +import common.tileentity.TileEntityDevice.Status; -public class ContainerMachine extends Container +public class ContainerTile extends Container { - private final IInventory machine; - private final TileEntityMachine tile; + private final IInventory tileInv; + private final TileEntityDevice tile; private int temperature; private Status status = Status.OFF; private final int[] resources; - public ContainerMachine(InventoryPlayer playerInv, TileEntityMachine tile, IInventory machine, EntityNPC player) + public ContainerTile(InventoryPlayer playerInv, TileEntityDevice tile, IInventory tileInv, EntityNPC player) { - this.machine = machine; + this.tileInv = tileInv; this.tile = tile; this.resources = new int[tile.getNumResources()]; - machine.openInventory(player); + tileInv.openInventory(player); int i = 71; - for (int j = 0; j < machine.getSizeInventory(); ++j) + for (int j = 0; j < tileInv.getSizeInventory(); ++j) { final int index = j; - this.addSlotToContainer(new Slot(machine, j, 8 + j * 18, 40) { + this.addSlotToContainer(new Slot(tileInv, j, 8 + j * 18, 40) { public boolean isItemValid(ItemStack stack) { - return ContainerMachine.this.tile.isItemValidForSlot(index, stack); + return ContainerTile.this.tile.isItemValidForSlot(index, stack); } }); } @@ -48,7 +48,7 @@ public class ContainerMachine extends Container public boolean canInteractWith(EntityNPC playerIn) { - return this.machine.isUseableByPlayer(playerIn); + return this.tileInv.isUseableByPlayer(playerIn); } protected boolean canTransfer(Slot slot, ItemStack stack) { @@ -65,19 +65,19 @@ public class ContainerMachine extends Container ItemStack itemstack1 = slot.getStack(); itemstack = itemstack1.copy(); - if (index < this.machine.getSizeInventory()) + if (index < this.tileInv.getSizeInventory()) { - if (!this.mergeItemStack(itemstack1, this.machine.getSizeInventory(), this.inventorySlots.size(), true)) + if (!this.mergeItemStack(itemstack1, this.tileInv.getSizeInventory(), this.inventorySlots.size(), true)) { return null; } } - else if (!this.mergeItemStack(itemstack1, 0, this.machine.getSizeInventory(), false)) + else if (!this.mergeItemStack(itemstack1, 0, this.tileInv.getSizeInventory(), false)) { return null; } - if (itemstack1.stackSize == 0) + if (itemstack1.size == 0) { slot.putStack((ItemStack)null); } @@ -93,13 +93,17 @@ public class ContainerMachine extends Container public void onContainerClosed(EntityNPC playerIn) { super.onContainerClosed(playerIn); - this.machine.closeInventory(playerIn); + this.tileInv.closeInventory(playerIn); } public void onCraftGuiOpened(ICrafting listener) { super.onCraftGuiOpened(listener); -// listener.sendAllWindowProperties(this, this.machine); + listener.sendProgressBarUpdate(this, this.resources.length, this.tile.getTemperature()); + listener.sendProgressBarUpdate(this, this.resources.length + 1, this.tile.getStatus().ordinal()); + for(int z = 0; z < this.resources.length; z++) { + listener.sendProgressBarUpdate(this, z, this.tile.getResource(z).getValue()); + } } public void updateProgressBar(int id, int data) @@ -118,14 +122,14 @@ public class ContainerMachine extends Container for (int i = 0; i < this.crafters.size(); ++i) { - ICrafting icrafting = (ICrafting)this.crafters.get(i); + ICrafting listener = this.crafters.get(i); if(this.temperature != this.tile.getTemperature()) - icrafting.sendProgressBarUpdate(this, this.resources.length, this.tile.getTemperature()); + listener.sendProgressBarUpdate(this, this.resources.length, this.tile.getTemperature()); if(this.status != this.tile.getStatus()) - icrafting.sendProgressBarUpdate(this, this.resources.length + 1, this.tile.getStatus().ordinal()); + listener.sendProgressBarUpdate(this, this.resources.length + 1, this.tile.getStatus().ordinal()); for(int z = 0; z < this.resources.length; z++) { if(this.resources[z] != this.tile.getResource(z).getValue()) - icrafting.sendProgressBarUpdate(this, z, this.tile.getResource(z).getValue()); + listener.sendProgressBarUpdate(this, z, this.tile.getResource(z).getValue()); } } diff --git a/java/src/game/inventory/ContainerWorkbench.java b/common/src/main/java/common/inventory/ContainerWorkbench.java similarity index 60% rename from java/src/game/inventory/ContainerWorkbench.java rename to common/src/main/java/common/inventory/ContainerWorkbench.java index 16904af..c0dbf6f 100755 --- a/java/src/game/inventory/ContainerWorkbench.java +++ b/common/src/main/java/common/inventory/ContainerWorkbench.java @@ -1,33 +1,36 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.CraftingRegistry; -import game.item.ItemStack; -import game.world.BlockPos; -import game.world.World; +import common.block.tech.BlockWorkbench; +import common.entity.npc.EntityNPC; +import common.init.CraftingRegistry; +import common.item.ItemStack; +import common.util.BlockPos; +import common.world.World; public class ContainerWorkbench extends Container { - /** The crafting matrix inventory (3x3). */ - public InventoryCrafting craftMatrix = new InventoryCrafting(this, 3, 3); - public IInventory craftResult = new InventoryCraftResult(); - private World worldObj; + private final int craftSlots; + public final InventoryCrafting craftMatrix; + public final IInventory craftResult = new InventoryCraftResult(); + private final World worldObj; + private final BlockPos pos; + private final BlockWorkbench block; - /** Position of the workbench */ - private BlockPos pos; - - public ContainerWorkbench(InventoryPlayer playerInventory, World worldIn, BlockPos posIn) + public ContainerWorkbench(InventoryPlayer playerInventory, World worldIn, BlockPos posIn, BlockWorkbench block) { + int size = block.getSize(); + this.block = block; this.worldObj = worldIn; this.pos = posIn; - this.addSlotToContainer(new SlotCrafting(playerInventory.player, this.craftMatrix, this.craftResult, 0, 124, 35)); + this.craftSlots = size * size; + this.craftMatrix = new InventoryCrafting(this, size, size); + this.addSlotToContainer(new SlotCrafting(playerInventory.player, this.craftMatrix, this.craftResult, 0, 134, 17 + ((size - 1) * 18) / 2)); - for (int i = 0; i < 3; ++i) + for (int i = 0; i < size; ++i) { - for (int j = 0; j < 3; ++j) + for (int j = 0; j < size; ++j) { - this.addSlotToContainer(new Slot(this.craftMatrix, j + i * 3, 30 + j * 18, 17 + i * 18)); + this.addSlotToContainer(new Slot(this.craftMatrix, j + i * size, 26 + j * 18, 17 + i * 18)); } } @@ -35,13 +38,13 @@ public class ContainerWorkbench extends Container { for (int i1 = 0; i1 < 9; ++i1) { - this.addSlotToContainer(new Slot(playerInventory, i1 + k * 9 + 9, 8 + i1 * 18, 84 + k * 18)); + this.addSlotToContainer(new Slot(playerInventory, i1 + k * 9 + 9, 8 + i1 * 18, 30 + size * 18 + k * 18)); } } for (int l = 0; l < 9; ++l) { - this.addSlotToContainer(new Slot(playerInventory, l, 8 + l * 18, 142)); + this.addSlotToContainer(new Slot(playerInventory, l, 8 + l * 18, 88 + size * 18)); } this.onCraftMatrixChanged(this.craftMatrix); @@ -64,7 +67,7 @@ public class ContainerWorkbench extends Container if (!this.worldObj.client) { - for (int i = 0; i < 9; ++i) + for (int i = 0; i < this.craftSlots; ++i) { ItemStack itemstack = this.craftMatrix.removeStackFromSlot(i); @@ -78,7 +81,7 @@ public class ContainerWorkbench extends Container public boolean canInteractWith(EntityNPC playerIn) { - return this.worldObj.getState(this.pos).getBlock() != Blocks.crafting_table ? false : playerIn.getDistanceSq((double)this.pos.getX() + 0.5D, (double)this.pos.getY() + 0.5D, (double)this.pos.getZ() + 0.5D) <= 64.0D; + return this.worldObj.getState(this.pos).getBlock() != this.block ? false : playerIn.getDistanceSq((double)this.pos.getX() + 0.5D, (double)this.pos.getY() + 0.5D, (double)this.pos.getZ() + 0.5D) <= 64.0D; } /** @@ -87,7 +90,7 @@ public class ContainerWorkbench extends Container public ItemStack transferStackInSlot(EntityNPC playerIn, int index) { ItemStack itemstack = null; - Slot slot = (Slot)this.inventorySlots.get(index); + Slot slot = this.inventorySlots.get(index); if (slot != null && slot.getHasStack()) { @@ -96,33 +99,33 @@ public class ContainerWorkbench extends Container if (index == 0) { - if (!this.mergeItemStack(itemstack1, 10, 46, true)) + if (!this.mergeItemStack(itemstack1, this.craftSlots + 1, this.craftSlots + 37, true)) { return null; } slot.onSlotChange(itemstack1, itemstack); } - else if (index >= 10 && index < 37) + else if (index >= this.craftSlots + 1 && index < this.craftSlots + 28) { - if (!this.mergeItemStack(itemstack1, 37, 46, false)) + if (!this.mergeItemStack(itemstack1, this.craftSlots + 28, this.craftSlots + 37, false)) { return null; } } - else if (index >= 37 && index < 46) + else if (index >= this.craftSlots + 28 && index < this.craftSlots + 37) { - if (!this.mergeItemStack(itemstack1, 10, 37, false)) + if (!this.mergeItemStack(itemstack1, this.craftSlots + 1, this.craftSlots + 28, false)) { return null; } } - else if (!this.mergeItemStack(itemstack1, 10, 46, false)) + else if (!this.mergeItemStack(itemstack1, this.craftSlots + 1, this.craftSlots + 37, false)) { return null; } - if (itemstack1.stackSize == 0) + if (itemstack1.size == 0) { slot.putStack((ItemStack)null); } @@ -131,7 +134,7 @@ public class ContainerWorkbench extends Container slot.onSlotChanged(); } - if (itemstack1.stackSize == itemstack.stackSize) + if (itemstack1.size == itemstack.size) { return null; } diff --git a/java/src/game/inventory/ICrafting.java b/common/src/main/java/common/inventory/ICrafting.java similarity index 87% rename from java/src/game/inventory/ICrafting.java rename to common/src/main/java/common/inventory/ICrafting.java index 68b1ffd..ce90d83 100755 --- a/java/src/game/inventory/ICrafting.java +++ b/common/src/main/java/common/inventory/ICrafting.java @@ -1,8 +1,8 @@ -package game.inventory; +package common.inventory; import java.util.List; -import game.item.ItemStack; +import common.item.ItemStack; public interface ICrafting { diff --git a/java/src/game/inventory/IInvBasic.java b/common/src/main/java/common/inventory/IInvBasic.java similarity index 87% rename from java/src/game/inventory/IInvBasic.java rename to common/src/main/java/common/inventory/IInvBasic.java index b0a8f76..880e0a2 100755 --- a/java/src/game/inventory/IInvBasic.java +++ b/common/src/main/java/common/inventory/IInvBasic.java @@ -1,4 +1,4 @@ -package game.inventory; +package common.inventory; public interface IInvBasic { diff --git a/java/src/game/inventory/IInventory.java b/common/src/main/java/common/inventory/IInventory.java similarity index 92% rename from java/src/game/inventory/IInventory.java rename to common/src/main/java/common/inventory/IInventory.java index b9ed4bb..e65cf6e 100755 --- a/java/src/game/inventory/IInventory.java +++ b/common/src/main/java/common/inventory/IInventory.java @@ -1,8 +1,8 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; -import game.tileentity.IWorldNameable; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; +import common.tileentity.IWorldNameable; public interface IInventory extends IWorldNameable { diff --git a/java/src/game/inventory/ISidedInventory.java b/common/src/main/java/common/inventory/ISidedInventory.java similarity index 86% rename from java/src/game/inventory/ISidedInventory.java rename to common/src/main/java/common/inventory/ISidedInventory.java index 076b4ae..2def255 100755 --- a/java/src/game/inventory/ISidedInventory.java +++ b/common/src/main/java/common/inventory/ISidedInventory.java @@ -1,7 +1,7 @@ -package game.inventory; +package common.inventory; -import game.item.ItemStack; -import game.world.Facing; +import common.item.ItemStack; +import common.util.Facing; public interface ISidedInventory extends IInventory { diff --git a/java/src/game/inventory/InventoryBasic.java b/common/src/main/java/common/inventory/InventoryBasic.java similarity index 91% rename from java/src/game/inventory/InventoryBasic.java rename to common/src/main/java/common/inventory/InventoryBasic.java index 38db51e..1e7086d 100755 --- a/java/src/game/inventory/InventoryBasic.java +++ b/common/src/main/java/common/inventory/InventoryBasic.java @@ -1,11 +1,10 @@ -package game.inventory; +package common.inventory; import java.util.List; -import game.collect.Lists; - -import game.entity.npc.EntityNPC; -import game.item.ItemStack; +import common.collect.Lists; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; public class InventoryBasic implements IInventory { @@ -69,7 +68,7 @@ public class InventoryBasic implements IInventory { if (this.inventoryContents[index] != null) { - if (this.inventoryContents[index].stackSize <= count) + if (this.inventoryContents[index].size <= count) { ItemStack itemstack1 = this.inventoryContents[index]; this.inventoryContents[index] = null; @@ -80,7 +79,7 @@ public class InventoryBasic implements IInventory { ItemStack itemstack = this.inventoryContents[index].splitStack(count); - if (this.inventoryContents[index].stackSize == 0) + if (this.inventoryContents[index].size == 0) { this.inventoryContents[index] = null; } @@ -113,14 +112,14 @@ public class InventoryBasic implements IInventory if (ItemStack.areItemsEqual(itemstack1, itemstack)) { int j = Math.min(this.getInventoryStackLimit(), itemstack1.getMaxStackSize()); - int k = Math.min(itemstack.stackSize, j - itemstack1.stackSize); + int k = Math.min(itemstack.size, j - itemstack1.size); if (k > 0) { - itemstack1.stackSize += k; - itemstack.stackSize -= k; + itemstack1.size += k; + itemstack.size -= k; - if (itemstack.stackSize <= 0) + if (itemstack.size <= 0) { this.markDirty(); return null; @@ -129,7 +128,7 @@ public class InventoryBasic implements IInventory } } - if (itemstack.stackSize != stack.stackSize) + if (itemstack.size != stack.size) { this.markDirty(); } @@ -161,9 +160,9 @@ public class InventoryBasic implements IInventory { this.inventoryContents[index] = stack; - if (stack != null && stack.stackSize > this.getInventoryStackLimit()) + if (stack != null && stack.size > this.getInventoryStackLimit()) { - stack.stackSize = this.getInventoryStackLimit(); + stack.size = this.getInventoryStackLimit(); } this.markDirty(); diff --git a/java/src/game/inventory/InventoryCraftResult.java b/common/src/main/java/common/inventory/InventoryCraftResult.java similarity index 97% rename from java/src/game/inventory/InventoryCraftResult.java rename to common/src/main/java/common/inventory/InventoryCraftResult.java index fe1a88f..6b41b16 100755 --- a/java/src/game/inventory/InventoryCraftResult.java +++ b/common/src/main/java/common/inventory/InventoryCraftResult.java @@ -1,7 +1,7 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; public class InventoryCraftResult implements IInventory { diff --git a/java/src/game/inventory/InventoryCrafting.java b/common/src/main/java/common/inventory/InventoryCrafting.java similarity index 96% rename from java/src/game/inventory/InventoryCrafting.java rename to common/src/main/java/common/inventory/InventoryCrafting.java index debb209..e026d87 100755 --- a/java/src/game/inventory/InventoryCrafting.java +++ b/common/src/main/java/common/inventory/InventoryCrafting.java @@ -1,7 +1,7 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; public class InventoryCrafting implements IInventory { @@ -98,7 +98,7 @@ public class InventoryCrafting implements IInventory { if (this.stackList[index] != null) { - if (this.stackList[index].stackSize <= count) + if (this.stackList[index].size <= count) { ItemStack itemstack1 = this.stackList[index]; this.stackList[index] = null; @@ -109,7 +109,7 @@ public class InventoryCrafting implements IInventory { ItemStack itemstack = this.stackList[index].splitStack(count); - if (this.stackList[index].stackSize == 0) + if (this.stackList[index].size == 0) { this.stackList[index] = null; } diff --git a/java/src/game/inventory/InventoryHelper.java b/common/src/main/java/common/inventory/InventoryHelper.java similarity index 75% rename from java/src/game/inventory/InventoryHelper.java rename to common/src/main/java/common/inventory/InventoryHelper.java index 28e04fa..97dbb15 100755 --- a/java/src/game/inventory/InventoryHelper.java +++ b/common/src/main/java/common/inventory/InventoryHelper.java @@ -1,12 +1,11 @@ -package game.inventory; +package common.inventory; -import game.entity.Entity; -import game.entity.item.EntityItem; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.rng.Random; -import game.world.BlockPos; -import game.world.World; +import common.entity.Entity; +import common.entity.item.EntityItem; +import common.item.ItemStack; +import common.rng.Random; +import common.util.BlockPos; +import common.world.World; public class InventoryHelper { @@ -41,21 +40,21 @@ public class InventoryHelper float f1 = RANDOM.floatv() * 0.8F + 0.1F; float f2 = RANDOM.floatv() * 0.8F + 0.1F; - while (stack.stackSize > 0) + while (stack.size > 0) { - int i = stack.stackSize > 64 ? stack.stackSize : (RANDOM.zrange(21) + 10); + int i = stack.size > 64 ? stack.size : (RANDOM.zrange(21) + 10); - if (i > stack.stackSize) + if (i > stack.size) { - i = stack.stackSize; + i = stack.size; } - stack.stackSize -= i; + stack.size -= i; EntityItem entityitem = new EntityItem(worldIn, x + (double)f, y + (double)f1, z + (double)f2, new ItemStack(stack.getItem(), i, stack.getMetadata())); if (stack.hasTagCompound()) { - entityitem.getEntityItem().setTagCompound((NBTTagCompound)stack.getTagCompound().copy()); + entityitem.getEntityItem().setTagCompound(stack.getTagCompound().copy()); } float f3 = 0.05F; diff --git a/java/src/game/inventory/InventoryLargeChest.java b/common/src/main/java/common/inventory/InventoryLargeChest.java similarity index 95% rename from java/src/game/inventory/InventoryLargeChest.java rename to common/src/main/java/common/inventory/InventoryLargeChest.java index 3de2405..7021e91 100755 --- a/java/src/game/inventory/InventoryLargeChest.java +++ b/common/src/main/java/common/inventory/InventoryLargeChest.java @@ -1,10 +1,10 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; -import game.tileentity.ILockableContainer; -import game.tileentity.LockCode; -import game.tileentity.TileEntityChest; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; +import common.tileentity.ILockableContainer; +import common.tileentity.Passcode; +import common.tileentity.TileEntityChest; public class InventoryLargeChest implements ILockableContainer { @@ -188,13 +188,13 @@ public class InventoryLargeChest implements ILockableContainer return this.upperChest.isLocked() || this.lowerChest.isLocked(); } - public void setLockCode(LockCode code) + public void setLockCode(Passcode code) { this.upperChest.setLockCode(code); this.lowerChest.setLockCode(code); } - public LockCode getLockCode() + public Passcode getLockCode() { return this.upperChest.getLockCode(); } diff --git a/java/src/game/inventory/InventoryMerchant.java b/common/src/main/java/common/inventory/InventoryMerchant.java similarity index 91% rename from java/src/game/inventory/InventoryMerchant.java rename to common/src/main/java/common/inventory/InventoryMerchant.java index 58a4ef1..b6f4baf 100755 --- a/java/src/game/inventory/InventoryMerchant.java +++ b/common/src/main/java/common/inventory/InventoryMerchant.java @@ -1,9 +1,9 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; -import game.village.MerchantRecipe; -import game.village.MerchantRecipeList; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; +import common.village.MerchantRecipe; +import common.village.MerchantRecipeList; public class InventoryMerchant implements IInventory { @@ -59,7 +59,7 @@ public class InventoryMerchant implements IInventory this.theInventory[index] = null; return itemstack2; } - else if (this.theInventory[index].stackSize <= count) + else if (this.theInventory[index].size <= count) { ItemStack itemstack1 = this.theInventory[index]; this.theInventory[index] = null; @@ -75,7 +75,7 @@ public class InventoryMerchant implements IInventory { ItemStack itemstack = this.theInventory[index].splitStack(count); - if (this.theInventory[index].stackSize == 0) + if (this.theInventory[index].size == 0) { this.theInventory[index] = null; } @@ -126,9 +126,9 @@ public class InventoryMerchant implements IInventory { this.theInventory[index] = stack; - if (stack != null && stack.stackSize > this.getInventoryStackLimit()) + if (stack != null && stack.size > this.getInventoryStackLimit()) { - stack.stackSize = this.getInventoryStackLimit(); + stack.size = this.getInventoryStackLimit(); } if (this.inventoryResetNeededOnSlotChange(index)) @@ -224,21 +224,21 @@ public class InventoryMerchant implements IInventory if (merchantrecipelist != null) { - MerchantRecipe merchantrecipe = merchantrecipelist.canRecipeBeUsed(itemstack, itemstack1, this.currentRecipeIndex); + MerchantRecipe merchantrecipe = merchantrecipelist.canUse(itemstack, itemstack1, this.currentRecipeIndex); if (merchantrecipe != null) // && !merchantrecipe.isRecipeDisabled()) { this.currentRecipe = merchantrecipe; - this.setInventorySlotContents(2, merchantrecipe.getItemToSell().copy()); + this.setInventorySlotContents(2, merchantrecipe.result().copy()); } else if (itemstack1 != null) { - merchantrecipe = merchantrecipelist.canRecipeBeUsed(itemstack1, itemstack, this.currentRecipeIndex); + merchantrecipe = merchantrecipelist.canUse(itemstack1, itemstack, this.currentRecipeIndex); if (merchantrecipe != null) // && !merchantrecipe.isRecipeDisabled()) { this.currentRecipe = merchantrecipe; - this.setInventorySlotContents(2, merchantrecipe.getItemToSell().copy()); + this.setInventorySlotContents(2, merchantrecipe.result().copy()); } else { diff --git a/java/src/game/inventory/InventoryPlayer.java b/common/src/main/java/common/inventory/InventoryPlayer.java similarity index 88% rename from java/src/game/inventory/InventoryPlayer.java rename to common/src/main/java/common/inventory/InventoryPlayer.java index 5450415..8802577 100755 --- a/java/src/game/inventory/InventoryPlayer.java +++ b/common/src/main/java/common/inventory/InventoryPlayer.java @@ -1,12 +1,12 @@ -package game.inventory; +package common.inventory; -import game.block.Block; -import game.entity.npc.EntityNPC; -import game.item.Item; -import game.item.ItemArmor; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; +import common.block.Block; +import common.entity.npc.EntityNPC; +import common.item.Item; +import common.item.ItemArmor; +import common.item.ItemStack; +import common.tags.TagObject; +import java.util.List; public class InventoryPlayer implements IInventory { @@ -85,7 +85,7 @@ public class InventoryPlayer implements IInventory { for (int i = 0; i < this.mainInventory.length; ++i) { - if (this.mainInventory[i] != null && this.mainInventory[i].getItem() == itemStackIn.getItem() && this.mainInventory[i].isStackable() && this.mainInventory[i].stackSize < this.mainInventory[i].getMaxStackSize() && this.mainInventory[i].stackSize < this.getInventoryStackLimit() && (!this.mainInventory[i].getHasSubtypes() || this.mainInventory[i].getMetadata() == itemStackIn.getMetadata()) && ItemStack.areItemStackTagsEqual(this.mainInventory[i], itemStackIn)) + if (this.mainInventory[i] != null && this.mainInventory[i].getItem() == itemStackIn.getItem() && this.mainInventory[i].isStackable() && this.mainInventory[i].size < this.mainInventory[i].getMaxStackSize() && this.mainInventory[i].size < this.getInventoryStackLimit() && (!this.mainInventory[i].getHasSubtypes() || this.mainInventory[i].getMetadata() == itemStackIn.getMetadata()) && ItemStack.areItemStackTagsEqual(this.mainInventory[i], itemStackIn)) { return i; } @@ -196,7 +196,7 @@ public class InventoryPlayer implements IInventory private int storePartialItemStack(ItemStack itemStackIn) { Item item = itemStackIn.getItem(); - int i = itemStackIn.stackSize; + int i = itemStackIn.size; int j = this.storeItemStack(itemStackIn); if (j < 0) @@ -216,20 +216,20 @@ public class InventoryPlayer implements IInventory if (itemStackIn.hasTagCompound()) { - this.mainInventory[j].setTagCompound((NBTTagCompound)itemStackIn.getTagCompound().copy()); + this.mainInventory[j].setTagCompound(itemStackIn.getTagCompound().copy()); } } int k = i; - if (i > this.mainInventory[j].getMaxStackSize() - this.mainInventory[j].stackSize) + if (i > this.mainInventory[j].getMaxStackSize() - this.mainInventory[j].size) { - k = this.mainInventory[j].getMaxStackSize() - this.mainInventory[j].stackSize; + k = this.mainInventory[j].getMaxStackSize() - this.mainInventory[j].size; } - if (k > this.getInventoryStackLimit() - this.mainInventory[j].stackSize) + if (k > this.getInventoryStackLimit() - this.mainInventory[j].size) { - k = this.getInventoryStackLimit() - this.mainInventory[j].stackSize; + k = this.getInventoryStackLimit() - this.mainInventory[j].size; } if (k == 0) @@ -239,7 +239,7 @@ public class InventoryPlayer implements IInventory else { i = i - k; - this.mainInventory[j].stackSize += k; + this.mainInventory[j].size += k; // this.mainInventory[j].animationsToGo = 5; return i; } @@ -274,7 +274,7 @@ public class InventoryPlayer implements IInventory } else { - if (--this.mainInventory[i].stackSize <= 0) + if (--this.mainInventory[i].size <= 0) { this.mainInventory[i] = null; } @@ -297,7 +297,7 @@ public class InventoryPlayer implements IInventory */ public boolean addItemStackToInventory(final ItemStack itemStackIn) { - if (itemStackIn != null && itemStackIn.stackSize != 0 && itemStackIn.getItem() != null) + if (itemStackIn != null && itemStackIn.size != 0 && itemStackIn.getItem() != null) { if (itemStackIn.isItemDamaged()) { @@ -307,7 +307,7 @@ public class InventoryPlayer implements IInventory { this.mainInventory[j] = ItemStack.copyItemStack(itemStackIn); // this.mainInventory[j].animationsToGo = 5; - itemStackIn.stackSize = 0; + itemStackIn.size = 0; return true; } // else if (this.player.creative) @@ -326,10 +326,10 @@ public class InventoryPlayer implements IInventory while (true) { - i = itemStackIn.stackSize; - itemStackIn.stackSize = this.storePartialItemStack(itemStackIn); + i = itemStackIn.size; + itemStackIn.size = this.storePartialItemStack(itemStackIn); - if (itemStackIn.stackSize <= 0 || itemStackIn.stackSize >= i) + if (itemStackIn.size <= 0 || itemStackIn.size >= i) { break; } @@ -342,7 +342,7 @@ public class InventoryPlayer implements IInventory // } // else // { - return itemStackIn.stackSize < i; + return itemStackIn.size < i; // } } } @@ -367,7 +367,7 @@ public class InventoryPlayer implements IInventory if (aitemstack[index] != null) { - if (aitemstack[index].stackSize <= count) + if (aitemstack[index].size <= count) { ItemStack itemstack1 = aitemstack[index]; aitemstack[index] = null; @@ -377,7 +377,7 @@ public class InventoryPlayer implements IInventory { ItemStack itemstack = aitemstack[index].splitStack(count); - if (aitemstack[index].stackSize == 0) + if (aitemstack[index].size == 0) { aitemstack[index] = null; } @@ -450,16 +450,16 @@ public class InventoryPlayer implements IInventory * * @param nbtTagListIn List to append tags to */ - public NBTTagList writeToNBT(NBTTagList nbtTagListIn) + public List writeToNBT(List nbtTagListIn) { for (int i = 0; i < this.mainInventory.length; ++i) { if (this.mainInventory[i] != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject nbttagcompound = new TagObject(); nbttagcompound.setByte("Slot", (byte)i); - this.mainInventory[i].writeToNBT(nbttagcompound); - nbtTagListIn.appendTag(nbttagcompound); + this.mainInventory[i].writeTags(nbttagcompound); + nbtTagListIn.add(nbttagcompound); } } @@ -467,10 +467,10 @@ public class InventoryPlayer implements IInventory { if (this.armorInventory[j] != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); + TagObject nbttagcompound1 = new TagObject(); nbttagcompound1.setByte("Slot", (byte)(j + 100)); - this.armorInventory[j].writeToNBT(nbttagcompound1); - nbtTagListIn.appendTag(nbttagcompound1); + this.armorInventory[j].writeTags(nbttagcompound1); + nbtTagListIn.add(nbttagcompound1); } } @@ -482,16 +482,16 @@ public class InventoryPlayer implements IInventory * * @param nbtTagListIn tagList to read from */ - public void readFromNBT(NBTTagList nbtTagListIn) + public void readFromNBT(List nbtTagListIn) { this.mainInventory = new ItemStack[36]; this.armorInventory = new ItemStack[4]; - for (int i = 0; i < nbtTagListIn.tagCount(); ++i) + for (int i = 0; i < nbtTagListIn.size(); ++i) { - NBTTagCompound nbttagcompound = nbtTagListIn.getCompoundTagAt(i); + TagObject nbttagcompound = nbtTagListIn.get(i); int j = nbttagcompound.getByte("Slot") & 255; - ItemStack itemstack = ItemStack.loadItemStackFromNBT(nbttagcompound); + ItemStack itemstack = ItemStack.readFromTag(nbttagcompound); if (itemstack != null) { @@ -564,17 +564,11 @@ public class InventoryPlayer implements IInventory return ItemStack.MAX_SIZE; } - public boolean canHeldItemHarvest(Block blockIn) - { - if (blockIn.getMaterial().isToolNotRequired()) - { + public boolean canHeldItemHarvest(Block block) { + if(!block.getMaterial().isToolRequired()) return true; - } - else - { - ItemStack itemstack = this.getStackInSlot(this.currentItem); - return itemstack != null ? itemstack.canHarvestBlock(blockIn) : false; - } + ItemStack stack = this.getStackInSlot(this.currentItem); + return stack != null && stack.canHarvestBlock(block); } /** @@ -624,7 +618,7 @@ public class InventoryPlayer implements IInventory { this.armorInventory[i].damageItem(damage, this.player); - if (this.armorInventory[i].stackSize == 0) + if (this.armorInventory[i].size == 0) { this.armorInventory[i] = null; } diff --git a/java/src/game/inventory/InventoryWarpChest.java b/common/src/main/java/common/inventory/InventoryWarpChest.java similarity index 64% rename from java/src/game/inventory/InventoryWarpChest.java rename to common/src/main/java/common/inventory/InventoryWarpChest.java index 0685445..af5b384 100755 --- a/java/src/game/inventory/InventoryWarpChest.java +++ b/common/src/main/java/common/inventory/InventoryWarpChest.java @@ -1,11 +1,12 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.world.BlockPos; +import common.collect.Lists; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.item.ItemStack; +import common.tags.TagObject; +import java.util.List; +import common.util.BlockPos; public class InventoryWarpChest extends InventoryBasic { @@ -21,28 +22,28 @@ public class InventoryWarpChest extends InventoryBasic this.associatedChest = chestTileEntity; } - public void loadInventoryFromNBT(NBTTagList p_70486_1_) + public void readTags(List list) { for (int i = 0; i < this.getSizeInventory(); ++i) { this.setInventorySlotContents(i, (ItemStack)null); } - for (int k = 0; k < p_70486_1_.tagCount(); ++k) + for (int k = 0; k < list.size(); ++k) { - NBTTagCompound nbttagcompound = p_70486_1_.getCompoundTagAt(k); - int j = nbttagcompound.getByte("Slot") & 255; + TagObject tag = list.get(k); + int j = tag.getByte("Slot") & 255; if (j >= 0 && j < this.getSizeInventory()) { - this.setInventorySlotContents(j, ItemStack.loadItemStackFromNBT(nbttagcompound)); + this.setInventorySlotContents(j, ItemStack.readFromTag(tag)); } } } - public NBTTagList saveInventoryToNBT() + public List writeTags() { - NBTTagList nbttaglist = new NBTTagList(); + List list = Lists.newArrayList(); for (int i = 0; i < this.getSizeInventory(); ++i) { @@ -50,14 +51,14 @@ public class InventoryWarpChest extends InventoryBasic if (itemstack != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setByte("Slot", (byte)i); - itemstack.writeToNBT(nbttagcompound); - nbttaglist.appendTag(nbttagcompound); + TagObject tag = new TagObject(); + tag.setByte("Slot", (byte)i); + itemstack.writeTags(tag); + list.add(tag); } } - return nbttaglist; + return list; } public boolean isUseableByPlayer(EntityNPC player) diff --git a/java/src/game/inventory/Slot.java b/common/src/main/java/common/inventory/Slot.java similarity index 96% rename from java/src/game/inventory/Slot.java rename to common/src/main/java/common/inventory/Slot.java index 1c22e6b..d386abc 100755 --- a/java/src/game/inventory/Slot.java +++ b/common/src/main/java/common/inventory/Slot.java @@ -1,7 +1,7 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; public class Slot { @@ -37,7 +37,7 @@ public class Slot { if (p_75220_1_.getItem() == p_75220_2_.getItem()) { - int i = p_75220_2_.stackSize - p_75220_1_.stackSize; + int i = p_75220_2_.size - p_75220_1_.size; if (i > 0) { diff --git a/java/src/game/inventory/SlotCrafting.java b/common/src/main/java/common/inventory/SlotCrafting.java similarity index 97% rename from java/src/game/inventory/SlotCrafting.java rename to common/src/main/java/common/inventory/SlotCrafting.java index 4bc90b2..363b5e9 100755 --- a/java/src/game/inventory/SlotCrafting.java +++ b/common/src/main/java/common/inventory/SlotCrafting.java @@ -1,8 +1,8 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.init.CraftingRegistry; -import game.item.ItemStack; +import common.entity.npc.EntityNPC; +import common.init.CraftingRegistry; +import common.item.ItemStack; public class SlotCrafting extends Slot { @@ -40,7 +40,7 @@ public class SlotCrafting extends Slot { if (this.getHasStack()) { - this.amountCrafted += Math.min(amount, this.getStack().stackSize); + this.amountCrafted += Math.min(amount, this.getStack().size); } return super.decrStackSize(amount); diff --git a/java/src/game/inventory/SlotFurnaceFuel.java b/common/src/main/java/common/inventory/SlotFurnaceFuel.java similarity index 85% rename from java/src/game/inventory/SlotFurnaceFuel.java rename to common/src/main/java/common/inventory/SlotFurnaceFuel.java index 422a196..23edd12 100755 --- a/java/src/game/inventory/SlotFurnaceFuel.java +++ b/common/src/main/java/common/inventory/SlotFurnaceFuel.java @@ -1,8 +1,8 @@ -package game.inventory; +package common.inventory; -import game.init.Items; -import game.item.ItemStack; -import game.tileentity.TileEntityFurnace; +import common.init.Items; +import common.item.ItemStack; +import common.tileentity.TileEntityFurnace; public class SlotFurnaceFuel extends Slot { diff --git a/java/src/game/inventory/SlotFurnaceOutput.java b/common/src/main/java/common/inventory/SlotFurnaceOutput.java similarity index 89% rename from java/src/game/inventory/SlotFurnaceOutput.java rename to common/src/main/java/common/inventory/SlotFurnaceOutput.java index e8ff6b2..877db02 100755 --- a/java/src/game/inventory/SlotFurnaceOutput.java +++ b/common/src/main/java/common/inventory/SlotFurnaceOutput.java @@ -1,11 +1,11 @@ -package game.inventory; +package common.inventory; -import game.entity.item.EntityXp; -import game.entity.npc.EntityNPC; -import game.init.Config; -import game.init.SmeltingRegistry; -import game.item.ItemStack; -import game.util.ExtMath; +import common.entity.item.EntityXp; +import common.entity.npc.EntityNPC; +import common.init.SmeltingRegistry; +import common.item.ItemStack; +import common.util.ExtMath; +import common.vars.Vars; public class SlotFurnaceOutput extends Slot { @@ -35,7 +35,7 @@ public class SlotFurnaceOutput extends Slot { if (this.getHasStack()) { - this.smelted += Math.min(amount, this.getStack().stackSize); + this.smelted += Math.min(amount, this.getStack().size); } return super.decrStackSize(amount); @@ -64,7 +64,7 @@ public class SlotFurnaceOutput extends Slot { // stack.onCrafting(this.thePlayer.worldObj, this.thePlayer, this.smelted); - if (!this.thePlayer.worldObj.client && Config.smeltingXP) + if (!this.thePlayer.worldObj.client && Vars.smeltingXP) { int xp = this.smelted; float smeltXp = SmeltingRegistry.getExperience(stack); diff --git a/java/src/game/inventory/SlotMerchantResult.java b/common/src/main/java/common/inventory/SlotMerchantResult.java similarity index 83% rename from java/src/game/inventory/SlotMerchantResult.java rename to common/src/main/java/common/inventory/SlotMerchantResult.java index 11c65a6..05172d5 100755 --- a/java/src/game/inventory/SlotMerchantResult.java +++ b/common/src/main/java/common/inventory/SlotMerchantResult.java @@ -1,8 +1,8 @@ -package game.inventory; +package common.inventory; -import game.entity.npc.EntityNPC; -import game.item.ItemStack; -import game.village.MerchantRecipe; +import common.entity.npc.EntityNPC; +import common.item.ItemStack; +import common.village.MerchantRecipe; public class SlotMerchantResult extends Slot { @@ -35,7 +35,7 @@ public class SlotMerchantResult extends Slot { if (this.getHasStack()) { - this.traded += Math.min(amount, this.getStack().stackSize); + this.traded += Math.min(amount, this.getStack().size); } return super.decrStackSize(amount); @@ -76,12 +76,12 @@ public class SlotMerchantResult extends Slot // this.theMerchant.useRecipe(merchantrecipe); // playerIn.triggerAchievement(StatRegistry.timesTradedWithNpcStat); - if (itemstack != null && itemstack.stackSize <= 0) + if (itemstack != null && itemstack.size <= 0) { itemstack = null; } - if (itemstack1 != null && itemstack1.stackSize <= 0) + if (itemstack1 != null && itemstack1.size <= 0) { itemstack1 = null; } @@ -94,21 +94,21 @@ public class SlotMerchantResult extends Slot private boolean doTrade(MerchantRecipe trade, ItemStack firstItem, ItemStack secondItem) { - ItemStack itemstack = trade.getItemToBuy(); - ItemStack itemstack1 = trade.getSecondItemToBuy(); + ItemStack itemstack = trade.first(); + ItemStack itemstack1 = trade.second(); if (firstItem != null && firstItem.getItem() == itemstack.getItem()) { if (itemstack1 != null && secondItem != null && itemstack1.getItem() == secondItem.getItem()) { - firstItem.stackSize -= itemstack.stackSize; - secondItem.stackSize -= itemstack1.stackSize; + firstItem.size -= itemstack.size; + secondItem.size -= itemstack1.size; return true; } if (itemstack1 == null && secondItem == null) { - firstItem.stackSize -= itemstack.stackSize; + firstItem.size -= itemstack.size; return true; } } diff --git a/common/src/main/java/common/item/CheatTab.java b/common/src/main/java/common/item/CheatTab.java new file mode 100755 index 0000000..b92c840 --- /dev/null +++ b/common/src/main/java/common/item/CheatTab.java @@ -0,0 +1,121 @@ +package common.item; + +import java.util.List; + +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; + +public enum CheatTab { + BLOCKS("Baumaterial") { + protected Item getIconItem() { + return ItemRegistry.getItemFromBlock(Blocks.glass); + } + }, + NATURE("Gestein und Natur") { + protected Item getIconItem() { + return ItemRegistry.getItemFromBlock(Blocks.grass); + } + }, + WOOD("Holz") { + protected Item getIconItem() { + return ItemRegistry.getItemFromBlock(Blocks.maple_planks); + } + }, + PLANTS("Pflanzen") { + protected Item getIconItem() { + return ItemRegistry.getItemFromBlock(Blocks.oak_leaves); + } + }, + DECORATION("Dekoration") { + protected Item getIconItem() { + return ItemRegistry.getItemFromBlock(Blocks.hay_block); + } + }, + TECHNOLOGY("Redstone & Technik") { + protected Item getIconItem() { + return ItemRegistry.getItemFromBlock(Blocks.tnt); + } + }, + GEMS("Erze & Teure Blöcke") { + protected Item getIconItem() { + return ItemRegistry.getItemFromBlock(Blocks.diamond_block); + } + }, + SPAWNERS("Mob & Itemspawner") { + protected Item getIconItem() { + return Items.minecart; + } + }, + TOOLS("Werkzeug") { + protected Item getIconItem() { + return Items.flint_and_steel; + } + }, + LIQUIDS("Flüssigkeiten") { + protected Item getIconItem() { + return Items.water_bucket; + } + }, + COMBAT("Kampf") { + protected Item getIconItem() { + return Items.bow; + } + }, + MAGIC("Tränke & Verzauberungen") { + protected Item getIconItem() { + return Items.potion; + } + }, + MATERIALS("Werkstoffe") { + protected Item getIconItem() { + return Items.leather; + } + }, + METALS("Metalle und Juwelen") { + protected Item getIconItem() { + return Items.iron_ingot; + } + }, + MISC("Verschiedenes & Nahrung") { + protected Item getIconItem() { + return Items.charge_crystal; + } + }; + + private final String name; + + private ItemStack icon; + + private CheatTab(String name) { + this.name = name; + } + + public int getHorizontal() { + return this.ordinal() % 12; + } + + public int getVertical() { + return this.ordinal() / 12; + } + + public String getName() { + return this.name; + } + + public ItemStack getIcon() { + if(this.icon == null) + this.icon = new ItemStack(this.getIconItem()); + return this.icon; + } + + protected abstract Item getIconItem(); + + public void filter(List list) { + for(Item item : ItemRegistry.REGISTRY) { + if(item != null && item.getTab() == this) { + item.getSubItems(item, this, list); + } + } + } +} diff --git a/java/src/game/item/Item.java b/common/src/main/java/common/item/Item.java similarity index 90% rename from java/src/game/item/Item.java rename to common/src/main/java/common/item/Item.java index 7a7f408..daa6b61 100755 --- a/java/src/game/item/Item.java +++ b/common/src/main/java/common/item/Item.java @@ -1,29 +1,28 @@ -package game.item; +package common.item; import java.util.List; import java.util.Map; import java.util.Set; -import game.collect.Maps; -import game.collect.Sets; - -import game.block.Block; -import game.color.TextColor; -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeModifier; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.nbt.NBTTagCompound; -import game.renderer.ItemMeshDefinition; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.HitPosition; -import game.world.Vec3; -import game.world.World; +import common.attributes.Attribute; +import common.attributes.UsageSlot; +import common.block.Block; +import common.collect.Sets; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.model.ItemMeshDefinition; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.rng.Random; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.util.HitPosition; +import common.util.Vec3; +import common.world.World; public class Item { @@ -105,7 +104,7 @@ public class Item /** * Called when an ItemStack with NBT data is read to potentially that ItemStack's NBT data */ - public boolean updateItemStackNBT(NBTTagCompound nbt) + public boolean updateItemStackNBT(TagObject nbt) { return false; } @@ -231,14 +230,6 @@ public class Item return this.display; } - /** - * If this function returns true (or the item is damageable), the ItemStack's NBT tag will be sent to the client. - */ - public boolean getShareTag() - { - return true; - } - public Item getContainerItem() { return this.containerItem; @@ -395,15 +386,13 @@ public class Item { return false; } - - public Map> getItemAttributeModifiers() - { - return Maps.newHashMap(); + + public int getAttackDamageBonus() { + return 0; } - public Map> getItemInventoryModifiers() + public void getModifiers(Map map, UsageSlot slot) { - return Maps.newHashMap(); } // public boolean canBeDyed() { @@ -428,7 +417,7 @@ public class Item // private static final Set VALID_TAGS = Sets.newHashSet("Name", "ench", "RepairCost"); - protected final boolean validateNbt(NBTTagCompound tag) { + protected final boolean validateNbt(TagObject tag) { return true; } @@ -478,14 +467,14 @@ public class Item // return false; // } //// if(tag.hasKey("display")) { -//// if(!tag.hasKey("display", 10)) { +//// if(!tag.hasTag("display")) { //// return false; //// } //// NBTTagCompound display = tag.getCompoundTag("display"); //// keys = display.getKeySet(); //// z = keys.size(); // if(tag.hasKey("Name")) { -// if(!tag.hasKey("Name", 8)) { +// if(!tag.hasString("Name")) { // return false; // } // if(tag.getString("Name").length() > 64) { @@ -505,7 +494,7 @@ public class Item //// } //// } //// else { -//// if(!display.hasKey("Lore", 9)) { +//// if(!display.hasList("Lore")) { //// return false; //// } //// NBTTagList lore = display.getTagList("Lore", 8); @@ -516,7 +505,7 @@ public class Item //// z--; //// } //// if(display.hasKey("color")) { -//// if(!display.hasKey("color", 3)) { +//// if(!display.hasInt("color")) { //// return false; //// } //// if(!this.canBeDyed()) { @@ -529,7 +518,7 @@ public class Item //// } //// } // if(tag.hasKey("RepairCost")) { -// if(!tag.hasKey("RepairCost", 3)) { +// if(!tag.hasInt("RepairCost")) { // return false; // } // if(tag.getInteger("RepairCost") < 1) { @@ -537,7 +526,7 @@ public class Item // } // } // if(tag.hasKey("ench")) { -// if(!tag.hasKey("ench", 9)) { +// if(!tag.hasList("ench")) { // return false; // } // NBTTagList ench = tag.getTagList("ench", 10); @@ -550,7 +539,7 @@ public class Item // Enchantment[] ecn = new Enchantment[ench.tagCount()]; // for(int e = 0; e < ench.tagCount(); e++) { // NBTTagCompound ec = ench.getCompoundTagAt(e); -// if(ec.getKeySet().size() != 2 || !ec.hasKey("id", 2) || !ec.hasKey("lvl", 2)) { +// if(ec.getKeySet().size() != 2 || !ec.hasShort("id") || !ec.hasShort("lvl")) { // return false; // } // int id = ec.getShort("id"); @@ -577,12 +566,12 @@ public class Item // } //// if(adv) { //// if(tag.hasKey("Unbreakable")) { -//// if(!tag.hasKey("Unbreakable", 1)) { +//// if(!tag.hasBoolean("Unbreakable")) { //// return false; //// } //// } //// if(tag.hasKey("HideFlags")) { -//// if(!tag.hasKey("HideFlags", 3)) { +//// if(!tag.hasInt("HideFlags")) { //// return false; //// } //// } @@ -660,8 +649,8 @@ public class Item return Transforms.ITEM; } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), name); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), name); } public ItemMeshDefinition getMesher() { diff --git a/java/src/game/item/ItemAction.java b/common/src/main/java/common/item/ItemAction.java similarity index 74% rename from java/src/game/item/ItemAction.java rename to common/src/main/java/common/item/ItemAction.java index 7e05c46..faf64d2 100755 --- a/java/src/game/item/ItemAction.java +++ b/common/src/main/java/common/item/ItemAction.java @@ -1,4 +1,4 @@ -package game.item; +package common.item; public enum ItemAction { NONE, EAT, DRINK, BLOCK, AIM; diff --git a/java/src/game/item/ItemAmmo.java b/common/src/main/java/common/item/ItemAmmo.java similarity index 86% rename from java/src/game/item/ItemAmmo.java rename to common/src/main/java/common/item/ItemAmmo.java index 0df9250..e76602a 100755 --- a/java/src/game/item/ItemAmmo.java +++ b/common/src/main/java/common/item/ItemAmmo.java @@ -1,4 +1,4 @@ -package game.item; +package common.item; public class ItemAmmo extends ItemMagnetic { private final int damage; @@ -6,7 +6,7 @@ public class ItemAmmo extends ItemMagnetic { public ItemAmmo(int damage, float explosion, int stack) { this.maxStackSize = stack; - this.setTab(CheatTab.tabCombat); + this.setTab(CheatTab.COMBAT); this.damage = damage; this.explosion = explosion; } diff --git a/java/src/game/item/ItemAnvilBlock.java b/common/src/main/java/common/item/ItemAnvilBlock.java similarity index 92% rename from java/src/game/item/ItemAnvilBlock.java rename to common/src/main/java/common/item/ItemAnvilBlock.java index 898f96e..8bf8549 100755 --- a/java/src/game/item/ItemAnvilBlock.java +++ b/common/src/main/java/common/item/ItemAnvilBlock.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.block.Block; +import common.block.Block; public class ItemAnvilBlock extends ItemMultiTexture { diff --git a/java/src/game/item/ItemAppleGold.java b/common/src/main/java/common/item/ItemAppleGold.java similarity index 89% rename from java/src/game/item/ItemAppleGold.java rename to common/src/main/java/common/item/ItemAppleGold.java index 5528983..a2b796a 100755 --- a/java/src/game/item/ItemAppleGold.java +++ b/common/src/main/java/common/item/ItemAppleGold.java @@ -1,12 +1,12 @@ -package game.item; +package common.item; import java.util.List; -import game.color.TextColor; -import game.entity.npc.EntityNPC; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.world.World; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.world.World; public class ItemAppleGold extends ItemFood { diff --git a/java/src/game/item/ItemArmor.java b/common/src/main/java/common/item/ItemArmor.java similarity index 71% rename from java/src/game/item/ItemArmor.java rename to common/src/main/java/common/item/ItemArmor.java index 74cedb3..3c5722c 100755 --- a/java/src/game/item/ItemArmor.java +++ b/common/src/main/java/common/item/ItemArmor.java @@ -1,29 +1,26 @@ -package game.item; +package common.item; import java.util.List; import java.util.Map; -import java.util.Set; - import java.util.function.Predicate; -import game.collect.Sets; -import game.block.BlockDispenser; -import game.dispenser.BehaviorDefaultDispenseItem; -import game.dispenser.IBehaviorDispenseItem; -import game.dispenser.IBlockSource; -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeModifier; -import game.entity.attributes.Attributes; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.DispenserRegistry; -import game.init.ToolMaterial; -import game.nbt.NBTTagCompound; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.World; +import common.attributes.Attribute; +import common.attributes.UsageSlot; +import common.block.tech.BlockDispenser; +import common.dispenser.BehaviorDefaultDispenseItem; +import common.dispenser.IBehaviorDispenseItem; +import common.dispenser.IBlockSource; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.DispenserRegistry; +import common.init.ToolMaterial; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.world.World; public class ItemArmor extends Item { @@ -50,7 +47,7 @@ public class ItemArmor extends Item int l = entitylivingbase.isPlayer() ? 1 : 0; int i1 = ItemArmor.getArmorPosition(stack); ItemStack itemstack = stack.copy(); - itemstack.stackSize = 1; + itemstack.size = 1; entitylivingbase.setItem(i1 - l, itemstack); // if (entitylivingbase instanceof EntityLiving) @@ -58,7 +55,7 @@ public class ItemArmor extends Item // ((EntityLiving)entitylivingbase).setDropChance(i1, 2.0F); // } - --stack.stackSize; + --stack.size; return stack; } else @@ -71,7 +68,7 @@ public class ItemArmor extends Item /** * Stores the armor type: 0 is helmet, 1 is plate, 2 is legs and 3 is boots */ - public final int armorType; + public final UsageSlot armorType; /** Holds the amount of damage that the armor reduces at full durability. */ public final int damageReduceAmount; @@ -86,16 +83,16 @@ public class ItemArmor extends Item private final ToolMaterial material; private final String texture; - public ItemArmor(ToolMaterial material, String texture, int armorType) + public ItemArmor(ToolMaterial material, String texture, UsageSlot armorType) { this.material = material; this.texture = texture; this.armorType = armorType; // this.renderIndex = renderIndex; - this.damageReduceAmount = material.getDamageReductionAmount(armorType); + this.damageReduceAmount = material.getDamageReduction(armorType); this.setMaxDamage(material.getDurability(armorType)); this.maxStackSize = 1; - this.setTab(CheatTab.tabCombat); + this.setTab(CheatTab.COMBAT); DispenserRegistry.REGISTRY.putObject(this, dispenserBehavior); } @@ -144,7 +141,7 @@ public class ItemArmor extends Item */ public boolean hasColor(ItemStack stack) { - return this.material.canBeDyed() && stack.hasTagCompound() && stack.getTagCompound().hasKey("color", 3); + return this.material.canBeDyed() && stack.hasTagCompound() && stack.getTagCompound().hasInt("color"); } /** @@ -158,15 +155,15 @@ public class ItemArmor extends Item } else { - NBTTagCompound nbttagcompound = stack.getTagCompound(); + TagObject nbttagcompound = stack.getTagCompound(); - if (nbttagcompound != null && nbttagcompound.hasKey("color", 3)) + if (nbttagcompound != null && nbttagcompound.hasInt("color")) { // NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); // -// if (nbttagcompound1 != null && nbttagcompound1.hasKey("color", 3)) +// if (nbttagcompound1 != null && nbttagcompound1.hasInt("color")) // { - return nbttagcompound.getInteger("color"); + return nbttagcompound.getInt("color"); // } } @@ -181,16 +178,16 @@ public class ItemArmor extends Item { if (this.material.canBeDyed()) { - NBTTagCompound nbttagcompound = stack.getTagCompound(); + TagObject nbttagcompound = stack.getTagCompound(); if (nbttagcompound != null) { // NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); - if (nbttagcompound.hasKey("color")) + if (nbttagcompound.hasInt("color")) { - nbttagcompound.removeTag("color"); - if(nbttagcompound.hasNoTags()) + nbttagcompound.remove("color"); + if(nbttagcompound.isEmpty()) stack.setTagCompound(null); } } @@ -208,22 +205,22 @@ public class ItemArmor extends Item } else { - NBTTagCompound nbttagcompound = stack.getTagCompound(); + TagObject nbttagcompound = stack.getTagCompound(); if (nbttagcompound == null) { - nbttagcompound = new NBTTagCompound(); + nbttagcompound = new TagObject(); stack.setTagCompound(nbttagcompound); } // NBTTagCompound nbttagcompound1 = nbttagcompound.getCompoundTag("display"); // -// if (!nbttagcompound.hasKey("display", 10)) +// if (!nbttagcompound.hasTag("display")) // { // nbttagcompound.setTag("display", nbttagcompound1); // } - nbttagcompound.setInteger("color", color); + nbttagcompound.setInt("color", color); } } @@ -246,7 +243,7 @@ public class ItemArmor extends Item if (itemstack == null) { playerIn.setItem(i, itemStackIn.copy()); - itemStackIn.stackSize = 0; + itemStackIn.size = 0; } return itemStackIn; @@ -256,18 +253,14 @@ public class ItemArmor extends Item // return this.material.canBeDyed(); // } - public Map> getItemAttributeModifiers() + public void getModifiers(Map map, UsageSlot slot) { - Map> multimap = super.getItemAttributeModifiers(); + if(slot != null && slot != this.armorType) + return; if(this.material.getRadiationReduction(this.armorType) > 0.0f) - multimap.put(Attributes.RADIATION_RESISTANCE, - Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID + (long)this.armorType + 1L, "Armor modifier " + (this.armorType + 1), - (double)this.material.getRadiationReduction(this.armorType), false))); + map.put(Attribute.RADIATION_RESISTANCE, this.material.getRadiationReduction(this.armorType)); if(this.material.getMagicReduction(this.armorType) > 0.0f) - multimap.put(Attributes.MAGIC_RESISTANCE, - Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID + (long)this.armorType + 1L, "Armor modifier " + (this.armorType + 1), - (double)this.material.getMagicReduction(this.armorType), false))); - return multimap; + map.put(Attribute.MAGIC_RESISTANCE, this.material.getMagicReduction(this.armorType)); } public boolean isMagnetic() { @@ -275,22 +268,22 @@ public class ItemArmor extends Item } public Transforms getTransform() { - return this.armorType == 0 ? Transforms.OFFSET2 : (this.armorType == 3 ? Transforms.OFFSET1 : + return this.armorType == UsageSlot.HEAD ? Transforms.OFFSET2 : (this.armorType == UsageSlot.FEET ? Transforms.OFFSET1 : super.getTransform()); } - public ModelBlock getModel(String name, int meta) { + public Model getModel(ModelProvider provider, String name, int meta) { if(this.material.canBeDyed()) - return new ModelBlock(this.getTransform(), name, name + "_overlay"); + return provider.getModel(this.getTransform(), name, name + "_overlay"); else - return super.getModel(name, meta); + return super.getModel(provider, name, meta); } public void addInformation(ItemStack stack, EntityNPC playerIn, List tooltip) { if(this.material.canBeDyed()) { int color = this.material.getDefaultColor(); - if(stack.hasTagCompound() && stack.getTagCompound().hasKey("color", 3)) - color = stack.getTagCompound().getInteger("color"); + if(stack.hasTagCompound() && stack.getTagCompound().hasInt("color")) + color = stack.getTagCompound().getInt("color"); tooltip.add("Farbe: #" + Integer.toHexString(color).toUpperCase()); } } @@ -303,16 +296,16 @@ public class ItemArmor extends Item // if(stack.getItem() != ItemRegistry.getItemFromBlock(Blocks.pumpkin) && stack.getItem() != Items.skull) { if(stack.getItem() instanceof ItemArmor) { switch(((ItemArmor)stack.getItem()).armorType) { - case 0: + case HEAD: return 4; - case 1: + case BODY: return 3; - case 2: + case LEGS: return 2; - case 3: + case FEET: return 1; } } diff --git a/common/src/main/java/common/item/ItemAxe.java b/common/src/main/java/common/item/ItemAxe.java new file mode 100755 index 0000000..d2230ed --- /dev/null +++ b/common/src/main/java/common/item/ItemAxe.java @@ -0,0 +1,14 @@ +package common.item; + +import common.block.Block; +import common.init.ToolMaterial; + +public class ItemAxe extends ItemTool { + public ItemAxe(ToolMaterial material) { + super(3, material); + } + + public boolean canUseOn(ItemStack stack, Block block) { + return block.canAxeHarvest(); + } +} diff --git a/java/src/game/item/ItemBanHammer.java b/common/src/main/java/common/item/ItemBanHammer.java similarity index 71% rename from java/src/game/item/ItemBanHammer.java rename to common/src/main/java/common/item/ItemBanHammer.java index 573af3f..17d20c1 100755 --- a/java/src/game/item/ItemBanHammer.java +++ b/common/src/main/java/common/item/ItemBanHammer.java @@ -1,21 +1,21 @@ -package game.item; +package common.item; import java.util.List; -import game.color.TextColor; -import game.entity.DamageSource; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.world.BoundingBox; -import game.world.Vec3; -import game.world.WorldServer; +import common.color.TextColor; +import common.entity.DamageSource; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.util.BoundingBox; +import common.util.Vec3; +import common.world.AWorldServer; public class ItemBanHammer extends ItemWand { public ItemBanHammer() { this.setColor(TextColor.DRED); } - public void onUse(ItemStack stack, EntityNPC player, WorldServer world, Vec3 vec) { + public void onUse(ItemStack stack, EntityNPC player, AWorldServer world, Vec3 vec) { List list = world.getEntitiesWithinAABB(EntityLiving.class, new BoundingBox( vec.xCoord - 3.5, vec.yCoord - 3.5, vec.zCoord - 3.5, vec.xCoord + 3.5, vec.yCoord + 3.5, vec.zCoord + 3.5)); for(EntityLiving entity : list) { diff --git a/java/src/game/item/ItemBanner.java b/common/src/main/java/common/item/ItemBanner.java similarity index 75% rename from java/src/game/item/ItemBanner.java rename to common/src/main/java/common/item/ItemBanner.java index 4885146..c5c76f6 100755 --- a/java/src/game/item/ItemBanner.java +++ b/common/src/main/java/common/item/ItemBanner.java @@ -1,30 +1,29 @@ -package game.item; +package common.item; import java.util.List; -import game.block.BlockStandingSign; -import game.block.BlockWallSign; -import game.color.DyeColor; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.model.ModelBakery; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.renderer.ItemMeshDefinition; -import game.renderer.blockmodel.ModelBlock; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityBanner; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.World; +import common.block.tile.BlockStandingSign; +import common.block.tile.BlockWallSign; +import common.color.DyeColor; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.model.ItemMeshDefinition; +import common.model.Model; +import common.model.ModelProvider; +import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityBanner; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.world.World; public class ItemBanner extends ItemBlock { public ItemBanner() { super(Blocks.banner); - this.setTab(CheatTab.tabDeco); + this.setTab(CheatTab.DECORATION); this.setHasSubtypes(true); this.setMaxDamage(0); } @@ -70,7 +69,7 @@ public class ItemBanner extends ItemBlock worldIn.setState(pos, Blocks.wall_banner.getState().withProperty(BlockWallSign.FACING, side), 3); } - --stack.stackSize; + --stack.size; TileEntity tileentity = worldIn.getTileEntity(pos); if (tileentity instanceof TileEntityBanner) @@ -96,16 +95,16 @@ public class ItemBanner extends ItemBlock */ public void addInformation(ItemStack stack, EntityNPC playerIn, List tooltip) { - NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + TagObject nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - if (nbttagcompound != null && nbttagcompound.hasKey("Patterns")) + if (nbttagcompound != null && nbttagcompound.hasList("Patterns")) { - NBTTagList nbttaglist = nbttagcompound.getTagList("Patterns", 10); + List nbttaglist = nbttagcompound.getList("Patterns"); - for (int i = 0; i < nbttaglist.tagCount() && i < 6; ++i) + for (int i = 0; i < nbttaglist.size() && i < 6; ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); - DyeColor enumdyecolor = DyeColor.byDyeDamage(nbttagcompound1.getInteger("Color")); + TagObject nbttagcompound1 = nbttaglist.get(i); + DyeColor enumdyecolor = DyeColor.byDyeDamage(nbttagcompound1.getInt("Color")); TileEntityBanner.EnumBannerPattern pattern = TileEntityBanner.EnumBannerPattern.getPatternByID(nbttagcompound1.getString("Pattern")); if (pattern != null) @@ -137,10 +136,10 @@ public class ItemBanner extends ItemBlock { for (DyeColor enumdyecolor : DyeColor.values()) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - TileEntityBanner.setBaseColorAndPatterns(nbttagcompound, enumdyecolor.getDyeDamage(), (NBTTagList)null); - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setTag("BlockEntityTag", nbttagcompound); + TagObject nbttagcompound = new TagObject(); + TileEntityBanner.setBaseColorAndPatterns(nbttagcompound, enumdyecolor.getDyeDamage(), null); + TagObject nbttagcompound1 = new TagObject(); + nbttagcompound1.setObject("BlockEntityTag", nbttagcompound); ItemStack itemstack = new ItemStack(itemIn, 1, enumdyecolor.getDyeDamage()); itemstack.setTagCompound(nbttagcompound1); subItems.add(itemstack); @@ -152,17 +151,17 @@ public class ItemBanner extends ItemBlock */ public CheatTab getTab() { - return CheatTab.tabDeco; + return CheatTab.DECORATION; } private DyeColor getBaseColor(ItemStack stack) { - NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + TagObject nbttagcompound = stack.getSubCompound("BlockEntityTag", false); DyeColor enumdyecolor = null; - if (nbttagcompound != null && nbttagcompound.hasKey("Base")) + if (nbttagcompound != null && nbttagcompound.hasInt("Base")) { - enumdyecolor = DyeColor.byDyeDamage(nbttagcompound.getInteger("Base")); + enumdyecolor = DyeColor.byDyeDamage(nbttagcompound.getInt("Base")); } else { @@ -174,12 +173,12 @@ public class ItemBanner extends ItemBlock // protected boolean validateNbt(NBTTagCompound tag) { // if(tag.hasKey("BlockEntityTag")) { -// if(!tag.hasKey("BlockEntityTag", 10)) { +// if(!tag.hasTag("BlockEntityTag")) { // return false; // } // NBTTagCompound etag = tag.getCompoundTag("BlockEntityTag"); // if(etag.hasKey("Patterns")) { -// if(!etag.hasKey("Patterns", 9)) { +// if(!etag.hasList("Patterns")) { // return false; // } // NBTTagList patterns = etag.getTagList("Patterns", 10); @@ -192,7 +191,7 @@ public class ItemBanner extends ItemBlock // } // } // if(etag.hasKey("Base")) { -// if(!etag.hasKey("Base", 3)) { +// if(!etag.hasInt("Base")) { // return false; // } // } @@ -214,7 +213,7 @@ public class ItemBanner extends ItemBlock subItems.add(new ItemStack(itemIn, 1, 0)); } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(ModelBakery.MODEL_ENTITY, this.getTransform()); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(provider.getEntityModel(), this.getTransform()); } } diff --git a/java/src/game/item/ItemBed.java b/common/src/main/java/common/item/ItemBed.java similarity index 87% rename from java/src/game/item/ItemBed.java rename to common/src/main/java/common/item/ItemBed.java index 8e5f276..0f17218 100755 --- a/java/src/game/item/ItemBed.java +++ b/common/src/main/java/common/item/ItemBed.java @@ -1,13 +1,13 @@ -package game.item; +package common.item; -import game.block.Block; -import game.block.BlockBed; -import game.entity.npc.EntityNPC; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.artificial.BlockBed; +import common.entity.npc.EntityNPC; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.world.State; +import common.world.World; public class ItemBed extends Item { @@ -16,7 +16,7 @@ public class ItemBed extends Item public ItemBed(BlockBed bedBlock) { this.bedBlock = bedBlock; - this.setTab(CheatTab.tabDeco); + this.setTab(CheatTab.DECORATION); } public Block getBlock() @@ -68,7 +68,7 @@ public class ItemBed extends Item worldIn.setState(blockpos, iblockstate2, 3); } - --stack.stackSize; + --stack.size; return true; } else diff --git a/java/src/game/item/ItemBlock.java b/common/src/main/java/common/item/ItemBlock.java similarity index 74% rename from java/src/game/item/ItemBlock.java rename to common/src/main/java/common/item/ItemBlock.java index 85c373f..8cdc501 100755 --- a/java/src/game/item/ItemBlock.java +++ b/common/src/main/java/common/item/ItemBlock.java @@ -1,21 +1,22 @@ -package game.item; +package common.item; import java.util.List; -import game.block.Block; -import game.color.TextColor; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.nbt.NBTTagCompound; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.color.TextColor; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; public class ItemBlock extends Item { @@ -61,7 +62,7 @@ public class ItemBlock extends Item pos = pos.offset(side); } - if (stack.stackSize == 0) + if (stack.size == 0) { return false; } @@ -85,7 +86,7 @@ public class ItemBlock extends Item } worldIn.playSound(this.block.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), 1.0F); - --stack.stackSize; + --stack.size; } return true; @@ -106,7 +107,7 @@ public class ItemBlock extends Item // } // else // { - if (p_179224_3_.hasTagCompound() && p_179224_3_.getTagCompound().hasKey("BlockEntityTag", 10)) + if (p_179224_3_.hasTagCompound() && p_179224_3_.getTagCompound().hasObject("BlockEntityTag")) { TileEntity tileentity = worldIn.getTileEntity(stack); @@ -117,18 +118,18 @@ public class ItemBlock extends Item return false; } - NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbttagcompound.copy(); - tileentity.writeToNBT(nbttagcompound); - NBTTagCompound nbttagcompound2 = (NBTTagCompound)p_179224_3_.getTagCompound().getTag("BlockEntityTag"); + TagObject nbttagcompound = new TagObject(); + TagObject nbttagcompound1 = nbttagcompound.copy(); + tileentity.writeTags(nbttagcompound); + TagObject nbttagcompound2 = p_179224_3_.getTagCompound().getObject("BlockEntityTag"); nbttagcompound.merge(nbttagcompound2); - nbttagcompound.setInteger("x", stack.getX()); - nbttagcompound.setInteger("y", stack.getY()); - nbttagcompound.setInteger("z", stack.getZ()); + nbttagcompound.setInt("x", stack.getX()); + nbttagcompound.setInt("y", stack.getY()); + nbttagcompound.setInt("z", stack.getZ()); if (!nbttagcompound.equals(nbttagcompound1)) { - tileentity.readFromNBT(nbttagcompound); + tileentity.readTags(nbttagcompound); tileentity.markDirty(); return true; } @@ -199,7 +200,7 @@ public class ItemBlock extends Item // // protected boolean validateNbt(NBTTagCompound tag) { // if(tag.hasKey("BlockEntityTag")) { -// if(!tag.hasKey("BlockEntityTag", 10)) { +// if(!tag.hasTag("BlockEntityTag")) { // return false; // } // } @@ -214,11 +215,11 @@ public class ItemBlock extends Item return this.flatTexture != null ? super.getTransform() : this.block.getTransform(); } - public ModelBlock getModel(String name, int meta) { - return this.flatTexture != null ? new ModelBlock(this.getTransform(), !this.flatTexture.isEmpty() ? this.flatTexture : - this.block.getModel(BlockRegistry.REGISTRY.getNameForObject(this.block).toString(), - this.block.getStateFromMeta(this.getMetadata(meta))).getPrimary() /* "blocks/" + name */) : - new ModelBlock(this.block.getModel(BlockRegistry.REGISTRY.getNameForObject(this.block).toString(), - this.block.getStateFromMeta(this.getMetadata(meta))), this.getTransform()); + public Model getModel(ModelProvider provider, String name, int meta) { + return this.flatTexture != null ? provider.getModel(this.getTransform(), !this.flatTexture.isEmpty() ? this.flatTexture : + this.block.getModel(provider, + BlockRegistry.getNameFromBlock(this.block).toString(), this.block.getStateFromMeta(this.getMetadata(meta))).getPrimary() /* "blocks/" + name */) : + provider.getModel(this.block.getModel(provider, + BlockRegistry.getNameFromBlock(this.block).toString(), this.block.getStateFromMeta(this.getMetadata(meta))), this.getTransform()); } } diff --git a/java/src/game/item/ItemBoat.java b/common/src/main/java/common/item/ItemBoat.java similarity index 90% rename from java/src/game/item/ItemBoat.java rename to common/src/main/java/common/item/ItemBoat.java index d33ba25..2d78fcf 100755 --- a/java/src/game/item/ItemBoat.java +++ b/common/src/main/java/common/item/ItemBoat.java @@ -1,24 +1,24 @@ -package game.item; +package common.item; import java.util.List; -import game.entity.Entity; -import game.entity.item.EntityBoat; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.HitPosition; -import game.world.Vec3; -import game.world.World; +import common.entity.Entity; +import common.entity.item.EntityBoat; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.HitPosition; +import common.util.Vec3; +import common.world.World; public class ItemBoat extends Item { public ItemBoat() { this.maxStackSize = 1; - this.setTab(CheatTab.tabSpawners); + this.setTab(CheatTab.SPAWNERS); } /** @@ -100,7 +100,7 @@ public class ItemBoat extends Item // if (!playerIn.creative) // { - --itemStackIn.stackSize; + --itemStackIn.size; // } // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); diff --git a/java/src/game/item/ItemBoltgun.java b/common/src/main/java/common/item/ItemBoltgun.java similarity index 80% rename from java/src/game/item/ItemBoltgun.java rename to common/src/main/java/common/item/ItemBoltgun.java index 3d25c5d..4c4f387 100755 --- a/java/src/game/item/ItemBoltgun.java +++ b/common/src/main/java/common/item/ItemBoltgun.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.init.Items; +import common.init.Items; public class ItemBoltgun extends ItemGunBase { public ItemBoltgun() { diff --git a/java/src/game/item/ItemBook.java b/common/src/main/java/common/item/ItemBook.java similarity index 86% rename from java/src/game/item/ItemBook.java rename to common/src/main/java/common/item/ItemBook.java index cc4dd7d..16c714e 100755 --- a/java/src/game/item/ItemBook.java +++ b/common/src/main/java/common/item/ItemBook.java @@ -1,4 +1,4 @@ -package game.item; +package common.item; public class ItemBook extends Item { @@ -7,7 +7,7 @@ public class ItemBook extends Item */ public boolean isItemTool(ItemStack stack) { - return stack.stackSize == 1; + return stack.size == 1; } /** diff --git a/java/src/game/item/ItemBow.java b/common/src/main/java/common/item/ItemBow.java similarity index 85% rename from java/src/game/item/ItemBow.java rename to common/src/main/java/common/item/ItemBow.java index 8147936..4ee6e40 100755 --- a/java/src/game/item/ItemBow.java +++ b/common/src/main/java/common/item/ItemBow.java @@ -1,16 +1,17 @@ -package game.item; +package common.item; import java.util.List; -import game.enchantment.Enchantment; -import game.enchantment.EnchantmentHelper; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityArrow; -import game.init.Items; -import game.init.SoundEvent; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.world.World; +import common.enchantment.Enchantment; +import common.enchantment.EnchantmentHelper; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityArrow; +import common.init.Items; +import common.init.SoundEvent; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.world.World; public class ItemBow extends Item { @@ -18,7 +19,7 @@ public class ItemBow extends Item { this.maxStackSize = 1; this.setMaxDamage(384); - this.setTab(CheatTab.tabCombat); + this.setTab(CheatTab.COMBAT); } /** @@ -26,7 +27,7 @@ public class ItemBow extends Item */ public void onPlayerStoppedUsing(ItemStack stack, World worldIn, EntityNPC playerIn, int timeLeft) { - boolean flag = /* playerIn.creative || */ EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0; + boolean flag = /* playerIn.creative || */ EnchantmentHelper.getEnchantmentLevel(Enchantment.INFINITY, stack) > 0; if (flag || playerIn.inventory.hasItem(Items.arrow)) { @@ -51,21 +52,21 @@ public class ItemBow extends Item entityarrow.setIsCritical(true); } - int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, stack); + int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.POWER, stack); if (j > 0) { entityarrow.setDamage(entityarrow.getDamage() + (double)j * 0.5D + 0.5D); } - int k = EnchantmentHelper.getEnchantmentLevel(Enchantment.punch.effectId, stack); + int k = EnchantmentHelper.getEnchantmentLevel(Enchantment.PUNCH, stack); if (k > 0) { entityarrow.setKnockbackStrength(k); } - if (EnchantmentHelper.getEnchantmentLevel(Enchantment.flame.effectId, stack) > 0) + if (EnchantmentHelper.getEnchantmentLevel(Enchantment.FLAME, stack) > 0) { entityarrow.setFire(100); } @@ -148,8 +149,8 @@ public class ItemBow extends Item return Transforms.RANGED; } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), meta == 0 ? "bow" : ("bow_pulling_" + (meta - 1))); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), meta == 0 ? "bow" : ("bow_pulling_" + (meta - 1))); } public boolean canBeWielded() { diff --git a/java/src/game/item/ItemBucket.java b/common/src/main/java/common/item/ItemBucket.java similarity index 84% rename from java/src/game/item/ItemBucket.java rename to common/src/main/java/common/item/ItemBucket.java index 65ef496..ad0b2dd 100755 --- a/java/src/game/item/ItemBucket.java +++ b/common/src/main/java/common/item/ItemBucket.java @@ -1,4 +1,4 @@ -package game.item; +package common.item; import java.util.ArrayDeque; import java.util.ArrayList; @@ -7,36 +7,36 @@ import java.util.List; import java.util.Queue; import java.util.Set; -import game.collect.Sets; - -import game.block.Block; -import game.block.BlockDynamicLiquid; -import game.block.BlockLiquid; -import game.block.BlockStaticLiquid; -import game.entity.npc.EntityNPC; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.FluidRegistry; -import game.init.ItemRegistry; -import game.init.Items; -import game.init.SoundEvent; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.world.BlockPos; -import game.world.HitPosition; -import game.world.State; -import game.world.Vec3i; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.liquid.BlockDynamicLiquid; +import common.block.liquid.BlockLiquid; +import common.block.liquid.BlockStaticLiquid; +import common.collect.Sets; +import common.entity.npc.EntityNPC; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.FluidRegistry; +import common.init.ItemRegistry; +import common.init.Items; +import common.init.SoundEvent; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ParticleType; +import common.util.BlockPos; +import common.util.HitPosition; +import common.util.Vec3i; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class ItemBucket extends Item { private final boolean recursive; private final BlockDynamicLiquid liquid; - private static boolean test(WorldServer world, BlockPos pos, Set blocks, int max, BlockPos origin, int radius) { - if(pos.getY() < 0 || pos.getY() > max) + private static boolean test(AWorldServer world, BlockPos pos, Set blocks, int max, BlockPos origin, int radius) { + if(pos.getY() < -World.MAX_SIZE_Y || pos.getY() > max) return false; if(pos.getX() < origin.getX() - radius || pos.getX() > origin.getX() + radius) return false; @@ -48,13 +48,13 @@ public class ItemBucket extends Item return blocks == null ? block instanceof BlockLiquid : blocks.contains(block); } - private static void setRecursive(WorldServer world, BlockPos origin, int radius, BlockStaticLiquid liquid) { + private static void setRecursive(AWorldServer world, BlockPos origin, int radius, BlockStaticLiquid liquid) { Queue queue = new ArrayDeque(); Set visited = new HashSet(); List dirs = new ArrayList(); Set blocks = liquid == null ? null : Sets.newHashSet(FluidRegistry.getDynamicBlock(liquid), liquid, Blocks.air); State state = (liquid == null ? Blocks.air : liquid).getState(); - int max = 511; + int max = World.MAX_SIZE_Y - 1; if(liquid != null) { dirs.add(new Vec3i(1, 0, 0)); @@ -104,7 +104,7 @@ public class ItemBucket extends Item this.maxStackSize = liquid == null ? 16 : 1; this.liquid = liquid; this.recursive = recursive; - this.setTab(CheatTab.tabTools); + this.setTab(liquid == null ? CheatTab.TOOLS : CheatTab.LIQUIDS); // if(!empty) // this.setHasSubtypes(true); } @@ -162,10 +162,10 @@ public class ItemBucket extends Item if(this.recursive) { if (material.isLiquid()) { if(!worldIn.client) - setRecursive((WorldServer)worldIn, blockpos, 4, null); + setRecursive((AWorldServer)worldIn, blockpos, 4, null); // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); // if(!playerIn.creative) - --itemStackIn.stackSize; + --itemStackIn.size; return itemStackIn; } } @@ -176,7 +176,7 @@ public class ItemBucket extends Item // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); Block block = iblockstate.getBlock(); return this.fillBucket(itemStackIn, playerIn, new ItemStack( - ItemRegistry.getRegisteredItem(BlockRegistry.REGISTRY.getNameForObject(block instanceof BlockDynamicLiquid + ItemRegistry.getRegisteredItem(BlockRegistry.getNameFromBlock(block instanceof BlockDynamicLiquid ? FluidRegistry.getStaticBlock((BlockDynamicLiquid)block) : block) + "_bucket"), 1, 0)); } @@ -200,7 +200,7 @@ public class ItemBucket extends Item { // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); if(this.recursive) { - --itemStackIn.stackSize; + --itemStackIn.size; return itemStackIn; } return new ItemStack(Items.bucket); @@ -219,7 +219,7 @@ public class ItemBucket extends Item // return emptyBuckets; // } // else - if (--emptyBuckets.stackSize <= 0) + if (--emptyBuckets.size <= 0) { return fullBucket; } @@ -251,7 +251,7 @@ public class ItemBucket extends Item } else { - if (worldIn.doesWaterVaporize(pos) && this.liquid.getMaterial() == Material.water) + if (worldIn.doesWaterVaporize(pos) && this.liquid.getMaterial() == Material.WATER) { int i = pos.getX(); int j = pos.getY(); @@ -272,7 +272,7 @@ public class ItemBucket extends Item if(this.recursive) { if(!worldIn.client) - setRecursive((WorldServer)worldIn, pos, 4, FluidRegistry.getStaticBlock(this.liquid)); + setRecursive((AWorldServer)worldIn, pos, 4, FluidRegistry.getStaticBlock(this.liquid)); } else { worldIn.setState(pos, this.liquid.getState(), 3); @@ -316,8 +316,8 @@ public class ItemBucket extends Item return true; } - public ModelBlock getModel(String name, int meta) { - return this.recursive ? new ModelBlock(this.getTransform(), name.substring("recursive_".length())) : super.getModel(name, meta); + public Model getModel(ModelProvider provider, String name, int meta) { + return this.recursive ? provider.getModel(this.getTransform(), name.substring("recursive_".length())) : super.getModel(provider, name, meta); } // public ItemMeshDefinition getMesher() { @@ -337,11 +337,11 @@ public class ItemBucket extends Item // subItems.add(new ItemStack(itemIn, 1, 0)); // } -// public ModelBlock getModel(String name, int meta) { +// public Model getModel(String name, int meta) { // if(this.empty) // return super.getModel(name, meta); // else -// return new ModelBlock(this.getTransform(), meta < 0 || meta >= FluidRegistry.getNumFluids() ? "bucket" : -// (BlockRegistry.REGISTRY.getNameForObject(FluidRegistry.getStaticBlock(meta)) + "_bucket")); +// return provider.getModel(this.getTransform(), meta < 0 || meta >= FluidRegistry.getNumFluids() ? "bucket" : +// (BlockRegistry.getNameFromBlock(FluidRegistry.getStaticBlock(meta)) + "_bucket")); // } } diff --git a/java/src/game/item/ItemBucketMilk.java b/common/src/main/java/common/item/ItemBucketMilk.java similarity index 65% rename from java/src/game/item/ItemBucketMilk.java rename to common/src/main/java/common/item/ItemBucketMilk.java index 5ffdc20..90f2e49 100755 --- a/java/src/game/item/ItemBucketMilk.java +++ b/common/src/main/java/common/item/ItemBucketMilk.java @@ -1,23 +1,18 @@ -package game.item; +package common.item; import java.util.Map; -import java.util.Set; - -import game.collect.Sets; - -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeModifier; -import game.entity.attributes.Attributes; -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.world.World; +import common.attributes.Attribute; +import common.attributes.UsageSlot; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.world.World; public class ItemBucketMilk extends Item { public ItemBucketMilk() { this.setMaxStackSize(1); - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } /** @@ -28,7 +23,7 @@ public class ItemBucketMilk extends Item { // if (!playerIn.creative) // { - --stack.stackSize; + --stack.size; // } if (!worldIn.client) @@ -37,7 +32,7 @@ public class ItemBucketMilk extends Item } // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); - return stack.stackSize <= 0 ? new ItemStack(Items.bucket) : stack; + return stack.size <= 0 ? new ItemStack(Items.bucket) : stack; } /** @@ -65,11 +60,10 @@ public class ItemBucketMilk extends Item return itemStackIn; } - public Map> getItemInventoryModifiers() + public void getModifiers(Map map, UsageSlot slot) { - Map> multimap = super.getItemInventoryModifiers(); - multimap.put(Attributes.RADIATION, Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID, "Milk modifier", -5.0, false, true, true))); - return multimap; + if(slot == null || slot == UsageSlot.INVENTORY) + map.put(Attribute.RADIATION, -5.0f); } public boolean isMagnetic() { diff --git a/java/src/game/item/ItemButton.java b/common/src/main/java/common/item/ItemButton.java similarity index 53% rename from java/src/game/item/ItemButton.java rename to common/src/main/java/common/item/ItemButton.java index 52a25e8..95b923b 100755 --- a/java/src/game/item/ItemButton.java +++ b/common/src/main/java/common/item/ItemButton.java @@ -1,7 +1,8 @@ -package game.item; +package common.item; -import game.block.BlockButton; -import game.renderer.blockmodel.ModelBlock; +import common.block.tech.BlockButton; +import common.model.Model; +import common.model.ModelProvider; public class ItemButton extends ItemBlock { private final BlockButton button; @@ -11,8 +12,8 @@ public class ItemButton extends ItemBlock { this.button = block; } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(new ModelBlock(this.button.getTexture()).add(5, 6, 6, 11, 10, 10) + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(provider.getModel(this.button.getTexture()).add(5, 6, 6, 11, 10, 10) .d().uv(5, 6, 11, 10).noCull().u().uv(5, 10, 11, 6).noCull() .ns().uv(5, 12, 11, 16).noCull().we().uv(6, 12, 10, 16).noCull(), this.getTransform()); } diff --git a/java/src/game/item/ItemCamera.java b/common/src/main/java/common/item/ItemCamera.java similarity index 85% rename from java/src/game/item/ItemCamera.java rename to common/src/main/java/common/item/ItemCamera.java index 482f7b8..7a19ef9 100755 --- a/java/src/game/item/ItemCamera.java +++ b/common/src/main/java/common/item/ItemCamera.java @@ -1,8 +1,8 @@ -package game.item; +package common.item; -import game.entity.npc.EntityNPC; -import game.world.BlockPos; -import game.world.World; +import common.entity.npc.EntityNPC; +import common.util.BlockPos; +import common.world.World; public class ItemCamera extends ItemMagnetic { public ItemCamera() { diff --git a/java/src/game/item/ItemCarrotOnAStick.java b/common/src/main/java/common/item/ItemCarrotOnAStick.java similarity index 86% rename from java/src/game/item/ItemCarrotOnAStick.java rename to common/src/main/java/common/item/ItemCarrotOnAStick.java index 33a15a4..83d923c 100755 --- a/java/src/game/item/ItemCarrotOnAStick.java +++ b/common/src/main/java/common/item/ItemCarrotOnAStick.java @@ -1,16 +1,16 @@ -package game.item; +package common.item; -import game.entity.animal.EntityPig; -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.renderer.blockmodel.Transforms; -import game.world.World; +import common.entity.animal.EntityPig; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.model.Transforms; +import common.world.World; public class ItemCarrotOnAStick extends Item { public ItemCarrotOnAStick() { - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); this.setMaxStackSize(1); this.setMaxDamage(25); } @@ -46,7 +46,7 @@ public class ItemCarrotOnAStick extends Item entitypig.getAIControlledByPlayer().boostSpeed(); itemStackIn.damageItem(7, playerIn); - if (itemStackIn.stackSize == 0) + if (itemStackIn.size == 0) { ItemStack itemstack = new ItemStack(Items.fishing_rod); itemstack.setTagCompound(itemStackIn.getTagCompound()); diff --git a/java/src/game/item/ItemChargedOrb.java b/common/src/main/java/common/item/ItemChargedOrb.java similarity index 92% rename from java/src/game/item/ItemChargedOrb.java rename to common/src/main/java/common/item/ItemChargedOrb.java index 928e51e..0b29515 100755 --- a/java/src/game/item/ItemChargedOrb.java +++ b/common/src/main/java/common/item/ItemChargedOrb.java @@ -1,24 +1,24 @@ -package game.item; +package common.item; -import game.block.BlockPortalFrame; -import game.color.TextColor; -import game.entity.item.EntityOrb; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Items; -import game.init.SoundEvent; -import game.renderer.particle.ParticleType; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.artificial.BlockPortalFrame; +import common.color.TextColor; +import common.entity.item.EntityOrb; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.init.SoundEvent; +import common.model.ParticleType; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; public class ItemChargedOrb extends ItemFragile { public ItemChargedOrb() { this.maxStackSize = 1; - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); this.setMaxDamage(16); this.setColor(TextColor.DMAGENTA); } @@ -57,7 +57,7 @@ public class ItemChargedOrb extends ItemFragile { worldIn.setState(pos, iblockstate.withProperty(BlockPortalFrame.ORB, Boolean.valueOf(true)), 2); worldIn.updateComparatorOutputLevel(pos, Blocks.portal_frame); - --stack.stackSize; + --stack.size; for (int i = 0; i < 16; ++i) { diff --git a/common/src/main/java/common/item/ItemChest.java b/common/src/main/java/common/item/ItemChest.java new file mode 100755 index 0000000..57e502c --- /dev/null +++ b/common/src/main/java/common/item/ItemChest.java @@ -0,0 +1,20 @@ +package common.item; + +import common.block.Block; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; + +public class ItemChest extends ItemBlock { + public ItemChest(Block block) { + super(block); + } + + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(provider.getEntityModel(), this.getTransform()); + } + + public Transforms getTransform() { + return Transforms.DEFAULT; + } +} diff --git a/java/src/game/item/ItemCloth.java b/common/src/main/java/common/item/ItemCloth.java similarity index 71% rename from java/src/game/item/ItemCloth.java rename to common/src/main/java/common/item/ItemCloth.java index 5892e22..6c20acb 100755 --- a/java/src/game/item/ItemCloth.java +++ b/common/src/main/java/common/item/ItemCloth.java @@ -1,8 +1,9 @@ -package game.item; +package common.item; -import game.block.Block; -import game.color.DyeColor; -import game.renderer.blockmodel.ModelBlock; +import common.block.Block; +import common.color.DyeColor; +import common.model.Model; +import common.model.ModelProvider; public class ItemCloth extends ItemBlock { @@ -39,8 +40,8 @@ public class ItemCloth extends ItemBlock return DyeColor.byMetadata(stack.getMetadata()).getSubject(this.display) + " " + super.getDisplay(stack); } - public ModelBlock getModel(String name, int meta) { - return this.flatTexture != null ? new ModelBlock(this.getTransform(), "blocks/" + DyeColor.byMetadata(meta).getName() + "_" + - this.flatTexture) : super.getModel(name, meta); + public Model getModel(ModelProvider provider, String name, int meta) { + return this.flatTexture != null ? provider.getModel(this.getTransform(), "blocks/" + DyeColor.byMetadata(meta).getName() + "_" + + this.flatTexture) : super.getModel(provider, name, meta); } } diff --git a/java/src/game/item/ItemCoal.java b/common/src/main/java/common/item/ItemCoal.java similarity index 74% rename from java/src/game/item/ItemCoal.java rename to common/src/main/java/common/item/ItemCoal.java index 4943f64..aa192ae 100755 --- a/java/src/game/item/ItemCoal.java +++ b/common/src/main/java/common/item/ItemCoal.java @@ -1,8 +1,9 @@ -package game.item; +package common.item; import java.util.List; -import game.renderer.blockmodel.ModelBlock; +import common.model.Model; +import common.model.ModelProvider; public class ItemCoal extends Item { @@ -10,7 +11,7 @@ public class ItemCoal extends Item { this.setHasSubtypes(true); this.setMaxDamage(0); - this.setTab(CheatTab.tabMetals); + this.setTab(CheatTab.METALS); } /** @@ -31,7 +32,7 @@ public class ItemCoal extends Item subItems.add(new ItemStack(itemIn, 1, 1)); } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), meta == 1 ? "charcoal" : "coal"); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), meta == 1 ? "charcoal" : "coal"); } } diff --git a/java/src/game/item/ItemColored.java b/common/src/main/java/common/item/ItemColored.java similarity index 97% rename from java/src/game/item/ItemColored.java rename to common/src/main/java/common/item/ItemColored.java index 4bddb9e..97f58a3 100755 --- a/java/src/game/item/ItemColored.java +++ b/common/src/main/java/common/item/ItemColored.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.block.Block; +import common.block.Block; public class ItemColored extends ItemBlock { diff --git a/java/src/game/item/ItemControl.java b/common/src/main/java/common/item/ItemControl.java similarity index 77% rename from java/src/game/item/ItemControl.java rename to common/src/main/java/common/item/ItemControl.java index 064f390..ececfaa 100755 --- a/java/src/game/item/ItemControl.java +++ b/common/src/main/java/common/item/ItemControl.java @@ -1,4 +1,4 @@ -package game.item; +package common.item; public enum ItemControl { PRIMARY, SECONDARY, TERTIARY, QUARTERNARY; diff --git a/java/src/game/item/ItemDie.java b/common/src/main/java/common/item/ItemDie.java similarity index 75% rename from java/src/game/item/ItemDie.java rename to common/src/main/java/common/item/ItemDie.java index c2f29ca..1afefd9 100755 --- a/java/src/game/item/ItemDie.java +++ b/common/src/main/java/common/item/ItemDie.java @@ -1,15 +1,16 @@ -package game.item; +package common.item; import java.util.List; -import game.color.TextColor; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityDie; -import game.init.SoundEvent; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.util.ExtMath; -import game.world.World; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityDie; +import common.init.SoundEvent; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.util.ExtMath; +import common.world.World; public class ItemDie extends Item { @@ -19,7 +20,7 @@ public class ItemDie extends Item public ItemDie() { - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); this.setMaxDamage(0); this.setHasSubtypes(true); } @@ -28,7 +29,7 @@ public class ItemDie extends Item { // if (!playerIn.creative) // { - --itemStackIn.stackSize; + --itemStackIn.size; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); @@ -59,8 +60,8 @@ public class ItemDie extends Item return Transforms.DICE; } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(new ModelBlock("items/die_d" + DIE_SIDES[meta] + "_side").add().nswe() + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(provider.getModel("items/die_d" + DIE_SIDES[meta] + "_side").add().nswe() .du("items/die_d" + DIE_SIDES[meta] + "_top"), this.getTransform()); } } diff --git a/java/src/game/item/ItemDispenser.java b/common/src/main/java/common/item/ItemDispenser.java similarity index 78% rename from java/src/game/item/ItemDispenser.java rename to common/src/main/java/common/item/ItemDispenser.java index fd60883..1a90ccf 100755 --- a/java/src/game/item/ItemDispenser.java +++ b/common/src/main/java/common/item/ItemDispenser.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.block.Block; +import common.block.Block; public class ItemDispenser extends ItemBlock { public ItemDispenser(Block block) { diff --git a/java/src/game/item/ItemDoor.java b/common/src/main/java/common/item/ItemDoor.java similarity index 87% rename from java/src/game/item/ItemDoor.java rename to common/src/main/java/common/item/ItemDoor.java index 8cff1fb..6a050be 100755 --- a/java/src/game/item/ItemDoor.java +++ b/common/src/main/java/common/item/ItemDoor.java @@ -1,14 +1,14 @@ -package game.item; +package common.item; -import game.block.Block; -import game.block.BlockDoor; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.material.Material; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.block.artificial.BlockDoor; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; public class ItemDoor extends Item { @@ -17,7 +17,7 @@ public class ItemDoor extends Item public ItemDoor(Block block) { this.block = block; - this.setTab(block.getMaterial() == Material.wood ? CheatTab.tabWood : CheatTab.tabTech); + this.setTab(block.getMaterial() == Material.WOOD ? CheatTab.WOOD : CheatTab.TECHNOLOGY); } public Block getBlock() @@ -55,7 +55,7 @@ public class ItemDoor extends Item else { placeDoor(worldIn, pos, Facing.fromAngle((double)playerIn.rotYaw), this.block, true); - --stack.stackSize; + --stack.size; return true; } } diff --git a/java/src/game/item/ItemDoublePlant.java b/common/src/main/java/common/item/ItemDoublePlant.java similarity index 70% rename from java/src/game/item/ItemDoublePlant.java rename to common/src/main/java/common/item/ItemDoublePlant.java index e326216..2e1875e 100755 --- a/java/src/game/item/ItemDoublePlant.java +++ b/common/src/main/java/common/item/ItemDoublePlant.java @@ -1,12 +1,13 @@ -package game.item; +package common.item; import java.util.function.Function; -import game.block.Block; -import game.block.BlockDoublePlant; -import game.block.BlockDoublePlant.EnumPlantType; -import game.color.Colorizer; -import game.renderer.blockmodel.ModelBlock; +import common.block.Block; +import common.block.foliage.BlockDoublePlant; +import common.block.foliage.BlockDoublePlant.EnumPlantType; +import common.color.Colorizer; +import common.model.Model; +import common.model.ModelProvider; public class ItemDoublePlant extends ItemMultiTexture { @@ -21,8 +22,8 @@ public class ItemDoublePlant extends ItemMultiTexture return blockdoubleplant$enumplanttype != BlockDoublePlant.EnumPlantType.GRASS && blockdoubleplant$enumplanttype != BlockDoublePlant.EnumPlantType.FERN ? super.getColorFromItemStack(stack, renderPass) : Colorizer.getGrassColor(0.5D, 1.0D); } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), "blocks/" + ( + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), "blocks/" + ( BlockDoublePlant.EnumPlantType.byMetadata(meta) == EnumPlantType.SUNFLOWER ? "sunflower_front" : BlockDoublePlant.EnumPlantType.byMetadata(meta).getName() + "_top")); } diff --git a/java/src/game/item/ItemDye.java b/common/src/main/java/common/item/ItemDye.java similarity index 84% rename from java/src/game/item/ItemDye.java rename to common/src/main/java/common/item/ItemDye.java index 46ca085..af0b10b 100755 --- a/java/src/game/item/ItemDye.java +++ b/common/src/main/java/common/item/ItemDye.java @@ -1,26 +1,26 @@ -package game.item; +package common.item; import java.util.List; -import game.block.Block; -import game.block.BlockBed; -import game.block.IGrowable; -import game.color.DyeColor; -import game.entity.animal.EntitySheep; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.particle.ParticleType; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityBeacon; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.block.artificial.BlockBed; +import common.block.foliage.IGrowable; +import common.color.DyeColor; +import common.entity.animal.EntitySheep; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.model.Model; +import common.model.ModelProvider; +import common.model.ParticleType; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityBeacon; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class ItemDye extends Item { @@ -30,7 +30,7 @@ public class ItemDye extends Item { this.setHasSubtypes(true); this.setMaxDamage(0); - this.setTab(CheatTab.tabMaterials); + this.setTab(CheatTab.MATERIALS); } /** @@ -94,7 +94,7 @@ public class ItemDye extends Item // if (!playerIn.creative) // { - --stack.stackSize; + --stack.size; // } } @@ -103,8 +103,8 @@ public class ItemDye extends Item } State iblockstate = worldIn.getState(pos); if(iblockstate.getBlock() instanceof BlockBed) { - Block bedBlock = BlockRegistry.getByNameOrId(enumdyecolor.getName() + "_bed"); - if(bedBlock != null) { + Block bedBlock = BlockRegistry.getRegisteredBlock(enumdyecolor.getName() + "_bed"); + if(bedBlock != Blocks.air) { if (iblockstate.getValue(BlockBed.PART) == BlockBed.EnumPartType.FOOT) { pos = pos.offset(iblockstate.getValue(BlockBed.FACING)); @@ -127,7 +127,7 @@ public class ItemDye extends Item worldIn.setState(pos, iblockstate1, 2); } // if(!playerIn.creative) - --stack.stackSize; + --stack.size; return true; } } @@ -136,7 +136,7 @@ public class ItemDye extends Item if(te instanceof TileEntityBeacon) { ((TileEntityBeacon)te).setBeamColor(enumdyecolor); // if(!playerIn.creative) - --stack.stackSize; + --stack.size; } } @@ -158,10 +158,10 @@ public class ItemDye extends Item { if (igrowable.canUseBonemeal(worldIn, worldIn.rand, target, iblockstate)) { - igrowable.grow((WorldServer)worldIn, worldIn.rand, target, iblockstate); + igrowable.grow((AWorldServer)worldIn, worldIn.rand, target, iblockstate); } - --stack.stackSize; + --stack.size; } return true; @@ -180,7 +180,7 @@ public class ItemDye extends Item Block block = worldIn.getState(pos).getBlock(); - if (block.getMaterial() != Material.air) + if (block != Blocks.air) { block.setBlockBoundsBasedOnState(worldIn, pos); @@ -207,7 +207,7 @@ public class ItemDye extends Item if (!entitysheep.getSheared() && entitysheep.getFleeceColor() != enumdyecolor) { entitysheep.setFleeceColor(enumdyecolor); - --stack.stackSize; + --stack.size; } return true; @@ -229,7 +229,7 @@ public class ItemDye extends Item } } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), "dye_" + DyeColor.byDyeDamage(meta).getName()); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), "dye_" + DyeColor.byDyeDamage(meta).getName()); } } diff --git a/java/src/game/item/ItemDynamite.java b/common/src/main/java/common/item/ItemDynamite.java similarity index 74% rename from java/src/game/item/ItemDynamite.java rename to common/src/main/java/common/item/ItemDynamite.java index ffd637d..d343350 100755 --- a/java/src/game/item/ItemDynamite.java +++ b/common/src/main/java/common/item/ItemDynamite.java @@ -1,12 +1,13 @@ -package game.item; +package common.item; import java.util.List; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityDynamite; -import game.init.SoundEvent; -import game.renderer.blockmodel.ModelBlock; -import game.world.World; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityDynamite; +import common.init.SoundEvent; +import common.model.Model; +import common.model.ModelProvider; +import common.world.World; public class ItemDynamite extends Item { @@ -15,7 +16,7 @@ public class ItemDynamite extends Item public ItemDynamite() { this.maxStackSize = 32; - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); this.setMaxDamage(0); this.setHasSubtypes(true); } @@ -27,7 +28,7 @@ public class ItemDynamite extends Item { // if (!playerIn.creative) // { - --itemStackIn.stackSize; + --itemStackIn.size; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); @@ -54,7 +55,7 @@ public class ItemDynamite extends Item return super.getDisplay(stack) + (exp == 0 ? "" : " " + TIERS[exp-1]); } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), "dynamite" + (meta == 0 ? "" : ("_" + meta))); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), "dynamite" + (meta == 0 ? "" : ("_" + meta))); } } diff --git a/java/src/game/item/ItemEditWand.java b/common/src/main/java/common/item/ItemEditWand.java similarity index 84% rename from java/src/game/item/ItemEditWand.java rename to common/src/main/java/common/item/ItemEditWand.java index 057a0f5..6d1baa9 100755 --- a/java/src/game/item/ItemEditWand.java +++ b/common/src/main/java/common/item/ItemEditWand.java @@ -1,14 +1,14 @@ -package game.item; +package common.item; -import game.entity.npc.EntityNPC; -import game.renderer.blockmodel.Transforms; -import game.world.BlockPos; -import game.world.World; +import common.entity.npc.EntityNPC; +import common.model.Transforms; +import common.util.BlockPos; +import common.world.World; public class ItemEditWand extends Item { public ItemEditWand() { this.maxStackSize = 1; - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } // public boolean canBreakBlocks() { diff --git a/java/src/game/item/ItemEffect.java b/common/src/main/java/common/item/ItemEffect.java similarity index 85% rename from java/src/game/item/ItemEffect.java rename to common/src/main/java/common/item/ItemEffect.java index fd5d017..c68b31a 100755 --- a/java/src/game/item/ItemEffect.java +++ b/common/src/main/java/common/item/ItemEffect.java @@ -1,4 +1,4 @@ -package game.item; +package common.item; public class ItemEffect extends Item { diff --git a/java/src/game/item/ItemEgg.java b/common/src/main/java/common/item/ItemEgg.java similarity index 75% rename from java/src/game/item/ItemEgg.java rename to common/src/main/java/common/item/ItemEgg.java index 2f95774..10a8f70 100755 --- a/java/src/game/item/ItemEgg.java +++ b/common/src/main/java/common/item/ItemEgg.java @@ -1,15 +1,15 @@ -package game.item; +package common.item; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityEgg; -import game.init.SoundEvent; -import game.world.World; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityEgg; +import common.init.SoundEvent; +import common.world.World; public class ItemEgg extends Item { public ItemEgg() { - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } /** @@ -19,7 +19,7 @@ public class ItemEgg extends Item { // if (!playerIn.creative) // { - --itemStackIn.stackSize; + --itemStackIn.size; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); diff --git a/java/src/game/item/ItemEnchantedBook.java b/common/src/main/java/common/item/ItemEnchantedBook.java similarity index 67% rename from java/src/game/item/ItemEnchantedBook.java rename to common/src/main/java/common/item/ItemEnchantedBook.java index bd1834f..37a1079 100755 --- a/java/src/game/item/ItemEnchantedBook.java +++ b/common/src/main/java/common/item/ItemEnchantedBook.java @@ -1,17 +1,17 @@ -package game.item; +package common.item; import java.util.List; -import game.color.TextColor; -import game.enchantment.Enchantment; -import game.enchantment.EnchantmentHelper; -import game.enchantment.RngEnchantment; -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.renderer.ItemMeshDefinition; -import game.rng.Random; +import common.collect.Lists; +import common.color.TextColor; +import common.enchantment.Enchantment; +import common.enchantment.EnchantmentHelper; +import common.enchantment.RngEnchantment; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.model.ItemMeshDefinition; +import common.rng.Random; +import common.tags.TagObject; public class ItemEnchantedBook extends Item { @@ -34,8 +34,8 @@ public class ItemEnchantedBook extends Item public void getSubItems(Item itemIn, CheatTab tab, List subItems) { - for (Enchantment enchantment : Enchantment.enchantmentsBookList) { - if(enchantment != null && enchantment.type != null) + for (Enchantment enchantment : Enchantment.values()) { + if(enchantment != null && enchantment.getType() != null) subItems.add(Items.enchanted_book.getEnchantedItemStack(new RngEnchantment(enchantment, enchantment.getMaxLevel()))); } } @@ -48,10 +48,10 @@ public class ItemEnchantedBook extends Item // return this.getEnchantments(stack).tagCount() > 0 ? ChatFormat.YELLOW : super.getColor(stack); // } - public NBTTagList getEnchantments(ItemStack stack) + public List getEnchantments(ItemStack stack) { - NBTTagCompound nbttagcompound = stack.getTagCompound(); - return nbttagcompound != null && nbttagcompound.hasKey("StoredEnchantments", 9) ? (NBTTagList)nbttagcompound.getTag("StoredEnchantments") : new NBTTagList(); + TagObject nbttagcompound = stack.getTagCompound(); + return nbttagcompound != null && nbttagcompound.hasList("StoredEnchantments") ? nbttagcompound.getList("StoredEnchantments") : Lists.newArrayList(); } /** @@ -60,18 +60,18 @@ public class ItemEnchantedBook extends Item public void addInformation(ItemStack stack, EntityNPC playerIn, List tooltip) { super.addInformation(stack, playerIn, tooltip); - NBTTagList nbttaglist = this.getEnchantments(stack); + List nbttaglist = this.getEnchantments(stack); if (nbttaglist != null) { - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - int j = nbttaglist.getCompoundTagAt(i).getShort("id"); - int k = nbttaglist.getCompoundTagAt(i).getShort("lvl"); + Enchantment j = Enchantment.getEnchantment(nbttaglist.get(i).getString("id")); - if (Enchantment.getEnchantmentById(j) != null) + if (j != null) { - tooltip.add(Enchantment.getEnchantmentById(j).getFormattedName(k)); + int k = nbttaglist.get(i).getShort("lvl"); + tooltip.add(j.getFormattedName(k)); } } } @@ -82,18 +82,18 @@ public class ItemEnchantedBook extends Item */ public void addEnchantment(ItemStack stack, RngEnchantment enchantment) { - NBTTagList nbttaglist = this.getEnchantments(stack); + List nbttaglist = this.getEnchantments(stack); boolean flag = true; - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + TagObject nbttagcompound = nbttaglist.get(i); - if (nbttagcompound.getShort("id") == enchantment.enchantmentobj.effectId) + if (Enchantment.getEnchantment(nbttagcompound.getString("id")) == enchantment.enchantment) { - if (nbttagcompound.getShort("lvl") < enchantment.enchantmentLevel) + if (nbttagcompound.getShort("lvl") < enchantment.level) { - nbttagcompound.setShort("lvl", (short)enchantment.enchantmentLevel); + nbttagcompound.setShort("lvl", (short)enchantment.level); } flag = false; @@ -103,18 +103,18 @@ public class ItemEnchantedBook extends Item if (flag) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - nbttagcompound1.setShort("id", (short)enchantment.enchantmentobj.effectId); - nbttagcompound1.setShort("lvl", (short)enchantment.enchantmentLevel); - nbttaglist.appendTag(nbttagcompound1); + TagObject nbttagcompound1 = new TagObject(); + nbttagcompound1.setString("id", enchantment.enchantment.getName()); + nbttagcompound1.setShort("lvl", (short)enchantment.level); + nbttaglist.add(nbttagcompound1); } if (!stack.hasTagCompound()) { - stack.setTagCompound(new NBTTagCompound()); + stack.setTagCompound(new TagObject()); } - stack.getTagCompound().setTag("StoredEnchantments", nbttaglist); + stack.getTagCompound().setList("StoredEnchantments", nbttaglist); } /** @@ -153,7 +153,7 @@ public class ItemEnchantedBook extends Item // // protected boolean validateNbt(NBTTagCompound tag) { // if(tag.hasKey("StoredEnchantments")) { -// if(!tag.hasKey("StoredEnchantments", 9)) { +// if(!tag.hasList("StoredEnchantments")) { // return false; // } // NBTTagList ench = tag.getTagList("StoredEnchantments", 10); @@ -166,7 +166,7 @@ public class ItemEnchantedBook extends Item // Enchantment[] ecn = new Enchantment[ench.tagCount()]; // for(int e = 0; e < ench.tagCount(); e++) { // NBTTagCompound ec = ench.getCompoundTagAt(e); -// if(ec.getKeySet().size() != 2 || !ec.hasKey("id", 2) || !ec.hasKey("lvl", 2)) { +// if(ec.getKeySet().size() != 2 || !ec.hasShort("id") || !ec.hasShort("lvl")) { // return false; // } // int id = ec.getShort("id"); diff --git a/java/src/game/item/ItemExpBottle.java b/common/src/main/java/common/item/ItemExpBottle.java similarity index 78% rename from java/src/game/item/ItemExpBottle.java rename to common/src/main/java/common/item/ItemExpBottle.java index 9d5fd72..754f347 100755 --- a/java/src/game/item/ItemExpBottle.java +++ b/common/src/main/java/common/item/ItemExpBottle.java @@ -1,15 +1,15 @@ -package game.item; +package common.item; -import game.entity.item.EntityXpBottle; -import game.entity.npc.EntityNPC; -import game.init.SoundEvent; -import game.world.World; +import common.entity.item.EntityXpBottle; +import common.entity.npc.EntityNPC; +import common.init.SoundEvent; +import common.world.World; public class ItemExpBottle extends Item { public ItemExpBottle() { - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } public boolean hasEffect(ItemStack stack) @@ -24,7 +24,7 @@ public class ItemExpBottle extends Item { // if (!playerIn.creative) // { - --itemStackIn.stackSize; + --itemStackIn.size; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); diff --git a/java/src/game/item/ItemExterminator.java b/common/src/main/java/common/item/ItemExterminator.java similarity index 80% rename from java/src/game/item/ItemExterminator.java rename to common/src/main/java/common/item/ItemExterminator.java index 002554b..cd5287d 100755 --- a/java/src/game/item/ItemExterminator.java +++ b/common/src/main/java/common/item/ItemExterminator.java @@ -1,11 +1,11 @@ -package game.item; +package common.item; -import game.color.TextColor; -import game.dimension.Space; -import game.entity.npc.EntityNPC; -import game.init.SoundEvent; -import game.world.World; -import game.world.WorldServer; +import common.color.TextColor; +import common.dimension.Space; +import common.entity.npc.EntityNPC; +import common.init.SoundEvent; +import common.world.World; +import common.world.AWorldServer; public class ItemExterminator extends ItemMagnetic { public ItemExterminator() { @@ -22,7 +22,7 @@ public class ItemExterminator extends ItemMagnetic { world.playSoundAtEntity(player, SoundEvent.CLICK, 1.0F); if(world.dimension == Space.INSTANCE) player.connection.addHotbar(TextColor.RED + "Der Weltraum kann nicht zerstört werden (lol)"); - else if(!((WorldServer)world).exterminate()) + else if(!((AWorldServer)world).exterminate()) player.connection.addHotbar(TextColor.YELLOW + "Die Welt %s ist bereits zerstört", world.dimension.getFormattedName(false)); else player.connection.addHotbar(TextColor.CRIMSON + "Die Welt %s wurde vernichtet >:)-", world.dimension.getFormattedName(false)); diff --git a/java/src/game/item/ItemFence.java b/common/src/main/java/common/item/ItemFence.java similarity index 78% rename from java/src/game/item/ItemFence.java rename to common/src/main/java/common/item/ItemFence.java index a36455d..cd6c5c0 100755 --- a/java/src/game/item/ItemFence.java +++ b/common/src/main/java/common/item/ItemFence.java @@ -1,16 +1,17 @@ -package game.item; +package common.item; -import game.block.Block; -import game.block.BlockFence; -import game.renderer.blockmodel.ModelBlock; +import common.block.Block; +import common.block.artificial.BlockFence; +import common.model.Model; +import common.model.ModelProvider; public class ItemFence extends ItemBlock { public ItemFence(Block block) { super(block); } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(new ModelBlock(((BlockFence)this.block).getTexture()).noOcclude() + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(provider.getModel(((BlockFence)this.block).getTexture()) .add(6, 0, 0, 10, 16, 4) .d().uv(6, 0, 10, 4) .u().uv(6, 0, 10, 4).noCull() diff --git a/java/src/game/item/ItemFireball.java b/common/src/main/java/common/item/ItemFireball.java similarity index 72% rename from java/src/game/item/ItemFireball.java rename to common/src/main/java/common/item/ItemFireball.java index dc9dc57..4cacb31 100755 --- a/java/src/game/item/ItemFireball.java +++ b/common/src/main/java/common/item/ItemFireball.java @@ -1,18 +1,17 @@ -package game.item; +package common.item; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.SoundEvent; -import game.material.Material; -import game.world.BlockPos; -import game.world.Facing; -import game.world.World; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.SoundEvent; +import common.util.BlockPos; +import common.util.Facing; +import common.world.World; public class ItemFireball extends Item { public ItemFireball() { - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } /** @@ -34,7 +33,7 @@ public class ItemFireball extends Item } else { - if (worldIn.getState(pos).getBlock().getMaterial() == Material.air) + if (worldIn.getState(pos).getBlock() == Blocks.air) { worldIn.playSound(SoundEvent.FIREBALL, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, 1.0F); worldIn.setState(pos, Blocks.fire.getState()); @@ -42,7 +41,7 @@ public class ItemFireball extends Item // if (!playerIn.creative) // { - --stack.stackSize; + --stack.size; // } return true; diff --git a/java/src/game/item/ItemFirework.java b/common/src/main/java/common/item/ItemFirework.java similarity index 71% rename from java/src/game/item/ItemFirework.java rename to common/src/main/java/common/item/ItemFirework.java index 3e867cc..4f207b2 100755 --- a/java/src/game/item/ItemFirework.java +++ b/common/src/main/java/common/item/ItemFirework.java @@ -1,16 +1,14 @@ -package game.item; +package common.item; import java.util.List; -import game.collect.Lists; - -import game.entity.item.EntityFireworks; -import game.entity.npc.EntityNPC; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.world.BlockPos; -import game.world.Facing; -import game.world.World; +import common.collect.Lists; +import common.entity.item.EntityFireworks; +import common.entity.npc.EntityNPC; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.Facing; +import common.world.World; public class ItemFirework extends Item { @@ -26,7 +24,7 @@ public class ItemFirework extends Item // if (!playerIn.creative) // { - --stack.stackSize; + --stack.size; // } return true; @@ -44,22 +42,22 @@ public class ItemFirework extends Item { if (stack.hasTagCompound()) { - NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("Fireworks"); + TagObject nbttagcompound = stack.getTagCompound().getObject("Fireworks"); if (nbttagcompound != null) { - if (nbttagcompound.hasKey("Flight", 99)) + if (nbttagcompound.hasByte("Flight")) { tooltip.add("Flugdauer: " + nbttagcompound.getByte("Flight")); } - NBTTagList nbttaglist = nbttagcompound.getTagList("Explosions", 10); + List nbttaglist = nbttagcompound.getList("Explosions"); - if (nbttaglist != null && nbttaglist.tagCount() > 0) + if (nbttaglist != null && nbttaglist.size() > 0) { - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound1 = nbttaglist.getCompoundTagAt(i); + TagObject nbttagcompound1 = nbttaglist.get(i); List list = Lists.newArrayList(); ItemFireworkCharge.addExplosionInfo(nbttagcompound1, list); diff --git a/java/src/game/item/ItemFireworkCharge.java b/common/src/main/java/common/item/ItemFireworkCharge.java similarity index 61% rename from java/src/game/item/ItemFireworkCharge.java rename to common/src/main/java/common/item/ItemFireworkCharge.java index 458a26b..14e9ba1 100755 --- a/java/src/game/item/ItemFireworkCharge.java +++ b/common/src/main/java/common/item/ItemFireworkCharge.java @@ -1,13 +1,12 @@ -package game.item; +package common.item; import java.util.List; -import game.color.DyeColor; -import game.entity.npc.EntityNPC; -import game.nbt.NBTBase; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagIntArray; -import game.renderer.blockmodel.ModelBlock; +import common.color.DyeColor; +import common.entity.npc.EntityNPC; +import common.model.Model; +import common.model.ModelProvider; +import common.tags.TagObject; public class ItemFireworkCharge extends Item { @@ -21,58 +20,44 @@ public class ItemFireworkCharge extends Item } else { - NBTBase nbtbase = getExplosionTag(stack, "Colors"); - - if (!(nbtbase instanceof NBTTagIntArray)) + if (stack.hasTagCompound()) { - return 9079434; - } - else - { - NBTTagIntArray nbttagintarray = (NBTTagIntArray)nbtbase; - int[] aint = nbttagintarray.getIntArray(); + TagObject nbttagcompound = stack.getTagCompound().getObject("Explosion"); - if (aint.length == 1) + if (nbttagcompound != null) { - return aint[0]; - } - else - { - int i = 0; - int j = 0; - int k = 0; + if(nbttagcompound.hasIntArray("Colors")) { + int[] aint = nbttagcompound.getIntArray("Colors"); - for (int l : aint) - { - i += (l & 16711680) >> 16; - j += (l & 65280) >> 8; - k += (l & 255) >> 0; - } + if (aint.length == 1) + { + return aint[0]; + } + else + { + int i = 0; + int j = 0; + int k = 0; - i = i / aint.length; - j = j / aint.length; - k = k / aint.length; - return i << 16 | j << 8 | k; + for (int l : aint) + { + i += (l & 16711680) >> 16; + j += (l & 65280) >> 8; + k += (l & 255) >> 0; + } + + i = i / aint.length; + j = j / aint.length; + k = k / aint.length; + return i << 16 | j << 8 | k; + } + } } } + return 9079434; } } - public static NBTBase getExplosionTag(ItemStack stack, String key) - { - if (stack.hasTagCompound()) - { - NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("Explosion"); - - if (nbttagcompound != null) - { - return nbttagcompound.getTag(key); - } - } - - return null; - } - /** * allows items to add custom lines of information to the mouseover description */ @@ -80,7 +65,7 @@ public class ItemFireworkCharge extends Item { if (stack.hasTagCompound()) { - NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("Explosion"); + TagObject nbttagcompound = stack.getTagCompound().getObject("Explosion"); if (nbttagcompound != null) { @@ -89,7 +74,7 @@ public class ItemFireworkCharge extends Item } } - public static void addExplosionInfo(NBTTagCompound nbt, List tooltip) + public static void addExplosionInfo(TagObject nbt, List tooltip) { byte b0 = nbt.getByte("Type"); @@ -174,14 +159,14 @@ public class ItemFireworkCharge extends Item tooltip.add(s1); } - boolean flag3 = nbt.getBoolean("Trail"); + boolean flag3 = nbt.getBool("Trail"); if (flag3) { tooltip.add("Schweif"); } - boolean flag4 = nbt.getBoolean("Flicker"); + boolean flag4 = nbt.getBool("Flicker"); if (flag4) { @@ -193,7 +178,7 @@ public class ItemFireworkCharge extends Item // return Sets.newHashSet("Explosion"); // } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), "firework_charge", "firework_charge_overlay"); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), "firework_charge", "firework_charge_overlay"); } } diff --git a/java/src/game/item/ItemFishFood.java b/common/src/main/java/common/item/ItemFishFood.java similarity index 90% rename from java/src/game/item/ItemFishFood.java rename to common/src/main/java/common/item/ItemFishFood.java index 93b554e..2a0f9b4 100755 --- a/java/src/game/item/ItemFishFood.java +++ b/common/src/main/java/common/item/ItemFishFood.java @@ -1,16 +1,16 @@ -package game.item; +package common.item; import java.util.List; import java.util.Map; -import game.collect.Maps; - -import game.entity.npc.EntityNPC; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.potion.PotionHelper; -import game.renderer.blockmodel.ModelBlock; -import game.world.World; +import common.collect.Maps; +import common.entity.npc.EntityNPC; +import common.model.Model; +import common.model.ModelProvider; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.potion.PotionHelper; +import common.world.World; public class ItemFishFood extends ItemFood { @@ -71,8 +71,8 @@ public class ItemFishFood extends ItemFood return (type.canCook() ? (this.cooked ? "Gebratener " : "Roher ") : "") + type.getName(); } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), (this.cooked ? "cooked_" : "") + FishType.byMetadata(meta).getTexture()); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), (this.cooked ? "cooked_" : "") + FishType.byMetadata(meta).getTexture()); } public static enum FishType diff --git a/java/src/game/item/ItemFishingRod.java b/common/src/main/java/common/item/ItemFishingRod.java similarity index 82% rename from java/src/game/item/ItemFishingRod.java rename to common/src/main/java/common/item/ItemFishingRod.java index ca91cc9..f7278f8 100755 --- a/java/src/game/item/ItemFishingRod.java +++ b/common/src/main/java/common/item/ItemFishingRod.java @@ -1,13 +1,14 @@ -package game.item; +package common.item; import java.util.List; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityHook; -import game.init.SoundEvent; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.world.World; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityHook; +import common.init.SoundEvent; +import common.model.Model; +import common.model.ModelProvider; +import common.model.Transforms; +import common.world.World; public class ItemFishingRod extends Item { @@ -15,7 +16,7 @@ public class ItemFishingRod extends Item { this.setMaxDamage(64); this.setMaxStackSize(1); - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } // /** @@ -87,7 +88,7 @@ public class ItemFishingRod extends Item return Transforms.TOOL_FLIP; } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), meta == 1 ? "fishing_rod_cast" : "fishing_rod"); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), meta == 1 ? "fishing_rod_cast" : "fishing_rod"); } } diff --git a/java/src/game/item/ItemFlintAndSteel.java b/common/src/main/java/common/item/ItemFlintAndSteel.java similarity index 61% rename from java/src/game/item/ItemFlintAndSteel.java rename to common/src/main/java/common/item/ItemFlintAndSteel.java index 677ca10..55ff3be 100755 --- a/java/src/game/item/ItemFlintAndSteel.java +++ b/common/src/main/java/common/item/ItemFlintAndSteel.java @@ -1,20 +1,23 @@ -package game.item; +package common.item; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.SoundEvent; -import game.material.Material; -import game.world.BlockPos; -import game.world.Facing; -import game.world.World; +import common.block.natural.BlockFire; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.SoundEvent; +import common.util.BlockPos; +import common.util.Facing; +import common.world.World; public class ItemFlintAndSteel extends Item { - public ItemFlintAndSteel() + private final BlockFire fireBlock; + + public ItemFlintAndSteel(BlockFire fireBlock) { + this.fireBlock = fireBlock; this.maxStackSize = 1; this.setMaxDamage(64); - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } /** @@ -30,10 +33,10 @@ public class ItemFlintAndSteel extends Item } else { - if (worldIn.getState(pos).getBlock().getMaterial() == Material.air) + if (worldIn.getState(pos).getBlock() == Blocks.air) { worldIn.playSound(SoundEvent.IGNITE, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, 1.0F); - worldIn.setState(pos, Blocks.fire.getState()); + worldIn.setState(pos, this.fireBlock.getState()); } stack.damageItem(1, playerIn); diff --git a/java/src/game/item/ItemFood.java b/common/src/main/java/common/item/ItemFood.java similarity index 92% rename from java/src/game/item/ItemFood.java rename to common/src/main/java/common/item/ItemFood.java index 346a215..9052904 100755 --- a/java/src/game/item/ItemFood.java +++ b/common/src/main/java/common/item/ItemFood.java @@ -1,10 +1,10 @@ -package game.item; +package common.item; -import game.entity.npc.EntityNPC; -import game.init.SoundEvent; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.world.World; +import common.entity.npc.EntityNPC; +import common.init.SoundEvent; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.world.World; public class ItemFood extends Item { @@ -21,7 +21,7 @@ public class ItemFood extends Item this.itemUseDuration = 32; this.healAmount = amount; this.isWolfsFavoriteMeat = isWolfFood; - this.setTab(CheatTab.tabMisc); + this.setTab(CheatTab.MISC); } /** @@ -31,7 +31,7 @@ public class ItemFood extends Item public ItemStack onItemUseFinish(ItemStack stack, World worldIn, EntityNPC playerIn) { // if(!playerIn.creative) - --stack.stackSize; + --stack.size; worldIn.playSoundAtEntity(playerIn, SoundEvent.EAT, 0.5F); playerIn.heal((int)((float)this.getHealAmount(stack) * 0.5f * (1.0f + worldIn.rand.floatv()))); this.onFoodEaten(stack, worldIn, playerIn); diff --git a/java/src/game/item/ItemFragile.java b/common/src/main/java/common/item/ItemFragile.java similarity index 82% rename from java/src/game/item/ItemFragile.java rename to common/src/main/java/common/item/ItemFragile.java index 1b0087b..3905b3a 100755 --- a/java/src/game/item/ItemFragile.java +++ b/common/src/main/java/common/item/ItemFragile.java @@ -1,4 +1,4 @@ -package game.item; +package common.item; public class ItemFragile extends Item { public boolean isFragile() { diff --git a/java/src/game/item/ItemGlassBottle.java b/common/src/main/java/common/item/ItemGlassBottle.java similarity index 74% rename from java/src/game/item/ItemGlassBottle.java rename to common/src/main/java/common/item/ItemGlassBottle.java index 448a435..d4b046a 100755 --- a/java/src/game/item/ItemGlassBottle.java +++ b/common/src/main/java/common/item/ItemGlassBottle.java @@ -1,18 +1,19 @@ -package game.item; +package common.item; -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.HitPosition; -import game.world.World; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.model.Model; +import common.model.ModelProvider; +import common.util.BlockPos; +import common.util.HitPosition; +import common.world.World; public class ItemGlassBottle extends Item { public ItemGlassBottle() { - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } /** @@ -42,12 +43,12 @@ public class ItemGlassBottle extends Item return itemStackIn; } - if (worldIn.getState(blockpos).getBlock().getMaterial() == Material.water) + if (worldIn.getState(blockpos).getBlock().getMaterial() == Material.WATER) { - --itemStackIn.stackSize; + --itemStackIn.size; // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); - if (itemStackIn.stackSize <= 0) + if (itemStackIn.size <= 0) { return new ItemStack(Items.potion); } @@ -63,7 +64,7 @@ public class ItemGlassBottle extends Item } } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), "potion_bottle_empty"); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), "potion_bottle_empty"); } } diff --git a/java/src/game/item/ItemGunBase.java b/common/src/main/java/common/item/ItemGunBase.java similarity index 82% rename from java/src/game/item/ItemGunBase.java rename to common/src/main/java/common/item/ItemGunBase.java index 77ca3f8..73f56ab 100755 --- a/java/src/game/item/ItemGunBase.java +++ b/common/src/main/java/common/item/ItemGunBase.java @@ -1,12 +1,12 @@ -package game.item; +package common.item; -import game.enchantment.Enchantment; -import game.enchantment.EnchantmentHelper; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityBullet; -import game.init.SoundEvent; -import game.renderer.blockmodel.Transforms; -import game.world.World; +import common.enchantment.Enchantment; +import common.enchantment.EnchantmentHelper; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityBullet; +import common.init.SoundEvent; +import common.model.Transforms; +import common.world.World; public abstract class ItemGunBase extends Item { @@ -17,7 +17,7 @@ public abstract class ItemGunBase extends Item { this.maxStackSize = 1; this.setMaxDamage(durability); - this.setTab(CheatTab.tabCombat); + this.setTab(CheatTab.COMBAT); } public ItemAction getItemPosition(ItemStack stack) @@ -30,13 +30,13 @@ public abstract class ItemGunBase extends Item if(stack.getItemDamage() >= this.getMaxDamage()) return stack; boolean flag = // playerIn.creative || - EnchantmentHelper.getEnchantmentLevel(Enchantment.infinity.effectId, stack) > 0; + EnchantmentHelper.getEnchantmentLevel(Enchantment.INFINITY, stack) > 0; if (flag || playerIn.inventory.hasItem(this.getAmmo())) { EntityBullet bullet = new EntityBullet(worldIn, playerIn, this.getVelocity()); bullet.setDamage(this.getAmmo().getDamage(stack)); - int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.power.effectId, stack); + int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.POWER, stack); if (j > 0) { diff --git a/java/src/game/item/ItemHoe.java b/common/src/main/java/common/item/ItemHoe.java similarity index 85% rename from java/src/game/item/ItemHoe.java rename to common/src/main/java/common/item/ItemHoe.java index 3e94c2c..9e7b7b7 100755 --- a/java/src/game/item/ItemHoe.java +++ b/common/src/main/java/common/item/ItemHoe.java @@ -1,16 +1,15 @@ -package game.item; +package common.item; -import game.block.Block; -import game.block.BlockDirt; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.ToolMaterial; -import game.material.Material; -import game.renderer.blockmodel.Transforms; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.natural.BlockDirt; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.ToolMaterial; +import common.model.Transforms; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; public class ItemHoe extends Item { @@ -20,8 +19,8 @@ public class ItemHoe extends Item { this.theToolMaterial = material; this.maxStackSize = 1; - this.setMaxDamage(material.getMaxUses()); - this.setTab(CheatTab.tabTools); + this.setMaxDamage(material.getDurability()); + this.setTab(CheatTab.TOOLS); } @@ -40,7 +39,7 @@ public class ItemHoe extends Item State iblockstate = worldIn.getState(pos); Block block = iblockstate.getBlock(); - if (side != Facing.DOWN && worldIn.getState(pos.up()).getBlock().getMaterial() == Material.air) + if (side != Facing.DOWN && worldIn.getState(pos.up()).getBlock() == Blocks.air) { if (block == Blocks.grass) { diff --git a/java/src/game/item/ItemHorseArmor.java b/common/src/main/java/common/item/ItemHorseArmor.java similarity index 79% rename from java/src/game/item/ItemHorseArmor.java rename to common/src/main/java/common/item/ItemHorseArmor.java index d987a42..3b60d1f 100755 --- a/java/src/game/item/ItemHorseArmor.java +++ b/common/src/main/java/common/item/ItemHorseArmor.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.init.ToolMaterial; +import common.init.ToolMaterial; public class ItemHorseArmor extends Item { private final ToolMaterial material; @@ -10,7 +10,7 @@ public class ItemHorseArmor extends Item { this.material = material; this.texture = texture; this.setMaxStackSize(1); - this.setTab(CheatTab.tabCombat); + this.setTab(CheatTab.COMBAT); } public boolean isMagnetic() { diff --git a/java/src/game/item/ItemHugeMushroom.java b/common/src/main/java/common/item/ItemHugeMushroom.java similarity index 79% rename from java/src/game/item/ItemHugeMushroom.java rename to common/src/main/java/common/item/ItemHugeMushroom.java index 06f4969..9ed6841 100755 --- a/java/src/game/item/ItemHugeMushroom.java +++ b/common/src/main/java/common/item/ItemHugeMushroom.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.block.Block; +import common.block.Block; public class ItemHugeMushroom extends ItemBlock { public ItemHugeMushroom(Block block) { diff --git a/java/src/game/item/ItemInfoWand.java b/common/src/main/java/common/item/ItemInfoWand.java similarity index 66% rename from java/src/game/item/ItemInfoWand.java rename to common/src/main/java/common/item/ItemInfoWand.java index c203564..6370462 100755 --- a/java/src/game/item/ItemInfoWand.java +++ b/common/src/main/java/common/item/ItemInfoWand.java @@ -1,18 +1,18 @@ -package game.item; +package common.item; -import game.biome.Biome; -import game.color.TextColor; -import game.entity.npc.EntityNPC; -import game.world.BlockPos; -import game.world.Vec3; -import game.world.WorldServer; +import common.biome.Biome; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.util.BlockPos; +import common.util.Vec3; +import common.world.AWorldServer; public class ItemInfoWand extends ItemWand { public ItemInfoWand() { this.setColor(TextColor.BLUE); } - public void onUse(ItemStack stack, EntityNPC player, WorldServer world, Vec3 vec) + public void onUse(ItemStack stack, EntityNPC player, AWorldServer world, Vec3 vec) { Biome biome = world.getBiomeGenForCoords(new BlockPos(vec.xCoord, 0, vec.zCoord)); player.connection.addHotbar(TextColor.NEON + "* Position bei Level %d: %.3f %.3f %.3f, %s [%d], %.2f °C", world.dimension.getDimensionId(), diff --git a/java/src/game/item/ItemKey.java b/common/src/main/java/common/item/ItemKey.java similarity index 65% rename from java/src/game/item/ItemKey.java rename to common/src/main/java/common/item/ItemKey.java index af70514..3eef65b 100755 --- a/java/src/game/item/ItemKey.java +++ b/common/src/main/java/common/item/ItemKey.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.renderer.blockmodel.Transforms; +import common.model.Transforms; public class ItemKey extends ItemMagnetic { public Transforms getTransform() { diff --git a/java/src/game/item/ItemLead.java b/common/src/main/java/common/item/ItemLead.java similarity index 82% rename from java/src/game/item/ItemLead.java rename to common/src/main/java/common/item/ItemLead.java index 03c7103..fc914a4 100755 --- a/java/src/game/item/ItemLead.java +++ b/common/src/main/java/common/item/ItemLead.java @@ -1,20 +1,20 @@ -package game.item; +package common.item; -import game.block.Block; -import game.block.BlockFence; -import game.entity.item.EntityLeashKnot; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.World; +import common.block.Block; +import common.block.artificial.BlockFence; +import common.entity.item.EntityLeashKnot; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.World; public class ItemLead extends Item { public ItemLead() { - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } /** diff --git a/java/src/game/item/ItemLeaves.java b/common/src/main/java/common/item/ItemLeaves.java similarity index 92% rename from java/src/game/item/ItemLeaves.java rename to common/src/main/java/common/item/ItemLeaves.java index b2b08fc..efe717c 100755 --- a/java/src/game/item/ItemLeaves.java +++ b/common/src/main/java/common/item/ItemLeaves.java @@ -1,7 +1,7 @@ -package game.item; +package common.item; -import game.block.BlockLeaves; -import game.block.LeavesType; +import common.block.foliage.BlockLeaves; +import common.block.foliage.LeavesType; public class ItemLeaves extends ItemBlock { diff --git a/java/src/game/item/ItemLightning.java b/common/src/main/java/common/item/ItemLightning.java similarity index 63% rename from java/src/game/item/ItemLightning.java rename to common/src/main/java/common/item/ItemLightning.java index f796fd4..5e2e23b 100755 --- a/java/src/game/item/ItemLightning.java +++ b/common/src/main/java/common/item/ItemLightning.java @@ -1,16 +1,16 @@ -package game.item; +package common.item; -import game.color.TextColor; -import game.entity.npc.EntityNPC; -import game.world.Vec3; -import game.world.WorldServer; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.util.Vec3; +import common.world.AWorldServer; public class ItemLightning extends ItemWand { public ItemLightning() { this.setColor(TextColor.NEON); } - public void onUse(ItemStack stack, EntityNPC player, WorldServer world, Vec3 vec) + public void onUse(ItemStack stack, EntityNPC player, AWorldServer world, Vec3 vec) { if(player.useMana(5)) world.strikeLightning(vec.xCoord - 0.5, vec.yCoord, vec.zCoord - 0.5, 0x532380, 230, true, player); diff --git a/java/src/game/item/ItemLilyPad.java b/common/src/main/java/common/item/ItemLilyPad.java similarity index 84% rename from java/src/game/item/ItemLilyPad.java rename to common/src/main/java/common/item/ItemLilyPad.java index 3e533a6..efe834d 100755 --- a/java/src/game/item/ItemLilyPad.java +++ b/common/src/main/java/common/item/ItemLilyPad.java @@ -1,14 +1,14 @@ -package game.item; +package common.item; -import game.block.Block; -import game.block.BlockDirectional; -import game.block.BlockLiquid; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.world.BlockPos; -import game.world.HitPosition; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.BlockDirectional; +import common.block.liquid.BlockLiquid; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.util.BlockPos; +import common.util.HitPosition; +import common.world.State; +import common.world.World; public class ItemLilyPad extends ItemColored { @@ -50,7 +50,7 @@ public class ItemLilyPad extends ItemColored // if (!playerIn.creative) // { - --itemStackIn.stackSize; + --itemStackIn.size; // } // playerIn.triggerAchievement(StatRegistry.objectUseStats[ItemRegistry.getIdFromItem(this)]); diff --git a/java/src/game/item/ItemMagnet.java b/common/src/main/java/common/item/ItemMagnet.java similarity index 87% rename from java/src/game/item/ItemMagnet.java rename to common/src/main/java/common/item/ItemMagnet.java index efa05c9..f2b8527 100755 --- a/java/src/game/item/ItemMagnet.java +++ b/common/src/main/java/common/item/ItemMagnet.java @@ -1,22 +1,21 @@ -package game.item; +package common.item; import java.util.List; - import java.util.function.Predicate; -import game.entity.Entity; -import game.entity.animal.EntityChicken; -import game.entity.npc.EntityNPC; -import game.renderer.blockmodel.Transforms; -import game.world.BoundingBox; -import game.world.Vec3; -import game.world.World; +import common.entity.Entity; +import common.entity.animal.EntityChicken; +import common.entity.npc.EntityNPC; +import common.model.Transforms; +import common.util.BoundingBox; +import common.util.Vec3; +import common.world.World; public class ItemMagnet extends Item { private final boolean chicken; public ItemMagnet(boolean chicken) { - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); this.setMaxStackSize(1); this.chicken = chicken; } diff --git a/java/src/game/item/ItemMagnetic.java b/common/src/main/java/common/item/ItemMagnetic.java similarity index 82% rename from java/src/game/item/ItemMagnetic.java rename to common/src/main/java/common/item/ItemMagnetic.java index 9bc1b6b..bcf2d1c 100755 --- a/java/src/game/item/ItemMagnetic.java +++ b/common/src/main/java/common/item/ItemMagnetic.java @@ -1,4 +1,4 @@ -package game.item; +package common.item; public class ItemMagnetic extends Item { public boolean isMagnetic() { diff --git a/java/src/game/item/ItemMetal.java b/common/src/main/java/common/item/ItemMetal.java similarity index 52% rename from java/src/game/item/ItemMetal.java rename to common/src/main/java/common/item/ItemMetal.java index 26a8f8a..58656dc 100755 --- a/java/src/game/item/ItemMetal.java +++ b/common/src/main/java/common/item/ItemMetal.java @@ -1,17 +1,12 @@ -package game.item; +package common.item; import java.util.List; import java.util.Map; -import java.util.Set; - -import game.collect.Sets; - -import game.color.TextColor; -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeModifier; -import game.entity.attributes.Attributes; -import game.entity.npc.EntityNPC; -import game.init.MetalType; +import common.attributes.Attribute; +import common.attributes.UsageSlot; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.init.MetalType; public class ItemMetal extends Item { private final MetalType metal; @@ -36,16 +31,14 @@ public class ItemMetal extends Item { // return this.metal.radioactivity > 0.0f ? ChatFormat.GREEN : super.getColor(stack); // } - public Map> getItemInventoryModifiers() + public void getModifiers(Map map, UsageSlot slot) { - Map> multimap = super.getItemInventoryModifiers(); - if(this.metal.radioactivity > 0.0f) - multimap.put(Attributes.RADIATION, Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID, "Metal modifier", (double)this.metal.radioactivity * 4.0, false, true, true))); - return multimap; + if((slot == null || slot == UsageSlot.INVENTORY) && this.metal.radioactivity > 0.0f) + map.put(Attribute.RADIATION, this.metal.radioactivity * 4.0f); } public float getRadiation(ItemStack stack) { - return this.metal.radioactivity * 0.25f * (float)stack.stackSize; + return this.metal.radioactivity * 0.25f * (float)stack.size; } public boolean isMagnetic() { diff --git a/java/src/game/item/ItemMetalBlock.java b/common/src/main/java/common/item/ItemMetalBlock.java similarity index 56% rename from java/src/game/item/ItemMetalBlock.java rename to common/src/main/java/common/item/ItemMetalBlock.java index b1ab01c..a6531b2 100755 --- a/java/src/game/item/ItemMetalBlock.java +++ b/common/src/main/java/common/item/ItemMetalBlock.java @@ -1,18 +1,13 @@ -package game.item; +package common.item; import java.util.List; import java.util.Map; -import java.util.Set; - -import game.collect.Sets; - -import game.block.Block; -import game.color.TextColor; -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeModifier; -import game.entity.attributes.Attributes; -import game.entity.npc.EntityNPC; -import game.init.MetalType; +import common.attributes.Attribute; +import common.attributes.UsageSlot; +import common.block.Block; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.init.MetalType; public class ItemMetalBlock extends ItemBlock { private final MetalType metal; @@ -40,16 +35,14 @@ public class ItemMetalBlock extends ItemBlock { // return this.metal.radioactivity > 0.0f ? ChatFormat.GREEN : super.getColor(stack); // } - public Map> getItemInventoryModifiers() + public void getModifiers(Map map, UsageSlot slot) { - Map> multimap = super.getItemInventoryModifiers(); - if(this.metal.radioactivity > 0.0f) - multimap.put(Attributes.RADIATION, Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID, "Metal modifier", (double)this.metal.radioactivity * 4.0 * (this.ore ? 2.0 : 9.0), false, true, true))); - return multimap; + if((slot == null || slot == UsageSlot.INVENTORY) && this.metal.radioactivity > 0.0f) + map.put(Attribute.RADIATION, this.metal.radioactivity * 4.0f * (this.ore ? 2.0f : 9.0f)); } public float getRadiation(ItemStack stack) { - return this.metal.radioactivity * (this.ore ? 0.5f : 2.0f) * (float)stack.stackSize; + return this.metal.radioactivity * (this.ore ? 0.5f : 2.0f) * (float)stack.size; } public boolean isMagnetic() { diff --git a/java/src/game/item/ItemMinecart.java b/common/src/main/java/common/item/ItemMinecart.java similarity index 88% rename from java/src/game/item/ItemMinecart.java rename to common/src/main/java/common/item/ItemMinecart.java index 8193a71..ccc8a41 100755 --- a/java/src/game/item/ItemMinecart.java +++ b/common/src/main/java/common/item/ItemMinecart.java @@ -1,18 +1,18 @@ -package game.item; +package common.item; -import game.block.BlockDispenser; -import game.block.BlockRailBase; -import game.dispenser.BehaviorDefaultDispenseItem; -import game.dispenser.IBehaviorDispenseItem; -import game.dispenser.IBlockSource; -import game.entity.item.EntityCart; -import game.entity.npc.EntityNPC; -import game.init.DispenserRegistry; -import game.material.Material; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.tech.BlockDispenser; +import common.block.tech.BlockRailBase; +import common.dispenser.BehaviorDefaultDispenseItem; +import common.dispenser.IBehaviorDispenseItem; +import common.dispenser.IBlockSource; +import common.entity.item.EntityCart; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.DispenserRegistry; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; public class ItemMinecart extends Item { @@ -44,7 +44,7 @@ public class ItemMinecart extends Item } else { - if (iblockstate.getBlock().getMaterial() != Material.air || !BlockRailBase.isRailBlock(world.getState(blockpos.down()))) + if (iblockstate.getBlock() != Blocks.air || !BlockRailBase.isRailBlock(world.getState(blockpos.down()))) { return this.behaviourDefaultDispenseItem.dispense(source, stack); } @@ -84,7 +84,7 @@ public class ItemMinecart extends Item { this.maxStackSize = 1; this.minecartType = type; - this.setTab(CheatTab.tabSpawners); + this.setTab(CheatTab.SPAWNERS); // if(type != EntityMinecart.EnumMinecartType.COMMAND_BLOCK) DispenserRegistry.REGISTRY.putObject(this, dispenserMinecartBehavior); } @@ -129,7 +129,7 @@ public class ItemMinecart extends Item // ((EntityMinecartCommandBlock)entityminecart).getCommandBlockLogic().setEnabled(((EntityNPCMP)playerIn).canUse(Permissions.CMDBLOCK)); } - --stack.stackSize; + --stack.size; return true; } else diff --git a/java/src/game/item/ItemMonsterPlacer.java b/common/src/main/java/common/item/ItemMonsterPlacer.java similarity index 64% rename from java/src/game/item/ItemMonsterPlacer.java rename to common/src/main/java/common/item/ItemMonsterPlacer.java index cc69eb4..c7faf25 100755 --- a/java/src/game/item/ItemMonsterPlacer.java +++ b/common/src/main/java/common/item/ItemMonsterPlacer.java @@ -1,27 +1,25 @@ -package game.item; +package common.item; import java.util.List; -import game.block.BlockFence; -import game.block.BlockLiquid; -import game.color.TextColor; -import game.dimension.Dimension; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.EntityEggInfo; -import game.init.EntityRegistry; -import game.init.UniverseRegistry; -import game.renderer.blockmodel.ModelBlock; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityMobSpawner; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.HitPosition; -import game.world.State; -import game.world.World; +import common.block.artificial.BlockFence; +import common.block.liquid.BlockLiquid; +import common.color.TextColor; +import common.dimension.Dimension; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.EntityInfo; +import common.init.EntityRegistry; +import common.init.UniverseRegistry; +import common.model.Model; +import common.model.ModelProvider; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.util.HitPosition; +import common.world.State; +import common.world.World; public class ItemMonsterPlacer extends Item { @@ -30,7 +28,7 @@ public class ItemMonsterPlacer extends Item public ItemMonsterPlacer(String entityId) { // this.setHasSubtypes(true); - this.setTab(CheatTab.tabSpawners); + this.setTab(CheatTab.SPAWNERS); this.entityId = entityId; } @@ -53,14 +51,14 @@ public class ItemMonsterPlacer extends Item public int getColorFromItemStack(ItemStack stack, int renderPass) { - EntityEggInfo egg = EntityRegistry.SPAWN_EGGS.get(this.entityId); - return egg != null ? (renderPass == 0 ? egg.primaryColor : egg.secondaryColor) : 16777215; + EntityInfo egg = EntityRegistry.SPAWN_EGGS.get(this.entityId); + return egg != null ? (renderPass == 0 ? egg.color1() : egg.color2()) : 16777215; } public void addInformation(ItemStack stack, EntityNPC player, List tooltip) { - EntityEggInfo egg = EntityRegistry.SPAWN_EGGS.get(this.entityId); + EntityInfo egg = EntityRegistry.SPAWN_EGGS.get(this.entityId); if(egg != null) { - Dimension dim = egg.origin == null ? null : UniverseRegistry.getDimension(egg.origin); + Dimension dim = egg.origin() == null ? null : UniverseRegistry.getDimension(egg.origin()); tooltip.add(TextColor.ORANGE + "Herkunft: " + (dim == null ? "???" : dim.getFormattedName(false))); } } @@ -82,26 +80,6 @@ public class ItemMonsterPlacer extends Item { State iblockstate = worldIn.getState(pos); - if (iblockstate.getBlock() == Blocks.mob_spawner) - { - TileEntity tileentity = worldIn.getTileEntity(pos); - - if (tileentity instanceof TileEntityMobSpawner) - { -// MobSpawnerBaseLogic mobspawnerbaselogic = ((TileEntityMobSpawner)tileentity).getSpawnerBaseLogic(); - ((TileEntityMobSpawner)tileentity).setEntityName(this.entityId); - tileentity.markDirty(); - worldIn.markBlockForUpdate(pos); - -// if (!playerIn.creative) -// { - --stack.stackSize; -// } - - return true; - } - } - pos = pos.offset(side); double d0 = 0.0D; @@ -113,7 +91,7 @@ public class ItemMonsterPlacer extends Item // int amount = Math.min(stack.stackSize, 128); // for(int z = 0; z < amount; z++) { - Entity entity = spawnCreature(worldIn, this.entityId, (double)pos.getX() + 0.5D, (double)pos.getY() + d0, (double)pos.getZ() + 0.5D); + Entity entity = spawnCreature(worldIn, this.entityId, (double)pos.getX() + 0.5D, (double)pos.getY() + d0, (double)pos.getZ() + 0.5D, false); if (entity != null) { @@ -129,7 +107,7 @@ public class ItemMonsterPlacer extends Item // if (!playerIn.creative) // { - --stack.stackSize; + --stack.size; // } } // } @@ -175,7 +153,7 @@ public class ItemMonsterPlacer extends Item { // int amount = Math.min(itemStackIn.stackSize, 128); // for(int z = 0; z < amount; z++) { - Entity entity = spawnCreature(worldIn, this.entityId, (double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D); + Entity entity = spawnCreature(worldIn, this.entityId, (double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D, false); if (entity != null) { @@ -191,7 +169,7 @@ public class ItemMonsterPlacer extends Item // if (!playerIn.creative) // { - --itemStackIn.stackSize; + --itemStackIn.size; // } // if(z == 0) @@ -206,38 +184,21 @@ public class ItemMonsterPlacer extends Item } } - /** - * Spawns the creature specified by the egg's type in the location specified by the last three parameters. - * Parameters: world, entityID, x, y, z. - */ - public static Entity spawnCreature(World worldIn, String entityID, double x, double y, double z) - { + public static EntityLiving spawnCreature(World worldIn, String entityID, double x, double y, double z, boolean check) { if (!EntityRegistry.SPAWN_EGGS.containsKey(entityID)) - { return null; - } - else - { - Entity entity = null; - - for (int i = 0; i < 1; ++i) - { - entity = EntityRegistry.createEntityByName(entityID, worldIn); - - if (entity instanceof EntityLiving) - { - EntityLiving entityliving = (EntityLiving)entity; - entity.setLocationAndAngles(x, y, z, ExtMath.wrapf(worldIn.rand.floatv() * 360.0F), 0.0F); - entityliving.headYaw = entityliving.rotYaw; - entityliving.yawOffset = entityliving.rotYaw; - entityliving.onInitialSpawn(null); - worldIn.spawnEntityInWorld(entity); - entityliving.playLivingSound(); - } - } - - return entity; - } + Entity entity = EntityRegistry.createEntityByName(entityID, worldIn); + if(!(entity instanceof EntityLiving living)) + return null; + living.setLocationAndAngles(x, y, z, ExtMath.wrapf(worldIn.rand.floatv() * 360.0F), 0.0F); + if(check && !living.isNotColliding()) + return null; + living.headYaw = living.rotYaw; + living.yawOffset = living.rotYaw; + living.onInitialSpawn(null); + worldIn.spawnEntityInWorld(living); + living.playLivingSound(); + return living; } // /** @@ -265,7 +226,7 @@ public class ItemMonsterPlacer extends Item // subItems.add(new ItemStack(itemIn, 1, 0)); // } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), "spawn_egg", "spawn_egg_overlay"); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), "spawn_egg", "spawn_egg_overlay"); } } diff --git a/java/src/game/item/ItemMultiTexture.java b/common/src/main/java/common/item/ItemMultiTexture.java similarity index 97% rename from java/src/game/item/ItemMultiTexture.java rename to common/src/main/java/common/item/ItemMultiTexture.java index 4fc0196..4a85c9f 100755 --- a/java/src/game/item/ItemMultiTexture.java +++ b/common/src/main/java/common/item/ItemMultiTexture.java @@ -1,8 +1,8 @@ -package game.item; +package common.item; import java.util.function.Function; -import game.block.Block; +import common.block.Block; public class ItemMultiTexture extends ItemBlock { diff --git a/java/src/game/item/ItemNameTag.java b/common/src/main/java/common/item/ItemNameTag.java similarity index 82% rename from java/src/game/item/ItemNameTag.java rename to common/src/main/java/common/item/ItemNameTag.java index 641f803..109c2e0 100755 --- a/java/src/game/item/ItemNameTag.java +++ b/common/src/main/java/common/item/ItemNameTag.java @@ -1,13 +1,13 @@ -package game.item; +package common.item; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; public class ItemNameTag extends Item { public ItemNameTag() { - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } /** @@ -24,7 +24,7 @@ public class ItemNameTag extends Item EntityLiving entityliving = (EntityLiving)target; entityliving.setCustomNameTag(stack.getDisplayName()); // entityliving.disableDespawn(); - --stack.stackSize; + --stack.size; return true; } else diff --git a/java/src/game/item/ItemNpcSpawner.java b/common/src/main/java/common/item/ItemNpcSpawner.java similarity index 78% rename from java/src/game/item/ItemNpcSpawner.java rename to common/src/main/java/common/item/ItemNpcSpawner.java index e215853..edc04b2 100755 --- a/java/src/game/item/ItemNpcSpawner.java +++ b/common/src/main/java/common/item/ItemNpcSpawner.java @@ -1,26 +1,27 @@ -package game.item; +package common.item; import java.lang.reflect.InvocationTargetException; import java.util.List; -import game.block.BlockFence; -import game.block.BlockLiquid; -import game.color.TextColor; -import game.dimension.Dimension; -import game.entity.Entity; -import game.entity.npc.CharacterInfo; -import game.entity.npc.EntityNPC; -import game.entity.npc.EntityNPC.CharacterTypeData; -import game.entity.types.EntityLiving; -import game.init.EntityRegistry; -import game.init.UniverseRegistry; -import game.renderer.blockmodel.ModelBlock; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.HitPosition; -import game.world.State; -import game.world.World; +import common.block.artificial.BlockFence; +import common.block.liquid.BlockLiquid; +import common.color.TextColor; +import common.dimension.Dimension; +import common.entity.Entity; +import common.entity.npc.CharacterInfo; +import common.entity.npc.EntityNPC; +import common.entity.npc.EntityNPC.CharacterTypeData; +import common.entity.types.EntityLiving; +import common.init.EntityRegistry; +import common.init.UniverseRegistry; +import common.model.Model; +import common.model.ModelProvider; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.util.HitPosition; +import common.world.State; +import common.world.World; public class ItemNpcSpawner extends Item { @@ -29,19 +30,28 @@ public class ItemNpcSpawner extends Item public ItemNpcSpawner(CharacterInfo spawned) { // this.setHasSubtypes(true); - this.setTab(CheatTab.tabSpawners); + this.setTab(CheatTab.SPAWNERS); this.spawned = spawned; } + + public CharacterInfo getSpawnedChar() { + return this.spawned; + } + + public String getCharName() { + CharacterInfo info = this.spawned; // SpeciesRegistry.CHARACTERS.get(stack.getMetadata() % SpeciesRegistry.CHARACTERS.size()); + String species = EntityRegistry.getEntityName(info.species.id); + if(info.species.prefix && info.type != null && !info.type.toString().isEmpty()) + species = info.type.toString(); + String character = info.name; + return species + (character.isEmpty() ? "" : (" " + character)); + } public String getDisplay(ItemStack stack) { String item = "Erschaffe"; - CharacterInfo info = this.spawned; // SpeciesRegistry.CHARACTERS.get(stack.getMetadata() % SpeciesRegistry.CHARACTERS.size()); - String species = EntityRegistry.getEntityName(info.species.id); - if(info.species.prefix && info.type != null && !info.type.toString().isEmpty()) - species = info.type.toString(); - String character = info.name; - item = item + " " + species + (character.isEmpty() ? "" : (" " + character)); + + item = item + " " + this.getCharName(); return item; } @@ -80,7 +90,7 @@ public class ItemNpcSpawner extends Item // int amount = Math.min(stack.stackSize, 128); // for(int z = 0; z < amount; z++) { - Entity entity = spawnNpc(worldIn, this.spawned, (double)pos.getX() + 0.5D, (double)pos.getY() + d0, (double)pos.getZ() + 0.5D); + Entity entity = spawnNpc(worldIn, this.spawned, (double)pos.getX() + 0.5D, (double)pos.getY() + d0, (double)pos.getZ() + 0.5D, false); if (entity != null) { @@ -91,7 +101,7 @@ public class ItemNpcSpawner extends Item // if (!playerIn.creative) // { - --stack.stackSize; + --stack.size; // } } // } @@ -134,7 +144,7 @@ public class ItemNpcSpawner extends Item { // int amount = Math.min(itemStackIn.stackSize, 128); // for(int z = 0; z < amount; z++) { - Entity entity = spawnNpc(worldIn, this.spawned, (double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D); + Entity entity = spawnNpc(worldIn, this.spawned, (double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D, false); if (entity != null) { @@ -145,7 +155,7 @@ public class ItemNpcSpawner extends Item // if (!playerIn.creative) // { - --itemStackIn.stackSize; + --itemStackIn.size; // } // if(z == 0) @@ -160,9 +170,8 @@ public class ItemNpcSpawner extends Item } } - public static Entity spawnNpc(World worldIn, CharacterInfo character, double x, double y, double z) + public static EntityNPC spawnNpc(World worldIn, CharacterInfo character, double x, double y, double z, boolean check) { -// CharacterInfo character = SpeciesRegistry.CHARACTERS.get(entityID % SpeciesRegistry.CHARACTERS.size()); EntityNPC entity; try { entity = character.species.clazz.getConstructor(World.class).newInstance(worldIn); @@ -171,10 +180,11 @@ public class ItemNpcSpawner extends Item throw new RuntimeException(e); } entity.setLocationAndAngles(x, y, z, ExtMath.wrapf(worldIn.rand.floatv() * 360.0F), 0.0F); + if(check && !entity.isNotColliding()) + return null; entity.headYaw = entity.rotYaw; entity.yawOffset = entity.rotYaw; entity.onInitialSpawn(new CharacterTypeData(character)); -// entity.setFromInfo(character); worldIn.spawnEntityInWorld(entity); return entity; } @@ -201,7 +211,7 @@ public class ItemNpcSpawner extends Item // subItems.add(new ItemStack(itemIn, 1, 0)); // } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), "npc_spawner", "npc_spawner_overlay"); + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), "npc_spawner", "npc_spawner_overlay"); } } diff --git a/java/src/game/item/ItemNugget.java b/common/src/main/java/common/item/ItemNugget.java similarity index 65% rename from java/src/game/item/ItemNugget.java rename to common/src/main/java/common/item/ItemNugget.java index 563df21..2fd2aef 100755 --- a/java/src/game/item/ItemNugget.java +++ b/common/src/main/java/common/item/ItemNugget.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.renderer.blockmodel.Transforms; +import common.model.Transforms; public class ItemNugget extends Item { public Transforms getTransform() { diff --git a/common/src/main/java/common/item/ItemPickaxe.java b/common/src/main/java/common/item/ItemPickaxe.java new file mode 100755 index 0000000..1a2c7ba --- /dev/null +++ b/common/src/main/java/common/item/ItemPickaxe.java @@ -0,0 +1,18 @@ +package common.item; + +import common.block.Block; +import common.init.ToolMaterial; + +public class ItemPickaxe extends ItemTool { + public ItemPickaxe(ToolMaterial material) { + super(2, material); + } + + public boolean canHarvestBlock(Block block) { + return block.getMiningLevel() >= 0 && this.getToolMaterial().getHarvestLevel() >= block.getMiningLevel(); + } + + public boolean canUseOn(ItemStack stack, Block block) { + return block.getMiningLevel() >= 0; + } +} diff --git a/java/src/game/item/ItemPiston.java b/common/src/main/java/common/item/ItemPiston.java similarity index 60% rename from java/src/game/item/ItemPiston.java rename to common/src/main/java/common/item/ItemPiston.java index 1a874da..1b83d88 100755 --- a/java/src/game/item/ItemPiston.java +++ b/common/src/main/java/common/item/ItemPiston.java @@ -1,8 +1,9 @@ -package game.item; +package common.item; -import game.block.Block; -import game.init.Blocks; -import game.renderer.blockmodel.ModelBlock; +import common.block.Block; +import common.init.Blocks; +import common.model.Model; +import common.model.ModelProvider; public class ItemPiston extends ItemBlock { @@ -24,8 +25,8 @@ public class ItemPiston extends ItemBlock return true; } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(new ModelBlock("piston_side").add().nswe().d("piston_bottom").u("piston_top" + (this.block == + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(provider.getModel("piston_side").add().nswe().d("piston_bottom").u("piston_top" + (this.block == Blocks.sticky_piston ? "_sticky" : "")), this.getTransform()); } } diff --git a/java/src/game/item/ItemPotion.java b/common/src/main/java/common/item/ItemPotion.java similarity index 72% rename from java/src/game/item/ItemPotion.java rename to common/src/main/java/common/item/ItemPotion.java index 43d5c93..29a9c7b 100755 --- a/java/src/game/item/ItemPotion.java +++ b/common/src/main/java/common/item/ItemPotion.java @@ -1,27 +1,22 @@ -package game.item; +package common.item; import java.util.Iterator; import java.util.List; import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import game.collect.Maps; -import game.collect.Sets; - -import game.color.TextColor; -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeModifier; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntityPotion; -import game.init.Items; -import game.init.SoundEvent; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.potion.PotionHelper; -import game.renderer.ItemMeshDefinition; -import game.renderer.blockmodel.ModelBlock; -import game.world.World; +import common.collect.Lists; +import common.collect.Maps; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityPotion; +import common.init.Items; +import common.init.SoundEvent; +import common.model.ItemMeshDefinition; +import common.model.Model; +import common.model.ModelProvider; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.potion.PotionHelper; +import common.world.World; public class ItemPotion extends Item { @@ -33,13 +28,13 @@ public class ItemPotion extends Item this.setMaxStackSize(1); this.setHasSubtypes(true); this.setMaxDamage(0); - this.setTab(CheatTab.tabMagic); + this.setTab(CheatTab.MAGIC); this.setColor(TextColor.ORK); } public List getEffects(ItemStack stack) { -// if (stack.hasTagCompound() && stack.getTagCompound().hasKey("CustomPotionEffects", 9)) +// if (stack.hasTagCompound() && stack.getTagCompound().hasList("CustomPotionEffects")) // { // List list1 = Lists.newArrayList(); // NBTTagList nbttaglist = stack.getTagCompound().getTagList("CustomPotionEffects", 10); @@ -92,7 +87,7 @@ public class ItemPotion extends Item { // if (!playerIn.creative) // { - --stack.stackSize; + --stack.size; // } if (!worldIn.client) @@ -103,7 +98,10 @@ public class ItemPotion extends Item { for (PotionEffect potioneffect : list) { - playerIn.addEffect(new PotionEffect(potioneffect)); + if(potioneffect.getPotion().isInstant()) + potioneffect.getPotion().onImpact(null, null, playerIn, potioneffect.getAmplifier(), 1.0); + else + playerIn.addEffect(new PotionEffect(potioneffect)); } } } @@ -112,7 +110,7 @@ public class ItemPotion extends Item // if (!playerIn.creative) // { - if (stack.stackSize <= 0) + if (stack.size <= 0) { return new ItemStack(Items.glass_bottle); } @@ -148,7 +146,7 @@ public class ItemPotion extends Item { // if (!playerIn.creative) // { - --itemStackIn.stackSize; + --itemStackIn.size; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); @@ -227,7 +225,7 @@ public class ItemPotion extends Item if (list != null && !list.isEmpty()) { - String s2 = ((PotionEffect)list.get(0)).getPotionName(); + String s2 = list.get(0).getPotionName(); // s2 = s2 + ".postfix"; return s + s2.trim(); } @@ -247,7 +245,7 @@ public class ItemPotion extends Item if ((stack.getMetadata() & 16383) != 0) { List list = Items.potion.getEffects(stack); - Map> multimap = Maps.newHashMap(); + List implications = Lists.newArrayList(); if (list != null && !list.isEmpty()) { @@ -255,31 +253,6 @@ public class ItemPotion extends Item { String s1 = potioneffect.getEffectName().trim(); Potion potion = potioneffect.getPotion(); - Map map = potion.getModifiers(); - - if (map != null && map.size() > 0) - { - for (Entry entry : map.entrySet()) - { - AttributeModifier attributemodifier = (AttributeModifier)entry.getValue(); - AttributeModifier attributemodifier1 = new AttributeModifier(attributemodifier.getName(), potion.getAmount(potioneffect.getAmplifier(), attributemodifier), attributemodifier.isMultiplied()); - Set set = multimap.get(entry.getKey()); - if(set == null) - multimap.put(entry.getKey(), set = Sets.newHashSet()); - set.add(attributemodifier1); -// multimap.put((Attribute)entry.getKey(), set); - } - } - - s1 = s1 + PotionHelper.getPotionPotency(potioneffect.getAmplifier()); -// if (potioneffect.getAmplifier() >= 1 && potioneffect.getAmplifier() <= 9) -// { -// s1 = s1 + " " + Strs.get("potion.potency." + potioneffect.getAmplifier()).trim(); -// } -// else if (potioneffect.getAmplifier() != 0) -// { -// s1 = s1 + " " + (potioneffect.getAmplifier() + 1); -// } if (potioneffect.getDuration() > 20) { @@ -294,6 +267,9 @@ public class ItemPotion extends Item { tooltip.add(TextColor.LGRAY + s1); } + String effectTip = potioneffect.getPotion().getTooltip(potioneffect.getAmplifier()); + if(effectTip != null) + implications.add(effectTip); } } else @@ -302,37 +278,11 @@ public class ItemPotion extends Item tooltip.add(TextColor.LGRAY + s); } - if (!multimap.isEmpty()) + if (!implications.isEmpty()) { tooltip.add(""); tooltip.add(TextColor.DMAGENTA + "Auswirkungen:"); - - for (Entry> entry1 : multimap.entrySet()) - { - for(AttributeModifier attributemodifier2 : entry1.getValue()) { - double d0 = attributemodifier2.getAmount(); - double d1; - - if (!attributemodifier2.isMultiplied()) - { - d1 = attributemodifier2.getAmount(); - } - else - { - d1 = attributemodifier2.getAmount() * 100.0D; - } - - if (d0 > 0.0D) - { - tooltip.add(TextColor.BLUE + String.format("+%s" + (attributemodifier2.isMultiplied() ? "%%" : "") + " %s", ItemStack.DECIMALFORMAT.format(d1), entry1.getKey().getDisplayName())); - } - else if (d0 < 0.0D) - { - d1 = d1 * -1.0D; - tooltip.add(TextColor.RED + String.format("-%s" + (attributemodifier2.isMultiplied() ? "%%" : "") + " %s", ItemStack.DECIMALFORMAT.format(d1), entry1.getKey().getDisplayName())); - } - } - } + tooltip.addAll(implications); } } } @@ -413,7 +363,7 @@ public class ItemPotion extends Item // if(!adv) { // return false; // } -// if(!tag.hasKey("CustomPotionEffects", 9)) { +// if(!tag.hasList("CustomPotionEffects")) { // return false; // } // NBTTagList effects = tag.getTagList("CustomPotionEffects", 10); @@ -439,8 +389,8 @@ public class ItemPotion extends Item subItems.add(new ItemStack(itemIn, 1, 16384)); } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), "potion_overlay", + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), "potion_overlay", isSplash(meta) ? "potion_bottle_splash" : "potion_bottle_drinkable"); } } diff --git a/java/src/game/item/ItemPressurePlate.java b/common/src/main/java/common/item/ItemPressurePlate.java similarity index 53% rename from java/src/game/item/ItemPressurePlate.java rename to common/src/main/java/common/item/ItemPressurePlate.java index 23095e4..e644b4b 100755 --- a/java/src/game/item/ItemPressurePlate.java +++ b/common/src/main/java/common/item/ItemPressurePlate.java @@ -1,16 +1,17 @@ -package game.item; +package common.item; -import game.block.Block; -import game.block.BlockBasePressurePlate; -import game.renderer.blockmodel.ModelBlock; +import common.block.Block; +import common.block.tech.BlockBasePressurePlate; +import common.model.Model; +import common.model.ModelProvider; public class ItemPressurePlate extends ItemBlock { public ItemPressurePlate(Block block) { super(block); } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(new ModelBlock(((BlockBasePressurePlate)this.block).getTexture()) + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(provider.getModel(((BlockBasePressurePlate)this.block).getTexture()) .add(1, 6, 1, 15, 10, 15) .d().uv(1, 1, 15, 15).noCull() .u().uv(1, 1, 15, 15).noCull() diff --git a/common/src/main/java/common/item/ItemRecord.java b/common/src/main/java/common/item/ItemRecord.java new file mode 100755 index 0000000..d43a90e --- /dev/null +++ b/common/src/main/java/common/item/ItemRecord.java @@ -0,0 +1,14 @@ +package common.item; + +import common.model.Model; +import common.model.ModelProvider; + +public class ItemRecord extends Item { + public ItemRecord() { + this.setTab(CheatTab.MISC); + } + + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel(this.getTransform(), "record_old"); + } +} diff --git a/java/src/game/item/ItemRedstone.java b/common/src/main/java/common/item/ItemRedstone.java similarity index 80% rename from java/src/game/item/ItemRedstone.java rename to common/src/main/java/common/item/ItemRedstone.java index 0c8fe07..27a1662 100755 --- a/java/src/game/item/ItemRedstone.java +++ b/common/src/main/java/common/item/ItemRedstone.java @@ -1,18 +1,18 @@ -package game.item; +package common.item; -import game.block.Block; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.world.BlockPos; -import game.world.Facing; -import game.world.World; +import common.block.Block; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.util.BlockPos; +import common.util.Facing; +import common.world.World; public class ItemRedstone extends Item { public ItemRedstone() { - this.setTab(CheatTab.tabTech); + this.setTab(CheatTab.TECHNOLOGY); } public Block getBlock() @@ -42,7 +42,7 @@ public class ItemRedstone extends Item } else if (Blocks.redstone.canPlaceBlockAt(worldIn, blockpos)) { - --stack.stackSize; + --stack.size; worldIn.setState(blockpos, Blocks.redstone.getState()); return true; } diff --git a/java/src/game/item/ItemRod.java b/common/src/main/java/common/item/ItemRod.java similarity index 64% rename from java/src/game/item/ItemRod.java rename to common/src/main/java/common/item/ItemRod.java index 5fa50e6..567d491 100755 --- a/java/src/game/item/ItemRod.java +++ b/common/src/main/java/common/item/ItemRod.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.renderer.blockmodel.Transforms; +import common.model.Transforms; public class ItemRod extends Item { public Transforms getTransform() { diff --git a/java/src/game/item/ItemSaddle.java b/common/src/main/java/common/item/ItemSaddle.java similarity index 84% rename from java/src/game/item/ItemSaddle.java rename to common/src/main/java/common/item/ItemSaddle.java index 60c9022..be30a91 100755 --- a/java/src/game/item/ItemSaddle.java +++ b/common/src/main/java/common/item/ItemSaddle.java @@ -1,15 +1,15 @@ -package game.item; +package common.item; -import game.entity.animal.EntityPig; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; +import common.entity.animal.EntityPig; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; public class ItemSaddle extends Item { public ItemSaddle() { this.maxStackSize = 1; - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } /** @@ -25,7 +25,7 @@ public class ItemSaddle extends Item { entitypig.setSaddled(true); // entitypig.worldObj.playSoundAtEntity(entitypig, "mob.horse.leather", 0.5F, 1.0F); - --stack.stackSize; + --stack.size; } return true; diff --git a/java/src/game/item/ItemSeedFood.java b/common/src/main/java/common/item/ItemSeedFood.java similarity index 82% rename from java/src/game/item/ItemSeedFood.java rename to common/src/main/java/common/item/ItemSeedFood.java index c268093..e7f7fb1 100755 --- a/java/src/game/item/ItemSeedFood.java +++ b/common/src/main/java/common/item/ItemSeedFood.java @@ -1,10 +1,10 @@ -package game.item; +package common.item; -import game.block.Block; -import game.entity.npc.EntityNPC; -import game.world.BlockPos; -import game.world.Facing; -import game.world.World; +import common.block.Block; +import common.entity.npc.EntityNPC; +import common.util.BlockPos; +import common.util.Facing; +import common.world.World; public class ItemSeedFood extends ItemFood { @@ -18,7 +18,7 @@ public class ItemSeedFood extends ItemFood super(healAmount, false); this.crops = crops; this.soilId = soil; - this.setTab(CheatTab.tabPlants); + this.setTab(CheatTab.PLANTS); } public Block getBlock() @@ -42,7 +42,7 @@ public class ItemSeedFood extends ItemFood else if (worldIn.getState(pos).getBlock() == this.soilId && worldIn.isAirBlock(pos.up())) { worldIn.setState(pos.up(), this.crops.getState()); - --stack.stackSize; + --stack.size; return true; } else diff --git a/java/src/game/item/ItemSeeds.java b/common/src/main/java/common/item/ItemSeeds.java similarity index 80% rename from java/src/game/item/ItemSeeds.java rename to common/src/main/java/common/item/ItemSeeds.java index 07472fe..6604c20 100755 --- a/java/src/game/item/ItemSeeds.java +++ b/common/src/main/java/common/item/ItemSeeds.java @@ -1,11 +1,11 @@ -package game.item; +package common.item; -import game.block.Block; -import game.entity.npc.EntityNPC; -import game.renderer.blockmodel.Transforms; -import game.world.BlockPos; -import game.world.Facing; -import game.world.World; +import common.block.Block; +import common.entity.npc.EntityNPC; +import common.model.Transforms; +import common.util.BlockPos; +import common.util.Facing; +import common.world.World; public class ItemSeeds extends Item { @@ -18,7 +18,7 @@ public class ItemSeeds extends Item { this.crops = crops; this.soilBlockID = soil; - this.setTab(CheatTab.tabPlants); + this.setTab(CheatTab.PLANTS); } public Block getBlock() @@ -42,7 +42,7 @@ public class ItemSeeds extends Item else if (worldIn.getState(pos).getBlock() == this.soilBlockID && worldIn.isAirBlock(pos.up())) { worldIn.setState(pos.up(), this.crops.getState()); - --stack.stackSize; + --stack.size; return true; } else diff --git a/java/src/game/item/ItemShears.java b/common/src/main/java/common/item/ItemShears.java similarity index 74% rename from java/src/game/item/ItemShears.java rename to common/src/main/java/common/item/ItemShears.java index 4e7ecf3..b3e3556 100755 --- a/java/src/game/item/ItemShears.java +++ b/common/src/main/java/common/item/ItemShears.java @@ -1,12 +1,12 @@ -package game.item; +package common.item; -import game.block.Block; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.ToolMaterial; -import game.material.Material; -import game.world.BlockPos; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.ToolMaterial; +import common.util.BlockPos; +import common.world.World; public class ItemShears extends Item { @@ -15,8 +15,8 @@ public class ItemShears extends Item public ItemShears(ToolMaterial material) { this.setMaxStackSize(1); - this.setMaxDamage(material.getMaxUses() - 12); - this.setTab(CheatTab.tabTools); + this.setMaxDamage(material.getDurability() - 12); + this.setTab(CheatTab.TOOLS); this.material = material; } @@ -35,12 +35,12 @@ public class ItemShears extends Item public boolean canHarvestBlock(Block blockIn) { - return blockIn.getMaterial() == Material.web || blockIn == Blocks.redstone || blockIn == Blocks.string; + return blockIn.getMaterial() == Material.FLUFF || blockIn == Blocks.redstone || blockIn == Blocks.string; } public float getStrVsBlock(ItemStack stack, Block state) { - return state.getShearsEfficiency() <= 0 ? 1.0F : (((float)state.getShearsEfficiency()) * (this.material.getEfficiencyOnProperMaterial() - 1.0F)); + return state.getShearsEfficiency() <= 0 ? 1.0F : (((float)state.getShearsEfficiency()) * (this.material.getEfficiency() - 1.0F)); // state != Blocks.web && state.getMaterial() != Material.leaves ? (state == Blocks.wool ? 5.0F : super.getStrVsBlock(stack, state)) : 15.0F; } diff --git a/common/src/main/java/common/item/ItemShovel.java b/common/src/main/java/common/item/ItemShovel.java new file mode 100755 index 0000000..5419e23 --- /dev/null +++ b/common/src/main/java/common/item/ItemShovel.java @@ -0,0 +1,19 @@ +package common.item; + +import common.block.Block; +import common.block.Material; +import common.init.ToolMaterial; + +public class ItemShovel extends ItemTool { + public ItemShovel(ToolMaterial material) { + super(1, material); + } + + public boolean canUseOn(ItemStack stack, Block block) { + return block.canShovelHarvest(); + } + + public boolean canHarvestBlock(Block block) { + return block.getMaterial() == Material.POWDER || block.getMaterial() == Material.DIGGABLE; + } +} diff --git a/java/src/game/item/ItemSign.java b/common/src/main/java/common/item/ItemSign.java similarity index 80% rename from java/src/game/item/ItemSign.java rename to common/src/main/java/common/item/ItemSign.java index 81e2b7f..d96831a 100755 --- a/java/src/game/item/ItemSign.java +++ b/common/src/main/java/common/item/ItemSign.java @@ -1,22 +1,22 @@ -package game.item; +package common.item; -import game.block.Block; -import game.block.BlockStandingSign; -import game.block.BlockWallSign; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.tileentity.TileEntity; -import game.tileentity.TileEntitySign; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.World; +import common.block.Block; +import common.block.tile.BlockStandingSign; +import common.block.tile.BlockWallSign; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.tileentity.TileEntity; +import common.tileentity.TileEntitySign; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.world.World; public class ItemSign extends Item { public ItemSign() { - this.setTab(CheatTab.tabDeco); + this.setTab(CheatTab.DECORATION); } public Block getBlock() @@ -65,7 +65,7 @@ public class ItemSign extends Item worldIn.setState(pos, Blocks.wall_sign.getState().withProperty(BlockWallSign.FACING, side), 3); } - --stack.stackSize; + --stack.size; TileEntity tileentity = worldIn.getTileEntity(pos); if (tileentity instanceof TileEntitySign && !ItemBlock.setTileEntityNBT(worldIn, playerIn, pos, stack)) @@ -84,7 +84,7 @@ public class ItemSign extends Item // // protected boolean validateNbt(NBTTagCompound tag) { // if(tag.hasKey("BlockEntityTag")) { -// if(!tag.hasKey("BlockEntityTag", 10)) { +// if(!tag.hasTag("BlockEntityTag")) { // return false; // } // } diff --git a/java/src/game/item/ItemSlab.java b/common/src/main/java/common/item/ItemSlab.java similarity index 95% rename from java/src/game/item/ItemSlab.java rename to common/src/main/java/common/item/ItemSlab.java index 6665cf7..e30370b 100755 --- a/java/src/game/item/ItemSlab.java +++ b/common/src/main/java/common/item/ItemSlab.java @@ -1,12 +1,12 @@ -package game.item; +package common.item; -import game.block.Block; -import game.block.BlockSlab; -import game.entity.npc.EntityNPC; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.artificial.BlockSlab; +import common.entity.npc.EntityNPC; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; public class ItemSlab extends ItemBlock { @@ -43,7 +43,7 @@ public class ItemSlab extends ItemBlock */ public boolean onItemUse(ItemStack stack, EntityNPC playerIn, World worldIn, BlockPos pos, Facing side, float hitX, float hitY, float hitZ) { - if (stack.stackSize == 0) + if (stack.size == 0) { return false; } @@ -69,7 +69,7 @@ public class ItemSlab extends ItemBlock if (worldIn.checkNoEntityCollision(this.slab.getCollisionBoundingBox(worldIn, pos, iblockstate1)) && worldIn.setState(pos, iblockstate1, 3)) { worldIn.playSound(this.slab.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), 1.0F); - --stack.stackSize; + --stack.size; } return true; @@ -143,7 +143,7 @@ public class ItemSlab extends ItemBlock if (worldIn.checkNoEntityCollision(this.slab.getCollisionBoundingBox(worldIn, pos, iblockstate1)) && worldIn.setState(pos, iblockstate1, 3)) { worldIn.playSound(this.slab.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), 1.0F); - --stack.stackSize; + --stack.size; } return true; @@ -173,7 +173,7 @@ public class ItemSlab extends ItemBlock if (worldIn.setState(pos, iblockstate1, 3)) { worldIn.playSound(this.slab.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), 1.0F); - --stack.stackSize; + --stack.size; } return true; diff --git a/java/src/game/item/ItemSmall.java b/common/src/main/java/common/item/ItemSmall.java similarity index 64% rename from java/src/game/item/ItemSmall.java rename to common/src/main/java/common/item/ItemSmall.java index 93f598d..8ddcaa2 100755 --- a/java/src/game/item/ItemSmall.java +++ b/common/src/main/java/common/item/ItemSmall.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.renderer.blockmodel.Transforms; +import common.model.Transforms; public class ItemSmall extends Item { public Transforms getTransform() { diff --git a/common/src/main/java/common/item/ItemSmallBlock.java b/common/src/main/java/common/item/ItemSmallBlock.java new file mode 100755 index 0000000..a311d63 --- /dev/null +++ b/common/src/main/java/common/item/ItemSmallBlock.java @@ -0,0 +1,57 @@ +package common.item; + +import common.block.Block; +import common.block.natural.BlockSnow; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import common.world.World; + +public class ItemSmallBlock extends Item { + private Block block; + + public ItemSmallBlock(Block block) { + this.block = block; + } + + public Block getBlock() { + return this.block; + } + + public boolean onItemUse(ItemStack stack, EntityNPC player, World world, BlockPos pos, Facing side, float hitX, float hitY, float hitZ) { + State state = world.getState(pos); + Block block = state.getBlock(); + + if(block == Blocks.snow_layer && state.getValue(BlockSnow.LAYERS).intValue() < 1) + side = Facing.UP; + else if(!block.isReplaceable(world, pos)) + pos = pos.offset(side); + + if(!player.canPlayerEdit(pos, side, stack) || stack.size == 0) + return false; + if(world.canBlockBePlaced(this.block, pos, false, side, null, stack)) { + State newState = this.block.onBlockPlaced(world, pos, side, hitX, hitY, hitZ, 0, player); + + if(world.setState(pos, newState, 3)) { + newState = world.getState(pos); + + if(newState.getBlock() == this.block) { + ItemBlock.setTileEntityNBT(world, player, pos, stack); + newState.getBlock().onBlockPlacedBy(world, pos, newState, player, stack); + } + + world.playSound(this.block.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), + (double)((float)pos.getZ() + 0.5F), 1.0F); + --stack.size; + return true; + } + } + return false; + } + + public boolean isMagnetic() { + return this.block.isMagnetic(); + } +} diff --git a/java/src/game/item/ItemSnow.java b/common/src/main/java/common/item/ItemSnow.java similarity index 87% rename from java/src/game/item/ItemSnow.java rename to common/src/main/java/common/item/ItemSnow.java index b51dcf1..f19ba09 100755 --- a/java/src/game/item/ItemSnow.java +++ b/common/src/main/java/common/item/ItemSnow.java @@ -1,13 +1,13 @@ -package game.item; +package common.item; -import game.block.Block; -import game.block.BlockSnow; -import game.entity.npc.EntityNPC; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.block.natural.BlockSnow; +import common.entity.npc.EntityNPC; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.State; +import common.world.World; public class ItemSnow extends ItemBlock { @@ -23,7 +23,7 @@ public class ItemSnow extends ItemBlock */ public boolean onItemUse(ItemStack stack, EntityNPC playerIn, World worldIn, BlockPos pos, Facing side, float hitX, float hitY, float hitZ) { - if (stack.stackSize == 0) + if (stack.size == 0) { return false; } @@ -56,7 +56,7 @@ public class ItemSnow extends ItemBlock if (axisalignedbb != null && worldIn.checkNoEntityCollision(axisalignedbb) && worldIn.setState(blockpos, iblockstate1, 2)) { worldIn.playSound(this.block.sound.getPlaceSound(), (double)((float)blockpos.getX() + 0.5F), (double)((float)blockpos.getY() + 0.5F), (double)((float)blockpos.getZ() + 0.5F), 1.0F); - --stack.stackSize; + --stack.size; return true; } } diff --git a/java/src/game/item/ItemSnowball.java b/common/src/main/java/common/item/ItemSnowball.java similarity index 75% rename from java/src/game/item/ItemSnowball.java rename to common/src/main/java/common/item/ItemSnowball.java index 7d1cb5e..08177e5 100755 --- a/java/src/game/item/ItemSnowball.java +++ b/common/src/main/java/common/item/ItemSnowball.java @@ -1,15 +1,15 @@ -package game.item; +package common.item; -import game.entity.npc.EntityNPC; -import game.entity.projectile.EntitySnowball; -import game.init.SoundEvent; -import game.world.World; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntitySnowball; +import common.init.SoundEvent; +import common.world.World; public class ItemSnowball extends Item { public ItemSnowball() { - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } /** @@ -19,7 +19,7 @@ public class ItemSnowball extends Item { // if (!playerIn.creative) // { - --itemStackIn.stackSize; + --itemStackIn.size; // } worldIn.playSoundAtEntity(playerIn, SoundEvent.THROW, 0.5F); diff --git a/java/src/game/item/ItemSoup.java b/common/src/main/java/common/item/ItemSoup.java similarity index 80% rename from java/src/game/item/ItemSoup.java rename to common/src/main/java/common/item/ItemSoup.java index 9ea2ace..daf6eba 100755 --- a/java/src/game/item/ItemSoup.java +++ b/common/src/main/java/common/item/ItemSoup.java @@ -1,9 +1,9 @@ -package game.item; +package common.item; -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.renderer.blockmodel.Transforms; -import game.world.World; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.model.Transforms; +import common.world.World; public class ItemSoup extends ItemFood { diff --git a/java/src/game/item/ItemSpaceNavigator.java b/common/src/main/java/common/item/ItemSpaceNavigator.java similarity index 88% rename from java/src/game/item/ItemSpaceNavigator.java rename to common/src/main/java/common/item/ItemSpaceNavigator.java index 0a78457..eb3841f 100755 --- a/java/src/game/item/ItemSpaceNavigator.java +++ b/common/src/main/java/common/item/ItemSpaceNavigator.java @@ -1,12 +1,12 @@ -package game.item; +package common.item; import java.util.List; -import game.color.TextColor; -import game.entity.npc.EntityNPC; -import game.init.UniverseRegistry; -import game.world.BlockPos; -import game.world.World; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.init.UniverseRegistry; +import common.util.BlockPos; +import common.world.World; public class ItemSpaceNavigator extends ItemMagnetic { public static String formatImperialTime(World world, boolean days) { @@ -15,12 +15,12 @@ public class ItemSpaceNavigator extends ItemMagnetic { long frac = (time * 1000L / UniverseRegistry.EARTH_YEAR) % 1000L; if(!world.dimension.getType().time) { return String.format("%d.%03d.%03d.M%d" + (days ? " T???.??? D???.???.G?" : ""), world.dimension.getTimeQualifier(), - frac, year % 1000L, year / 1000L); + frac, year % 1000L, year / 1000L + 1L); } long day = time / world.dimension.getRotationalPeriod(); time = time % world.dimension.getRotationalPeriod(); return String.format("%d.%03d.%03d.M%d" + (days ? " T%03d.%03d D%03d.%03d.G%d" : ""), world.dimension.getTimeQualifier(), - frac, year % 1000L, year / 1000L, + frac, year % 1000L, year / 1000L + 1L, time / 1000L, time % 1000L, (day / 1000L) % 1000L, day % 1000L, day / 1000000L); } diff --git a/java/src/game/item/ItemStack.java b/common/src/main/java/common/item/ItemStack.java similarity index 66% rename from java/src/game/item/ItemStack.java rename to common/src/main/java/common/item/ItemStack.java index c6fcc06..82a92c2 100755 --- a/java/src/game/item/ItemStack.java +++ b/common/src/main/java/common/item/ItemStack.java @@ -1,99 +1,76 @@ -package game.item; +package common.item; import java.text.DecimalFormat; import java.util.List; import java.util.Map; import java.util.Map.Entry; -import java.util.Set; -import game.collect.Lists; -import game.collect.Maps; - -import game.block.Block; -import game.color.TextColor; -import game.enchantment.Enchantment; -import game.enchantment.EnchantmentDurability; -import game.enchantment.EnchantmentHelper; -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeModifier; -import game.entity.attributes.Attributes; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.BlockRegistry; -import game.init.ItemRegistry; -import game.nbt.NBTBase; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.World; +import common.attributes.Attribute; +import common.attributes.UsageSlot; +import common.block.Block; +import common.collect.Lists; +import common.collect.Maps; +import common.color.TextColor; +import common.enchantment.Enchantment; +import common.enchantment.EnchantmentHelper; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.BlockRegistry; +import common.init.ItemRegistry; +import common.rng.Random; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.Facing; +import common.world.World; public final class ItemStack { public static final int MAX_SIZE = 67108864; public static final DecimalFormat DECIMALFORMAT = new DecimalFormat("#.###"); - /** Size of the stack. */ - public int stackSize; - - /** - * Number of animation frames to go when receiving an item (by walking into it, for example). - */ -// public int animationsToGo; + public int size; private Item item; + private TagObject tag; + private int meta; - /** - * A NBTTagMap containing data about an ItemStack. Can only be used for non stackable items - */ - private NBTTagCompound stackTagCompound; - private int itemDamage; - - /** Item frame this stack is on, or null if not on an item frame. */ -// private EntityFrame itemFrame; -// private Block canDestroyCacheBlock; -// private boolean canDestroyCacheResult; -// private Block canPlaceOnCacheBlock; -// private boolean canPlaceOnCacheResult; - - public ItemStack(Block blockIn) + public ItemStack(Block block) { - this((Block)blockIn, 1); + this(block, 1); } - public ItemStack(Block blockIn, int amount) + public ItemStack(Block block, int amount) { - this((Block)blockIn, amount, 0); + this(block, amount, 0); } - public ItemStack(Block blockIn, int amount, int meta) + public ItemStack(Block block, int amount, int meta) { - this(ItemRegistry.getItemFromBlock(blockIn), amount, meta); + this(ItemRegistry.getItemFromBlock(block), amount, meta); } - public ItemStack(Item itemIn) + public ItemStack(Item item) { - this((Item)itemIn, 1); + this(item, 1); } - public ItemStack(Item itemIn, int amount) + public ItemStack(Item item, int amount) { - this((Item)itemIn, amount, 0); + this(item, amount, 0); } - public ItemStack(Item itemIn, int amount, int meta) + public ItemStack(Item item, int amount, int meta) { // this.canDestroyCacheBlock = null; // this.canDestroyCacheResult = false; // this.canPlaceOnCacheBlock = null; // this.canPlaceOnCacheResult = false; - this.item = itemIn; - this.stackSize = amount; - this.itemDamage = meta; + this.item = item; + this.size = amount; + this.meta = meta; - if (this.itemDamage < 0) + if (this.meta < 0) { - this.itemDamage = 0; + this.meta = 0; } } @@ -114,10 +91,10 @@ public final class ItemStack return (amount / 1000000000) + "B+"; } - public static ItemStack loadItemStackFromNBT(NBTTagCompound nbt) + public static ItemStack readFromTag(TagObject tag) { ItemStack itemstack = new ItemStack(); - itemstack.readFromNBT(nbt); + itemstack.readTags(tag); return itemstack.getItem() != null ? itemstack : null; } @@ -134,14 +111,14 @@ public final class ItemStack */ public ItemStack splitStack(int amount) { - ItemStack itemstack = new ItemStack(this.item, amount, this.itemDamage); + ItemStack itemstack = new ItemStack(this.item, amount, this.meta); - if (this.stackTagCompound != null) + if (this.tag != null) { - itemstack.stackTagCompound = (NBTTagCompound)this.stackTagCompound.copy(); + itemstack.tag = this.tag.copy(); } - this.stackSize -= amount; + this.size -= amount; return itemstack; } @@ -192,52 +169,52 @@ public final class ItemStack } /** - * Write the stack fields to a NBT object. Return the new NBT object. + * Write the stack fields to a object. Return the new object. */ - public NBTTagCompound writeToNBT(NBTTagCompound nbt) + public TagObject writeTags(TagObject tag) { - String resourcelocation = ItemRegistry.REGISTRY.getNameForObject(this.item); - nbt.setString("id", resourcelocation == null ? "air" : resourcelocation.toString()); - nbt.setInteger("Count", this.stackSize); - nbt.setShort("Damage", (short)this.itemDamage); + String resourcelocation = ItemRegistry.getNameFromItem(this.item); + tag.setString("id", resourcelocation == null ? "air" : resourcelocation.toString()); + tag.setInt("Count", this.size); + tag.setShort("Damage", (short)this.meta); - if (this.stackTagCompound != null) + if (this.tag != null) { - nbt.setTag("tag", this.stackTagCompound); + tag.setObject("tag", this.tag); } - return nbt; + return tag; } /** - * Read the stack fields from a NBT object. + * Read the stack fields from a object. */ - public void readFromNBT(NBTTagCompound nbt) + public void readTags(TagObject tag) { - if (nbt.hasKey("id", 8)) + if (tag.hasString("id")) { - this.item = ItemRegistry.getRegisteredItem(nbt.getString("id")); + this.item = ItemRegistry.getRegisteredItem(tag.getString("id")); } else { - this.item = ItemRegistry.getItemById(nbt.getShort("id")); + this.item = ItemRegistry.getItemById(tag.getShort("id")); } - this.stackSize = nbt.getInteger("Count"); - this.itemDamage = nbt.getShort("Damage"); + this.size = tag.getInt("Count"); + this.meta = tag.getShort("Damage"); - if (this.itemDamage < 0) + if (this.meta < 0) { - this.itemDamage = 0; + this.meta = 0; } - if (nbt.hasKey("tag", 10)) + if (tag.hasObject("tag")) { - this.stackTagCompound = nbt.getCompoundTag("tag"); + this.tag = tag.getObject("tag"); if (this.item != null) { - this.item.updateItemStackNBT(this.stackTagCompound); + this.item.updateItemStackNBT(this.tag); } } } @@ -270,7 +247,7 @@ public final class ItemStack // { // if(!breakable) { // if(this.stackTagCompound == null) { -// this.setTagCompound(new NBTTagCompound()); +// this.setTagCompound(new TagObject()); // } // this.stackTagCompound.setBoolean("Unbreakable", true); // this.setItemDamage(0); @@ -295,26 +272,26 @@ public final class ItemStack */ public boolean isItemDamaged() { - return this.isItemStackDamageable() && this.itemDamage > 0; + return this.isItemStackDamageable() && this.meta > 0; } public int getItemDamage() { - return this.itemDamage; + return this.meta; } public int getMetadata() { - return this.itemDamage; + return this.meta; } public void setItemDamage(int meta) { - this.itemDamage = meta; + this.meta = meta; - if (this.itemDamage < 0) + if (this.meta < 0) { - this.itemDamage = 0; + this.meta = 0; } } @@ -342,12 +319,12 @@ public final class ItemStack { if (amount > 0) { - int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.unbreaking.effectId, this); + int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.UNBREAKING, this); int j = 0; for (int k = 0; i > 0 && k < amount; ++k) { - if (EnchantmentDurability.negateDamage(this, i, rand)) + if (Enchantment.negateDamage(this, i, rand)) { ++j; } @@ -361,8 +338,8 @@ public final class ItemStack } } - this.itemDamage += amount; - return this.itemDamage > this.getMaxDamage(); + this.meta += amount; + return this.meta > this.getMaxDamage(); } } @@ -378,25 +355,25 @@ public final class ItemStack if (this.attemptDamageItem(amount, entityIn.getRNG())) { entityIn.renderBrokenItemStack(this); - --this.stackSize; + --this.size; if (entityIn.isPlayer()) { EntityNPC entityplayer = (EntityNPC)entityIn; // entityplayer.triggerAchievement(StatRegistry.objectBreakStats[ItemRegistry.getIdFromItem(this.item)]); - if (this.stackSize == 0 && this.getItem() instanceof ItemBow) + if (this.size == 0 && this.getItem() instanceof ItemBow) { entityplayer.destroyCurrentEquippedItem(); } } - if (this.stackSize < 0) + if (this.size < 0) { - this.stackSize = 0; + this.size = 0; } - this.itemDamage = 0; + this.meta = 0; } } // } @@ -446,11 +423,11 @@ public final class ItemStack */ public ItemStack copy() { - ItemStack itemstack = new ItemStack(this.item, this.stackSize, this.itemDamage); + ItemStack itemstack = new ItemStack(this.item, this.size, this.meta); - if (this.stackTagCompound != null) + if (this.tag != null) { - itemstack.stackTagCompound = (NBTTagCompound)this.stackTagCompound.copy(); + itemstack.tag = this.tag.copy(); } return itemstack; @@ -458,7 +435,7 @@ public final class ItemStack public static boolean areItemStackTagsEqual(ItemStack stackA, ItemStack stackB) { - return stackA == null && stackB == null ? true : (stackA != null && stackB != null ? (stackA.stackTagCompound == null && stackB.stackTagCompound != null ? false : stackA.stackTagCompound == null || stackA.stackTagCompound.equals(stackB.stackTagCompound)) : false); + return stackA == null && stackB == null ? true : (stackA != null && stackB != null ? (stackA.tag == null && stackB.tag != null ? false : stackA.tag == null || stackA.tag.equals(stackB.tag)) : false); } /** @@ -474,7 +451,7 @@ public final class ItemStack */ private boolean isItemStackEqual(ItemStack other) { - return this.stackSize != other.stackSize ? false : (this.item != other.item ? false : (this.itemDamage != other.itemDamage ? false : (this.stackTagCompound == null && other.stackTagCompound != null ? false : this.stackTagCompound == null || this.stackTagCompound.equals(other.stackTagCompound)))); + return this.size != other.size ? false : (this.item != other.item ? false : (this.meta != other.meta ? false : (this.tag == null && other.tag != null ? false : this.tag == null || this.tag.equals(other.tag)))); } /** @@ -491,7 +468,7 @@ public final class ItemStack */ public boolean isItemEqual(ItemStack other) { - return other != null && this.item == other.item && this.itemDamage == other.itemDamage; + return other != null && this.item == other.item && this.meta == other.meta; } // public String getUnlocalizedName() @@ -565,29 +542,29 @@ public final class ItemStack */ public boolean hasTagCompound() { - return this.stackTagCompound != null; + return this.tag != null; } /** * Returns the NBTTagCompound of the ItemStack. */ - public NBTTagCompound getTagCompound() + public TagObject getTagCompound() { - return this.stackTagCompound; + return this.tag; } /** * Get an NBTTagCompound from this stack's NBT data. */ - public NBTTagCompound getSubCompound(String key, boolean create) + public TagObject getSubCompound(String key, boolean create) { - if (this.stackTagCompound != null && this.stackTagCompound.hasKey(key, 10)) + if (this.tag != null && this.tag.hasObject(key)) { - return this.stackTagCompound.getCompoundTag(key); + return this.tag.getObject(key); } else if (create) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject nbttagcompound = new TagObject(); this.setTagInfo(key, nbttagcompound); return nbttagcompound; } @@ -597,17 +574,17 @@ public final class ItemStack } } - public NBTTagList getEnchantmentTagList() + public List getEnchantmentTagList() { - return this.stackTagCompound == null ? null : this.stackTagCompound.getTagList("ench", 10); + return this.tag == null ? null : this.tag.getList("ench"); } /** * Assigns a NBTTagCompound to the ItemStack, does not validate that only non-stackable items can have it. */ - public void setTagCompound(NBTTagCompound nbt) + public void setTagCompound(TagObject nbt) { - this.stackTagCompound = nbt; + this.tag = nbt; } /** @@ -617,13 +594,13 @@ public final class ItemStack { String s = this.getItem().getDisplay(this); - if (this.stackTagCompound != null && this.stackTagCompound.hasKey("Name", 8)) + if (this.tag != null && this.tag.hasString("Name")) { // NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag("display"); // -// if (nbttagcompound.hasKey("Name", 8)) +// if (nbttagcompound.hasString("Name")) // { - s = this.stackTagCompound.getString("Name"); + s = this.tag.getString("Name"); // } } @@ -640,17 +617,17 @@ public final class ItemStack public ItemStack setStackDisplayName(String displayName) { - if (this.stackTagCompound == null) + if (this.tag == null) { - this.stackTagCompound = new NBTTagCompound(); + this.tag = new TagObject(); } -// if (!this.stackTagCompound.hasKey("display", 10)) +// if (!this.stackTagCompound.hasTag("display")) // { // this.stackTagCompound.setTag("display", new NBTTagCompound()); // } - this.stackTagCompound.setString("Name", displayName); + this.tag.setString("Name", displayName); return this; } @@ -661,7 +638,7 @@ public final class ItemStack // this.stackTagCompound = new NBTTagCompound(); // } // -// if (!this.stackTagCompound.hasKey("display", 10)) +// if (!this.stackTagCompound.hasTag("display")) // { // this.stackTagCompound.setTag("display", new NBTTagCompound()); // } @@ -681,7 +658,7 @@ public final class ItemStack // return null; // } // -// if (!this.stackTagCompound.hasKey("display", 10)) +// if (!this.stackTagCompound.hasTag("display")) // { // return null; // } @@ -725,14 +702,14 @@ public final class ItemStack */ public void clearCustomName() { - if (this.stackTagCompound != null) + if (this.tag != null) { - if (this.stackTagCompound.hasKey("Name", 8)) + if (this.tag.hasString("Name")) { // NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag("display"); - this.stackTagCompound.removeTag("Name"); + this.tag.remove("Name"); - if (this.stackTagCompound.hasNoTags()) + if (this.tag.isEmpty()) { // this.stackTagCompound.removeTag("display"); // @@ -749,7 +726,7 @@ public final class ItemStack // { // if (this.stackTagCompound != null) // { -// if (this.stackTagCompound.hasKey("display", 10)) +// if (this.stackTagCompound.hasTag("display")) // { // NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag("display"); // nbttagcompound.removeTag("Lore"); @@ -772,7 +749,7 @@ public final class ItemStack */ public boolean hasDisplayName() { - return this.stackTagCompound != null && this.stackTagCompound.hasKey("Name", 8); + return this.tag != null && this.tag.hasString("Name"); } public List getTooltip(EntityNPC playerIn) @@ -785,8 +762,8 @@ public final class ItemStack // s = ChatFormat.ITALIC + s; // } - if(this.stackSize != 1) - s = TextColor.YELLOW + "" + this.stackSize + " " + TextColor.RESET + s; + if(this.size != 1) + s = TextColor.YELLOW + "" + this.size + " " + TextColor.RESET + s; s = s + TextColor.RESET; @@ -806,7 +783,7 @@ public final class ItemStack if (this.getHasSubtypes()) { - s1 = s1 + String.format("%d", this.itemDamage); + s1 = s1 + String.format("%d", this.meta); } // else // { @@ -842,28 +819,28 @@ public final class ItemStack { // if ((i1 & 1) == 0) // { - NBTTagList nbttaglist = this.getEnchantmentTagList(); + List nbttaglist = this.getEnchantmentTagList(); if (nbttaglist != null) { - for (int j = 0; j < nbttaglist.tagCount(); ++j) + for (int j = 0; j < nbttaglist.size(); ++j) { - int k = nbttaglist.getCompoundTagAt(j).getShort("id"); - int l = nbttaglist.getCompoundTagAt(j).getShort("lvl"); + Enchantment k = Enchantment.getEnchantment(nbttaglist.get(j).getString("id")); - if (Enchantment.getEnchantmentById(k) != null) + if (k != null) { - list.add(Enchantment.getEnchantmentById(k).getFormattedName(l)); + int l = nbttaglist.get(j).getShort("lvl"); + list.add(k.getFormattedName(l)); } } } // } -// if (this.stackTagCompound.hasKey("display", 10)) +// if (this.stackTagCompound.hasTag("display")) // { // NBTTagCompound nbttagcompound = this.stackTagCompound.getCompoundTag("display"); // -// if (nbttagcompound.hasKey("color", 3)) +// if (nbttagcompound.hasInt("color")) // { // if (advanced) // { @@ -889,57 +866,41 @@ public final class ItemStack //// } // } } + + int damage = this.item.getAttackDamageBonus(); + damage += EnchantmentHelper.getDamageModifier(this); + if(damage != 0) { + if(damage > 0) + list.add(TextColor.BLUE + String.format("+%d Angriffsschaden", damage)); + else + list.add(TextColor.RED + String.format("-%d Angriffsschaden", damage)); + } - Map> multimap = this.getAttributeModifiers(3); + Map mods = this.getAttributeModifiers(null); - if (!multimap.isEmpty()) // && (i1 & 2) == 0) + if (!mods.isEmpty()) { list.add(""); - - for (Entry> entry : multimap.entrySet()) + for (Entry entry : mods.entrySet()) { - for(AttributeModifier mod : entry.getValue()) { - double amt = mod.getAmount(); - - if (mod.getID() == Attributes.ITEM_VAL_ID) - { - amt += (double)EnchantmentHelper.getDamageModifier(this); - } - - double num; - - if (!mod.isMultiplied()) - { - num = amt; - } - else - { - num = amt * 100.0D; - } - - if(mod.isInventory() && this.stackSize != 1) { - double total = num * (double)this.stackSize; - if (amt > 0.0D) - list.add(TextColor.BLUE + String.format("+%s" + (mod.isMultiplied() ? "%%" : "") + " %s [%dx +%s" + (mod.isMultiplied() ? "%%" : "") + "]", DECIMALFORMAT.format(total), entry.getKey().getDisplayName(), this.stackSize, DECIMALFORMAT.format(num))); - else if (amt < 0.0D) - list.add(TextColor.RED + String.format("-%s" + (mod.isMultiplied() ? "%%" : "") + " %s [%dx -%s" + (mod.isMultiplied() ? "%%" : "") + "]", DECIMALFORMAT.format(total * -1.0), entry.getKey().getDisplayName(), this.stackSize, DECIMALFORMAT.format(num * -1.0))); - } - else { - if (amt > 0.0D) - list.add(TextColor.BLUE + String.format("+%s" + (mod.isMultiplied() ? "%%" : "") + " %s", DECIMALFORMAT.format(num), entry.getKey().getDisplayName())); - else if (amt < 0.0D) - list.add(TextColor.RED + String.format("-%s" + (mod.isMultiplied() ? "%%" : "") + " %s", DECIMALFORMAT.format(num * -1.0), entry.getKey().getDisplayName())); - } + float amt = entry.getValue(); + if(this.size != 1) { + double total = amt * (double)this.size; + if (amt > 0.0D) + list.add(TextColor.BLUE + String.format("+%s %s [%dx +%s]", DECIMALFORMAT.format(total), entry.getKey(), this.size, DECIMALFORMAT.format(amt))); + else if (amt < 0.0D) + list.add(TextColor.RED + String.format("-%s %s [%dx -%s]", DECIMALFORMAT.format(total * -1.0), entry.getKey(), this.size, DECIMALFORMAT.format(amt * -1.0))); + } + else { + if (amt > 0.0D) + list.add(TextColor.BLUE + String.format("+%s %s", DECIMALFORMAT.format(amt), entry.getKey())); + else if (amt < 0.0D) + list.add(TextColor.RED + String.format("-%s %s", DECIMALFORMAT.format(amt * -1.0), entry.getKey())); } } } - if (this.hasTagCompound() && this.getTagCompound().getBoolean("Unbreakable")) // && (i1 & 4) == 0) - { - list.add(TextColor.BLUE + "Unzerstörbar"); - } - -// if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanDestroy", 9) && (i1 & 8) == 0) +// if (this.hasTagCompound() && this.stackTagCompound.hasList("CanDestroy") && (i1 & 8) == 0) // { // NBTTagList nbttaglist2 = this.stackTagCompound.getTagList("CanDestroy", 8); // @@ -964,7 +925,7 @@ public final class ItemStack // } // } // -// if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanPlaceOn", 9) && (i1 & 16) == 0) +// if (this.hasTagCompound() && this.stackTagCompound.hasList("CanPlaceOn") && (i1 & 16) == 0) // { // NBTTagList nbttaglist3 = this.stackTagCompound.getTagList("CanPlaceOn", 8); // @@ -996,12 +957,15 @@ public final class ItemStack list.add(String.format("Haltbarkeit: %d" + (this.isItemDamaged() ? " / %d" : ""), this.isItemDamaged() ? (this.getMaxDamage() - this.getItemDamage()) : this.getMaxDamage(), this.getMaxDamage())); } + + if(this.getRepairCost() > 0) + list.add("Reparaturkosten: " + this.getRepairCost() + " Mana"); - list.add(TextColor.GRAY + ItemRegistry.REGISTRY.getNameForObject(this.item)); + list.add(TextColor.GRAY + ItemRegistry.getNameFromItem(this.item)); if (this.hasTagCompound()) { - list.add(TextColor.GRAY + String.format("NBT-Tags: %d", this.getTagCompound().getKeySet().size())); + list.add(TextColor.GRAY + String.format("NBT-Tags: %d", this.getTagCompound().keySet().size())); } // } @@ -1031,41 +995,41 @@ public final class ItemStack */ public void addEnchantment(Enchantment ench, int level) { - if (this.stackTagCompound == null) + if (this.tag == null) { - this.setTagCompound(new NBTTagCompound()); + this.setTagCompound(new TagObject()); } - if (!this.stackTagCompound.hasKey("ench", 9)) + if (!this.tag.hasList("ench")) { - this.stackTagCompound.setTag("ench", new NBTTagList()); + this.tag.setList("ench", Lists.newArrayList()); } - NBTTagList nbttaglist = this.stackTagCompound.getTagList("ench", 10); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setShort("id", (short)ench.effectId); + List nbttaglist = this.tag.getList("ench"); + TagObject nbttagcompound = new TagObject(); + nbttagcompound.setString("id", ench.getName()); nbttagcompound.setShort("lvl", (short)(/* (byte) */ level)); - nbttaglist.appendTag(nbttagcompound); + nbttaglist.add(nbttagcompound); } /** * Removes an enchantment from the ItemStack. */ public boolean removeEnchantment(Enchantment ench) { - if(this.stackTagCompound == null) { + if(this.tag == null) { return false; } - if(!this.stackTagCompound.hasKey("ench", 9)) { + if(!this.tag.hasList("ench")) { return false; } - NBTTagList oldEnch = this.stackTagCompound.getTagList("ench", 10); - NBTTagList newEnch = new NBTTagList(); + List oldEnch = this.tag.getList("ench"); + List newEnch = Lists.newArrayList(); boolean changed = false; - NBTTagCompound tag; - for(int z = 0; z < oldEnch.tagCount(); z++) { - tag = oldEnch.getCompoundTagAt(z); - if(tag.getShort("id") != ench.effectId) { - newEnch.appendTag(tag); + TagObject tag; + for(int z = 0; z < oldEnch.size(); z++) { + tag = oldEnch.get(z); + if(Enchantment.getEnchantment(tag.getString("id")) != ench) { + newEnch.add(tag); } else { changed = true; @@ -1074,14 +1038,14 @@ public final class ItemStack if(!changed) { return false; } - if(newEnch.tagCount() == 0) { - this.stackTagCompound.removeTag("ench"); - if(this.stackTagCompound.hasNoTags()) { - this.stackTagCompound = null; + if(newEnch.size() == 0) { + this.tag.remove("ench"); + if(this.tag.isEmpty()) { + this.tag = null; } } else { - this.stackTagCompound.setTag("ench", newEnch); + this.tag.setList("ench", newEnch); } return true; } @@ -1090,15 +1054,15 @@ public final class ItemStack * Removes all enchantments from the ItemStack. */ public boolean clearEnchantments() { - if(this.stackTagCompound == null) { + if(this.tag == null) { return false; } - if(!this.stackTagCompound.hasKey("ench", 9)) { + if(!this.tag.hasList("ench")) { return false; } - this.stackTagCompound.removeTag("ench"); - if(this.stackTagCompound.hasNoTags()) { - this.stackTagCompound = null; + this.tag.remove("ench"); + if(this.tag.isEmpty()) { + this.tag = null; } return true; } @@ -1108,17 +1072,27 @@ public final class ItemStack */ public boolean isItemEnchanted() { - return this.stackTagCompound != null && this.stackTagCompound.hasKey("ench", 9); + return this.tag != null && this.tag.hasList("ench"); } - public void setTagInfo(String key, NBTBase value) + public void setTagInfo(String key, TagObject value) { - if (this.stackTagCompound == null) + if (this.tag == null) { - this.setTagCompound(new NBTTagCompound()); + this.setTagCompound(new TagObject()); } - this.stackTagCompound.setTag(key, value); + this.tag.setObject(key, value); + } + + public void setTagInfo(String key, List value) + { + if (this.tag == null) + { + this.setTagCompound(new TagObject()); + } + + this.tag.setList(key, value); } // public boolean canEditBlocks() @@ -1155,7 +1129,7 @@ public final class ItemStack */ public int getRepairCost() { - return this.hasTagCompound() && this.stackTagCompound.hasKey("RepairCost", 3) ? this.stackTagCompound.getInteger("RepairCost") : 0; + return this.hasTagCompound() && this.tag.hasInt("RepairCost") ? this.tag.getInt("RepairCost") : 0; } /** @@ -1164,62 +1138,32 @@ public final class ItemStack public void setRepairCost(int cost) { if(cost == 0) { - if(this.stackTagCompound == null) { + if(this.tag == null) { return; } - if(!this.stackTagCompound.hasKey("RepairCost", 3)) { + if(!this.tag.hasInt("RepairCost")) { return; } - this.stackTagCompound.removeTag("RepairCost"); - if(this.stackTagCompound.hasNoTags()) { - this.stackTagCompound = null; + this.tag.remove("RepairCost"); + if(this.tag.isEmpty()) { + this.tag = null; } return; } if (!this.hasTagCompound()) { - this.stackTagCompound = new NBTTagCompound(); + this.tag = new TagObject(); } - this.stackTagCompound.setInteger("RepairCost", cost); + this.tag.setInt("RepairCost", cost); } - public Map> getAttributeModifiers(int type) - { - Map> multimap; - -// if ((type & 1) == 1 && this.hasTagCompound() && this.stackTagCompound.hasKey("AttributeModifiers", 9)) -// { -// multimap = HashMultimap.create(); -// NBTTagList nbttaglist = this.stackTagCompound.getTagList("AttributeModifiers", 10); -// -// for (int i = 0; i < nbttaglist.tagCount(); ++i) -// { -// NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); -// AttributeModifier attributemodifier = Attributes.readAttributeModifierFromNBT(nbttagcompound); -// -// if (attributemodifier != null && attributemodifier.getID() != 0L) -// { -// multimap.put(nbttagcompound.getString("AttributeName"), attributemodifier); -// } -// } -// } -// else - if((type & 1) == 1) - { - multimap = this.getItem().getItemAttributeModifiers(); - } - else { - multimap = Maps.newHashMap(); - } - - if((type & 2) == 2) { - multimap.putAll(this.getItem().getItemInventoryModifiers()); - } - - return multimap; - } + public Map getAttributeModifiers(UsageSlot slot) { + Map map = Maps.newEnumMap(Attribute.class); + this.getItem().getModifiers(map, slot); + return map; + } public void setItem(Item newItem) { @@ -1236,7 +1180,7 @@ public final class ItemStack // { // this.canDestroyCacheBlock = blockIn; // -// if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanDestroy", 9)) +// if (this.hasTagCompound() && this.stackTagCompound.hasList("CanDestroy")) // { // NBTTagList nbttaglist = this.stackTagCompound.getTagList("CanDestroy", 8); // @@ -1267,7 +1211,7 @@ public final class ItemStack // { // this.canPlaceOnCacheBlock = blockIn; // -// if (this.hasTagCompound() && this.stackTagCompound.hasKey("CanPlaceOn", 9)) +// if (this.hasTagCompound() && this.stackTagCompound.hasList("CanPlaceOn")) // { // NBTTagList nbttaglist = this.stackTagCompound.getTagList("CanPlaceOn", 8); // diff --git a/java/src/game/item/ItemStick.java b/common/src/main/java/common/item/ItemStick.java similarity index 64% rename from java/src/game/item/ItemStick.java rename to common/src/main/java/common/item/ItemStick.java index 1810890..20113f5 100755 --- a/java/src/game/item/ItemStick.java +++ b/common/src/main/java/common/item/ItemStick.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.renderer.blockmodel.Transforms; +import common.model.Transforms; public class ItemStick extends Item { public Transforms getTransform() { diff --git a/java/src/game/item/ItemSword.java b/common/src/main/java/common/item/ItemSword.java similarity index 73% rename from java/src/game/item/ItemSword.java rename to common/src/main/java/common/item/ItemSword.java index f3511d9..2a741fa 100755 --- a/java/src/game/item/ItemSword.java +++ b/common/src/main/java/common/item/ItemSword.java @@ -1,22 +1,14 @@ -package game.item; +package common.item; -import java.util.Map; -import java.util.Set; - -import game.collect.Sets; - -import game.block.Block; -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeModifier; -import game.entity.attributes.Attributes; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.ToolMaterial; -import game.material.Material; -import game.renderer.blockmodel.Transforms; -import game.world.BlockPos; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.ToolMaterial; +import common.model.Transforms; +import common.util.BlockPos; +import common.world.World; public class ItemSword extends Item { @@ -27,9 +19,9 @@ public class ItemSword extends Item { this.material = material; this.maxStackSize = 1; - this.setMaxDamage(material.getMaxUses()); - this.setTab(CheatTab.tabCombat); - this.attackDamage = 4 + material.getDamageVsEntity(); + this.setMaxDamage(material.getDurability()); + this.setTab(CheatTab.COMBAT); + this.attackDamage = 4 + material.getDamage(); } /** @@ -37,7 +29,7 @@ public class ItemSword extends Item */ public int getDamageVsEntity() { - return this.material.getDamageVsEntity(); + return this.material.getDamage(); } public ToolMaterial getToolMaterial() @@ -54,7 +46,7 @@ public class ItemSword extends Item else { Material material = state.getMaterial(); - return material != Material.plants && material != Material.vine && material != Material.coral && material != Material.leaves && material != Material.gourd ? 1.0F : 1.5F; + return material != Material.PLANT && material != Material.BUSH && material != Material.LEAVES && material != Material.SOFT ? 1.0F : 1.5F; } } @@ -145,12 +137,9 @@ public class ItemSword extends Item { return this.material.isRepairItem(repair.getItem()) ? true : super.getIsRepairable(toRepair, repair); } - - public Map> getItemAttributeModifiers() - { - Map> multimap = super.getItemAttributeModifiers(); - multimap.put(Attributes.ATTACK_DAMAGE, Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID, "Weapon modifier", this.attackDamage, false))); - return multimap; + + public int getAttackDamageBonus() { + return this.attackDamage; } // public boolean canBreakBlocks() { diff --git a/java/src/game/item/ItemTNT.java b/common/src/main/java/common/item/ItemTNT.java similarity index 88% rename from java/src/game/item/ItemTNT.java rename to common/src/main/java/common/item/ItemTNT.java index 4e3548a..6aa1b7d 100755 --- a/java/src/game/item/ItemTNT.java +++ b/common/src/main/java/common/item/ItemTNT.java @@ -1,7 +1,7 @@ -package game.item; +package common.item; -import game.block.Block; -import game.color.TextColor; +import common.block.Block; +import common.color.TextColor; public class ItemTNT extends ItemBlock { diff --git a/java/src/game/item/ItemTiny.java b/common/src/main/java/common/item/ItemTiny.java similarity index 64% rename from java/src/game/item/ItemTiny.java rename to common/src/main/java/common/item/ItemTiny.java index d51b8fd..96b9e8f 100755 --- a/java/src/game/item/ItemTiny.java +++ b/common/src/main/java/common/item/ItemTiny.java @@ -1,6 +1,6 @@ -package game.item; +package common.item; -import game.renderer.blockmodel.Transforms; +import common.model.Transforms; public class ItemTiny extends Item { public Transforms getTransform() { diff --git a/common/src/main/java/common/item/ItemTool.java b/common/src/main/java/common/item/ItemTool.java new file mode 100755 index 0000000..28e0768 --- /dev/null +++ b/common/src/main/java/common/item/ItemTool.java @@ -0,0 +1,68 @@ +package common.item; + +import common.block.Block; +import common.entity.types.EntityLiving; +import common.init.ToolMaterial; +import common.model.Transforms; +import common.util.BlockPos; +import common.world.World; + +public abstract class ItemTool extends Item { + private final float efficiency; + private final int damage; + private final ToolMaterial material; + + public ItemTool(int damage, ToolMaterial material) { + this.material = material; + this.maxStackSize = 1; + this.setMaxDamage(material.getDurability()); + this.efficiency = material.getEfficiency(); + this.damage = damage + material.getDamage(); + this.setTab(CheatTab.TOOLS); + } + + public abstract boolean canUseOn(ItemStack stack, Block block); + + public float getStrVsBlock(ItemStack stack, Block block) { + return !this.canUseOn(stack, block) ? 1.0F : this.efficiency; + } + + public boolean hitEntity(ItemStack stack, EntityLiving target, EntityLiving attacker) { + stack.damageItem(2, attacker); + return true; + } + + public boolean onBlockDestroyed(ItemStack stack, World world, Block block, BlockPos pos, EntityLiving player) { + if(block.getBlockHardness(world, pos) != 0.0f) + stack.damageItem(1, player); + return true; + } + + public ToolMaterial getToolMaterial() { + return this.material; + } + + public int getItemEnchantability() { + return this.material.getEnchantability(); + } + + public boolean getIsRepairable(ItemStack stack, ItemStack repair) { + return this.material.isRepairItem(repair.getItem()) ? true : super.getIsRepairable(stack, repair); + } + + public int getAttackDamageBonus() { + return this.damage; + } + + public boolean isMagnetic() { + return this.material.isMagnetic(); + } + + public Transforms getTransform() { + return Transforms.TOOL; + } + + public boolean canBeWielded() { + return true; + } +} diff --git a/java/src/game/item/ItemWall.java b/common/src/main/java/common/item/ItemWall.java similarity index 65% rename from java/src/game/item/ItemWall.java rename to common/src/main/java/common/item/ItemWall.java index 6b6be4c..9e138fd 100755 --- a/java/src/game/item/ItemWall.java +++ b/common/src/main/java/common/item/ItemWall.java @@ -1,19 +1,20 @@ -package game.item; +package common.item; import java.util.function.Function; -import game.block.Block; -import game.block.BlockWall; -import game.renderer.blockmodel.ModelBlock; +import common.block.Block; +import common.block.artificial.BlockWall; +import common.model.Model; +import common.model.ModelProvider; public class ItemWall extends ItemMultiTexture { public ItemWall(Block block, Block block2, Function nameFunction) { super(block, block2, nameFunction); } - public ModelBlock getModel(String name, int meta) { - return new ModelBlock( - new ModelBlock(this.block.getStateFromMeta(this.getMetadata(meta)).getValue(BlockWall.VARIANT).getName()).noOcclude() + public Model getModel(ModelProvider provider, String name, int meta) { + return provider.getModel( + provider.getModel(this.block.getStateFromMeta(this.getMetadata(meta)).getValue(BlockWall.VARIANT).getName()) .add(4, 0, 4, 12, 16, 12) .d().uv(4, 4, 12, 12) .u().uv(4, 4, 12, 12).noCull() diff --git a/java/src/game/item/ItemWand.java b/common/src/main/java/common/item/ItemWand.java similarity index 68% rename from java/src/game/item/ItemWand.java rename to common/src/main/java/common/item/ItemWand.java index 172198d..f0a494d 100755 --- a/java/src/game/item/ItemWand.java +++ b/common/src/main/java/common/item/ItemWand.java @@ -1,21 +1,21 @@ -package game.item; +package common.item; import java.util.List; -import game.color.TextColor; -import game.entity.npc.EntityNPC; -import game.renderer.blockmodel.Transforms; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.Vec3; -import game.world.World; -import game.world.WorldServer; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.model.Transforms; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; +import common.util.Vec3; +import common.world.World; +import common.world.AWorldServer; public abstract class ItemWand extends Item { public ItemWand() { this.maxStackSize = 1; - this.setTab(CheatTab.tabTools); + this.setTab(CheatTab.TOOLS); } // public boolean canBreakBlocks() { @@ -38,7 +38,7 @@ public abstract class ItemWand extends Item { // { // if(playerIn.worldObj.client) // return true; -// this.onUse(stack, (EntityNPCMP)playerIn, (WorldServer)playerIn.worldObj, new Vec3(target.posX, target.posY + target.height / 2.0, target.posZ)); +// this.onUse(stack, (EntityNPCMP)playerIn, (IWorldServer)playerIn.worldObj, new Vec3(target.posX, target.posY + target.height / 2.0, target.posZ)); // return true; // } @@ -46,7 +46,7 @@ public abstract class ItemWand extends Item { if(control == ItemControl.SECONDARY && !world.client && block == null) { BlockPos vec = world.getBlockTrace(player, this.getRange(stack, player)); if(vec != null) - this.onUse(stack, player, (WorldServer)world, new Vec3( + this.onUse(stack, player, (AWorldServer)world, new Vec3( ExtMath.floord(vec.getX()) + 0.5, ExtMath.floord(vec.getY()) + 1.0, ExtMath.floord(vec.getZ()) + 0.5)); } return control == ItemControl.SECONDARY; @@ -58,7 +58,7 @@ public abstract class ItemWand extends Item { // EntityNPCMP entity = (EntityNPCMP)player; if(pos != null) { // pos = side.getAxisDirection() == AxisDirection.NEGATIVE ? pos.offset(side) : pos; - this.onUse(stack, player, (WorldServer)world, new Vec3(pos.getX() + hitX, pos.getY() + hitY, pos.getZ() + hitZ)); + this.onUse(stack, player, (AWorldServer)world, new Vec3(pos.getX() + hitX, pos.getY() + hitY, pos.getZ() + hitZ)); } return true; } @@ -71,12 +71,12 @@ public abstract class ItemWand extends Item { // public boolean hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker) { // if(attacker.worldObj.client) // return true; -// this.onUse(stack, (EntityNPCMP)attacker, (WorldServer)attacker.worldObj, new Vec3(target.posX, target.posY + target.height / 2.0, target.posZ)); +// this.onUse(stack, (EntityNPCMP)attacker, (IWorldServer)attacker.worldObj, new Vec3(target.posX, target.posY + target.height / 2.0, target.posZ)); // return true; // } public abstract int getRange(ItemStack stack, EntityNPC player); - public abstract void onUse(ItemStack stack, EntityNPC player, WorldServer world, Vec3 vec); + public abstract void onUse(ItemStack stack, EntityNPC player, AWorldServer world, Vec3 vec); public Transforms getTransform() { return Transforms.TOOL; diff --git a/java/src/game/item/ItemWeatherToken.java b/common/src/main/java/common/item/ItemWeatherToken.java similarity index 76% rename from java/src/game/item/ItemWeatherToken.java rename to common/src/main/java/common/item/ItemWeatherToken.java index 2bc3fb7..bff9568 100755 --- a/java/src/game/item/ItemWeatherToken.java +++ b/common/src/main/java/common/item/ItemWeatherToken.java @@ -1,11 +1,11 @@ -package game.item; +package common.item; -import game.color.TextColor; -import game.entity.npc.EntityNPC; -import game.init.SoundEvent; -import game.world.Weather; -import game.world.World; -import game.world.WorldServer; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.init.SoundEvent; +import common.world.Weather; +import common.world.World; +import common.world.AWorldServer; public class ItemWeatherToken extends ItemMagnetic { private final Weather weather; @@ -20,11 +20,11 @@ public class ItemWeatherToken extends ItemMagnetic { { if(worldIn.dimension.getType().weather) { // if (!playerIn.creative) - --itemStackIn.stackSize; + --itemStackIn.size; worldIn.playSoundAtEntity(playerIn, SoundEvent.SPELL, 0.5F); if (!worldIn.client) { - WorldServer world = (WorldServer)worldIn; + AWorldServer world = (AWorldServer)worldIn; if(!world.isExterminated()) { world.setWeather(this.weather); world.resetWeather(); diff --git a/java/src/game/item/RngLoot.java b/common/src/main/java/common/item/RngLoot.java similarity index 85% rename from java/src/game/item/RngLoot.java rename to common/src/main/java/common/item/RngLoot.java index b4599cd..b8c9c4e 100755 --- a/java/src/game/item/RngLoot.java +++ b/common/src/main/java/common/item/RngLoot.java @@ -1,12 +1,12 @@ -package game.item; +package common.item; import java.util.Collections; -import game.inventory.IInventory; -import game.rng.Random; -import game.rng.RngItem; -import game.rng.WeightedList; -import game.tileentity.TileEntityDispenser; +import common.inventory.IInventory; +import common.rng.Random; +import common.rng.RngItem; +import common.rng.WeightedList; +import common.tileentity.TileEntityDispenser; public class RngLoot extends RngItem { @@ -34,7 +34,7 @@ public class RngLoot extends RngItem if(this.item == null) return null; ItemStack stack = this.item.copy(); - stack.stackSize = this.minStackSize + rand.zrange(this.maxStackSize - this.minStackSize + 1); + stack.size = this.minStackSize + rand.zrange(this.maxStackSize - this.minStackSize + 1); return stack; } @@ -48,7 +48,7 @@ public class RngLoot extends RngItem if (loot.item.getMaxStackSize() >= j) { ItemStack itemstack1 = loot.item.copy(); - itemstack1.stackSize = j; + itemstack1.size = j; inv.setInventorySlotContents(random.zrange(inv.getSizeInventory()), itemstack1); } else @@ -56,7 +56,7 @@ public class RngLoot extends RngItem for (int k = 0; k < j; ++k) { ItemStack itemstack = loot.item.copy(); - itemstack.stackSize = 1; + itemstack.size = 1; inv.setInventorySlotContents(random.zrange(inv.getSizeInventory()), itemstack); } } @@ -73,7 +73,7 @@ public class RngLoot extends RngItem if (loot.item.getMaxStackSize() >= j) { ItemStack itemstack1 = loot.item.copy(); - itemstack1.stackSize = j; + itemstack1.size = j; dispenser.setInventorySlotContents(random.zrange(dispenser.getSizeInventory()), itemstack1); } else @@ -81,7 +81,7 @@ public class RngLoot extends RngItem for (int k = 0; k < j; ++k) { ItemStack itemstack = loot.item.copy(); - itemstack.stackSize = 1; + itemstack.size = 1; dispenser.setInventorySlotContents(random.zrange(dispenser.getSizeInventory()), itemstack); } } diff --git a/java/src/game/log/Log.java b/common/src/main/java/common/log/Log.java similarity index 88% rename from java/src/game/log/Log.java rename to common/src/main/java/common/log/Log.java index e328a1c..ea68b87 100644 --- a/java/src/game/log/Log.java +++ b/common/src/main/java/common/log/Log.java @@ -1,15 +1,14 @@ -package game.log; +package common.log; import java.io.PrintWriter; import java.io.StringWriter; import java.util.List; -import game.collect.Lists; - -import game.color.TextColor; -import game.future.ListenableFuture; -import game.network.IThreadListener; -import game.util.Util; +import common.collect.Lists; +import common.color.TextColor; +import common.future.ListenableFuture; +import common.network.IThreadListener; +import common.util.Util; public enum Log { SYSTEM("System"), @@ -18,8 +17,7 @@ public enum Log { CONSOLE("Console"), TICK("Tick"), SOUND("Sound"), - JNI("JNI"), - NETTY("Netty"); + NETWORK("Network"); private static class LogMessage { private final LogLevel level; @@ -45,6 +43,7 @@ public enum Log { private static final List LOG = Lists.newArrayList(); private static LogLevel level = LogLevel.INFO; + private static boolean colors = true; private static IThreadListener sync = new IThreadListener() { public ListenableFuture schedule(Runnable run) { return null; @@ -72,14 +71,16 @@ public enum Log { if(pos - last != 0) System.err.print(str.substring(last, pos)); color = TextColor.getColor(c); // (c >= CHR_COLORS2) && (c <= CHR_COLORE2) ? aux_colors[c - CHR_COLORS2] : text_colors[c - CHR_COLORS1]; - System.err.printf("\u001b[38;2;%d;%d;%dm", (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff); + if(colors) + System.err.printf("\u001b[38;2;%d;%d;%dm", (color >> 16) & 0xff, (color >> 8) & 0xff, color & 0xff); last = ++pos; continue; } else if(c == CHR_CRESET) { if(pos - last != 0) System.err.print(str.substring(last, pos)); - System.err.print("\u001b[0m"); + if(colors) + System.err.print("\u001b[0m"); last = ++pos; continue; } @@ -100,7 +101,7 @@ public enum Log { if(pos >= str.length() && pos - last != 0) System.err.print(str.substring(last, pos)); } - System.err.print("\u001b[0m\n"); + System.err.print(colors ? "\u001b[0m\n" : "\n"); } public static String str_time(long time) { @@ -111,7 +112,12 @@ public enum Log { return time > 0 ? String.format("%dD+%02d:%02d:%02d", time, hrs, mins, secs) : String.format("%02d:%02d:%02d", hrs, mins, secs); } - public static void init(IThreadListener sync) { + public static void init() { + Log.colors = System.getProperty("log.nocolor") == null && !Util.WINDOWS; + Log.level = LogLevel.parse(System.getProperty("log.level", LogLevel.INFO.id)); + } + + public static void setSync(IThreadListener sync) { Log.sync = sync; } diff --git a/java/src/game/log/LogLevel.java b/common/src/main/java/common/log/LogLevel.java similarity index 60% rename from java/src/game/log/LogLevel.java rename to common/src/main/java/common/log/LogLevel.java index 2af9bb6..e436d04 100644 --- a/java/src/game/log/LogLevel.java +++ b/common/src/main/java/common/log/LogLevel.java @@ -1,10 +1,11 @@ -package game.log; +package common.log; -import game.color.TextColor; -import game.properties.IStringSerializable; -import game.util.Displayable; +import common.color.TextColor; +import common.util.Displayable; +import common.util.ExtMath; +import common.util.Identifyable; -public enum LogLevel implements Displayable, IStringSerializable { +public enum LogLevel implements Displayable, Identifyable { SILENT("silent", "Nichts", "UNK?", TextColor.BLACK), USER("user", "Benutzer", "USER", TextColor.WHITE), ERROR("error", "Fehler", "ERR!", TextColor.RED), @@ -19,6 +20,19 @@ public enum LogLevel implements Displayable, IStringSerializable { public final String log; public final TextColor color; + public static LogLevel parse(String str) { + for(LogLevel level : values()) { + if(level.id.equalsIgnoreCase(str)) + return level; + } + try { + return values()[ExtMath.clampi(Integer.parseUnsignedInt(str), 0, values().length - 1)]; + } + catch(NumberFormatException e) { + return INFO; + } + } + private LogLevel(String id, String name, String log, TextColor color) { this.id = id; this.name = name; diff --git a/common/src/main/java/common/model/BlockLayer.java b/common/src/main/java/common/model/BlockLayer.java new file mode 100755 index 0000000..49d2d51 --- /dev/null +++ b/common/src/main/java/common/model/BlockLayer.java @@ -0,0 +1,18 @@ +package common.model; + +public enum BlockLayer { + SOLID("Solid"), + CUTOUT_MIPPED("Mipped Cutout"), + CUTOUT("Cutout"), + TRANSLUCENT("Translucent"); + + private final String name; + + private BlockLayer(String name) { + this.name = name; + } + + public String toString() { + return this.name; + } +} diff --git a/common/src/main/java/common/model/ItemMeshDefinition.java b/common/src/main/java/common/model/ItemMeshDefinition.java new file mode 100755 index 0000000..354f27f --- /dev/null +++ b/common/src/main/java/common/model/ItemMeshDefinition.java @@ -0,0 +1,7 @@ +package common.model; + +import common.item.ItemStack; + +public interface ItemMeshDefinition { + String getModelLocation(ItemStack stack); +} diff --git a/common/src/main/java/common/model/Model.java b/common/src/main/java/common/model/Model.java new file mode 100644 index 0000000..ba446c8 --- /dev/null +++ b/common/src/main/java/common/model/Model.java @@ -0,0 +1,176 @@ +package common.model; + +import common.util.Facing; + +public abstract class Model { + public abstract Model uvLock(); + public abstract Model rotate(ModelRotation rot); + public abstract Model add(float x1, float y1, float z1, float x2, float y2, float z2); + public abstract Model noShade(); + public abstract Model rotate(float x, float y, float z, Facing.Axis axisIn, float angleIn, boolean rescaleIn); + public abstract Model face(String texture, Facing... faces); + public abstract Model cull(Facing cull); + public abstract Model tint(); + public abstract Model rot(int rot); + public abstract Model uv(float x1, float y1, float x2, float y2); + public abstract String getPrimary(); + + public Model slab(boolean upper) { + return this.slab(upper, this.getPrimary(), this.getPrimary()); + } + + public Model slab(boolean upper, String du) { + return this.slab(upper, du, du); + } + + public Model slab(boolean upper, String down, String up) { + return this.add(0, upper ? 8 : 0, 0, 16, upper ? 16 : 8, 16).nswe().uv(0, upper ? 0 : 8, 16, upper ? 8 : 16) + .d(down).cull(upper ? null : Facing.DOWN).u(up).cull(upper ? Facing.UP : null); + } + + public Model vslab(Facing dir) { + return this.vslab(dir, this.getPrimary(), this.getPrimary()); + } + + public Model vslab(Facing dir, String du) { + return this.vslab(dir, du, du); + } + + public Model vslab(Facing dir, String down, String up) { + return this.add(0, 0, 0, 16, 16, 8).du().uv(0, 8, 16, 16).we().uv(0, 8, 16, 16).rot(90).n(down).s(up).noCull().rotate(ModelRotation.getNorthRot(dir)); + } + + public Model cross() { + return this + .add(0.8f, 0f, 8f, 15.2f, 16f, 8f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) + .ns().uv(0, 0, 16, 16).noCull() + .add(8f, 0f, 0.8f, 8f, 16f, 15.2f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) + .we().uv(0, 0, 16, 16).noCull(); + } + + public Model crossTint() { + return this + .add(0.8f, 0f, 8f, 15.2f, 16f, 8f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) + .ns().uv(0, 0, 16, 16).noCull().tint() + .add(8f, 0f, 0.8f, 8f, 16f, 15.2f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) + .we().uv(0, 0, 16, 16).noCull().tint(); + } + + public Model stairs(boolean upper, boolean inner, boolean outer, boolean left, Facing dir, String down, String up) { + this.add(0, 0, 0, 16, 8, 16).d(down).uv(0, 0, 16, 16).u(up).noCull().uv(0, 0, 16, 16).nswe().uv(0, 8, 16, 16); + if(outer) + this.add(8, 8, 8, 16, 16, 16).d(down).uv(8, 0, 16, 8).u(up).uv(8, 8, 16, 16).n().noCull().uv(0, 0, 8, 8).s().uv(8, 0, 16, 8) + .w().noCull().uv(8, 0, 16, 8).e().uv(0, 0, 8, 8); + else + this.add(8, 8, 0, 16, 16, 16).d(down).uv(inner ? 8 : 0, 0, 16, 16).u(up).uv(inner ? 8 : 0, 0, 16, 16).n().uv(0, 0, 8, 8) + .s().uv(8, 0, 16, 8).w().noCull().uv(0, 0, 16, 8).e().uv(0, 0, 16, 8); + if(inner) + this.add(0, 8, 8, 8, 16, 16).d(down).uv(0, 0, 8, 8).u(up).uv(0, 8, 8, 16).n().noCull().uv(8, 0, 16, 8).s().uv(0, 0, 8, 8) + .w().uv(8, 0, 16, 8).e().uv(0, 0, 8, 8); + return this.rotate(ModelRotation.getEastRot(left ? Facing.getHorizontal(dir.getHorizontalIndex() + 3) : dir, upper)).uvLock(); + } + + public Model add() { + return this.add(0, 0, 0, 16, 16, 16); + } + + public Model d(String textureIn) { + return this.face(textureIn, Facing.DOWN); + } + + public Model u(String textureIn) { + return this.face(textureIn, Facing.UP); + } + + public Model n(String textureIn) { + return this.face(textureIn, Facing.NORTH); + } + + public Model s(String textureIn) { + return this.face(textureIn, Facing.SOUTH); + } + + public Model w(String textureIn) { + return this.face(textureIn, Facing.WEST); + } + + public Model e(String textureIn) { + return this.face(textureIn, Facing.EAST); + } + + public Model nswe(String textureIn) { + return this.face(textureIn, Facing.NORTH, Facing.SOUTH, Facing.WEST, Facing.EAST); + } + + public Model dnswe(String textureIn) { + return this.face(textureIn, Facing.DOWN, Facing.NORTH, Facing.SOUTH, Facing.WEST, Facing.EAST); + } + + public Model du(String textureIn) { + return this.face(textureIn, Facing.DOWN, Facing.UP); + } + + public Model ns(String textureIn) { + return this.face(textureIn, Facing.NORTH, Facing.SOUTH); + } + + public Model we(String textureIn) { + return this.face(textureIn, Facing.WEST, Facing.EAST); + } + + public Model all(String textureIn) { + return this.face(textureIn, Facing.DOWN, Facing.UP, Facing.NORTH, Facing.SOUTH, Facing.WEST, Facing.EAST); + } + + public Model d() { + return this.d(this.getPrimary()); + } + + public Model u() { + return this.u(this.getPrimary()); + } + + public Model n() { + return this.n(this.getPrimary()); + } + + public Model s() { + return this.s(this.getPrimary()); + } + + public Model w() { + return this.w(this.getPrimary()); + } + + public Model e() { + return this.e(this.getPrimary()); + } + + public Model nswe() { + return this.nswe(this.getPrimary()); + } + + public Model dnswe() { + return this.dnswe(this.getPrimary()); + } + + public Model du() { + return this.du(this.getPrimary()); + } + + public Model ns() { + return this.ns(this.getPrimary()); + } + + public Model we() { + return this.we(this.getPrimary()); + } + + public Model all() { + return this.all(this.getPrimary()); + } + + public Model noCull() { + return this.cull(null); + } +} \ No newline at end of file diff --git a/common/src/main/java/common/model/ModelProvider.java b/common/src/main/java/common/model/ModelProvider.java new file mode 100644 index 0000000..4cf3877 --- /dev/null +++ b/common/src/main/java/common/model/ModelProvider.java @@ -0,0 +1,86 @@ +package common.model; + +import common.util.Facing; +import common.util.Facing.Axis; + +public interface ModelProvider { + Model getModel(String primary); + Model getModel(Transforms transform, String ... layers); + Model getModel(Model parent, Transforms transform); + Model getEntityModel(); + + public static class DummyModel extends Model { + public Model uvLock() { + return this; + } + + public Model rotate(ModelRotation rot) { + return this; + } + + public Model add(float x1, float y1, float z1, float x2, float y2, float z2) { + return this; + } + + public Model noShade() { + return this; + } + + public Model rotate(float x, float y, float z, Axis axisIn, float angleIn, boolean rescaleIn) { + return this; + } + + public Model face(String texture, Facing... faces) { + return this; + } + + public Model cull(Facing cull) { + return this; + } + + public Model tint() { + return this; + } + + public Model rot(int rot) { + return this; + } + + public Model uv(float x1, float y1, float x2, float y2) { + return this; + } + + public String getPrimary() { + return ""; + } + + } + + public static class BlockModelProvider { + private static ModelProvider provider = new ModelProvider() { + public Model getModel(Model parent, Transforms transform) { + return new DummyModel(); + } + + public Model getModel(Transforms transform, String... layers) { + return new DummyModel(); + } + + public Model getModel(String primary) { + return new DummyModel(); + } + + public Model getEntityModel() { + return new DummyModel(); + } + }; + } + + public static void setProvider(ModelProvider provider) { + BlockModelProvider.provider = provider; + } + + public static ModelProvider getModelProvider() { + return BlockModelProvider.provider; + } +} diff --git a/java/src/game/model/ModelRotation.java b/common/src/main/java/common/model/ModelRotation.java similarity index 95% rename from java/src/game/model/ModelRotation.java rename to common/src/main/java/common/model/ModelRotation.java index 5eae937..b4c1973 100755 --- a/java/src/game/model/ModelRotation.java +++ b/common/src/main/java/common/model/ModelRotation.java @@ -1,13 +1,12 @@ -package game.model; +package common.model; import java.util.Map; -import game.collect.Maps; - -import game.renderer.Matrix4f; -import game.renderer.Vector3f; -import game.util.ExtMath; -import game.world.Facing; +import common.collect.Maps; +import common.util.ExtMath; +import common.util.Facing; +import common.util.Matrix4f; +import common.util.Vector3f; public enum ModelRotation { diff --git a/java/src/game/renderer/particle/ParticleType.java b/common/src/main/java/common/model/ParticleType.java similarity index 97% rename from java/src/game/renderer/particle/ParticleType.java rename to common/src/main/java/common/model/ParticleType.java index 4e3911e..cace491 100755 --- a/java/src/game/renderer/particle/ParticleType.java +++ b/common/src/main/java/common/model/ParticleType.java @@ -1,10 +1,10 @@ -package game.renderer.particle; +package common.model; import java.util.List; import java.util.Map; -import game.collect.Lists; -import game.collect.Maps; +import common.collect.Lists; +import common.collect.Maps; public enum ParticleType { diff --git a/common/src/main/java/common/model/Transform.java b/common/src/main/java/common/model/Transform.java new file mode 100755 index 0000000..7451efd --- /dev/null +++ b/common/src/main/java/common/model/Transform.java @@ -0,0 +1,5 @@ +package common.model; + +public record Transform(float rotationX, float rotationY, float rotationZ, float translationX, float translationY, float translationZ, float scale) { + public static final Transform IDENTITY = new Transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f); +} diff --git a/common/src/main/java/common/model/Transforms.java b/common/src/main/java/common/model/Transforms.java new file mode 100755 index 0000000..4ca6fee --- /dev/null +++ b/common/src/main/java/common/model/Transforms.java @@ -0,0 +1,169 @@ +package common.model; + +public enum Transforms { + DEFAULT( + Transform.IDENTITY, + Transform.IDENTITY, + Transform.IDENTITY, + Transform.IDENTITY + ), + ANVIL( + transform(10.0f, -45.0f, 170.0f, 0.25f, 1.5f, -2.5f, 0.375f), + Transform.IDENTITY, + Transform.IDENTITY, + Transform.IDENTITY + ), + BLOCK( + transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f), + Transform.IDENTITY, + Transform.IDENTITY, + Transform.IDENTITY + ), + ITEM( + transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -3.0f, 0.55f), + transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + TOOL_FLIP( + transform(180.0f, 90.0f, -35.0f, 0.0f, 0.0f, -3.5f, 0.85f), + transform(0.0f, 45.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + TOOL( + transform(0.0f, 90.0f, -35.0f, 0.0f, 1.25f, -3.5f, 0.85f), + transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + OFFSET2( + transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.25f, 0.55f), + transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + LAYER( + transform(10.0f, -45.0f, 170.0f, 0.0f, 0.25f, -2.75f, 0.375f), + transform(0.0f, 0.0f, 0.0f, 0.0f, 5.25f, 0.0f, 1.0f), + Transform.IDENTITY, + Transform.IDENTITY + ), + DICE( + transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -1.75f, 0.15f), + transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.4f), + transform(135.0f, -55.0f, 180.0f, 0.0f, 0.0f, 0.0f, 1.1f), + transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.4f) + ), + STAIRS( + transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f), + Transform.IDENTITY, + transform(0.0f, 180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), + Transform.IDENTITY + ), + OFFSET1( + transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.5f, 0.55f), + transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + GATE( + transform(0.0f, -90.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f), + transform(0.0f, 90.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), + Transform.IDENTITY, + Transform.IDENTITY + ), + NUGGET( + transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.0f, 0.55f), + transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + SKULL( + transform(180.0f, -45.0f, 0.0f, 0.0f, 1.0f, -2.5f, 0.25f), + transform(0.0f, -180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.55f), + transform(0.0f, 180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.7f), + Transform.IDENTITY + ), + BUTTON( + transform(10.0f, -45.0f, 170.0f, 0.0f, 1.0f, -1.75f, 0.375f), + Transform.IDENTITY, + Transform.IDENTITY, + Transform.IDENTITY + ), + RANGED( + transform(5.0f, 80.0f, -45.0f, 0.75f, 0.0f, 0.25f, 1.0f), + transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + BANNER( + transform(0.0f, 90.0f, -90.0f, 0.0f, 0.0f, -4.0f, 0.5f), + transform(0.0f, 225.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), + transform(0.0f, -65.0f, 0.0f, 0.0f, -3.0f, 0.0f, 0.85f), + Transform.IDENTITY + ), + FENCE( + transform(0.0f, 0.0f, 180.0f, 0.0f, 1.5f, -2.75f, 0.375f), + Transform.IDENTITY, + transform(0.0f, 90.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f), + Transform.IDENTITY + ), + FLAT( + transform(10.0f, -45.0f, 170.0f, 0.0f, 0.25f, -2.75f, 0.375f), + transform(0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 0.0f, 1.0f), + Transform.IDENTITY, + Transform.IDENTITY + ), + ROD( + transform(0.0f, 90.0f, -35.0f, 0.0f, 0.75f, -3.5f, 0.85f), + transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ), + KEY( + transform(0.0f, 270.0f, -35.0f, 0.0f, 1.25f, -3.5f, 0.85f), + transform(180.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f), + Transform.IDENTITY, + Transform.IDENTITY + ); + + public static enum Camera { + NONE, + THIRD_PERSON, + FIRST_PERSON, + GUI, + GROUND; + } + + private static Transform transform(float rx, float ry, float rz, float tx, float ty, float tz, float scale) { + return new Transform(rx, ry, rz, tx * 0.0625f, ty * 0.0625f, tz * 0.0625f, scale); + } + + public final Transform third; + public final Transform first; + public final Transform gui; + public final Transform ground; + + private Transforms(Transform third, Transform first, Transform gui, Transform ground) { + this.third = third; + this.first = first; + this.gui = gui; + this.ground = ground; + } + + public Transform get(Camera type) { + switch(type) { + case THIRD_PERSON: + return this.third; + case FIRST_PERSON: + return this.first; + case GUI: + return this.gui; + case GROUND: + return this.ground; + default: + return Transform.IDENTITY; + } + } +} diff --git a/common/src/main/java/common/net/bootstrap/AbstractBootstrap.java b/common/src/main/java/common/net/bootstrap/AbstractBootstrap.java new file mode 100644 index 0000000..51ed7ec --- /dev/null +++ b/common/src/main/java/common/net/bootstrap/AbstractBootstrap.java @@ -0,0 +1,474 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.bootstrap; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.LinkedHashMap; +import java.util.Map; + +import common.net.channel.Channel; +import common.net.channel.ChannelException; +import common.net.channel.ChannelFuture; +import common.net.channel.ChannelFutureListener; +import common.net.channel.ChannelHandler; +import common.net.channel.ChannelOption; +import common.net.channel.ChannelPromise; +import common.net.channel.DefaultChannelPromise; +import common.net.channel.EventLoopGroup; +import common.net.util.AttributeKey; +import common.net.util.concurrent.EventExecutor; +import common.net.util.concurrent.GlobalEventExecutor; +import common.net.util.internal.StringUtil; + +/** + * {@link AbstractBootstrap} is a helper class that makes it easy to bootstrap a {@link Channel}. It support + * method-chaining to provide an easy way to configure the {@link AbstractBootstrap}. + * + *

When not used in a {@link ServerBootstrap} context, the {@link #bind()} methods are useful for connectionless + * transports such as datagram (UDP).

+ */ +public abstract class AbstractBootstrap, C extends Channel> implements Cloneable { + + private volatile EventLoopGroup group; + private volatile ChannelFactory channelFactory; + private volatile SocketAddress localAddress; + private final Map, Object> options = new LinkedHashMap, Object>(); + private final Map, Object> attrs = new LinkedHashMap, Object>(); + private volatile ChannelHandler handler; + + AbstractBootstrap() { + // Disallow extending from a different package. + } + + AbstractBootstrap(AbstractBootstrap bootstrap) { + group = bootstrap.group; + channelFactory = bootstrap.channelFactory; + handler = bootstrap.handler; + localAddress = bootstrap.localAddress; + synchronized (bootstrap.options) { + options.putAll(bootstrap.options); + } + synchronized (bootstrap.attrs) { + attrs.putAll(bootstrap.attrs); + } + } + + /** + * The {@link EventLoopGroup} which is used to handle all the events for the to-be-creates + * {@link Channel} + */ + + public B group(EventLoopGroup group) { + if (group == null) { + throw new NullPointerException("group"); + } + if (this.group != null) { + throw new IllegalStateException("group set already"); + } + this.group = group; + return (B) this; + } + + /** + * The {@link Class} which is used to create {@link Channel} instances from. + * You either use this or {@link #channelFactory(ChannelFactory)} if your + * {@link Channel} implementation has no no-args constructor. + */ + public B channel(Class channelClass) { + if (channelClass == null) { + throw new NullPointerException("channelClass"); + } + return channelFactory(new BootstrapChannelFactory(channelClass)); + } + + /** + * {@link ChannelFactory} which is used to create {@link Channel} instances from + * when calling {@link #bind()}. This method is usually only used if {@link #channel(Class)} + * is not working for you because of some more complex needs. If your {@link Channel} implementation + * has a no-args constructor, its highly recommend to just use {@link #channel(Class)} for + * simplify your code. + */ + + public B channelFactory(ChannelFactory channelFactory) { + if (channelFactory == null) { + throw new NullPointerException("channelFactory"); + } + if (this.channelFactory != null) { + throw new IllegalStateException("channelFactory set already"); + } + + this.channelFactory = channelFactory; + return (B) this; + } + + /** + * The {@link SocketAddress} which is used to bind the local "end" to. + * + */ + + public B localAddress(SocketAddress localAddress) { + this.localAddress = localAddress; + return (B) this; + } + + /** + * @see {@link #localAddress(SocketAddress)} + */ + public B localAddress(int inetPort) { + return localAddress(new InetSocketAddress(inetPort)); + } + + /** + * @see {@link #localAddress(SocketAddress)} + */ + public B localAddress(String inetHost, int inetPort) { + return localAddress(new InetSocketAddress(inetHost, inetPort)); + } + + /** + * @see {@link #localAddress(SocketAddress)} + */ + public B localAddress(InetAddress inetHost, int inetPort) { + return localAddress(new InetSocketAddress(inetHost, inetPort)); + } + + /** + * Allow to specify a {@link ChannelOption} which is used for the {@link Channel} instances once they got + * created. Use a value of {@code null} to remove a previous set {@link ChannelOption}. + */ + + public B option(ChannelOption option, T value) { + if (option == null) { + throw new NullPointerException("option"); + } + if (value == null) { + synchronized (options) { + options.remove(option); + } + } else { + synchronized (options) { + options.put(option, value); + } + } + return (B) this; + } + + /** + * Allow to specify an initial attribute of the newly created {@link Channel}. If the {@code value} is + * {@code null}, the attribute of the specified {@code key} is removed. + */ + public B attr(AttributeKey key, T value) { + if (key == null) { + throw new NullPointerException("key"); + } + if (value == null) { + synchronized (attrs) { + attrs.remove(key); + } + } else { + synchronized (attrs) { + attrs.put(key, value); + } + } + + + B b = (B) this; + return b; + } + + /** + * Validate all the parameters. Sub-classes may override this, but should + * call the super method in that case. + */ + + public B validate() { + if (group == null) { + throw new IllegalStateException("group not set"); + } + if (channelFactory == null) { + throw new IllegalStateException("channel or channelFactory not set"); + } + return (B) this; + } + + /** + * Returns a deep clone of this bootstrap which has the identical configuration. This method is useful when making + * multiple {@link Channel}s with similar settings. Please note that this method does not clone the + * {@link EventLoopGroup} deeply but shallowly, making the group a shared resource. + */ + @Override + + public abstract B clone(); + + /** + * Create a new {@link Channel} and register it with an {@link EventLoop}. + */ + public ChannelFuture register() { + validate(); + return initAndRegister(); + } + + /** + * Create a new {@link Channel} and bind it. + */ + public ChannelFuture bind() { + validate(); + SocketAddress localAddress = this.localAddress; + if (localAddress == null) { + throw new IllegalStateException("localAddress not set"); + } + return doBind(localAddress); + } + + /** + * Create a new {@link Channel} and bind it. + */ + public ChannelFuture bind(int inetPort) { + return bind(new InetSocketAddress(inetPort)); + } + + /** + * Create a new {@link Channel} and bind it. + */ + public ChannelFuture bind(String inetHost, int inetPort) { + return bind(new InetSocketAddress(inetHost, inetPort)); + } + + /** + * Create a new {@link Channel} and bind it. + */ + public ChannelFuture bind(InetAddress inetHost, int inetPort) { + return bind(new InetSocketAddress(inetHost, inetPort)); + } + + /** + * Create a new {@link Channel} and bind it. + */ + public ChannelFuture bind(SocketAddress localAddress) { + validate(); + if (localAddress == null) { + throw new NullPointerException("localAddress"); + } + return doBind(localAddress); + } + + private ChannelFuture doBind(final SocketAddress localAddress) { + final ChannelFuture regFuture = initAndRegister(); + final Channel channel = regFuture.channel(); + if (regFuture.cause() != null) { + return regFuture; + } + + final ChannelPromise promise; + if (regFuture.isDone()) { + promise = channel.newPromise(); + doBind0(regFuture, channel, localAddress, promise); + } else { + // Registration future is almost always fulfilled already, but just in case it's not. + promise = new PendingRegistrationPromise(channel); + regFuture.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + doBind0(regFuture, channel, localAddress, promise); + } + }); + } + + return promise; + } + + final ChannelFuture initAndRegister() { + final Channel channel = channelFactory().newChannel(); + try { + init(channel); + } catch (Throwable t) { + channel.unsafe().closeForcibly(); + // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor + return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t); + } + + ChannelFuture regFuture = group().register(channel); + if (regFuture.cause() != null) { + if (channel.isRegistered()) { + channel.close(); + } else { + channel.unsafe().closeForcibly(); + } + } + + // If we are here and the promise is not failed, it's one of the following cases: + // 1) If we attempted registration from the event loop, the registration has been completed at this point. + // i.e. It's safe to attempt bind() or connect() now because the channel has been registered. + // 2) If we attempted registration from the other thread, the registration request has been successfully + // added to the event loop's task queue for later execution. + // i.e. It's safe to attempt bind() or connect() now: + // because bind() or connect() will be executed *after* the scheduled registration task is executed + // because register(), bind(), and connect() are all bound to the same thread. + + return regFuture; + } + + abstract void init(Channel channel) throws Exception; + + private static void doBind0( + final ChannelFuture regFuture, final Channel channel, + final SocketAddress localAddress, final ChannelPromise promise) { + + // This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up + // the pipeline in its channelRegistered() implementation. + channel.eventLoop().execute(new Runnable() { + @Override + public void run() { + if (regFuture.isSuccess()) { + channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE); + } else { + promise.setFailure(regFuture.cause()); + } + } + }); + } + + /** + * the {@link ChannelHandler} to use for serving the requests. + */ + + public B handler(ChannelHandler handler) { + if (handler == null) { + throw new NullPointerException("handler"); + } + this.handler = handler; + return (B) this; + } + + final SocketAddress localAddress() { + return localAddress; + } + + final ChannelFactory channelFactory() { + return channelFactory; + } + + final ChannelHandler handler() { + return handler; + } + + /** + * Return the configured {@link EventLoopGroup} or {@code null} if non is configured yet. + */ + public final EventLoopGroup group() { + return group; + } + + final Map, Object> options() { + return options; + } + + final Map, Object> attrs() { + return attrs; + } + + @Override + public String toString() { + StringBuilder buf = new StringBuilder(); + buf.append(StringUtil.simpleClassName(this)); + buf.append('('); + if (group != null) { + buf.append("group: "); + buf.append(StringUtil.simpleClassName(group)); + buf.append(", "); + } + if (channelFactory != null) { + buf.append("channelFactory: "); + buf.append(channelFactory); + buf.append(", "); + } + if (localAddress != null) { + buf.append("localAddress: "); + buf.append(localAddress); + buf.append(", "); + } + synchronized (options) { + if (!options.isEmpty()) { + buf.append("options: "); + buf.append(options); + buf.append(", "); + } + } + synchronized (attrs) { + if (!attrs.isEmpty()) { + buf.append("attrs: "); + buf.append(attrs); + buf.append(", "); + } + } + if (handler != null) { + buf.append("handler: "); + buf.append(handler); + buf.append(", "); + } + if (buf.charAt(buf.length() - 1) == '(') { + buf.append(')'); + } else { + buf.setCharAt(buf.length() - 2, ')'); + buf.setLength(buf.length() - 1); + } + return buf.toString(); + } + + private static final class BootstrapChannelFactory implements ChannelFactory { + private final Class clazz; + + BootstrapChannelFactory(Class clazz) { + this.clazz = clazz; + } + + @Override + public T newChannel() { + try { + return clazz.getConstructor().newInstance(); + } catch (Throwable t) { + throw new ChannelException("Unable to create Channel from class " + clazz, t); + } + } + + @Override + public String toString() { + return StringUtil.simpleClassName(clazz) + ".class"; + } + } + + private static final class PendingRegistrationPromise extends DefaultChannelPromise { + private PendingRegistrationPromise(Channel channel) { + super(channel); + } + + @Override + protected EventExecutor executor() { + if (channel().isRegistered()) { + // If the registration was a success we can just call super.executor() which will return + // channel.eventLoop(). + // + // See https://github.com/netty/netty/issues/2586 + return super.executor(); + } + // The registration failed so we can only use the GlobalEventExecutor as last resort to notify. + return GlobalEventExecutor.INSTANCE; + } + } +} diff --git a/common/src/main/java/common/net/bootstrap/Bootstrap.java b/common/src/main/java/common/net/bootstrap/Bootstrap.java new file mode 100644 index 0000000..dd59fb0 --- /dev/null +++ b/common/src/main/java/common/net/bootstrap/Bootstrap.java @@ -0,0 +1,233 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.bootstrap; + +import java.net.InetAddress; +import java.net.InetSocketAddress; +import java.net.SocketAddress; +import java.util.Map; +import java.util.Map.Entry; + +import common.net.channel.Channel; +import common.net.channel.ChannelFuture; +import common.net.channel.ChannelFutureListener; +import common.net.channel.ChannelOption; +import common.net.channel.ChannelPipeline; +import common.net.channel.ChannelPromise; +import common.net.util.AttributeKey; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * A {@link Bootstrap} that makes it easy to bootstrap a {@link Channel} to use + * for clients. + * + *

The {@link #bind()} methods are useful in combination with connectionless transports such as datagram (UDP). + * For regular TCP connections, please use the provided {@link #connect()} methods.

+ */ +public final class Bootstrap extends AbstractBootstrap { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(Bootstrap.class); + + private volatile SocketAddress remoteAddress; + + public Bootstrap() { } + + private Bootstrap(Bootstrap bootstrap) { + super(bootstrap); + remoteAddress = bootstrap.remoteAddress; + } + + /** + * The {@link SocketAddress} to connect to once the {@link #connect()} method + * is called. + */ + public Bootstrap remoteAddress(SocketAddress remoteAddress) { + this.remoteAddress = remoteAddress; + return this; + } + + /** + * @see {@link #remoteAddress(SocketAddress)} + */ + public Bootstrap remoteAddress(String inetHost, int inetPort) { + remoteAddress = new InetSocketAddress(inetHost, inetPort); + return this; + } + + /** + * @see {@link #remoteAddress(SocketAddress)} + */ + public Bootstrap remoteAddress(InetAddress inetHost, int inetPort) { + remoteAddress = new InetSocketAddress(inetHost, inetPort); + return this; + } + + /** + * Connect a {@link Channel} to the remote peer. + */ + public ChannelFuture connect() { + validate(); + SocketAddress remoteAddress = this.remoteAddress; + if (remoteAddress == null) { + throw new IllegalStateException("remoteAddress not set"); + } + + return doConnect(remoteAddress, localAddress()); + } + + /** + * Connect a {@link Channel} to the remote peer. + */ + public ChannelFuture connect(String inetHost, int inetPort) { + return connect(new InetSocketAddress(inetHost, inetPort)); + } + + /** + * Connect a {@link Channel} to the remote peer. + */ + public ChannelFuture connect(InetAddress inetHost, int inetPort) { + return connect(new InetSocketAddress(inetHost, inetPort)); + } + + /** + * Connect a {@link Channel} to the remote peer. + */ + public ChannelFuture connect(SocketAddress remoteAddress) { + if (remoteAddress == null) { + throw new NullPointerException("remoteAddress"); + } + + validate(); + return doConnect(remoteAddress, localAddress()); + } + + /** + * Connect a {@link Channel} to the remote peer. + */ + public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { + if (remoteAddress == null) { + throw new NullPointerException("remoteAddress"); + } + validate(); + return doConnect(remoteAddress, localAddress); + } + + /** + * @see {@link #connect()} + */ + private ChannelFuture doConnect(final SocketAddress remoteAddress, final SocketAddress localAddress) { + final ChannelFuture regFuture = initAndRegister(); + final Channel channel = regFuture.channel(); + if (regFuture.cause() != null) { + return regFuture; + } + + final ChannelPromise promise = channel.newPromise(); + if (regFuture.isDone()) { + doConnect0(regFuture, channel, remoteAddress, localAddress, promise); + } else { + regFuture.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + doConnect0(regFuture, channel, remoteAddress, localAddress, promise); + } + }); + } + + return promise; + } + + private static void doConnect0( + final ChannelFuture regFuture, final Channel channel, + final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) { + + // This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up + // the pipeline in its channelRegistered() implementation. + channel.eventLoop().execute(new Runnable() { + @Override + public void run() { + if (regFuture.isSuccess()) { + if (localAddress == null) { + channel.connect(remoteAddress, promise); + } else { + channel.connect(remoteAddress, localAddress, promise); + } + promise.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); + } else { + promise.setFailure(regFuture.cause()); + } + } + }); + } + + @Override + + void init(Channel channel) throws Exception { + ChannelPipeline p = channel.pipeline(); + p.addLast(handler()); + + final Map, Object> options = options(); + synchronized (options) { + for (Entry, Object> e: options.entrySet()) { + try { + if (!channel.config().setOption((ChannelOption) e.getKey(), e.getValue())) { + logger.warn("Unknown channel option: " + e); + } + } catch (Throwable t) { + logger.warn("Failed to set a channel option: " + channel, t); + } + } + } + + final Map, Object> attrs = attrs(); + synchronized (attrs) { + for (Entry, Object> e: attrs.entrySet()) { + channel.attr((AttributeKey) e.getKey()).set(e.getValue()); + } + } + } + + @Override + public Bootstrap validate() { + super.validate(); + if (handler() == null) { + throw new IllegalStateException("handler not set"); + } + return this; + } + + @Override + + public Bootstrap clone() { + return new Bootstrap(this); + } + + @Override + public String toString() { + if (remoteAddress == null) { + return super.toString(); + } + + StringBuilder buf = new StringBuilder(super.toString()); + buf.setLength(buf.length() - 1); + buf.append(", remoteAddress: "); + buf.append(remoteAddress); + buf.append(')'); + + return buf.toString(); + } +} diff --git a/common/src/main/java/common/net/bootstrap/ChannelFactory.java b/common/src/main/java/common/net/bootstrap/ChannelFactory.java new file mode 100644 index 0000000..d6e48e3 --- /dev/null +++ b/common/src/main/java/common/net/bootstrap/ChannelFactory.java @@ -0,0 +1,29 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.bootstrap; + +import common.net.channel.Channel; + +/** + * Factory that creates a new {@link Channel} on {@link Bootstrap#bind()}, {@link Bootstrap#connect()}, and + * {@link ServerBootstrap#bind()}. + */ +public interface ChannelFactory { + /** + * Creates a new channel. + */ + T newChannel(); +} diff --git a/common/src/main/java/common/net/bootstrap/ServerBootstrap.java b/common/src/main/java/common/net/bootstrap/ServerBootstrap.java new file mode 100644 index 0000000..96144f9 --- /dev/null +++ b/common/src/main/java/common/net/bootstrap/ServerBootstrap.java @@ -0,0 +1,332 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.bootstrap; + +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; + +import common.net.channel.Channel; +import common.net.channel.ChannelConfig; +import common.net.channel.ChannelFuture; +import common.net.channel.ChannelFutureListener; +import common.net.channel.ChannelHandler; +import common.net.channel.ChannelHandlerContext; +import common.net.channel.ChannelInboundHandlerAdapter; +import common.net.channel.ChannelInitializer; +import common.net.channel.ChannelOption; +import common.net.channel.ChannelPipeline; +import common.net.channel.EventLoopGroup; +import common.net.channel.ServerChannel; +import common.net.util.AttributeKey; +import common.net.util.internal.StringUtil; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * {@link Bootstrap} sub-class which allows easy bootstrap of {@link ServerChannel} + * + */ +public final class ServerBootstrap extends AbstractBootstrap { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(ServerBootstrap.class); + + private final Map, Object> childOptions = new LinkedHashMap, Object>(); + private final Map, Object> childAttrs = new LinkedHashMap, Object>(); + private volatile EventLoopGroup childGroup; + private volatile ChannelHandler childHandler; + + public ServerBootstrap() { } + + private ServerBootstrap(ServerBootstrap bootstrap) { + super(bootstrap); + childGroup = bootstrap.childGroup; + childHandler = bootstrap.childHandler; + synchronized (bootstrap.childOptions) { + childOptions.putAll(bootstrap.childOptions); + } + synchronized (bootstrap.childAttrs) { + childAttrs.putAll(bootstrap.childAttrs); + } + } + + /** + * Specify the {@link EventLoopGroup} which is used for the parent (acceptor) and the child (client). + */ + @Override + public ServerBootstrap group(EventLoopGroup group) { + return group(group, group); + } + + /** + * Set the {@link EventLoopGroup} for the parent (acceptor) and the child (client). These + * {@link EventLoopGroup}'s are used to handle all the events and IO for {@link SocketChannel} and + * {@link Channel}'s. + */ + public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup) { + super.group(parentGroup); + if (childGroup == null) { + throw new NullPointerException("childGroup"); + } + if (this.childGroup != null) { + throw new IllegalStateException("childGroup set already"); + } + this.childGroup = childGroup; + return this; + } + + /** + * Allow to specify a {@link ChannelOption} which is used for the {@link Channel} instances once they get created + * (after the acceptor accepted the {@link Channel}). Use a value of {@code null} to remove a previous set + * {@link ChannelOption}. + */ + public ServerBootstrap childOption(ChannelOption childOption, T value) { + if (childOption == null) { + throw new NullPointerException("childOption"); + } + if (value == null) { + synchronized (childOptions) { + childOptions.remove(childOption); + } + } else { + synchronized (childOptions) { + childOptions.put(childOption, value); + } + } + return this; + } + + /** + * Set the specific {@link AttributeKey} with the given value on every child {@link Channel}. If the value is + * {@code null} the {@link AttributeKey} is removed + */ + public ServerBootstrap childAttr(AttributeKey childKey, T value) { + if (childKey == null) { + throw new NullPointerException("childKey"); + } + if (value == null) { + childAttrs.remove(childKey); + } else { + childAttrs.put(childKey, value); + } + return this; + } + + /** + * Set the {@link ChannelHandler} which is used to serve the request for the {@link Channel}'s. + */ + public ServerBootstrap childHandler(ChannelHandler childHandler) { + if (childHandler == null) { + throw new NullPointerException("childHandler"); + } + this.childHandler = childHandler; + return this; + } + + /** + * Return the configured {@link EventLoopGroup} which will be used for the child channels or {@code null} + * if non is configured yet. + */ + public EventLoopGroup childGroup() { + return childGroup; + } + + @Override + void init(Channel channel) throws Exception { + final Map, Object> options = options(); + synchronized (options) { + channel.config().setOptions(options); + } + + final Map, Object> attrs = attrs(); + synchronized (attrs) { + for (Entry, Object> e: attrs.entrySet()) { + + AttributeKey key = (AttributeKey) e.getKey(); + channel.attr(key).set(e.getValue()); + } + } + + ChannelPipeline p = channel.pipeline(); + if (handler() != null) { + p.addLast(handler()); + } + + final EventLoopGroup currentChildGroup = childGroup; + final ChannelHandler currentChildHandler = childHandler; + final Entry, Object>[] currentChildOptions; + final Entry, Object>[] currentChildAttrs; + synchronized (childOptions) { + currentChildOptions = childOptions.entrySet().toArray(newOptionArray(childOptions.size())); + } + synchronized (childAttrs) { + currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(childAttrs.size())); + } + + p.addLast(new ChannelInitializer() { + @Override + public void initChannel(Channel ch) throws Exception { + ch.pipeline().addLast(new ServerBootstrapAcceptor( + currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs)); + } + }); + } + + @Override + public ServerBootstrap validate() { + super.validate(); + if (childHandler == null) { + throw new IllegalStateException("childHandler not set"); + } + if (childGroup == null) { + logger.warn("childGroup is not set. Using parentGroup instead."); + childGroup = group(); + } + return this; + } + + + private static Entry, Object>[] newOptionArray(int size) { + return new Entry[size]; + } + + + private static Entry, Object>[] newAttrArray(int size) { + return new Entry[size]; + } + + private static class ServerBootstrapAcceptor extends ChannelInboundHandlerAdapter { + + private final EventLoopGroup childGroup; + private final ChannelHandler childHandler; + private final Entry, Object>[] childOptions; + private final Entry, Object>[] childAttrs; + + ServerBootstrapAcceptor( + EventLoopGroup childGroup, ChannelHandler childHandler, + Entry, Object>[] childOptions, Entry, Object>[] childAttrs) { + this.childGroup = childGroup; + this.childHandler = childHandler; + this.childOptions = childOptions; + this.childAttrs = childAttrs; + } + + @Override + + public void channelRead(ChannelHandlerContext ctx, Object msg) { + final Channel child = (Channel) msg; + + child.pipeline().addLast(childHandler); + + for (Entry, Object> e: childOptions) { + try { + if (!child.config().setOption((ChannelOption) e.getKey(), e.getValue())) { + logger.warn("Unknown channel option: " + e); + } + } catch (Throwable t) { + logger.warn("Failed to set a channel option: " + child, t); + } + } + + for (Entry, Object> e: childAttrs) { + child.attr((AttributeKey) e.getKey()).set(e.getValue()); + } + + try { + childGroup.register(child).addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + if (!future.isSuccess()) { + forceClose(child, future.cause()); + } + } + }); + } catch (Throwable t) { + forceClose(child, t); + } + } + + private static void forceClose(Channel child, Throwable t) { + child.unsafe().closeForcibly(); + logger.warn("Failed to register an accepted channel: " + child, t); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + final ChannelConfig config = ctx.channel().config(); + if (config.isAutoRead()) { + // stop accept new connections for 1 second to allow the channel to recover + // See https://github.com/netty/netty/issues/1328 + config.setAutoRead(false); + ctx.channel().eventLoop().schedule(new Runnable() { + @Override + public void run() { + config.setAutoRead(true); + } + }, 1, TimeUnit.SECONDS); + } + // still let the exceptionCaught event flow through the pipeline to give the user + // a chance to do something with it + ctx.fireExceptionCaught(cause); + } + } + + @Override + + public ServerBootstrap clone() { + return new ServerBootstrap(this); + } + + @Override + public String toString() { + StringBuilder buf = new StringBuilder(super.toString()); + buf.setLength(buf.length() - 1); + buf.append(", "); + if (childGroup != null) { + buf.append("childGroup: "); + buf.append(StringUtil.simpleClassName(childGroup)); + buf.append(", "); + } + synchronized (childOptions) { + if (!childOptions.isEmpty()) { + buf.append("childOptions: "); + buf.append(childOptions); + buf.append(", "); + } + } + synchronized (childAttrs) { + if (!childAttrs.isEmpty()) { + buf.append("childAttrs: "); + buf.append(childAttrs); + buf.append(", "); + } + } + if (childHandler != null) { + buf.append("childHandler: "); + buf.append(childHandler); + buf.append(", "); + } + if (buf.charAt(buf.length() - 1) == '(') { + buf.append(')'); + } else { + buf.setCharAt(buf.length() - 2, ')'); + buf.setLength(buf.length() - 1); + } + + return buf.toString(); + } +} diff --git a/common/src/main/java/common/net/buffer/AbstractByteBuf.java b/common/src/main/java/common/net/buffer/AbstractByteBuf.java new file mode 100644 index 0000000..5c0676f --- /dev/null +++ b/common/src/main/java/common/net/buffer/AbstractByteBuf.java @@ -0,0 +1,1190 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; +import java.nio.charset.Charset; + +import common.net.util.IllegalReferenceCountException; +import common.net.util.ResourceLeakDetector; +import common.net.util.internal.StringUtil; +import common.util.Util; + + +/** + * A skeletal implementation of a buffer. + */ +public abstract class AbstractByteBuf extends ByteBuf { + + static final ResourceLeakDetector leakDetector = new ResourceLeakDetector(ByteBuf.class); + + int readerIndex; + int writerIndex; + private int markedReaderIndex; + private int markedWriterIndex; + + private int maxCapacity; + + private SwappedByteBuf swappedBuf; + + protected AbstractByteBuf(int maxCapacity) { + if (maxCapacity < 0) { + throw new IllegalArgumentException("maxCapacity: " + maxCapacity + " (expected: >= 0)"); + } + this.maxCapacity = maxCapacity; + } + + @Override + public int maxCapacity() { + return maxCapacity; + } + + protected final void maxCapacity(int maxCapacity) { + this.maxCapacity = maxCapacity; + } + + @Override + public int readerIndex() { + return readerIndex; + } + + @Override + public ByteBuf readerIndex(int readerIndex) { + if (readerIndex < 0 || readerIndex > writerIndex) { + throw new IndexOutOfBoundsException(String.format( + "readerIndex: %d (expected: 0 <= readerIndex <= writerIndex(%d))", readerIndex, writerIndex)); + } + this.readerIndex = readerIndex; + return this; + } + + @Override + public int writerIndex() { + return writerIndex; + } + + @Override + public ByteBuf writerIndex(int writerIndex) { + if (writerIndex < readerIndex || writerIndex > capacity()) { + throw new IndexOutOfBoundsException(String.format( + "writerIndex: %d (expected: readerIndex(%d) <= writerIndex <= capacity(%d))", + writerIndex, readerIndex, capacity())); + } + this.writerIndex = writerIndex; + return this; + } + + @Override + public ByteBuf setIndex(int readerIndex, int writerIndex) { + if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) { + throw new IndexOutOfBoundsException(String.format( + "readerIndex: %d, writerIndex: %d (expected: 0 <= readerIndex <= writerIndex <= capacity(%d))", + readerIndex, writerIndex, capacity())); + } + this.readerIndex = readerIndex; + this.writerIndex = writerIndex; + return this; + } + + @Override + public ByteBuf clear() { + readerIndex = writerIndex = 0; + return this; + } + + @Override + public boolean isReadable() { + return writerIndex > readerIndex; + } + + @Override + public boolean isReadable(int numBytes) { + return writerIndex - readerIndex >= numBytes; + } + + @Override + public boolean isWritable() { + return capacity() > writerIndex; + } + + @Override + public boolean isWritable(int numBytes) { + return capacity() - writerIndex >= numBytes; + } + + @Override + public int readableBytes() { + return writerIndex - readerIndex; + } + + @Override + public int writableBytes() { + return capacity() - writerIndex; + } + + @Override + public int maxWritableBytes() { + return maxCapacity() - writerIndex; + } + + @Override + public ByteBuf markReaderIndex() { + markedReaderIndex = readerIndex; + return this; + } + + @Override + public ByteBuf resetReaderIndex() { + readerIndex(markedReaderIndex); + return this; + } + + @Override + public ByteBuf markWriterIndex() { + markedWriterIndex = writerIndex; + return this; + } + + @Override + public ByteBuf resetWriterIndex() { + writerIndex = markedWriterIndex; + return this; + } + + @Override + public ByteBuf discardReadBytes() { + ensureAccessible(); + if (readerIndex == 0) { + return this; + } + + if (readerIndex != writerIndex) { + setBytes(0, this, readerIndex, writerIndex - readerIndex); + writerIndex -= readerIndex; + adjustMarkers(readerIndex); + readerIndex = 0; + } else { + adjustMarkers(readerIndex); + writerIndex = readerIndex = 0; + } + return this; + } + + @Override + public ByteBuf discardSomeReadBytes() { + ensureAccessible(); + if (readerIndex == 0) { + return this; + } + + if (readerIndex == writerIndex) { + adjustMarkers(readerIndex); + writerIndex = readerIndex = 0; + return this; + } + + if (readerIndex >= capacity() >>> 1) { + setBytes(0, this, readerIndex, writerIndex - readerIndex); + writerIndex -= readerIndex; + adjustMarkers(readerIndex); + readerIndex = 0; + } + return this; + } + + protected final void adjustMarkers(int decrement) { + int markedReaderIndex = this.markedReaderIndex; + if (markedReaderIndex <= decrement) { + this.markedReaderIndex = 0; + int markedWriterIndex = this.markedWriterIndex; + if (markedWriterIndex <= decrement) { + this.markedWriterIndex = 0; + } else { + this.markedWriterIndex = markedWriterIndex - decrement; + } + } else { + this.markedReaderIndex = markedReaderIndex - decrement; + markedWriterIndex -= decrement; + } + } + + @Override + public ByteBuf ensureWritable(int minWritableBytes) { + if (minWritableBytes < 0) { + throw new IllegalArgumentException(String.format( + "minWritableBytes: %d (expected: >= 0)", minWritableBytes)); + } + + if (minWritableBytes <= writableBytes()) { + return this; + } + + if (minWritableBytes > maxCapacity - writerIndex) { + throw new IndexOutOfBoundsException(String.format( + "writerIndex(%d) + minWritableBytes(%d) exceeds maxCapacity(%d): %s", + writerIndex, minWritableBytes, maxCapacity, this)); + } + + // Normalize the current capacity to the power of 2. + int newCapacity = calculateNewCapacity(writerIndex + minWritableBytes); + + // Adjust to the new capacity. + capacity(newCapacity); + return this; + } + + @Override + public int ensureWritable(int minWritableBytes, boolean force) { + if (minWritableBytes < 0) { + throw new IllegalArgumentException(String.format( + "minWritableBytes: %d (expected: >= 0)", minWritableBytes)); + } + + if (minWritableBytes <= writableBytes()) { + return 0; + } + + if (minWritableBytes > maxCapacity - writerIndex) { + if (force) { + if (capacity() == maxCapacity()) { + return 1; + } + + capacity(maxCapacity()); + return 3; + } + } + + // Normalize the current capacity to the power of 2. + int newCapacity = calculateNewCapacity(writerIndex + minWritableBytes); + + // Adjust to the new capacity. + capacity(newCapacity); + return 2; + } + + private int calculateNewCapacity(int minNewCapacity) { + final int maxCapacity = this.maxCapacity; + final int threshold = 1048576 * 4; // 4 MiB page + + if (minNewCapacity == threshold) { + return threshold; + } + + // If over threshold, do not double but just increase by threshold. + if (minNewCapacity > threshold) { + int newCapacity = minNewCapacity / threshold * threshold; + if (newCapacity > maxCapacity - threshold) { + newCapacity = maxCapacity; + } else { + newCapacity += threshold; + } + return newCapacity; + } + + // Not over threshold. Double up to 4 MiB, starting from 64. + int newCapacity = 64; + while (newCapacity < minNewCapacity) { + newCapacity <<= 1; + } + + return Math.min(newCapacity, maxCapacity); + } + + @Override + public ByteBuf order(ByteOrder endianness) { + if (endianness == null) { + throw new NullPointerException("endianness"); + } + if (endianness == order()) { + return this; + } + + SwappedByteBuf swappedBuf = this.swappedBuf; + if (swappedBuf == null) { + this.swappedBuf = swappedBuf = newSwappedByteBuf(); + } + return swappedBuf; + } + + /** + * Creates a new {@link SwappedByteBuf} for this {@link ByteBuf} instance. + */ + protected SwappedByteBuf newSwappedByteBuf() { + return new SwappedByteBuf(this); + } + + @Override + public byte getByte(int index) { + checkIndex(index); + return _getByte(index); + } + + protected abstract byte _getByte(int index); + + @Override + public boolean getBoolean(int index) { + return getByte(index) != 0; + } + + @Override + public short getUnsignedByte(int index) { + return (short) (getByte(index) & 0xFF); + } + + @Override + public short getShort(int index) { + checkIndex(index, 2); + return _getShort(index); + } + + protected abstract short _getShort(int index); + + @Override + public int getUnsignedShort(int index) { + return getShort(index) & 0xFFFF; + } + + @Override + public int getUnsignedMedium(int index) { + checkIndex(index, 3); + return _getUnsignedMedium(index); + } + + protected abstract int _getUnsignedMedium(int index); + + @Override + public int getMedium(int index) { + int value = getUnsignedMedium(index); + if ((value & 0x800000) != 0) { + value |= 0xff000000; + } + return value; + } + + @Override + public int getInt(int index) { + checkIndex(index, 4); + return _getInt(index); + } + + protected abstract int _getInt(int index); + + @Override + public long getUnsignedInt(int index) { + return getInt(index) & 0xFFFFFFFFL; + } + + @Override + public long getLong(int index) { + checkIndex(index, 8); + return _getLong(index); + } + + protected abstract long _getLong(int index); + + @Override + public char getChar(int index) { + return (char) getShort(index); + } + + @Override + public float getFloat(int index) { + return Float.intBitsToFloat(getInt(index)); + } + + @Override + public double getDouble(int index) { + return Double.longBitsToDouble(getLong(index)); + } + + @Override + public ByteBuf getBytes(int index, byte[] dst) { + getBytes(index, dst, 0, dst.length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst) { + getBytes(index, dst, dst.writableBytes()); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int length) { + getBytes(index, dst, dst.writerIndex(), length); + dst.writerIndex(dst.writerIndex() + length); + return this; + } + + @Override + public ByteBuf setByte(int index, int value) { + checkIndex(index); + _setByte(index, value); + return this; + } + + protected abstract void _setByte(int index, int value); + + @Override + public ByteBuf setBoolean(int index, boolean value) { + setByte(index, value ? 1 : 0); + return this; + } + + @Override + public ByteBuf setShort(int index, int value) { + checkIndex(index, 2); + _setShort(index, value); + return this; + } + + protected abstract void _setShort(int index, int value); + + @Override + public ByteBuf setChar(int index, int value) { + setShort(index, value); + return this; + } + + @Override + public ByteBuf setMedium(int index, int value) { + checkIndex(index, 3); + _setMedium(index, value); + return this; + } + + protected abstract void _setMedium(int index, int value); + + @Override + public ByteBuf setInt(int index, int value) { + checkIndex(index, 4); + _setInt(index, value); + return this; + } + + protected abstract void _setInt(int index, int value); + + @Override + public ByteBuf setFloat(int index, float value) { + setInt(index, Float.floatToRawIntBits(value)); + return this; + } + + @Override + public ByteBuf setLong(int index, long value) { + checkIndex(index, 8); + _setLong(index, value); + return this; + } + + protected abstract void _setLong(int index, long value); + + @Override + public ByteBuf setDouble(int index, double value) { + setLong(index, Double.doubleToRawLongBits(value)); + return this; + } + + @Override + public ByteBuf setBytes(int index, byte[] src) { + setBytes(index, src, 0, src.length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src) { + setBytes(index, src, src.readableBytes()); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int length) { + checkIndex(index, length); + if (src == null) { + throw new NullPointerException("src"); + } + if (length > src.readableBytes()) { + throw new IndexOutOfBoundsException(String.format( + "length(%d) exceeds src.readableBytes(%d) where src is: %s", length, src.readableBytes(), src)); + } + + setBytes(index, src, src.readerIndex(), length); + src.readerIndex(src.readerIndex() + length); + return this; + } + + @Override + public ByteBuf setZero(int index, int length) { + if (length == 0) { + return this; + } + + checkIndex(index, length); + + int nLong = length >>> 3; + int nBytes = length & 7; + for (int i = nLong; i > 0; i --) { + setLong(index, 0); + index += 8; + } + if (nBytes == 4) { + setInt(index, 0); + } else if (nBytes < 4) { + for (int i = nBytes; i > 0; i --) { + setByte(index, (byte) 0); + index ++; + } + } else { + setInt(index, 0); + index += 4; + for (int i = nBytes - 4; i > 0; i --) { + setByte(index, (byte) 0); + index ++; + } + } + return this; + } + + @Override + public byte readByte() { + checkReadableBytes(1); + int i = readerIndex; + byte b = getByte(i); + readerIndex = i + 1; + return b; + } + + @Override + public boolean readBoolean() { + return readByte() != 0; + } + + @Override + public short readUnsignedByte() { + return (short) (readByte() & 0xFF); + } + + @Override + public short readShort() { + checkReadableBytes(2); + short v = _getShort(readerIndex); + readerIndex += 2; + return v; + } + + @Override + public int readUnsignedShort() { + return readShort() & 0xFFFF; + } + + @Override + public int readMedium() { + int value = readUnsignedMedium(); + if ((value & 0x800000) != 0) { + value |= 0xff000000; + } + return value; + } + + @Override + public int readUnsignedMedium() { + checkReadableBytes(3); + int v = _getUnsignedMedium(readerIndex); + readerIndex += 3; + return v; + } + + @Override + public int readInt() { + checkReadableBytes(4); + int v = _getInt(readerIndex); + readerIndex += 4; + return v; + } + + @Override + public long readUnsignedInt() { + return readInt() & 0xFFFFFFFFL; + } + + @Override + public long readLong() { + checkReadableBytes(8); + long v = _getLong(readerIndex); + readerIndex += 8; + return v; + } + + @Override + public char readChar() { + return (char) readShort(); + } + + @Override + public float readFloat() { + return Float.intBitsToFloat(readInt()); + } + + @Override + public double readDouble() { + return Double.longBitsToDouble(readLong()); + } + + @Override + public ByteBuf readBytes(int length) { + checkReadableBytes(length); + if (length == 0) { + return Unpooled.EMPTY_BUFFER; + } + + // Use an unpooled heap buffer because there's no way to mandate a user to free the returned buffer. + ByteBuf buf = Unpooled.buffer(length, maxCapacity); + buf.writeBytes(this, readerIndex, length); + readerIndex += length; + return buf; + } + + @Override + public ByteBuf readSlice(int length) { + ByteBuf slice = slice(readerIndex, length); + readerIndex += length; + return slice; + } + + @Override + public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { + checkReadableBytes(length); + getBytes(readerIndex, dst, dstIndex, length); + readerIndex += length; + return this; + } + + @Override + public ByteBuf readBytes(byte[] dst) { + readBytes(dst, 0, dst.length); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuf dst) { + readBytes(dst, dst.writableBytes()); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int length) { + if (length > dst.writableBytes()) { + throw new IndexOutOfBoundsException(String.format( + "length(%d) exceeds dst.writableBytes(%d) where dst is: %s", length, dst.writableBytes(), dst)); + } + readBytes(dst, dst.writerIndex(), length); + dst.writerIndex(dst.writerIndex() + length); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { + checkReadableBytes(length); + getBytes(readerIndex, dst, dstIndex, length); + readerIndex += length; + return this; + } + + @Override + public ByteBuf readBytes(ByteBuffer dst) { + int length = dst.remaining(); + checkReadableBytes(length); + getBytes(readerIndex, dst); + readerIndex += length; + return this; + } + + @Override + public int readBytes(GatheringByteChannel out, int length) + throws IOException { + checkReadableBytes(length); + int readBytes = getBytes(readerIndex, out, length); + readerIndex += readBytes; + return readBytes; + } + + @Override + public ByteBuf readBytes(OutputStream out, int length) throws IOException { + checkReadableBytes(length); + getBytes(readerIndex, out, length); + readerIndex += length; + return this; + } + + @Override + public ByteBuf skipBytes(int length) { + checkReadableBytes(length); + readerIndex += length; + return this; + } + + @Override + public ByteBuf writeBoolean(boolean value) { + writeByte(value ? 1 : 0); + return this; + } + + @Override + public ByteBuf writeByte(int value) { + ensureAccessible(); + ensureWritable(1); + _setByte(writerIndex++, value); + return this; + } + + @Override + public ByteBuf writeShort(int value) { + ensureAccessible(); + ensureWritable(2); + _setShort(writerIndex, value); + writerIndex += 2; + return this; + } + + @Override + public ByteBuf writeMedium(int value) { + ensureAccessible(); + ensureWritable(3); + _setMedium(writerIndex, value); + writerIndex += 3; + return this; + } + + @Override + public ByteBuf writeInt(int value) { + ensureAccessible(); + ensureWritable(4); + _setInt(writerIndex, value); + writerIndex += 4; + return this; + } + + @Override + public ByteBuf writeLong(long value) { + ensureAccessible(); + ensureWritable(8); + _setLong(writerIndex, value); + writerIndex += 8; + return this; + } + + @Override + public ByteBuf writeChar(int value) { + writeShort(value); + return this; + } + + @Override + public ByteBuf writeFloat(float value) { + writeInt(Float.floatToRawIntBits(value)); + return this; + } + + @Override + public ByteBuf writeDouble(double value) { + writeLong(Double.doubleToRawLongBits(value)); + return this; + } + + @Override + public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { + ensureAccessible(); + ensureWritable(length); + setBytes(writerIndex, src, srcIndex, length); + writerIndex += length; + return this; + } + + @Override + public ByteBuf writeBytes(byte[] src) { + writeBytes(src, 0, src.length); + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuf src) { + writeBytes(src, src.readableBytes()); + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuf src, int length) { + if (length > src.readableBytes()) { + throw new IndexOutOfBoundsException(String.format( + "length(%d) exceeds src.readableBytes(%d) where src is: %s", length, src.readableBytes(), src)); + } + writeBytes(src, src.readerIndex(), length); + src.readerIndex(src.readerIndex() + length); + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { + ensureAccessible(); + ensureWritable(length); + setBytes(writerIndex, src, srcIndex, length); + writerIndex += length; + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuffer src) { + ensureAccessible(); + int length = src.remaining(); + ensureWritable(length); + setBytes(writerIndex, src); + writerIndex += length; + return this; + } + + @Override + public int writeBytes(InputStream in, int length) + throws IOException { + ensureAccessible(); + ensureWritable(length); + int writtenBytes = setBytes(writerIndex, in, length); + if (writtenBytes > 0) { + writerIndex += writtenBytes; + } + return writtenBytes; + } + + @Override + public int writeBytes(ScatteringByteChannel in, int length) throws IOException { + ensureAccessible(); + ensureWritable(length); + int writtenBytes = setBytes(writerIndex, in, length); + if (writtenBytes > 0) { + writerIndex += writtenBytes; + } + return writtenBytes; + } + + @Override + public ByteBuf writeZero(int length) { + if (length == 0) { + return this; + } + + ensureWritable(length); + checkIndex(writerIndex, length); + + int nLong = length >>> 3; + int nBytes = length & 7; + for (int i = nLong; i > 0; i --) { + writeLong(0); + } + if (nBytes == 4) { + writeInt(0); + } else if (nBytes < 4) { + for (int i = nBytes; i > 0; i --) { + writeByte((byte) 0); + } + } else { + writeInt(0); + for (int i = nBytes - 4; i > 0; i --) { + writeByte((byte) 0); + } + } + return this; + } + + @Override + public ByteBuf copy() { + return copy(readerIndex, readableBytes()); + } + + @Override + public ByteBuf duplicate() { + return new DuplicatedByteBuf(this); + } + + @Override + public ByteBuf slice() { + return slice(readerIndex, readableBytes()); + } + + @Override + public ByteBuf slice(int index, int length) { + if (length == 0) { + return Unpooled.EMPTY_BUFFER; + } + + return new SlicedByteBuf(this, index, length); + } + + @Override + public ByteBuffer nioBuffer() { + return nioBuffer(readerIndex, readableBytes()); + } + + @Override + public ByteBuffer[] nioBuffers() { + return nioBuffers(readerIndex, readableBytes()); + } + + @Override + public String toString(Charset charset) { + return toString(readerIndex, readableBytes(), charset); + } + + @Override + public String toString(int index, int length, Charset charset) { + if (length == 0) { + return ""; + } + + ByteBuffer nioBuffer; + if (nioBufferCount() == 1) { + nioBuffer = nioBuffer(index, length); + } else { + nioBuffer = ByteBuffer.allocate(length); + getBytes(index, nioBuffer); + nioBuffer.flip(); + } + + return ByteBufUtil.decodeString(nioBuffer, charset); + } + + @Override + public int indexOf(int fromIndex, int toIndex, byte value) { + return ByteBufUtil.indexOf(this, fromIndex, toIndex, value); + } + + @Override + public int bytesBefore(byte value) { + return bytesBefore(readerIndex(), readableBytes(), value); + } + + @Override + public int bytesBefore(int length, byte value) { + checkReadableBytes(length); + return bytesBefore(readerIndex(), length, value); + } + + @Override + public int bytesBefore(int index, int length, byte value) { + int endIndex = indexOf(index, index + length, value); + if (endIndex < 0) { + return -1; + } + return endIndex - index; + } + + @Override + public int forEachByte(ByteBufProcessor processor) { + int index = readerIndex; + int length = writerIndex - index; + ensureAccessible(); + return forEachByteAsc0(index, length, processor); + } + + @Override + public int forEachByte(int index, int length, ByteBufProcessor processor) { + checkIndex(index, length); + return forEachByteAsc0(index, length, processor); + } + + private int forEachByteAsc0(int index, int length, ByteBufProcessor processor) { + if (processor == null) { + throw new NullPointerException("processor"); + } + + if (length == 0) { + return -1; + } + + final int endIndex = index + length; + int i = index; + try { + do { + if (processor.process(_getByte(i))) { + i ++; + } else { + return i; + } + } while (i < endIndex); + } catch (Exception e) { + Util.throwUnchecked(e); + } + + return -1; + } + + @Override + public int forEachByteDesc(ByteBufProcessor processor) { + int index = readerIndex; + int length = writerIndex - index; + ensureAccessible(); + return forEachByteDesc0(index, length, processor); + } + + @Override + public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { + checkIndex(index, length); + + return forEachByteDesc0(index, length, processor); + } + + private int forEachByteDesc0(int index, int length, ByteBufProcessor processor) { + + if (processor == null) { + throw new NullPointerException("processor"); + } + + if (length == 0) { + return -1; + } + + int i = index + length - 1; + try { + do { + if (processor.process(_getByte(i))) { + i --; + } else { + return i; + } + } while (i >= index); + } catch (Exception e) { + Util.throwUnchecked(e); + } + + return -1; + } + + @Override + public int hashCode() { + return ByteBufUtil.hashCode(this); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o instanceof ByteBuf) { + return ByteBufUtil.equals(this, (ByteBuf) o); + } + return false; + } + + @Override + public int compareTo(ByteBuf that) { + return ByteBufUtil.compare(this, that); + } + + @Override + public String toString() { + if (refCnt() == 0) { + return StringUtil.simpleClassName(this) + "(freed)"; + } + + StringBuilder buf = new StringBuilder(); + buf.append(StringUtil.simpleClassName(this)); + buf.append("(ridx: "); + buf.append(readerIndex); + buf.append(", widx: "); + buf.append(writerIndex); + buf.append(", cap: "); + buf.append(capacity()); + if (maxCapacity != Integer.MAX_VALUE) { + buf.append('/'); + buf.append(maxCapacity); + } + + ByteBuf unwrapped = unwrap(); + if (unwrapped != null) { + buf.append(", unwrapped: "); + buf.append(unwrapped); + } + buf.append(')'); + return buf.toString(); + } + + protected final void checkIndex(int index) { + ensureAccessible(); + if (index < 0 || index >= capacity()) { + throw new IndexOutOfBoundsException(String.format( + "index: %d (expected: range(0, %d))", index, capacity())); + } + } + + protected final void checkIndex(int index, int fieldLength) { + ensureAccessible(); + if (fieldLength < 0) { + throw new IllegalArgumentException("length: " + fieldLength + " (expected: >= 0)"); + } + if (index < 0 || index > capacity() - fieldLength) { + throw new IndexOutOfBoundsException(String.format( + "index: %d, length: %d (expected: range(0, %d))", index, fieldLength, capacity())); + } + } + + protected final void checkSrcIndex(int index, int length, int srcIndex, int srcCapacity) { + checkIndex(index, length); + if (srcIndex < 0 || srcIndex > srcCapacity - length) { + throw new IndexOutOfBoundsException(String.format( + "srcIndex: %d, length: %d (expected: range(0, %d))", srcIndex, length, srcCapacity)); + } + } + + protected final void checkDstIndex(int index, int length, int dstIndex, int dstCapacity) { + checkIndex(index, length); + if (dstIndex < 0 || dstIndex > dstCapacity - length) { + throw new IndexOutOfBoundsException(String.format( + "dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dstCapacity)); + } + } + + /** + * Throws an {@link IndexOutOfBoundsException} if the current + * {@linkplain #readableBytes() readable bytes} of this buffer is less + * than the specified value. + */ + protected final void checkReadableBytes(int minimumReadableBytes) { + ensureAccessible(); + if (minimumReadableBytes < 0) { + throw new IllegalArgumentException("minimumReadableBytes: " + minimumReadableBytes + " (expected: >= 0)"); + } + if (readerIndex > writerIndex - minimumReadableBytes) { + throw new IndexOutOfBoundsException(String.format( + "readerIndex(%d) + length(%d) exceeds writerIndex(%d): %s", + readerIndex, minimumReadableBytes, writerIndex, this)); + } + } + + /** + * Should be called by every method that tries to access the buffers content to check + * if the buffer was released before. + */ + protected final void ensureAccessible() { + if (refCnt() == 0) { + throw new IllegalReferenceCountException(0); + } + } +} diff --git a/common/src/main/java/common/net/buffer/AbstractByteBufAllocator.java b/common/src/main/java/common/net/buffer/AbstractByteBufAllocator.java new file mode 100644 index 0000000..0b4cc21 --- /dev/null +++ b/common/src/main/java/common/net/buffer/AbstractByteBufAllocator.java @@ -0,0 +1,185 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import common.net.util.ResourceLeak; +import common.net.util.ResourceLeakDetector; +import common.net.util.internal.StringUtil; + +/** + * Skeletal {@link ByteBufAllocator} implementation to extend. + */ +public abstract class AbstractByteBufAllocator implements ByteBufAllocator { + private static final int DEFAULT_INITIAL_CAPACITY = 256; + private static final int DEFAULT_MAX_COMPONENTS = 16; + + protected static ByteBuf toLeakAwareBuffer(ByteBuf buf) { + ResourceLeak leak; + switch (ResourceLeakDetector.getLevel()) { + case SIMPLE: + leak = AbstractByteBuf.leakDetector.open(buf); + if (leak != null) { + buf = new SimpleLeakAwareByteBuf(buf, leak); + } + break; + case ADVANCED: + case PARANOID: + leak = AbstractByteBuf.leakDetector.open(buf); + if (leak != null) { + buf = new AdvancedLeakAwareByteBuf(buf, leak); + } + break; + } + return buf; + } + + private final ByteBuf emptyBuf; + + /** + * Create new instance + * + * @param preferDirect {@code true} if {@link #buffer(int)} should try to allocate a direct buffer rather than + * a heap buffer + */ + protected AbstractByteBufAllocator() { + emptyBuf = new EmptyByteBuf(this); + } + + @Override + public ByteBuf buffer() { + return heapBuffer(); + } + + @Override + public ByteBuf buffer(int initialCapacity) { + return heapBuffer(initialCapacity); + } + + @Override + public ByteBuf buffer(int initialCapacity, int maxCapacity) { + return heapBuffer(initialCapacity, maxCapacity); + } + + @Override + public ByteBuf ioBuffer() { + return heapBuffer(DEFAULT_INITIAL_CAPACITY); + } + + @Override + public ByteBuf ioBuffer(int initialCapacity) { + return heapBuffer(initialCapacity); + } + + @Override + public ByteBuf ioBuffer(int initialCapacity, int maxCapacity) { + return heapBuffer(initialCapacity, maxCapacity); + } + + @Override + public ByteBuf heapBuffer() { + return heapBuffer(DEFAULT_INITIAL_CAPACITY, Integer.MAX_VALUE); + } + + @Override + public ByteBuf heapBuffer(int initialCapacity) { + return heapBuffer(initialCapacity, Integer.MAX_VALUE); + } + + @Override + public ByteBuf heapBuffer(int initialCapacity, int maxCapacity) { + if (initialCapacity == 0 && maxCapacity == 0) { + return emptyBuf; + } + validate(initialCapacity, maxCapacity); + return newHeapBuffer(initialCapacity, maxCapacity); + } + + @Override + public ByteBuf directBuffer() { + return directBuffer(DEFAULT_INITIAL_CAPACITY, Integer.MAX_VALUE); + } + + @Override + public ByteBuf directBuffer(int initialCapacity) { + return directBuffer(initialCapacity, Integer.MAX_VALUE); + } + + @Override + public ByteBuf directBuffer(int initialCapacity, int maxCapacity) { + if (initialCapacity == 0 && maxCapacity == 0) { + return emptyBuf; + } + validate(initialCapacity, maxCapacity); + return newDirectBuffer(initialCapacity, maxCapacity); + } + + @Override + public CompositeByteBuf compositeBuffer() { + return compositeHeapBuffer(); + } + + @Override + public CompositeByteBuf compositeBuffer(int maxNumComponents) { + return compositeHeapBuffer(maxNumComponents); + } + + @Override + public CompositeByteBuf compositeHeapBuffer() { + return compositeHeapBuffer(DEFAULT_MAX_COMPONENTS); + } + + @Override + public CompositeByteBuf compositeHeapBuffer(int maxNumComponents) { + return new CompositeByteBuf(this, false, maxNumComponents); + } + + @Override + public CompositeByteBuf compositeDirectBuffer() { + return compositeDirectBuffer(DEFAULT_MAX_COMPONENTS); + } + + @Override + public CompositeByteBuf compositeDirectBuffer(int maxNumComponents) { + return new CompositeByteBuf(this, true, maxNumComponents); + } + + private static void validate(int initialCapacity, int maxCapacity) { + if (initialCapacity < 0) { + throw new IllegalArgumentException("initialCapacity: " + initialCapacity + " (expectd: 0+)"); + } + if (initialCapacity > maxCapacity) { + throw new IllegalArgumentException(String.format( + "initialCapacity: %d (expected: not greater than maxCapacity(%d)", + initialCapacity, maxCapacity)); + } + } + + /** + * Create a heap {@link ByteBuf} with the given initialCapacity and maxCapacity. + */ + protected abstract ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity); + + /** + * Create a direct {@link ByteBuf} with the given initialCapacity and maxCapacity. + */ + protected abstract ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity); + + @Override + public String toString() { + return StringUtil.simpleClassName(this); + } +} diff --git a/common/src/main/java/common/net/buffer/AbstractDerivedByteBuf.java b/common/src/main/java/common/net/buffer/AbstractDerivedByteBuf.java new file mode 100644 index 0000000..5fad3e7 --- /dev/null +++ b/common/src/main/java/common/net/buffer/AbstractDerivedByteBuf.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import java.nio.ByteBuffer; + +/** + * Abstract base class for {@link ByteBuf} implementations that wrap another + * {@link ByteBuf}. + */ +public abstract class AbstractDerivedByteBuf extends AbstractByteBuf { + + protected AbstractDerivedByteBuf(int maxCapacity) { + super(maxCapacity); + } + + @Override + public final int refCnt() { + return unwrap().refCnt(); + } + + @Override + public final ByteBuf retain() { + unwrap().retain(); + return this; + } + + @Override + public final ByteBuf retain(int increment) { + unwrap().retain(increment); + return this; + } + + @Override + public final boolean release() { + return unwrap().release(); + } + + @Override + public final boolean release(int decrement) { + return unwrap().release(decrement); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + return nioBuffer(index, length); + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + return unwrap().nioBuffer(index, length); + } +} diff --git a/common/src/main/java/common/net/buffer/AbstractReferenceCountedByteBuf.java b/common/src/main/java/common/net/buffer/AbstractReferenceCountedByteBuf.java new file mode 100644 index 0000000..d15a7e2 --- /dev/null +++ b/common/src/main/java/common/net/buffer/AbstractReferenceCountedByteBuf.java @@ -0,0 +1,139 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; + +import common.net.util.IllegalReferenceCountException; + +/** + * Abstract base class for {@link ByteBuf} implementations that count references. + */ +public abstract class AbstractReferenceCountedByteBuf extends AbstractByteBuf { + + private static final AtomicIntegerFieldUpdater refCntUpdater; + + static { + AtomicIntegerFieldUpdater updater = + null; + if (updater == null) { + updater = AtomicIntegerFieldUpdater.newUpdater(AbstractReferenceCountedByteBuf.class, "refCnt"); + } + refCntUpdater = updater; + } + + private volatile int refCnt = 1; + + protected AbstractReferenceCountedByteBuf(int maxCapacity) { + super(maxCapacity); + } + + @Override + public final int refCnt() { + return refCnt; + } + + /** + * An unsafe operation intended for use by a subclass that sets the reference count of the buffer directly + */ + protected final void setRefCnt(int refCnt) { + this.refCnt = refCnt; + } + + @Override + public ByteBuf retain() { + for (;;) { + int refCnt = this.refCnt; + if (refCnt == 0) { + throw new IllegalReferenceCountException(0, 1); + } + if (refCnt == Integer.MAX_VALUE) { + throw new IllegalReferenceCountException(Integer.MAX_VALUE, 1); + } + if (refCntUpdater.compareAndSet(this, refCnt, refCnt + 1)) { + break; + } + } + return this; + } + + @Override + public ByteBuf retain(int increment) { + if (increment <= 0) { + throw new IllegalArgumentException("increment: " + increment + " (expected: > 0)"); + } + + for (;;) { + int refCnt = this.refCnt; + if (refCnt == 0) { + throw new IllegalReferenceCountException(0, increment); + } + if (refCnt > Integer.MAX_VALUE - increment) { + throw new IllegalReferenceCountException(refCnt, increment); + } + if (refCntUpdater.compareAndSet(this, refCnt, refCnt + increment)) { + break; + } + } + return this; + } + + @Override + public final boolean release() { + for (;;) { + int refCnt = this.refCnt; + if (refCnt == 0) { + throw new IllegalReferenceCountException(0, -1); + } + + if (refCntUpdater.compareAndSet(this, refCnt, refCnt - 1)) { + if (refCnt == 1) { + deallocate(); + return true; + } + return false; + } + } + } + + @Override + public final boolean release(int decrement) { + if (decrement <= 0) { + throw new IllegalArgumentException("decrement: " + decrement + " (expected: > 0)"); + } + + for (;;) { + int refCnt = this.refCnt; + if (refCnt < decrement) { + throw new IllegalReferenceCountException(refCnt, -decrement); + } + + if (refCntUpdater.compareAndSet(this, refCnt, refCnt - decrement)) { + if (refCnt == decrement) { + deallocate(); + return true; + } + return false; + } + } + } + + /** + * Called once {@link #refCnt()} is equals 0. + */ + protected abstract void deallocate(); +} diff --git a/common/src/main/java/common/net/buffer/AdvancedLeakAwareByteBuf.java b/common/src/main/java/common/net/buffer/AdvancedLeakAwareByteBuf.java new file mode 100644 index 0000000..2cd77b6 --- /dev/null +++ b/common/src/main/java/common/net/buffer/AdvancedLeakAwareByteBuf.java @@ -0,0 +1,724 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; +import java.nio.charset.Charset; + +import common.net.util.ResourceLeak; + +final class AdvancedLeakAwareByteBuf extends WrappedByteBuf { + + private final ResourceLeak leak; + + AdvancedLeakAwareByteBuf(ByteBuf buf, ResourceLeak leak) { + super(buf); + this.leak = leak; + } + + @Override + public boolean release() { + boolean deallocated = super.release(); + if (deallocated) { + leak.close(); + } else { + leak.record(); + } + return deallocated; + } + + @Override + public boolean release(int decrement) { + boolean deallocated = super.release(decrement); + if (deallocated) { + leak.close(); + } else { + leak.record(); + } + return deallocated; + } + + @Override + public ByteBuf order(ByteOrder endianness) { + leak.record(); + if (order() == endianness) { + return this; + } else { + return new AdvancedLeakAwareByteBuf(super.order(endianness), leak); + } + } + + @Override + public ByteBuf slice() { + leak.record(); + return new AdvancedLeakAwareByteBuf(super.slice(), leak); + } + + @Override + public ByteBuf slice(int index, int length) { + leak.record(); + return new AdvancedLeakAwareByteBuf(super.slice(index, length), leak); + } + + @Override + public ByteBuf duplicate() { + leak.record(); + return new AdvancedLeakAwareByteBuf(super.duplicate(), leak); + } + + @Override + public ByteBuf readSlice(int length) { + leak.record(); + return new AdvancedLeakAwareByteBuf(super.readSlice(length), leak); + } + + @Override + public ByteBuf discardReadBytes() { + leak.record(); + return super.discardReadBytes(); + } + + @Override + public ByteBuf discardSomeReadBytes() { + leak.record(); + return super.discardSomeReadBytes(); + } + + @Override + public ByteBuf ensureWritable(int minWritableBytes) { + leak.record(); + return super.ensureWritable(minWritableBytes); + } + + @Override + public int ensureWritable(int minWritableBytes, boolean force) { + leak.record(); + return super.ensureWritable(minWritableBytes, force); + } + + @Override + public boolean getBoolean(int index) { + leak.record(); + return super.getBoolean(index); + } + + @Override + public byte getByte(int index) { + leak.record(); + return super.getByte(index); + } + + @Override + public short getUnsignedByte(int index) { + leak.record(); + return super.getUnsignedByte(index); + } + + @Override + public short getShort(int index) { + leak.record(); + return super.getShort(index); + } + + @Override + public int getUnsignedShort(int index) { + leak.record(); + return super.getUnsignedShort(index); + } + + @Override + public int getMedium(int index) { + leak.record(); + return super.getMedium(index); + } + + @Override + public int getUnsignedMedium(int index) { + leak.record(); + return super.getUnsignedMedium(index); + } + + @Override + public int getInt(int index) { + leak.record(); + return super.getInt(index); + } + + @Override + public long getUnsignedInt(int index) { + leak.record(); + return super.getUnsignedInt(index); + } + + @Override + public long getLong(int index) { + leak.record(); + return super.getLong(index); + } + + @Override + public char getChar(int index) { + leak.record(); + return super.getChar(index); + } + + @Override + public float getFloat(int index) { + leak.record(); + return super.getFloat(index); + } + + @Override + public double getDouble(int index) { + leak.record(); + return super.getDouble(index); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst) { + leak.record(); + return super.getBytes(index, dst); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int length) { + leak.record(); + return super.getBytes(index, dst, length); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + leak.record(); + return super.getBytes(index, dst, dstIndex, length); + } + + @Override + public ByteBuf getBytes(int index, byte[] dst) { + leak.record(); + return super.getBytes(index, dst); + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + leak.record(); + return super.getBytes(index, dst, dstIndex, length); + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + leak.record(); + return super.getBytes(index, dst); + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + leak.record(); + return super.getBytes(index, out, length); + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { + leak.record(); + return super.getBytes(index, out, length); + } + + @Override + public ByteBuf setBoolean(int index, boolean value) { + leak.record(); + return super.setBoolean(index, value); + } + + @Override + public ByteBuf setByte(int index, int value) { + leak.record(); + return super.setByte(index, value); + } + + @Override + public ByteBuf setShort(int index, int value) { + leak.record(); + return super.setShort(index, value); + } + + @Override + public ByteBuf setMedium(int index, int value) { + leak.record(); + return super.setMedium(index, value); + } + + @Override + public ByteBuf setInt(int index, int value) { + leak.record(); + return super.setInt(index, value); + } + + @Override + public ByteBuf setLong(int index, long value) { + leak.record(); + return super.setLong(index, value); + } + + @Override + public ByteBuf setChar(int index, int value) { + leak.record(); + return super.setChar(index, value); + } + + @Override + public ByteBuf setFloat(int index, float value) { + leak.record(); + return super.setFloat(index, value); + } + + @Override + public ByteBuf setDouble(int index, double value) { + leak.record(); + return super.setDouble(index, value); + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src) { + leak.record(); + return super.setBytes(index, src); + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int length) { + leak.record(); + return super.setBytes(index, src, length); + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + leak.record(); + return super.setBytes(index, src, srcIndex, length); + } + + @Override + public ByteBuf setBytes(int index, byte[] src) { + leak.record(); + return super.setBytes(index, src); + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + leak.record(); + return super.setBytes(index, src, srcIndex, length); + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + leak.record(); + return super.setBytes(index, src); + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + leak.record(); + return super.setBytes(index, in, length); + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + leak.record(); + return super.setBytes(index, in, length); + } + + @Override + public ByteBuf setZero(int index, int length) { + leak.record(); + return super.setZero(index, length); + } + + @Override + public boolean readBoolean() { + leak.record(); + return super.readBoolean(); + } + + @Override + public byte readByte() { + leak.record(); + return super.readByte(); + } + + @Override + public short readUnsignedByte() { + leak.record(); + return super.readUnsignedByte(); + } + + @Override + public short readShort() { + leak.record(); + return super.readShort(); + } + + @Override + public int readUnsignedShort() { + leak.record(); + return super.readUnsignedShort(); + } + + @Override + public int readMedium() { + leak.record(); + return super.readMedium(); + } + + @Override + public int readUnsignedMedium() { + leak.record(); + return super.readUnsignedMedium(); + } + + @Override + public int readInt() { + leak.record(); + return super.readInt(); + } + + @Override + public long readUnsignedInt() { + leak.record(); + return super.readUnsignedInt(); + } + + @Override + public long readLong() { + leak.record(); + return super.readLong(); + } + + @Override + public char readChar() { + leak.record(); + return super.readChar(); + } + + @Override + public float readFloat() { + leak.record(); + return super.readFloat(); + } + + @Override + public double readDouble() { + leak.record(); + return super.readDouble(); + } + + @Override + public ByteBuf readBytes(int length) { + leak.record(); + return super.readBytes(length); + } + + @Override + public ByteBuf readBytes(ByteBuf dst) { + leak.record(); + return super.readBytes(dst); + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int length) { + leak.record(); + return super.readBytes(dst, length); + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { + leak.record(); + return super.readBytes(dst, dstIndex, length); + } + + @Override + public ByteBuf readBytes(byte[] dst) { + leak.record(); + return super.readBytes(dst); + } + + @Override + public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { + leak.record(); + return super.readBytes(dst, dstIndex, length); + } + + @Override + public ByteBuf readBytes(ByteBuffer dst) { + leak.record(); + return super.readBytes(dst); + } + + @Override + public ByteBuf readBytes(OutputStream out, int length) throws IOException { + leak.record(); + return super.readBytes(out, length); + } + + @Override + public int readBytes(GatheringByteChannel out, int length) throws IOException { + leak.record(); + return super.readBytes(out, length); + } + + @Override + public ByteBuf skipBytes(int length) { + leak.record(); + return super.skipBytes(length); + } + + @Override + public ByteBuf writeBoolean(boolean value) { + leak.record(); + return super.writeBoolean(value); + } + + @Override + public ByteBuf writeByte(int value) { + leak.record(); + return super.writeByte(value); + } + + @Override + public ByteBuf writeShort(int value) { + leak.record(); + return super.writeShort(value); + } + + @Override + public ByteBuf writeMedium(int value) { + leak.record(); + return super.writeMedium(value); + } + + @Override + public ByteBuf writeInt(int value) { + leak.record(); + return super.writeInt(value); + } + + @Override + public ByteBuf writeLong(long value) { + leak.record(); + return super.writeLong(value); + } + + @Override + public ByteBuf writeChar(int value) { + leak.record(); + return super.writeChar(value); + } + + @Override + public ByteBuf writeFloat(float value) { + leak.record(); + return super.writeFloat(value); + } + + @Override + public ByteBuf writeDouble(double value) { + leak.record(); + return super.writeDouble(value); + } + + @Override + public ByteBuf writeBytes(ByteBuf src) { + leak.record(); + return super.writeBytes(src); + } + + @Override + public ByteBuf writeBytes(ByteBuf src, int length) { + leak.record(); + return super.writeBytes(src, length); + } + + @Override + public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { + leak.record(); + return super.writeBytes(src, srcIndex, length); + } + + @Override + public ByteBuf writeBytes(byte[] src) { + leak.record(); + return super.writeBytes(src); + } + + @Override + public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { + leak.record(); + return super.writeBytes(src, srcIndex, length); + } + + @Override + public ByteBuf writeBytes(ByteBuffer src) { + leak.record(); + return super.writeBytes(src); + } + + @Override + public int writeBytes(InputStream in, int length) throws IOException { + leak.record(); + return super.writeBytes(in, length); + } + + @Override + public int writeBytes(ScatteringByteChannel in, int length) throws IOException { + leak.record(); + return super.writeBytes(in, length); + } + + @Override + public ByteBuf writeZero(int length) { + leak.record(); + return super.writeZero(length); + } + + @Override + public int indexOf(int fromIndex, int toIndex, byte value) { + leak.record(); + return super.indexOf(fromIndex, toIndex, value); + } + + @Override + public int bytesBefore(byte value) { + leak.record(); + return super.bytesBefore(value); + } + + @Override + public int bytesBefore(int length, byte value) { + leak.record(); + return super.bytesBefore(length, value); + } + + @Override + public int bytesBefore(int index, int length, byte value) { + leak.record(); + return super.bytesBefore(index, length, value); + } + + @Override + public int forEachByte(ByteBufProcessor processor) { + leak.record(); + return super.forEachByte(processor); + } + + @Override + public int forEachByte(int index, int length, ByteBufProcessor processor) { + leak.record(); + return super.forEachByte(index, length, processor); + } + + @Override + public int forEachByteDesc(ByteBufProcessor processor) { + leak.record(); + return super.forEachByteDesc(processor); + } + + @Override + public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { + leak.record(); + return super.forEachByteDesc(index, length, processor); + } + + @Override + public ByteBuf copy() { + leak.record(); + return super.copy(); + } + + @Override + public ByteBuf copy(int index, int length) { + leak.record(); + return super.copy(index, length); + } + + @Override + public int nioBufferCount() { + leak.record(); + return super.nioBufferCount(); + } + + @Override + public ByteBuffer nioBuffer() { + leak.record(); + return super.nioBuffer(); + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + leak.record(); + return super.nioBuffer(index, length); + } + + @Override + public ByteBuffer[] nioBuffers() { + leak.record(); + return super.nioBuffers(); + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + leak.record(); + return super.nioBuffers(index, length); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + leak.record(); + return super.internalNioBuffer(index, length); + } + + @Override + public String toString(Charset charset) { + leak.record(); + return super.toString(charset); + } + + @Override + public String toString(int index, int length, Charset charset) { + leak.record(); + return super.toString(index, length, charset); + } + + @Override + public ByteBuf retain() { + leak.record(); + return super.retain(); + } + + @Override + public ByteBuf retain(int increment) { + leak.record(); + return super.retain(increment); + } + + @Override + public ByteBuf capacity(int newCapacity) { + leak.record(); + return super.capacity(newCapacity); + } +} diff --git a/common/src/main/java/common/net/buffer/ByteBuf.java b/common/src/main/java/common/net/buffer/ByteBuf.java new file mode 100644 index 0000000..fabaf0c --- /dev/null +++ b/common/src/main/java/common/net/buffer/ByteBuf.java @@ -0,0 +1,1875 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; +import java.nio.charset.Charset; + +import common.net.util.ReferenceCounted; + +/** + * A random and sequential accessible sequence of zero or more bytes (octets). + * This interface provides an abstract view for one or more primitive byte + * arrays ({@code byte[]}) and {@linkplain ByteBuffer NIO buffers}. + * + *

Creation of a buffer

+ * + * It is recommended to create a new buffer using the helper methods in + * {@link Unpooled} rather than calling an individual implementation's + * constructor. + * + *

Random Access Indexing

+ * + * Just like an ordinary primitive byte array, {@link ByteBuf} uses + * zero-based indexing. + * It means the index of the first byte is always {@code 0} and the index of the last byte is + * always {@link #capacity() capacity - 1}. For example, to iterate all bytes of a buffer, you + * can do the following, regardless of its internal implementation: + * + *
+ * {@link ByteBuf} buffer = ...;
+ * for (int i = 0; i < buffer.capacity(); i ++) {
+ *     byte b = buffer.getByte(i);
+ *     System.out.println((char) b);
+ * }
+ * 
+ * + *

Sequential Access Indexing

+ * + * {@link ByteBuf} provides two pointer variables to support sequential + * read and write operations - {@link #readerIndex() readerIndex} for a read + * operation and {@link #writerIndex() writerIndex} for a write operation + * respectively. The following diagram shows how a buffer is segmented into + * three areas by the two pointers: + * + *
+ *      +-------------------+------------------+------------------+
+ *      | discardable bytes |  readable bytes  |  writable bytes  |
+ *      |                   |     (CONTENT)    |                  |
+ *      +-------------------+------------------+------------------+
+ *      |                   |                  |                  |
+ *      0      <=      readerIndex   <=   writerIndex    <=    capacity
+ * 
+ * + *

Readable bytes (the actual content)

+ * + * This segment is where the actual data is stored. Any operation whose name + * starts with {@code read} or {@code skip} will get or skip the data at the + * current {@link #readerIndex() readerIndex} and increase it by the number of + * read bytes. If the argument of the read operation is also a + * {@link ByteBuf} and no destination index is specified, the specified + * buffer's {@link #writerIndex() writerIndex} is increased together. + *

+ * If there's not enough content left, {@link IndexOutOfBoundsException} is + * raised. The default value of newly allocated, wrapped or copied buffer's + * {@link #readerIndex() readerIndex} is {@code 0}. + * + *

+ * // Iterates the readable bytes of a buffer.
+ * {@link ByteBuf} buffer = ...;
+ * while (buffer.readable()) {
+ *     System.out.println(buffer.readByte());
+ * }
+ * 
+ * + *

Writable bytes

+ * + * This segment is a undefined space which needs to be filled. Any operation + * whose name ends with {@code write} will write the data at the current + * {@link #writerIndex() writerIndex} and increase it by the number of written + * bytes. If the argument of the write operation is also a {@link ByteBuf}, + * and no source index is specified, the specified buffer's + * {@link #readerIndex() readerIndex} is increased together. + *

+ * If there's not enough writable bytes left, {@link IndexOutOfBoundsException} + * is raised. The default value of newly allocated buffer's + * {@link #writerIndex() writerIndex} is {@code 0}. The default value of + * wrapped or copied buffer's {@link #writerIndex() writerIndex} is the + * {@link #capacity() capacity} of the buffer. + * + *

+ * // Fills the writable bytes of a buffer with random integers.
+ * {@link ByteBuf} buffer = ...;
+ * while (buffer.maxWritableBytes() >= 4) {
+ *     buffer.writeInt(random.nextInt());
+ * }
+ * 
+ * + *

Discardable bytes

+ * + * This segment contains the bytes which were read already by a read operation. + * Initially, the size of this segment is {@code 0}, but its size increases up + * to the {@link #writerIndex() writerIndex} as read operations are executed. + * The read bytes can be discarded by calling {@link #discardReadBytes()} to + * reclaim unused area as depicted by the following diagram: + * + *
+ *  BEFORE discardReadBytes()
+ *
+ *      +-------------------+------------------+------------------+
+ *      | discardable bytes |  readable bytes  |  writable bytes  |
+ *      +-------------------+------------------+------------------+
+ *      |                   |                  |                  |
+ *      0      <=      readerIndex   <=   writerIndex    <=    capacity
+ *
+ *
+ *  AFTER discardReadBytes()
+ *
+ *      +------------------+--------------------------------------+
+ *      |  readable bytes  |    writable bytes (got more space)   |
+ *      +------------------+--------------------------------------+
+ *      |                  |                                      |
+ * readerIndex (0) <= writerIndex (decreased)        <=        capacity
+ * 
+ * + * Please note that there is no guarantee about the content of writable bytes + * after calling {@link #discardReadBytes()}. The writable bytes will not be + * moved in most cases and could even be filled with completely different data + * depending on the underlying buffer implementation. + * + *

Clearing the buffer indexes

+ * + * You can set both {@link #readerIndex() readerIndex} and + * {@link #writerIndex() writerIndex} to {@code 0} by calling {@link #clear()}. + * It does not clear the buffer content (e.g. filling with {@code 0}) but just + * clears the two pointers. Please also note that the semantic of this + * operation is different from {@link ByteBuffer#clear()}. + * + *
+ *  BEFORE clear()
+ *
+ *      +-------------------+------------------+------------------+
+ *      | discardable bytes |  readable bytes  |  writable bytes  |
+ *      +-------------------+------------------+------------------+
+ *      |                   |                  |                  |
+ *      0      <=      readerIndex   <=   writerIndex    <=    capacity
+ *
+ *
+ *  AFTER clear()
+ *
+ *      +---------------------------------------------------------+
+ *      |             writable bytes (got more space)             |
+ *      +---------------------------------------------------------+
+ *      |                                                         |
+ *      0 = readerIndex = writerIndex            <=            capacity
+ * 
+ * + *

Search operations

+ * + * For simple single-byte searches, use {@link #indexOf(int, int, byte)} and {@link #bytesBefore(int, int, byte)}. + * {@link #bytesBefore(byte)} is especially useful when you deal with a {@code NUL}-terminated string. + * For complicated searches, use {@link #forEachByte(int, int, ByteBufProcessor)} with a {@link ByteBufProcessor} + * implementation. + * + *

Mark and reset

+ * + * There are two marker indexes in every buffer. One is for storing + * {@link #readerIndex() readerIndex} and the other is for storing + * {@link #writerIndex() writerIndex}. You can always reposition one of the + * two indexes by calling a reset method. It works in a similar fashion to + * the mark and reset methods in {@link InputStream} except that there's no + * {@code readlimit}. + * + *

Derived buffers

+ * + * You can create a view of an existing buffer by calling either + * {@link #duplicate()}, {@link #slice()} or {@link #slice(int, int)}. + * A derived buffer will have an independent {@link #readerIndex() readerIndex}, + * {@link #writerIndex() writerIndex} and marker indexes, while it shares + * other internal data representation, just like a NIO buffer does. + *

+ * In case a completely fresh copy of an existing buffer is required, please + * call {@link #copy()} method instead. + * + *

Conversion to existing JDK types

+ * + *

Byte array

+ * + * If a {@link ByteBuf} is backed by a byte array (i.e. {@code byte[]}), + * you can access it directly via the {@link #array()} method. To determine + * if a buffer is backed by a byte array, {@link #hasArray()} should be used. + * + *

NIO Buffers

+ * + * If a {@link ByteBuf} can be converted into an NIO {@link ByteBuffer} which shares its + * content (i.e. view buffer), you can get it via the {@link #nioBuffer()} method. To determine + * if a buffer can be converted into an NIO buffer, use {@link #nioBufferCount()}. + * + *

Strings

+ * + * Various {@link #toString(Charset)} methods convert a {@link ByteBuf} + * into a {@link String}. Please note that {@link #toString()} is not a + * conversion method. + * + *

I/O Streams

+ * + * Please refer to {@link ByteBufInputStream} and + * {@link ByteBufOutputStream}. + */ + +public abstract class ByteBuf implements ReferenceCounted, Comparable { + + /** + * Returns the number of bytes (octets) this buffer can contain. + */ + public abstract int capacity(); + + /** + * Adjusts the capacity of this buffer. If the {@code newCapacity} is less than the current + * capacity, the content of this buffer is truncated. If the {@code newCapacity} is greater + * than the current capacity, the buffer is appended with unspecified data whose length is + * {@code (newCapacity - currentCapacity)}. + */ + public abstract ByteBuf capacity(int newCapacity); + + /** + * Returns the maximum allowed capacity of this buffer. If a user attempts to increase the + * capacity of this buffer beyond the maximum capacity using {@link #capacity(int)} or + * {@link #ensureWritable(int)}, those methods will raise an + * {@link IllegalArgumentException}. + */ + public abstract int maxCapacity(); + + /** + * Returns the {@link ByteBufAllocator} which created this buffer. + */ + public abstract ByteBufAllocator alloc(); + + /** + * Returns the endianness + * of this buffer. + */ + public abstract ByteOrder order(); + + /** + * Returns a buffer with the specified {@code endianness} which shares the whole region, + * indexes, and marks of this buffer. Modifying the content, the indexes, or the marks of the + * returned buffer or this buffer affects each other's content, indexes, and marks. If the + * specified {@code endianness} is identical to this buffer's byte order, this method can + * return {@code this}. This method does not modify {@code readerIndex} or {@code writerIndex} + * of this buffer. + */ + public abstract ByteBuf order(ByteOrder endianness); + + /** + * Return the underlying buffer instance if this buffer is a wrapper of another buffer. + * + * @return {@code null} if this buffer is not a wrapper + */ + public abstract ByteBuf unwrap(); + + /** + * Returns {@code true} if and only if this buffer is backed by an + * NIO direct buffer. + */ + public abstract boolean isDirect(); + + /** + * Returns the {@code readerIndex} of this buffer. + */ + public abstract int readerIndex(); + + /** + * Sets the {@code readerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code readerIndex} is + * less than {@code 0} or + * greater than {@code this.writerIndex} + */ + public abstract ByteBuf readerIndex(int readerIndex); + + /** + * Returns the {@code writerIndex} of this buffer. + */ + public abstract int writerIndex(); + + /** + * Sets the {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code writerIndex} is + * less than {@code this.readerIndex} or + * greater than {@code this.capacity} + */ + public abstract ByteBuf writerIndex(int writerIndex); + + /** + * Sets the {@code readerIndex} and {@code writerIndex} of this buffer + * in one shot. This method is useful when you have to worry about the + * invocation order of {@link #readerIndex(int)} and {@link #writerIndex(int)} + * methods. For example, the following code will fail: + * + *
+     * // Create a buffer whose readerIndex, writerIndex and capacity are
+     * // 0, 0 and 8 respectively.
+     * {@link ByteBuf} buf = {@link Unpooled}.buffer(8);
+     *
+     * // IndexOutOfBoundsException is thrown because the specified
+     * // readerIndex (2) cannot be greater than the current writerIndex (0).
+     * buf.readerIndex(2);
+     * buf.writerIndex(4);
+     * 
+ * + * The following code will also fail: + * + *
+     * // Create a buffer whose readerIndex, writerIndex and capacity are
+     * // 0, 8 and 8 respectively.
+     * {@link ByteBuf} buf = {@link Unpooled}.wrappedBuffer(new byte[8]);
+     *
+     * // readerIndex becomes 8.
+     * buf.readLong();
+     *
+     * // IndexOutOfBoundsException is thrown because the specified
+     * // writerIndex (4) cannot be less than the current readerIndex (8).
+     * buf.writerIndex(4);
+     * buf.readerIndex(2);
+     * 
+ * + * By contrast, this method guarantees that it never + * throws an {@link IndexOutOfBoundsException} as long as the specified + * indexes meet basic constraints, regardless what the current index + * values of the buffer are: + * + *
+     * // No matter what the current state of the buffer is, the following
+     * // call always succeeds as long as the capacity of the buffer is not
+     * // less than 4.
+     * buf.setIndex(2, 4);
+     * 
+ * + * @throws IndexOutOfBoundsException + * if the specified {@code readerIndex} is less than 0, + * if the specified {@code writerIndex} is less than the specified + * {@code readerIndex} or if the specified {@code writerIndex} is + * greater than {@code this.capacity} + */ + public abstract ByteBuf setIndex(int readerIndex, int writerIndex); + + /** + * Returns the number of readable bytes which is equal to + * {@code (this.writerIndex - this.readerIndex)}. + */ + public abstract int readableBytes(); + + /** + * Returns the number of writable bytes which is equal to + * {@code (this.capacity - this.writerIndex)}. + */ + public abstract int writableBytes(); + + /** + * Returns the maximum possible number of writable bytes, which is equal to + * {@code (this.maxCapacity - this.writerIndex)}. + */ + public abstract int maxWritableBytes(); + + /** + * Returns {@code true} + * if and only if {@code (this.writerIndex - this.readerIndex)} is greater + * than {@code 0}. + */ + public abstract boolean isReadable(); + + /** + * Returns {@code true} if and only if this buffer contains equal to or more than the specified number of elements. + */ + public abstract boolean isReadable(int size); + + /** + * Returns {@code true} + * if and only if {@code (this.capacity - this.writerIndex)} is greater + * than {@code 0}. + */ + public abstract boolean isWritable(); + + /** + * Returns {@code true} if and only if this buffer has enough room to allow writing the specified number of + * elements. + */ + public abstract boolean isWritable(int size); + + /** + * Sets the {@code readerIndex} and {@code writerIndex} of this buffer to + * {@code 0}. + * This method is identical to {@link #setIndex(int, int) setIndex(0, 0)}. + *

+ * Please note that the behavior of this method is different + * from that of NIO buffer, which sets the {@code limit} to + * the {@code capacity} of the buffer. + */ + public abstract ByteBuf clear(); + + /** + * Marks the current {@code readerIndex} in this buffer. You can + * reposition the current {@code readerIndex} to the marked + * {@code readerIndex} by calling {@link #resetReaderIndex()}. + * The initial value of the marked {@code readerIndex} is {@code 0}. + */ + public abstract ByteBuf markReaderIndex(); + + /** + * Repositions the current {@code readerIndex} to the marked + * {@code readerIndex} in this buffer. + * + * @throws IndexOutOfBoundsException + * if the current {@code writerIndex} is less than the marked + * {@code readerIndex} + */ + public abstract ByteBuf resetReaderIndex(); + + /** + * Marks the current {@code writerIndex} in this buffer. You can + * reposition the current {@code writerIndex} to the marked + * {@code writerIndex} by calling {@link #resetWriterIndex()}. + * The initial value of the marked {@code writerIndex} is {@code 0}. + */ + public abstract ByteBuf markWriterIndex(); + + /** + * Repositions the current {@code writerIndex} to the marked + * {@code writerIndex} in this buffer. + * + * @throws IndexOutOfBoundsException + * if the current {@code readerIndex} is greater than the marked + * {@code writerIndex} + */ + public abstract ByteBuf resetWriterIndex(); + + /** + * Discards the bytes between the 0th index and {@code readerIndex}. + * It moves the bytes between {@code readerIndex} and {@code writerIndex} + * to the 0th index, and sets {@code readerIndex} and {@code writerIndex} + * to {@code 0} and {@code oldWriterIndex - oldReaderIndex} respectively. + *

+ * Please refer to the class documentation for more detailed explanation. + */ + public abstract ByteBuf discardReadBytes(); + + /** + * Similar to {@link ByteBuf#discardReadBytes()} except that this method might discard + * some, all, or none of read bytes depending on its internal implementation to reduce + * overall memory bandwidth consumption at the cost of potentially additional memory + * consumption. + */ + public abstract ByteBuf discardSomeReadBytes(); + + /** + * Makes sure the number of {@linkplain #writableBytes() the writable bytes} + * is equal to or greater than the specified value. If there is enough + * writable bytes in this buffer, this method returns with no side effect. + * Otherwise, it raises an {@link IllegalArgumentException}. + * + * @param minWritableBytes + * the expected minimum number of writable bytes + * @throws IndexOutOfBoundsException + * if {@link #writerIndex()} + {@code minWritableBytes} > {@link #maxCapacity()} + */ + public abstract ByteBuf ensureWritable(int minWritableBytes); + + /** + * Tries to make sure the number of {@linkplain #writableBytes() the writable bytes} + * is equal to or greater than the specified value. Unlike {@link #ensureWritable(int)}, + * this method does not raise an exception but returns a code. + * + * @param minWritableBytes + * the expected minimum number of writable bytes + * @param force + * When {@link #writerIndex()} + {@code minWritableBytes} > {@link #maxCapacity()}: + *

    + *
  • {@code true} - the capacity of the buffer is expanded to {@link #maxCapacity()}
  • + *
  • {@code false} - the capacity of the buffer is unchanged
  • + *
+ * @return {@code 0} if the buffer has enough writable bytes, and its capacity is unchanged. + * {@code 1} if the buffer does not have enough bytes, and its capacity is unchanged. + * {@code 2} if the buffer has enough writable bytes, and its capacity has been increased. + * {@code 3} if the buffer does not have enough bytes, but its capacity has been + * increased to its maximum. + */ + public abstract int ensureWritable(int minWritableBytes, boolean force); + + /** + * Gets a boolean at the specified absolute (@code index) in this buffer. + * This method does not modify the {@code readerIndex} or {@code writerIndex} + * of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 1} is greater than {@code this.capacity} + */ + public abstract boolean getBoolean(int index); + + /** + * Gets a byte at the specified absolute {@code index} in this buffer. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 1} is greater than {@code this.capacity} + */ + public abstract byte getByte(int index); + + /** + * Gets an unsigned byte at the specified absolute {@code index} in this + * buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 1} is greater than {@code this.capacity} + */ + public abstract short getUnsignedByte(int index); + + /** + * Gets a 16-bit short integer at the specified absolute {@code index} in + * this buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 2} is greater than {@code this.capacity} + */ + public abstract short getShort(int index); + + /** + * Gets an unsigned 16-bit short integer at the specified absolute + * {@code index} in this buffer. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 2} is greater than {@code this.capacity} + */ + public abstract int getUnsignedShort(int index); + + /** + * Gets a 24-bit medium integer at the specified absolute {@code index} in + * this buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 3} is greater than {@code this.capacity} + */ + public abstract int getMedium(int index); + + /** + * Gets an unsigned 24-bit medium integer at the specified absolute + * {@code index} in this buffer. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 3} is greater than {@code this.capacity} + */ + public abstract int getUnsignedMedium(int index); + + /** + * Gets a 32-bit integer at the specified absolute {@code index} in + * this buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} + */ + public abstract int getInt(int index); + + /** + * Gets an unsigned 32-bit integer at the specified absolute {@code index} + * in this buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} + */ + public abstract long getUnsignedInt(int index); + + /** + * Gets a 64-bit long integer at the specified absolute {@code index} in + * this buffer. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} + */ + public abstract long getLong(int index); + + /** + * Gets a 2-byte UTF-16 character at the specified absolute + * {@code index} in this buffer. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 2} is greater than {@code this.capacity} + */ + public abstract char getChar(int index); + + /** + * Gets a 32-bit floating point number at the specified absolute + * {@code index} in this buffer. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} + */ + public abstract float getFloat(int index); + + /** + * Gets a 64-bit floating point number at the specified absolute + * {@code index} in this buffer. This method does not modify + * {@code readerIndex} or {@code writerIndex} of this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} + */ + public abstract double getDouble(int index); + + /** + * Transfers this buffer's data to the specified destination starting at + * the specified absolute {@code index} until the destination becomes + * non-writable. This method is basically same with + * {@link #getBytes(int, ByteBuf, int, int)}, except that this + * method increases the {@code writerIndex} of the destination by the + * number of the transferred bytes while + * {@link #getBytes(int, ByteBuf, int, int)} does not. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * the source buffer (i.e. {@code this}). + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * if {@code index + dst.writableBytes} is greater than + * {@code this.capacity} + */ + public abstract ByteBuf getBytes(int index, ByteBuf dst); + + /** + * Transfers this buffer's data to the specified destination starting at + * the specified absolute {@code index}. This method is basically same + * with {@link #getBytes(int, ByteBuf, int, int)}, except that this + * method increases the {@code writerIndex} of the destination by the + * number of the transferred bytes while + * {@link #getBytes(int, ByteBuf, int, int)} does not. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * the source buffer (i.e. {@code this}). + * + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code length} is greater than {@code dst.writableBytes} + */ + public abstract ByteBuf getBytes(int index, ByteBuf dst, int length); + + /** + * Transfers this buffer's data to the specified destination starting at + * the specified absolute {@code index}. + * This method does not modify {@code readerIndex} or {@code writerIndex} + * of both the source (i.e. {@code this}) and the destination. + * + * @param dstIndex the first index of the destination + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0}, + * if the specified {@code dstIndex} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code dstIndex + length} is greater than + * {@code dst.capacity} + */ + public abstract ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length); + + /** + * Transfers this buffer's data to the specified destination starting at + * the specified absolute {@code index}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * if {@code index + dst.length} is greater than + * {@code this.capacity} + */ + public abstract ByteBuf getBytes(int index, byte[] dst); + + /** + * Transfers this buffer's data to the specified destination starting at + * the specified absolute {@code index}. + * This method does not modify {@code readerIndex} or {@code writerIndex} + * of this buffer. + * + * @param dstIndex the first index of the destination + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0}, + * if the specified {@code dstIndex} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code dstIndex + length} is greater than + * {@code dst.length} + */ + public abstract ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length); + + /** + * Transfers this buffer's data to the specified destination starting at + * the specified absolute {@code index} until the destination's position + * reaches its limit. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer while the destination's {@code position} will be increased. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * if {@code index + dst.remaining()} is greater than + * {@code this.capacity} + */ + public abstract ByteBuf getBytes(int index, ByteBuffer dst); + + /** + * Transfers this buffer's data to the specified stream starting at the + * specified absolute {@code index}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * if {@code index + length} is greater than + * {@code this.capacity} + * @throws IOException + * if the specified stream threw an exception during I/O + */ + public abstract ByteBuf getBytes(int index, OutputStream out, int length) throws IOException; + + /** + * Transfers this buffer's data to the specified channel starting at the + * specified absolute {@code index}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @param length the maximum number of bytes to transfer + * + * @return the actual number of bytes written out to the specified channel + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * if {@code index + length} is greater than + * {@code this.capacity} + * @throws IOException + * if the specified channel threw an exception during I/O + */ + public abstract int getBytes(int index, GatheringByteChannel out, int length) throws IOException; + + /** + * Sets the specified boolean at the specified absolute {@code index} in this + * buffer. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 1} is greater than {@code this.capacity} + */ + public abstract ByteBuf setBoolean(int index, boolean value); + + /** + * Sets the specified byte at the specified absolute {@code index} in this + * buffer. The 24 high-order bits of the specified value are ignored. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 1} is greater than {@code this.capacity} + */ + public abstract ByteBuf setByte(int index, int value); + + /** + * Sets the specified 16-bit short integer at the specified absolute + * {@code index} in this buffer. The 16 high-order bits of the specified + * value are ignored. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 2} is greater than {@code this.capacity} + */ + public abstract ByteBuf setShort(int index, int value); + + /** + * Sets the specified 24-bit medium integer at the specified absolute + * {@code index} in this buffer. Please note that the most significant + * byte is ignored in the specified value. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 3} is greater than {@code this.capacity} + */ + public abstract ByteBuf setMedium(int index, int value); + + /** + * Sets the specified 32-bit integer at the specified absolute + * {@code index} in this buffer. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} + */ + public abstract ByteBuf setInt(int index, int value); + + /** + * Sets the specified 64-bit long integer at the specified absolute + * {@code index} in this buffer. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} + */ + public abstract ByteBuf setLong(int index, long value); + + /** + * Sets the specified 2-byte UTF-16 character at the specified absolute + * {@code index} in this buffer. + * The 16 high-order bits of the specified value are ignored. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 2} is greater than {@code this.capacity} + */ + public abstract ByteBuf setChar(int index, int value); + + /** + * Sets the specified 32-bit floating-point number at the specified + * absolute {@code index} in this buffer. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 4} is greater than {@code this.capacity} + */ + public abstract ByteBuf setFloat(int index, float value); + + /** + * Sets the specified 64-bit floating-point number at the specified + * absolute {@code index} in this buffer. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * {@code index + 8} is greater than {@code this.capacity} + */ + public abstract ByteBuf setDouble(int index, double value); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the specified absolute {@code index} until the source buffer becomes + * unreadable. This method is basically same with + * {@link #setBytes(int, ByteBuf, int, int)}, except that this + * method increases the {@code readerIndex} of the source buffer by + * the number of the transferred bytes while + * {@link #setBytes(int, ByteBuf, int, int)} does not. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * the source buffer (i.e. {@code this}). + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * if {@code index + src.readableBytes} is greater than + * {@code this.capacity} + */ + public abstract ByteBuf setBytes(int index, ByteBuf src); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the specified absolute {@code index}. This method is basically same + * with {@link #setBytes(int, ByteBuf, int, int)}, except that this + * method increases the {@code readerIndex} of the source buffer by + * the number of the transferred bytes while + * {@link #setBytes(int, ByteBuf, int, int)} does not. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * the source buffer (i.e. {@code this}). + * + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code length} is greater than {@code src.readableBytes} + */ + public abstract ByteBuf setBytes(int index, ByteBuf src, int length); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the specified absolute {@code index}. + * This method does not modify {@code readerIndex} or {@code writerIndex} + * of both the source (i.e. {@code this}) and the destination. + * + * @param srcIndex the first index of the source + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0}, + * if the specified {@code srcIndex} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code srcIndex + length} is greater than + * {@code src.capacity} + */ + public abstract ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length); + + /** + * Transfers the specified source array's data to this buffer starting at + * the specified absolute {@code index}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * if {@code index + src.length} is greater than + * {@code this.capacity} + */ + public abstract ByteBuf setBytes(int index, byte[] src); + + /** + * Transfers the specified source array's data to this buffer starting at + * the specified absolute {@code index}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0}, + * if the specified {@code srcIndex} is less than {@code 0}, + * if {@code index + length} is greater than + * {@code this.capacity}, or + * if {@code srcIndex + length} is greater than {@code src.length} + */ + public abstract ByteBuf setBytes(int index, byte[] src, int srcIndex, int length); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the specified absolute {@code index} until the source buffer's position + * reaches its limit. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * if {@code index + src.remaining()} is greater than + * {@code this.capacity} + */ + public abstract ByteBuf setBytes(int index, ByteBuffer src); + + /** + * Transfers the content of the specified source stream to this buffer + * starting at the specified absolute {@code index}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @param length the number of bytes to transfer + * + * @return the actual number of bytes read in from the specified channel. + * {@code -1} if the specified channel is closed. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * if {@code index + length} is greater than {@code this.capacity} + * @throws IOException + * if the specified stream threw an exception during I/O + */ + public abstract int setBytes(int index, InputStream in, int length) throws IOException; + + /** + * Transfers the content of the specified source channel to this buffer + * starting at the specified absolute {@code index}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @param length the maximum number of bytes to transfer + * + * @return the actual number of bytes read in from the specified channel. + * {@code -1} if the specified channel is closed. + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * if {@code index + length} is greater than {@code this.capacity} + * @throws IOException + * if the specified channel threw an exception during I/O + */ + public abstract int setBytes(int index, ScatteringByteChannel in, int length) throws IOException; + + /** + * Fills this buffer with NUL (0x00) starting at the specified + * absolute {@code index}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @param length the number of NULs to write to the buffer + * + * @throws IndexOutOfBoundsException + * if the specified {@code index} is less than {@code 0} or + * if {@code index + length} is greater than {@code this.capacity} + */ + public abstract ByteBuf setZero(int index, int length); + + /** + * Gets a boolean at the current {@code readerIndex} and increases + * the {@code readerIndex} by {@code 1} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 1} + */ + public abstract boolean readBoolean(); + + /** + * Gets a byte at the current {@code readerIndex} and increases + * the {@code readerIndex} by {@code 1} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 1} + */ + public abstract byte readByte(); + + /** + * Gets an unsigned byte at the current {@code readerIndex} and increases + * the {@code readerIndex} by {@code 1} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 1} + */ + public abstract short readUnsignedByte(); + + /** + * Gets a 16-bit short integer at the current {@code readerIndex} + * and increases the {@code readerIndex} by {@code 2} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 2} + */ + public abstract short readShort(); + + /** + * Gets an unsigned 16-bit short integer at the current {@code readerIndex} + * and increases the {@code readerIndex} by {@code 2} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 2} + */ + public abstract int readUnsignedShort(); + + /** + * Gets a 24-bit medium integer at the current {@code readerIndex} + * and increases the {@code readerIndex} by {@code 3} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 3} + */ + public abstract int readMedium(); + + /** + * Gets an unsigned 24-bit medium integer at the current {@code readerIndex} + * and increases the {@code readerIndex} by {@code 3} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 3} + */ + public abstract int readUnsignedMedium(); + + /** + * Gets a 32-bit integer at the current {@code readerIndex} + * and increases the {@code readerIndex} by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 4} + */ + public abstract int readInt(); + + /** + * Gets an unsigned 32-bit integer at the current {@code readerIndex} + * and increases the {@code readerIndex} by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 4} + */ + public abstract long readUnsignedInt(); + + /** + * Gets a 64-bit integer at the current {@code readerIndex} + * and increases the {@code readerIndex} by {@code 8} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 8} + */ + public abstract long readLong(); + + /** + * Gets a 2-byte UTF-16 character at the current {@code readerIndex} + * and increases the {@code readerIndex} by {@code 2} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 2} + */ + public abstract char readChar(); + + /** + * Gets a 32-bit floating point number at the current {@code readerIndex} + * and increases the {@code readerIndex} by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 4} + */ + public abstract float readFloat(); + + /** + * Gets a 64-bit floating point number at the current {@code readerIndex} + * and increases the {@code readerIndex} by {@code 8} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.readableBytes} is less than {@code 8} + */ + public abstract double readDouble(); + + /** + * Transfers this buffer's data to a newly created buffer starting at + * the current {@code readerIndex} and increases the {@code readerIndex} + * by the number of the transferred bytes (= {@code length}). + * The returned buffer's {@code readerIndex} and {@code writerIndex} are + * {@code 0} and {@code length} respectively. + * + * @param length the number of bytes to transfer + * + * @return the newly created buffer which contains the transferred bytes + * + * @throws IndexOutOfBoundsException + * if {@code length} is greater than {@code this.readableBytes} + */ + public abstract ByteBuf readBytes(int length); + + /** + * Returns a new slice of this buffer's sub-region starting at the current + * {@code readerIndex} and increases the {@code readerIndex} by the size + * of the new slice (= {@code length}). + * + * @param length the size of the new slice + * + * @return the newly created slice + * + * @throws IndexOutOfBoundsException + * if {@code length} is greater than {@code this.readableBytes} + */ + public abstract ByteBuf readSlice(int length); + + /** + * Transfers this buffer's data to the specified destination starting at + * the current {@code readerIndex} until the destination becomes + * non-writable, and increases the {@code readerIndex} by the number of the + * transferred bytes. This method is basically same with + * {@link #readBytes(ByteBuf, int, int)}, except that this method + * increases the {@code writerIndex} of the destination by the number of + * the transferred bytes while {@link #readBytes(ByteBuf, int, int)} + * does not. + * + * @throws IndexOutOfBoundsException + * if {@code dst.writableBytes} is greater than + * {@code this.readableBytes} + */ + public abstract ByteBuf readBytes(ByteBuf dst); + + /** + * Transfers this buffer's data to the specified destination starting at + * the current {@code readerIndex} and increases the {@code readerIndex} + * by the number of the transferred bytes (= {@code length}). This method + * is basically same with {@link #readBytes(ByteBuf, int, int)}, + * except that this method increases the {@code writerIndex} of the + * destination by the number of the transferred bytes (= {@code length}) + * while {@link #readBytes(ByteBuf, int, int)} does not. + * + * @throws IndexOutOfBoundsException + * if {@code length} is greater than {@code this.readableBytes} or + * if {@code length} is greater than {@code dst.writableBytes} + */ + public abstract ByteBuf readBytes(ByteBuf dst, int length); + + /** + * Transfers this buffer's data to the specified destination starting at + * the current {@code readerIndex} and increases the {@code readerIndex} + * by the number of the transferred bytes (= {@code length}). + * + * @param dstIndex the first index of the destination + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if the specified {@code dstIndex} is less than {@code 0}, + * if {@code length} is greater than {@code this.readableBytes}, or + * if {@code dstIndex + length} is greater than + * {@code dst.capacity} + */ + public abstract ByteBuf readBytes(ByteBuf dst, int dstIndex, int length); + + /** + * Transfers this buffer's data to the specified destination starting at + * the current {@code readerIndex} and increases the {@code readerIndex} + * by the number of the transferred bytes (= {@code dst.length}). + * + * @throws IndexOutOfBoundsException + * if {@code dst.length} is greater than {@code this.readableBytes} + */ + public abstract ByteBuf readBytes(byte[] dst); + + /** + * Transfers this buffer's data to the specified destination starting at + * the current {@code readerIndex} and increases the {@code readerIndex} + * by the number of the transferred bytes (= {@code length}). + * + * @param dstIndex the first index of the destination + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if the specified {@code dstIndex} is less than {@code 0}, + * if {@code length} is greater than {@code this.readableBytes}, or + * if {@code dstIndex + length} is greater than {@code dst.length} + */ + public abstract ByteBuf readBytes(byte[] dst, int dstIndex, int length); + + /** + * Transfers this buffer's data to the specified destination starting at + * the current {@code readerIndex} until the destination's position + * reaches its limit, and increases the {@code readerIndex} by the + * number of the transferred bytes. + * + * @throws IndexOutOfBoundsException + * if {@code dst.remaining()} is greater than + * {@code this.readableBytes} + */ + public abstract ByteBuf readBytes(ByteBuffer dst); + + /** + * Transfers this buffer's data to the specified stream starting at the + * current {@code readerIndex}. + * + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if {@code length} is greater than {@code this.readableBytes} + * @throws IOException + * if the specified stream threw an exception during I/O + */ + public abstract ByteBuf readBytes(OutputStream out, int length) throws IOException; + + /** + * Transfers this buffer's data to the specified stream starting at the + * current {@code readerIndex}. + * + * @param length the maximum number of bytes to transfer + * + * @return the actual number of bytes written out to the specified channel + * + * @throws IndexOutOfBoundsException + * if {@code length} is greater than {@code this.readableBytes} + * @throws IOException + * if the specified channel threw an exception during I/O + */ + public abstract int readBytes(GatheringByteChannel out, int length) throws IOException; + + /** + * Increases the current {@code readerIndex} by the specified + * {@code length} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code length} is greater than {@code this.readableBytes} + */ + public abstract ByteBuf skipBytes(int length); + + /** + * Sets the specified boolean at the current {@code writerIndex} + * and increases the {@code writerIndex} by {@code 1} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 1} + */ + public abstract ByteBuf writeBoolean(boolean value); + + /** + * Sets the specified byte at the current {@code writerIndex} + * and increases the {@code writerIndex} by {@code 1} in this buffer. + * The 24 high-order bits of the specified value are ignored. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 1} + */ + public abstract ByteBuf writeByte(int value); + + /** + * Sets the specified 16-bit short integer at the current + * {@code writerIndex} and increases the {@code writerIndex} by {@code 2} + * in this buffer. The 16 high-order bits of the specified value are ignored. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 2} + */ + public abstract ByteBuf writeShort(int value); + + /** + * Sets the specified 24-bit medium integer at the current + * {@code writerIndex} and increases the {@code writerIndex} by {@code 3} + * in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 3} + */ + public abstract ByteBuf writeMedium(int value); + + /** + * Sets the specified 32-bit integer at the current {@code writerIndex} + * and increases the {@code writerIndex} by {@code 4} in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 4} + */ + public abstract ByteBuf writeInt(int value); + + /** + * Sets the specified 64-bit long integer at the current + * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} + * in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 8} + */ + public abstract ByteBuf writeLong(long value); + + /** + * Sets the specified 2-byte UTF-16 character at the current + * {@code writerIndex} and increases the {@code writerIndex} by {@code 2} + * in this buffer. The 16 high-order bits of the specified value are ignored. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 2} + */ + public abstract ByteBuf writeChar(int value); + + /** + * Sets the specified 32-bit floating point number at the current + * {@code writerIndex} and increases the {@code writerIndex} by {@code 4} + * in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 4} + */ + public abstract ByteBuf writeFloat(float value); + + /** + * Sets the specified 64-bit floating point number at the current + * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} + * in this buffer. + * + * @throws IndexOutOfBoundsException + * if {@code this.writableBytes} is less than {@code 8} + */ + public abstract ByteBuf writeDouble(double value); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the current {@code writerIndex} until the source buffer becomes + * unreadable, and increases the {@code writerIndex} by the number of + * the transferred bytes. This method is basically same with + * {@link #writeBytes(ByteBuf, int, int)}, except that this method + * increases the {@code readerIndex} of the source buffer by the number of + * the transferred bytes while {@link #writeBytes(ByteBuf, int, int)} + * does not. + * + * @throws IndexOutOfBoundsException + * if {@code src.readableBytes} is greater than + * {@code this.writableBytes} + */ + public abstract ByteBuf writeBytes(ByteBuf src); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the current {@code writerIndex} and increases the {@code writerIndex} + * by the number of the transferred bytes (= {@code length}). This method + * is basically same with {@link #writeBytes(ByteBuf, int, int)}, + * except that this method increases the {@code readerIndex} of the source + * buffer by the number of the transferred bytes (= {@code length}) while + * {@link #writeBytes(ByteBuf, int, int)} does not. + * + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if {@code length} is greater than {@code this.writableBytes} or + * if {@code length} is greater then {@code src.readableBytes} + */ + public abstract ByteBuf writeBytes(ByteBuf src, int length); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the current {@code writerIndex} and increases the {@code writerIndex} + * by the number of the transferred bytes (= {@code length}). + * + * @param srcIndex the first index of the source + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if the specified {@code srcIndex} is less than {@code 0}, + * if {@code srcIndex + length} is greater than + * {@code src.capacity}, or + * if {@code length} is greater than {@code this.writableBytes} + */ + public abstract ByteBuf writeBytes(ByteBuf src, int srcIndex, int length); + + /** + * Transfers the specified source array's data to this buffer starting at + * the current {@code writerIndex} and increases the {@code writerIndex} + * by the number of the transferred bytes (= {@code src.length}). + * + * @throws IndexOutOfBoundsException + * if {@code src.length} is greater than {@code this.writableBytes} + */ + public abstract ByteBuf writeBytes(byte[] src); + + /** + * Transfers the specified source array's data to this buffer starting at + * the current {@code writerIndex} and increases the {@code writerIndex} + * by the number of the transferred bytes (= {@code length}). + * + * @param srcIndex the first index of the source + * @param length the number of bytes to transfer + * + * @throws IndexOutOfBoundsException + * if the specified {@code srcIndex} is less than {@code 0}, + * if {@code srcIndex + length} is greater than + * {@code src.length}, or + * if {@code length} is greater than {@code this.writableBytes} + */ + public abstract ByteBuf writeBytes(byte[] src, int srcIndex, int length); + + /** + * Transfers the specified source buffer's data to this buffer starting at + * the current {@code writerIndex} until the source buffer's position + * reaches its limit, and increases the {@code writerIndex} by the + * number of the transferred bytes. + * + * @throws IndexOutOfBoundsException + * if {@code src.remaining()} is greater than + * {@code this.writableBytes} + */ + public abstract ByteBuf writeBytes(ByteBuffer src); + + /** + * Transfers the content of the specified stream to this buffer + * starting at the current {@code writerIndex} and increases the + * {@code writerIndex} by the number of the transferred bytes. + * + * @param length the number of bytes to transfer + * + * @return the actual number of bytes read in from the specified stream + * + * @throws IndexOutOfBoundsException + * if {@code length} is greater than {@code this.writableBytes} + * @throws IOException + * if the specified stream threw an exception during I/O + */ + public abstract int writeBytes(InputStream in, int length) throws IOException; + + /** + * Transfers the content of the specified channel to this buffer + * starting at the current {@code writerIndex} and increases the + * {@code writerIndex} by the number of the transferred bytes. + * + * @param length the maximum number of bytes to transfer + * + * @return the actual number of bytes read in from the specified channel + * + * @throws IndexOutOfBoundsException + * if {@code length} is greater than {@code this.writableBytes} + * @throws IOException + * if the specified channel threw an exception during I/O + */ + public abstract int writeBytes(ScatteringByteChannel in, int length) throws IOException; + + /** + * Fills this buffer with NUL (0x00) starting at the current + * {@code writerIndex} and increases the {@code writerIndex} by the + * specified {@code length}. + * + * @param length the number of NULs to write to the buffer + * + * @throws IndexOutOfBoundsException + * if {@code length} is greater than {@code this.writableBytes} + */ + public abstract ByteBuf writeZero(int length); + + /** + * Locates the first occurrence of the specified {@code value} in this + * buffer. The search takes place from the specified {@code fromIndex} + * (inclusive) to the specified {@code toIndex} (exclusive). + *

+ * If {@code fromIndex} is greater than {@code toIndex}, the search is + * performed in a reversed order. + *

+ * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @return the absolute index of the first occurrence if found. + * {@code -1} otherwise. + */ + public abstract int indexOf(int fromIndex, int toIndex, byte value); + + /** + * Locates the first occurrence of the specified {@code value} in this + * buffer. The search takes place from the current {@code readerIndex} + * (inclusive) to the current {@code writerIndex} (exclusive). + *

+ * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @return the number of bytes between the current {@code readerIndex} + * and the first occurrence if found. {@code -1} otherwise. + */ + public abstract int bytesBefore(byte value); + + /** + * Locates the first occurrence of the specified {@code value} in this + * buffer. The search starts from the current {@code readerIndex} + * (inclusive) and lasts for the specified {@code length}. + *

+ * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @return the number of bytes between the current {@code readerIndex} + * and the first occurrence if found. {@code -1} otherwise. + * + * @throws IndexOutOfBoundsException + * if {@code length} is greater than {@code this.readableBytes} + */ + public abstract int bytesBefore(int length, byte value); + + /** + * Locates the first occurrence of the specified {@code value} in this + * buffer. The search starts from the specified {@code index} (inclusive) + * and lasts for the specified {@code length}. + *

+ * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @return the number of bytes between the specified {@code index} + * and the first occurrence if found. {@code -1} otherwise. + * + * @throws IndexOutOfBoundsException + * if {@code index + length} is greater than {@code this.capacity} + */ + public abstract int bytesBefore(int index, int length, byte value); + + /** + * Iterates over the readable bytes of this buffer with the specified {@code processor} in ascending order. + * + * @return {@code -1} if the processor iterated to or beyond the end of the readable bytes. + * The last-visited index If the {@link ByteBufProcessor#process(byte)} returned {@code false}. + */ + public abstract int forEachByte(ByteBufProcessor processor); + + /** + * Iterates over the specified area of this buffer with the specified {@code processor} in ascending order. + * (i.e. {@code index}, {@code (index + 1)}, .. {@code (index + length - 1)}) + * + * @return {@code -1} if the processor iterated to or beyond the end of the specified area. + * The last-visited index If the {@link ByteBufProcessor#process(byte)} returned {@code false}. + */ + public abstract int forEachByte(int index, int length, ByteBufProcessor processor); + + /** + * Iterates over the readable bytes of this buffer with the specified {@code processor} in descending order. + * + * @return {@code -1} if the processor iterated to or beyond the beginning of the readable bytes. + * The last-visited index If the {@link ByteBufProcessor#process(byte)} returned {@code false}. + */ + public abstract int forEachByteDesc(ByteBufProcessor processor); + + /** + * Iterates over the specified area of this buffer with the specified {@code processor} in descending order. + * (i.e. {@code (index + length - 1)}, {@code (index + length - 2)}, ... {@code index}) + * + * + * @return {@code -1} if the processor iterated to or beyond the beginning of the specified area. + * The last-visited index If the {@link ByteBufProcessor#process(byte)} returned {@code false}. + */ + public abstract int forEachByteDesc(int index, int length, ByteBufProcessor processor); + + /** + * Returns a copy of this buffer's readable bytes. Modifying the content + * of the returned buffer or this buffer does not affect each other at all. + * This method is identical to {@code buf.copy(buf.readerIndex(), buf.readableBytes())}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + */ + public abstract ByteBuf copy(); + + /** + * Returns a copy of this buffer's sub-region. Modifying the content of + * the returned buffer or this buffer does not affect each other at all. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + */ + public abstract ByteBuf copy(int index, int length); + + /** + * Returns a slice of this buffer's readable bytes. Modifying the content + * of the returned buffer or this buffer affects each other's content + * while they maintain separate indexes and marks. This method is + * identical to {@code buf.slice(buf.readerIndex(), buf.readableBytes())}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + */ + public abstract ByteBuf slice(); + + /** + * Returns a slice of this buffer's sub-region. Modifying the content of + * the returned buffer or this buffer affects each other's content while + * they maintain separate indexes and marks. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + */ + public abstract ByteBuf slice(int index, int length); + + /** + * Returns a buffer which shares the whole region of this buffer. + * Modifying the content of the returned buffer or this buffer affects + * each other's content while they maintain separate indexes and marks. + * This method is identical to {@code buf.slice(0, buf.capacity())}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + */ + public abstract ByteBuf duplicate(); + + /** + * Returns the maximum number of NIO {@link ByteBuffer}s that consist this buffer. Note that {@link #nioBuffers()} + * or {@link #nioBuffers(int, int)} might return a less number of {@link ByteBuffer}s. + * + * @return {@code -1} if this buffer has no underlying {@link ByteBuffer}. + * the number of the underlying {@link ByteBuffer}s if this buffer has at least one underlying + * {@link ByteBuffer}. Note that this method does not return {@code 0} to avoid confusion. + * + * @see #nioBuffer() + * @see #nioBuffer(int, int) + * @see #nioBuffers() + * @see #nioBuffers(int, int) + */ + public abstract int nioBufferCount(); + + /** + * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}. The returned buffer + * shares the content with this buffer, while changing the position and limit of the returned + * NIO buffer does not affect the indexes and marks of this buffer. This method is identical + * to {@code buf.nioBuffer(buf.readerIndex(), buf.readableBytes())}. This method does not + * modify {@code readerIndex} or {@code writerIndex} of this buffer. Please note that the + * returned NIO buffer will not see the changes of this buffer if this buffer is a dynamic + * buffer and it adjusted its capacity. + * + * @throws UnsupportedOperationException + * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself + * + * @see #nioBufferCount() + * @see #nioBuffers() + * @see #nioBuffers(int, int) + */ + public abstract ByteBuffer nioBuffer(); + + /** + * Exposes this buffer's sub-region as an NIO {@link ByteBuffer}. The returned buffer + * shares the content with this buffer, while changing the position and limit of the returned + * NIO buffer does not affect the indexes and marks of this buffer. This method does not + * modify {@code readerIndex} or {@code writerIndex} of this buffer. Please note that the + * returned NIO buffer will not see the changes of this buffer if this buffer is a dynamic + * buffer and it adjusted its capacity. + * + * @throws UnsupportedOperationException + * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself + * + * @see #nioBufferCount() + * @see #nioBuffers() + * @see #nioBuffers(int, int) + */ + public abstract ByteBuffer nioBuffer(int index, int length); + + /** + * Internal use only: Exposes the internal NIO buffer. + */ + public abstract ByteBuffer internalNioBuffer(int index, int length); + + /** + * Exposes this buffer's readable bytes as an NIO {@link ByteBuffer}'s. The returned buffer + * shares the content with this buffer, while changing the position and limit of the returned + * NIO buffer does not affect the indexes and marks of this buffer. This method does not + * modify {@code readerIndex} or {@code writerIndex} of this buffer. Please note that the + * returned NIO buffer will not see the changes of this buffer if this buffer is a dynamic + * buffer and it adjusted its capacity. + * + * + * @throws UnsupportedOperationException + * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself + * + * @see #nioBufferCount() + * @see #nioBuffer() + * @see #nioBuffer(int, int) + */ + public abstract ByteBuffer[] nioBuffers(); + + /** + * Exposes this buffer's bytes as an NIO {@link ByteBuffer}'s for the specified index and length + * The returned buffer shares the content with this buffer, while changing the position and limit + * of the returned NIO buffer does not affect the indexes and marks of this buffer. This method does + * not modify {@code readerIndex} or {@code writerIndex} of this buffer. Please note that the + * returned NIO buffer will not see the changes of this buffer if this buffer is a dynamic + * buffer and it adjusted its capacity. + * + * @throws UnsupportedOperationException + * if this buffer cannot create a {@link ByteBuffer} that shares the content with itself + * + * @see #nioBufferCount() + * @see #nioBuffer() + * @see #nioBuffer(int, int) + */ + public abstract ByteBuffer[] nioBuffers(int index, int length); + + /** + * Returns {@code true} if and only if this buffer has a backing byte array. + * If this method returns true, you can safely call {@link #array()} and + * {@link #arrayOffset()}. + */ + public abstract boolean hasArray(); + + /** + * Returns the backing byte array of this buffer. + * + * @throws UnsupportedOperationException + * if there no accessible backing byte array + */ + public abstract byte[] array(); + + /** + * Returns the offset of the first byte within the backing byte array of + * this buffer. + * + * @throws UnsupportedOperationException + * if there no accessible backing byte array + */ + public abstract int arrayOffset(); + + /** + * Returns the low-level memory address that point to the first byte of ths backing data. + * + * @throws UnsupportedOperationException + * if this buffer does not support accessing the low-level memory address + */ + public final long memoryAddress() { + throw new UnsupportedOperationException(); + } + + /** + * Decodes this buffer's readable bytes into a string with the specified + * character set name. This method is identical to + * {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName)}. + * This method does not modify {@code readerIndex} or {@code writerIndex} of + * this buffer. + * + * @throws UnsupportedCharsetException + * if the specified character set name is not supported by the + * current VM + */ + public abstract String toString(Charset charset); + + /** + * Decodes this buffer's sub-region into a string with the specified + * character set. This method does not modify {@code readerIndex} or + * {@code writerIndex} of this buffer. + */ + public abstract String toString(int index, int length, Charset charset); + + /** + * Returns a hash code which was calculated from the content of this + * buffer. If there's a byte array which is + * {@linkplain #equals(Object) equal to} this array, both arrays should + * return the same value. + */ + @Override + public abstract int hashCode(); + + /** + * Determines if the content of the specified buffer is identical to the + * content of this array. 'Identical' here means: + *

    + *
  • the size of the contents of the two buffers are same and
  • + *
  • every single byte of the content of the two buffers are same.
  • + *
+ * Please note that it does not compare {@link #readerIndex()} nor + * {@link #writerIndex()}. This method also returns {@code false} for + * {@code null} and an object which is not an instance of + * {@link ByteBuf} type. + */ + @Override + public abstract boolean equals(Object obj); + + /** + * Compares the content of the specified buffer to the content of this + * buffer. Comparison is performed in the same manner with the string + * comparison functions of various languages such as {@code strcmp}, + * {@code memcmp} and {@link String#compareTo(String)}. + */ + @Override + public abstract int compareTo(ByteBuf buffer); + + /** + * Returns the string representation of this buffer. This method does not + * necessarily return the whole content of the buffer but returns + * the values of the key properties such as {@link #readerIndex()}, + * {@link #writerIndex()} and {@link #capacity()}. + */ + @Override + public abstract String toString(); + + @Override + public abstract ByteBuf retain(int increment); + + @Override + public abstract ByteBuf retain(); +} diff --git a/common/src/main/java/common/net/buffer/ByteBufAllocator.java b/common/src/main/java/common/net/buffer/ByteBufAllocator.java new file mode 100644 index 0000000..045f669 --- /dev/null +++ b/common/src/main/java/common/net/buffer/ByteBufAllocator.java @@ -0,0 +1,128 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +/** + * Implementations are responsible to allocate buffers. Implementations of this interface are expected to be + * thread-safe. + */ +public interface ByteBufAllocator { + + ByteBufAllocator DEFAULT = ByteBufUtil.DEFAULT_ALLOCATOR; + + /** + * Allocate a {@link ByteBuf}. If it is a direct or heap buffer + * depends on the actual implementation. + */ + ByteBuf buffer(); + + /** + * Allocate a {@link ByteBuf} with the given initial capacity. + * If it is a direct or heap buffer depends on the actual implementation. + */ + ByteBuf buffer(int initialCapacity); + + /** + * Allocate a {@link ByteBuf} with the given initial capacity and the given + * maximal capacity. If it is a direct or heap buffer depends on the actual + * implementation. + */ + ByteBuf buffer(int initialCapacity, int maxCapacity); + + /** + * Allocate a {@link ByteBuf}, preferably a direct buffer which is suitable for I/O. + */ + ByteBuf ioBuffer(); + + /** + * Allocate a {@link ByteBuf}, preferably a direct buffer which is suitable for I/O. + */ + ByteBuf ioBuffer(int initialCapacity); + + /** + * Allocate a {@link ByteBuf}, preferably a direct buffer which is suitable for I/O. + */ + ByteBuf ioBuffer(int initialCapacity, int maxCapacity); + + /** + * Allocate a heap {@link ByteBuf}. + */ + ByteBuf heapBuffer(); + + /** + * Allocate a heap {@link ByteBuf} with the given initial capacity. + */ + ByteBuf heapBuffer(int initialCapacity); + + /** + * Allocate a heap {@link ByteBuf} with the given initial capacity and the given + * maximal capacity. + */ + ByteBuf heapBuffer(int initialCapacity, int maxCapacity); + + /** + * Allocate a direct {@link ByteBuf}. + */ + ByteBuf directBuffer(); + + /** + * Allocate a direct {@link ByteBuf} with the given initial capacity. + */ + ByteBuf directBuffer(int initialCapacity); + + /** + * Allocate a direct {@link ByteBuf} with the given initial capacity and the given + * maximal capacity. + */ + ByteBuf directBuffer(int initialCapacity, int maxCapacity); + + /** + * Allocate a {@link CompositeByteBuf}. + * If it is a direct or heap buffer depends on the actual implementation. + */ + CompositeByteBuf compositeBuffer(); + + /** + * Allocate a {@link CompositeByteBuf} with the given maximum number of components that can be stored in it. + * If it is a direct or heap buffer depends on the actual implementation. + */ + CompositeByteBuf compositeBuffer(int maxNumComponents); + + /** + * Allocate a heap {@link CompositeByteBuf}. + */ + CompositeByteBuf compositeHeapBuffer(); + + /** + * Allocate a heap {@link CompositeByteBuf} with the given maximum number of components that can be stored in it. + */ + CompositeByteBuf compositeHeapBuffer(int maxNumComponents); + + /** + * Allocate a direct {@link CompositeByteBuf}. + */ + CompositeByteBuf compositeDirectBuffer(); + + /** + * Allocate a direct {@link CompositeByteBuf} with the given maximum number of components that can be stored in it. + */ + CompositeByteBuf compositeDirectBuffer(int maxNumComponents); + + /** + * Returns {@code true} if direct {@link ByteBuf}'s are pooled + */ + boolean isDirectBufferPooled(); +} diff --git a/common/src/main/java/common/net/buffer/ByteBufInputStream.java b/common/src/main/java/common/net/buffer/ByteBufInputStream.java new file mode 100644 index 0000000..70a0925 --- /dev/null +++ b/common/src/main/java/common/net/buffer/ByteBufInputStream.java @@ -0,0 +1,257 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.DataInput; +import java.io.DataInputStream; +import java.io.EOFException; +import java.io.IOException; +import java.io.InputStream; + +/** + * An {@link InputStream} which reads data from a {@link ByteBuf}. + *

+ * A read operation against this stream will occur at the {@code readerIndex} + * of its underlying buffer and the {@code readerIndex} will increase during + * the read operation. Please note that it only reads up to the number of + * readable bytes determined at the moment of construction. Therefore, + * updating {@link ByteBuf#writerIndex()} will not affect the return + * value of {@link #available()}. + *

+ * This stream implements {@link DataInput} for your convenience. + * The endianness of the stream is not always big endian but depends on + * the endianness of the underlying buffer. + * + * @see ByteBufOutputStream + */ +public class ByteBufInputStream extends InputStream implements DataInput { + + private final ByteBuf buffer; + private final int startIndex; + private final int endIndex; + + /** + * Creates a new stream which reads data from the specified {@code buffer} + * starting at the current {@code readerIndex} and ending at the current + * {@code writerIndex}. + */ + public ByteBufInputStream(ByteBuf buffer) { + this(buffer, buffer.readableBytes()); + } + + /** + * Creates a new stream which reads data from the specified {@code buffer} + * starting at the current {@code readerIndex} and ending at + * {@code readerIndex + length}. + * + * @throws IndexOutOfBoundsException + * if {@code readerIndex + length} is greater than + * {@code writerIndex} + */ + public ByteBufInputStream(ByteBuf buffer, int length) { + if (buffer == null) { + throw new NullPointerException("buffer"); + } + if (length < 0) { + throw new IllegalArgumentException("length: " + length); + } + if (length > buffer.readableBytes()) { + throw new IndexOutOfBoundsException("Too many bytes to be read - Needs " + + length + ", maximum is " + buffer.readableBytes()); + } + + this.buffer = buffer; + startIndex = buffer.readerIndex(); + endIndex = startIndex + length; + buffer.markReaderIndex(); + } + + /** + * Returns the number of read bytes by this stream so far. + */ + public int readBytes() { + return buffer.readerIndex() - startIndex; + } + + @Override + public int available() throws IOException { + return endIndex - buffer.readerIndex(); + } + + @Override + public void mark(int readlimit) { + buffer.markReaderIndex(); + } + + @Override + public boolean markSupported() { + return true; + } + + @Override + public int read() throws IOException { + if (!buffer.isReadable()) { + return -1; + } + return buffer.readByte() & 0xff; + } + + @Override + public int read(byte[] b, int off, int len) throws IOException { + int available = available(); + if (available == 0) { + return -1; + } + + len = Math.min(available, len); + buffer.readBytes(b, off, len); + return len; + } + + @Override + public void reset() throws IOException { + buffer.resetReaderIndex(); + } + + @Override + public long skip(long n) throws IOException { + if (n > Integer.MAX_VALUE) { + return skipBytes(Integer.MAX_VALUE); + } else { + return skipBytes((int) n); + } + } + + @Override + public boolean readBoolean() throws IOException { + checkAvailable(1); + return read() != 0; + } + + @Override + public byte readByte() throws IOException { + if (!buffer.isReadable()) { + throw new EOFException(); + } + return buffer.readByte(); + } + + @Override + public char readChar() throws IOException { + return (char) readShort(); + } + + @Override + public double readDouble() throws IOException { + return Double.longBitsToDouble(readLong()); + } + + @Override + public float readFloat() throws IOException { + return Float.intBitsToFloat(readInt()); + } + + @Override + public void readFully(byte[] b) throws IOException { + readFully(b, 0, b.length); + } + + @Override + public void readFully(byte[] b, int off, int len) throws IOException { + checkAvailable(len); + buffer.readBytes(b, off, len); + } + + @Override + public int readInt() throws IOException { + checkAvailable(4); + return buffer.readInt(); + } + + private final StringBuilder lineBuf = new StringBuilder(); + + @Override + public String readLine() throws IOException { + lineBuf.setLength(0); + + loop: while (true) { + if (!buffer.isReadable()) { + return lineBuf.length() > 0 ? lineBuf.toString() : null; + } + + int c = buffer.readUnsignedByte(); + switch (c) { + case '\n': + break loop; + + case '\r': + if (buffer.isReadable() && (char) buffer.getUnsignedByte(buffer.readerIndex()) == '\n') { + buffer.skipBytes(1); + } + break loop; + + default: + lineBuf.append((char) c); + } + } + + return lineBuf.toString(); + } + + @Override + public long readLong() throws IOException { + checkAvailable(8); + return buffer.readLong(); + } + + @Override + public short readShort() throws IOException { + checkAvailable(2); + return buffer.readShort(); + } + + @Override + public String readUTF() throws IOException { + return DataInputStream.readUTF(this); + } + + @Override + public int readUnsignedByte() throws IOException { + return readByte() & 0xff; + } + + @Override + public int readUnsignedShort() throws IOException { + return readShort() & 0xffff; + } + + @Override + public int skipBytes(int n) throws IOException { + int nBytes = Math.min(available(), n); + buffer.skipBytes(nBytes); + return nBytes; + } + + private void checkAvailable(int fieldSize) throws IOException { + if (fieldSize < 0) { + throw new IndexOutOfBoundsException("fieldSize cannot be a negative number"); + } + if (fieldSize > available()) { + throw new EOFException("fieldSize is too long! Length is " + fieldSize + + ", but maximum is " + available()); + } + } +} diff --git a/common/src/main/java/common/net/buffer/ByteBufOutputStream.java b/common/src/main/java/common/net/buffer/ByteBufOutputStream.java new file mode 100644 index 0000000..81af491 --- /dev/null +++ b/common/src/main/java/common/net/buffer/ByteBufOutputStream.java @@ -0,0 +1,146 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.DataOutput; +import java.io.DataOutputStream; +import java.io.IOException; +import java.io.OutputStream; + +/** + * An {@link OutputStream} which writes data to a {@link ByteBuf}. + *

+ * A write operation against this stream will occur at the {@code writerIndex} + * of its underlying buffer and the {@code writerIndex} will increase during + * the write operation. + *

+ * This stream implements {@link DataOutput} for your convenience. + * The endianness of the stream is not always big endian but depends on + * the endianness of the underlying buffer. + * + * @see ByteBufInputStream + */ +public class ByteBufOutputStream extends OutputStream implements DataOutput { + + private final ByteBuf buffer; + private final int startIndex; + private final DataOutputStream utf8out = new DataOutputStream(this); + + /** + * Creates a new stream which writes data to the specified {@code buffer}. + */ + public ByteBufOutputStream(ByteBuf buffer) { + if (buffer == null) { + throw new NullPointerException("buffer"); + } + this.buffer = buffer; + startIndex = buffer.writerIndex(); + } + + /** + * Returns the number of written bytes by this stream so far. + */ + public int writtenBytes() { + return buffer.writerIndex() - startIndex; + } + + @Override + public void write(byte[] b, int off, int len) throws IOException { + if (len == 0) { + return; + } + + buffer.writeBytes(b, off, len); + } + + @Override + public void write(byte[] b) throws IOException { + buffer.writeBytes(b); + } + + @Override + public void write(int b) throws IOException { + buffer.writeByte((byte) b); + } + + @Override + public void writeBoolean(boolean v) throws IOException { + write(v? (byte) 1 : (byte) 0); + } + + @Override + public void writeByte(int v) throws IOException { + write(v); + } + + @Override + public void writeBytes(String s) throws IOException { + int len = s.length(); + for (int i = 0; i < len; i ++) { + write((byte) s.charAt(i)); + } + } + + @Override + public void writeChar(int v) throws IOException { + writeShort((short) v); + } + + @Override + public void writeChars(String s) throws IOException { + int len = s.length(); + for (int i = 0 ; i < len ; i ++) { + writeChar(s.charAt(i)); + } + } + + @Override + public void writeDouble(double v) throws IOException { + writeLong(Double.doubleToLongBits(v)); + } + + @Override + public void writeFloat(float v) throws IOException { + writeInt(Float.floatToIntBits(v)); + } + + @Override + public void writeInt(int v) throws IOException { + buffer.writeInt(v); + } + + @Override + public void writeLong(long v) throws IOException { + buffer.writeLong(v); + } + + @Override + public void writeShort(int v) throws IOException { + buffer.writeShort((short) v); + } + + @Override + public void writeUTF(String s) throws IOException { + utf8out.writeUTF(s); + } + + /** + * Returns the buffer where this stream is writing data. + */ + public ByteBuf buffer() { + return buffer; + } +} diff --git a/common/src/main/java/common/net/buffer/ByteBufProcessor.java b/common/src/main/java/common/net/buffer/ByteBufProcessor.java new file mode 100644 index 0000000..67f4ad4 --- /dev/null +++ b/common/src/main/java/common/net/buffer/ByteBufProcessor.java @@ -0,0 +1,126 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +public interface ByteBufProcessor { + + /** + * Aborts on a {@code NUL (0x00)}. + */ + ByteBufProcessor FIND_NUL = new ByteBufProcessor() { + @Override + public boolean process(byte value) throws Exception { + return value != 0; + } + }; + + /** + * Aborts on a non-{@code NUL (0x00)}. + */ + ByteBufProcessor FIND_NON_NUL = new ByteBufProcessor() { + @Override + public boolean process(byte value) throws Exception { + return value == 0; + } + }; + + /** + * Aborts on a {@code CR ('\r')}. + */ + ByteBufProcessor FIND_CR = new ByteBufProcessor() { + @Override + public boolean process(byte value) throws Exception { + return value != '\r'; + } + }; + + /** + * Aborts on a non-{@code CR ('\r')}. + */ + ByteBufProcessor FIND_NON_CR = new ByteBufProcessor() { + @Override + public boolean process(byte value) throws Exception { + return value == '\r'; + } + }; + + /** + * Aborts on a {@code LF ('\n')}. + */ + ByteBufProcessor FIND_LF = new ByteBufProcessor() { + @Override + public boolean process(byte value) throws Exception { + return value != '\n'; + } + }; + + /** + * Aborts on a non-{@code LF ('\n')}. + */ + ByteBufProcessor FIND_NON_LF = new ByteBufProcessor() { + @Override + public boolean process(byte value) throws Exception { + return value == '\n'; + } + }; + + /** + * Aborts on a {@code CR ('\r')} or a {@code LF ('\n')}. + */ + ByteBufProcessor FIND_CRLF = new ByteBufProcessor() { + @Override + public boolean process(byte value) throws Exception { + return value != '\r' && value != '\n'; + } + }; + + /** + * Aborts on a byte which is neither a {@code CR ('\r')} nor a {@code LF ('\n')}. + */ + ByteBufProcessor FIND_NON_CRLF = new ByteBufProcessor() { + @Override + public boolean process(byte value) throws Exception { + return value == '\r' || value == '\n'; + } + }; + + /** + * Aborts on a linear whitespace (a ({@code ' '} or a {@code '\t'}). + */ + ByteBufProcessor FIND_LINEAR_WHITESPACE = new ByteBufProcessor() { + @Override + public boolean process(byte value) throws Exception { + return value != ' ' && value != '\t'; + } + }; + + /** + * Aborts on a byte which is not a linear whitespace (neither {@code ' '} nor {@code '\t'}). + */ + ByteBufProcessor FIND_NON_LINEAR_WHITESPACE = new ByteBufProcessor() { + @Override + public boolean process(byte value) throws Exception { + return value == ' ' || value == '\t'; + } + }; + + /** + * @return {@code true} if the processor wants to continue the loop and handle the next byte in the buffer. + * {@code false} if the processor wants to stop handling bytes and abort the loop. + */ + boolean process(byte value) throws Exception; +} diff --git a/common/src/main/java/common/net/buffer/ByteBufUtil.java b/common/src/main/java/common/net/buffer/ByteBufUtil.java new file mode 100644 index 0000000..0aa19d6 --- /dev/null +++ b/common/src/main/java/common/net/buffer/ByteBufUtil.java @@ -0,0 +1,444 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderResult; +import java.util.Locale; + +import common.net.util.CharsetUtil; +import common.net.util.Recycler; +import common.net.util.Recycler.Handle; +import common.net.util.internal.SystemPropertyUtil; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * A collection of utility methods that is related with handling {@link ByteBuf}. + */ +public final class ByteBufUtil { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(ByteBufUtil.class); + + private static final char[] HEXDUMP_TABLE = new char[256 * 4]; + + static final ByteBufAllocator DEFAULT_ALLOCATOR; + + private static final int THREAD_LOCAL_BUFFER_SIZE; + + static { + final char[] DIGITS = "0123456789abcdef".toCharArray(); + for (int i = 0; i < 256; i ++) { + HEXDUMP_TABLE[ i << 1 ] = DIGITS[i >>> 4 & 0x0F]; + HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F]; + } + + String allocType = SystemPropertyUtil.get("game.net.allocator.type", "unpooled").toLowerCase(Locale.US).trim(); + ByteBufAllocator alloc; + if ("unpooled".equals(allocType)) { + alloc = UnpooledByteBufAllocator.DEFAULT; + logger.debug("-Dgame.net.allocator.type: {}", allocType); + } else if ("pooled".equals(allocType)) { + alloc = PooledByteBufAllocator.DEFAULT; + logger.debug("-Dgame.net.allocator.type: {}", allocType); + } else { + alloc = UnpooledByteBufAllocator.DEFAULT; + logger.debug("-Dgame.net.allocator.type: unpooled (unknown: {})", allocType); + } + + DEFAULT_ALLOCATOR = alloc; + + THREAD_LOCAL_BUFFER_SIZE = SystemPropertyUtil.getInt("game.net.threadLocalDirectBufferSize", 64 * 1024); + logger.debug("-Dgame.net.threadLocalDirectBufferSize: {}", THREAD_LOCAL_BUFFER_SIZE); + } + + /** + * Returns a hex dump + * of the specified buffer's readable bytes. + */ + public static String hexDump(ByteBuf buffer) { + return hexDump(buffer, buffer.readerIndex(), buffer.readableBytes()); + } + + /** + * Returns a hex dump + * of the specified buffer's sub-region. + */ + public static String hexDump(ByteBuf buffer, int fromIndex, int length) { + if (length < 0) { + throw new IllegalArgumentException("length: " + length); + } + if (length == 0) { + return ""; + } + + int endIndex = fromIndex + length; + char[] buf = new char[length << 1]; + + int srcIdx = fromIndex; + int dstIdx = 0; + for (; srcIdx < endIndex; srcIdx ++, dstIdx += 2) { + System.arraycopy( + HEXDUMP_TABLE, buffer.getUnsignedByte(srcIdx) << 1, + buf, dstIdx, 2); + } + + return new String(buf); + } + + /** + * Calculates the hash code of the specified buffer. This method is + * useful when implementing a new buffer type. + */ + public static int hashCode(ByteBuf buffer) { + final int aLen = buffer.readableBytes(); + final int intCount = aLen >>> 2; + final int byteCount = aLen & 3; + + int hashCode = 1; + int arrayIndex = buffer.readerIndex(); + if (buffer.order() == ByteOrder.BIG_ENDIAN) { + for (int i = intCount; i > 0; i --) { + hashCode = 31 * hashCode + buffer.getInt(arrayIndex); + arrayIndex += 4; + } + } else { + for (int i = intCount; i > 0; i --) { + hashCode = 31 * hashCode + swapInt(buffer.getInt(arrayIndex)); + arrayIndex += 4; + } + } + + for (int i = byteCount; i > 0; i --) { + hashCode = 31 * hashCode + buffer.getByte(arrayIndex ++); + } + + if (hashCode == 0) { + hashCode = 1; + } + + return hashCode; + } + + /** + * Returns {@code true} if and only if the two specified buffers are + * identical to each other as described in {@code ChannelBuffer#equals(Object)}. + * This method is useful when implementing a new buffer type. + */ + public static boolean equals(ByteBuf bufferA, ByteBuf bufferB) { + final int aLen = bufferA.readableBytes(); + if (aLen != bufferB.readableBytes()) { + return false; + } + + final int longCount = aLen >>> 3; + final int byteCount = aLen & 7; + + int aIndex = bufferA.readerIndex(); + int bIndex = bufferB.readerIndex(); + + if (bufferA.order() == bufferB.order()) { + for (int i = longCount; i > 0; i --) { + if (bufferA.getLong(aIndex) != bufferB.getLong(bIndex)) { + return false; + } + aIndex += 8; + bIndex += 8; + } + } else { + for (int i = longCount; i > 0; i --) { + if (bufferA.getLong(aIndex) != swapLong(bufferB.getLong(bIndex))) { + return false; + } + aIndex += 8; + bIndex += 8; + } + } + + for (int i = byteCount; i > 0; i --) { + if (bufferA.getByte(aIndex) != bufferB.getByte(bIndex)) { + return false; + } + aIndex ++; + bIndex ++; + } + + return true; + } + + /** + * Compares the two specified buffers as described in {@link ByteBuf#compareTo(ByteBuf)}. + * This method is useful when implementing a new buffer type. + */ + public static int compare(ByteBuf bufferA, ByteBuf bufferB) { + final int aLen = bufferA.readableBytes(); + final int bLen = bufferB.readableBytes(); + final int minLength = Math.min(aLen, bLen); + final int uintCount = minLength >>> 2; + final int byteCount = minLength & 3; + + int aIndex = bufferA.readerIndex(); + int bIndex = bufferB.readerIndex(); + + if (bufferA.order() == bufferB.order()) { + for (int i = uintCount; i > 0; i --) { + long va = bufferA.getUnsignedInt(aIndex); + long vb = bufferB.getUnsignedInt(bIndex); + if (va > vb) { + return 1; + } + if (va < vb) { + return -1; + } + aIndex += 4; + bIndex += 4; + } + } else { + for (int i = uintCount; i > 0; i --) { + long va = bufferA.getUnsignedInt(aIndex); + long vb = swapInt(bufferB.getInt(bIndex)) & 0xFFFFFFFFL; + if (va > vb) { + return 1; + } + if (va < vb) { + return -1; + } + aIndex += 4; + bIndex += 4; + } + } + + for (int i = byteCount; i > 0; i --) { + short va = bufferA.getUnsignedByte(aIndex); + short vb = bufferB.getUnsignedByte(bIndex); + if (va > vb) { + return 1; + } + if (va < vb) { + return -1; + } + aIndex ++; + bIndex ++; + } + + return aLen - bLen; + } + + /** + * The default implementation of {@link ByteBuf#indexOf(int, int, byte)}. + * This method is useful when implementing a new buffer type. + */ + public static int indexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { + if (fromIndex <= toIndex) { + return firstIndexOf(buffer, fromIndex, toIndex, value); + } else { + return lastIndexOf(buffer, fromIndex, toIndex, value); + } + } + + /** + * Toggles the endianness of the specified 16-bit short integer. + */ + public static short swapShort(short value) { + return Short.reverseBytes(value); + } + + /** + * Toggles the endianness of the specified 24-bit medium integer. + */ + public static int swapMedium(int value) { + int swapped = value << 16 & 0xff0000 | value & 0xff00 | value >>> 16 & 0xff; + if ((swapped & 0x800000) != 0) { + swapped |= 0xff000000; + } + return swapped; + } + + /** + * Toggles the endianness of the specified 32-bit integer. + */ + public static int swapInt(int value) { + return Integer.reverseBytes(value); + } + + /** + * Toggles the endianness of the specified 64-bit long integer. + */ + public static long swapLong(long value) { + return Long.reverseBytes(value); + } + + /** + * Read the given amount of bytes into a new {@link ByteBuf} that is allocated from the {@link ByteBufAllocator}. + */ + public static ByteBuf readBytes(ByteBufAllocator alloc, ByteBuf buffer, int length) { + boolean release = true; + ByteBuf dst = alloc.buffer(length); + try { + buffer.readBytes(dst); + release = false; + return dst; + } finally { + if (release) { + dst.release(); + } + } + } + + private static int firstIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { + fromIndex = Math.max(fromIndex, 0); + if (fromIndex >= toIndex || buffer.capacity() == 0) { + return -1; + } + + for (int i = fromIndex; i < toIndex; i ++) { + if (buffer.getByte(i) == value) { + return i; + } + } + + return -1; + } + + private static int lastIndexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value) { + fromIndex = Math.min(fromIndex, buffer.capacity()); + if (fromIndex < 0 || buffer.capacity() == 0) { + return -1; + } + + for (int i = fromIndex - 1; i >= toIndex; i --) { + if (buffer.getByte(i) == value) { + return i; + } + } + + return -1; + } + + /** + * Encode the given {@link CharBuffer} using the given {@link Charset} into a new {@link ByteBuf} which + * is allocated via the {@link ByteBufAllocator}. + */ + public static ByteBuf encodeString(ByteBufAllocator alloc, CharBuffer src, Charset charset) { + return encodeString0(alloc, false, src, charset); + } + + static ByteBuf encodeString0(ByteBufAllocator alloc, boolean enforceHeap, CharBuffer src, Charset charset) { + final CharsetEncoder encoder = CharsetUtil.getEncoder(charset); + int length = (int) ((double) src.remaining() * encoder.maxBytesPerChar()); + boolean release = true; + final ByteBuf dst; + if (enforceHeap) { + dst = alloc.heapBuffer(length); + } else { + dst = alloc.buffer(length); + } + try { + final ByteBuffer dstBuf = dst.internalNioBuffer(0, length); + final int pos = dstBuf.position(); + CoderResult cr = encoder.encode(src, dstBuf, true); + if (!cr.isUnderflow()) { + cr.throwException(); + } + cr = encoder.flush(dstBuf); + if (!cr.isUnderflow()) { + cr.throwException(); + } + dst.writerIndex(dst.writerIndex() + dstBuf.position() - pos); + release = false; + return dst; + } catch (CharacterCodingException x) { + throw new IllegalStateException(x); + } finally { + if (release) { + dst.release(); + } + } + } + + static String decodeString(ByteBuffer src, Charset charset) { + final CharsetDecoder decoder = CharsetUtil.getDecoder(charset); + final CharBuffer dst = CharBuffer.allocate( + (int) ((double) src.remaining() * decoder.maxCharsPerByte())); + try { + CoderResult cr = decoder.decode(src, dst, true); + if (!cr.isUnderflow()) { + cr.throwException(); + } + cr = decoder.flush(dst); + if (!cr.isUnderflow()) { + cr.throwException(); + } + } catch (CharacterCodingException x) { + throw new IllegalStateException(x); + } + return dst.flip().toString(); + } + + /** + * Returns a cached thread-local direct buffer, if available. + * + * @return a cached thread-local direct buffer, if available. {@code null} otherwise. + */ + public static ByteBuf threadLocalDirectBuffer() { + if (THREAD_LOCAL_BUFFER_SIZE <= 0) { + return null; + } + + return ThreadLocalDirectByteBuf.newInstance(); + } + + static final class ThreadLocalDirectByteBuf extends UnpooledDirectByteBuf { + + private static final Recycler RECYCLER = new Recycler() { + @Override + protected ThreadLocalDirectByteBuf newObject(Handle handle) { + return new ThreadLocalDirectByteBuf(handle); + } + }; + + static ThreadLocalDirectByteBuf newInstance() { + ThreadLocalDirectByteBuf buf = RECYCLER.get(); + buf.setRefCnt(1); + return buf; + } + + private final Handle handle; + + private ThreadLocalDirectByteBuf(Handle handle) { + super(UnpooledByteBufAllocator.DEFAULT, 256, Integer.MAX_VALUE); + this.handle = handle; + } + + @Override + protected void deallocate() { + if (capacity() > THREAD_LOCAL_BUFFER_SIZE) { + super.deallocate(); + } else { + clear(); + RECYCLER.recycle(this, handle); + } + } + } + + private ByteBufUtil() { } +} diff --git a/common/src/main/java/common/net/buffer/CompositeByteBuf.java b/common/src/main/java/common/net/buffer/CompositeByteBuf.java new file mode 100644 index 0000000..1c93f11 --- /dev/null +++ b/common/src/main/java/common/net/buffer/CompositeByteBuf.java @@ -0,0 +1,1586 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; + +import common.net.util.ResourceLeak; +import common.net.util.internal.EmptyArrays; + +/** + * A virtual buffer which shows multiple buffers as a single merged buffer. It is recommended to use + * {@link ByteBufAllocator#compositeBuffer()} or {@link Unpooled#wrappedBuffer(ByteBuf...)} instead of calling the + * constructor explicitly. + */ +public class CompositeByteBuf extends AbstractReferenceCountedByteBuf { + + private final ResourceLeak leak; + private final ByteBufAllocator alloc; + private final boolean direct; + private final List components = new ArrayList(); + private final int maxNumComponents; + private static final ByteBuffer FULL_BYTEBUFFER = (ByteBuffer) ByteBuffer.allocate(1).position(1); + + private boolean freed; + + public CompositeByteBuf(ByteBufAllocator alloc, boolean direct, int maxNumComponents) { + super(Integer.MAX_VALUE); + if (alloc == null) { + throw new NullPointerException("alloc"); + } + this.alloc = alloc; + this.direct = direct; + this.maxNumComponents = maxNumComponents; + leak = leakDetector.open(this); + } + + public CompositeByteBuf(ByteBufAllocator alloc, boolean direct, int maxNumComponents, ByteBuf... buffers) { + super(Integer.MAX_VALUE); + if (alloc == null) { + throw new NullPointerException("alloc"); + } + if (maxNumComponents < 2) { + throw new IllegalArgumentException( + "maxNumComponents: " + maxNumComponents + " (expected: >= 2)"); + } + + this.alloc = alloc; + this.direct = direct; + this.maxNumComponents = maxNumComponents; + + addComponents0(0, buffers); + consolidateIfNeeded(); + setIndex(0, capacity()); + leak = leakDetector.open(this); + } + + public CompositeByteBuf( + ByteBufAllocator alloc, boolean direct, int maxNumComponents, Iterable buffers) { + super(Integer.MAX_VALUE); + if (alloc == null) { + throw new NullPointerException("alloc"); + } + if (maxNumComponents < 2) { + throw new IllegalArgumentException( + "maxNumComponents: " + maxNumComponents + " (expected: >= 2)"); + } + + this.alloc = alloc; + this.direct = direct; + this.maxNumComponents = maxNumComponents; + addComponents0(0, buffers); + consolidateIfNeeded(); + setIndex(0, capacity()); + leak = leakDetector.open(this); + } + + /** + * Add the given {@link ByteBuf}. + * + * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. + * If you need to have it increased you need to handle it by your own. + * + * @param buffer the {@link ByteBuf} to add + */ + public CompositeByteBuf addComponent(ByteBuf buffer) { + addComponent0(components.size(), buffer); + consolidateIfNeeded(); + return this; + } + + /** + * Add the given {@link ByteBuf}s. + * + * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. + * If you need to have it increased you need to handle it by your own. + * + * @param buffers the {@link ByteBuf}s to add + */ + public CompositeByteBuf addComponents(ByteBuf... buffers) { + addComponents0(components.size(), buffers); + consolidateIfNeeded(); + return this; + } + + /** + * Add the given {@link ByteBuf}s. + * + * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. + * If you need to have it increased you need to handle it by your own. + * + * @param buffers the {@link ByteBuf}s to add + */ + public CompositeByteBuf addComponents(Iterable buffers) { + addComponents0(components.size(), buffers); + consolidateIfNeeded(); + return this; + } + + /** + * Add the given {@link ByteBuf} on the specific index. + * + * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. + * If you need to have it increased you need to handle it by your own. + * + * @param cIndex the index on which the {@link ByteBuf} will be added + * @param buffer the {@link ByteBuf} to add + */ + public CompositeByteBuf addComponent(int cIndex, ByteBuf buffer) { + addComponent0(cIndex, buffer); + consolidateIfNeeded(); + return this; + } + + private int addComponent0(int cIndex, ByteBuf buffer) { + checkComponentIndex(cIndex); + + if (buffer == null) { + throw new NullPointerException("buffer"); + } + + int readableBytes = buffer.readableBytes(); + if (readableBytes == 0) { + return cIndex; + } + + // No need to consolidate - just add a component to the list. + Component c = new Component(buffer.order(ByteOrder.BIG_ENDIAN).slice()); + if (cIndex == components.size()) { + components.add(c); + if (cIndex == 0) { + c.endOffset = readableBytes; + } else { + Component prev = components.get(cIndex - 1); + c.offset = prev.endOffset; + c.endOffset = c.offset + readableBytes; + } + } else { + components.add(cIndex, c); + updateComponentOffsets(cIndex); + } + return cIndex; + } + + /** + * Add the given {@link ByteBuf}s on the specific index + * + * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. + * If you need to have it increased you need to handle it by your own. + * + * @param cIndex the index on which the {@link ByteBuf} will be added. + * @param buffers the {@link ByteBuf}s to add + */ + public CompositeByteBuf addComponents(int cIndex, ByteBuf... buffers) { + addComponents0(cIndex, buffers); + consolidateIfNeeded(); + return this; + } + + private int addComponents0(int cIndex, ByteBuf... buffers) { + checkComponentIndex(cIndex); + + if (buffers == null) { + throw new NullPointerException("buffers"); + } + + int readableBytes = 0; + for (ByteBuf b: buffers) { + if (b == null) { + break; + } + readableBytes += b.readableBytes(); + } + + if (readableBytes == 0) { + return cIndex; + } + + // No need for consolidation + for (ByteBuf b: buffers) { + if (b == null) { + break; + } + if (b.isReadable()) { + cIndex = addComponent0(cIndex, b) + 1; + int size = components.size(); + if (cIndex > size) { + cIndex = size; + } + } else { + b.release(); + } + } + return cIndex; + } + + /** + * Add the given {@link ByteBuf}s on the specific index + * + * Be aware that this method does not increase the {@code writerIndex} of the {@link CompositeByteBuf}. + * If you need to have it increased you need to handle it by your own. + * + * @param cIndex the index on which the {@link ByteBuf} will be added. + * @param buffers the {@link ByteBuf}s to add + */ + public CompositeByteBuf addComponents(int cIndex, Iterable buffers) { + addComponents0(cIndex, buffers); + consolidateIfNeeded(); + return this; + } + + private int addComponents0(int cIndex, Iterable buffers) { + if (buffers == null) { + throw new NullPointerException("buffers"); + } + + if (buffers instanceof ByteBuf) { + // If buffers also implements ByteBuf (e.g. CompositeByteBuf), it has to go to addComponent(ByteBuf). + return addComponent0(cIndex, (ByteBuf) buffers); + } + + if (!(buffers instanceof Collection)) { + List list = new ArrayList(); + for (ByteBuf b: buffers) { + list.add(b); + } + buffers = list; + } + + Collection col = (Collection) buffers; + return addComponents0(cIndex, col.toArray(new ByteBuf[col.size()])); + } + + /** + * This should only be called as last operation from a method as this may adjust the underlying + * array of components and so affect the index etc. + */ + private void consolidateIfNeeded() { + // Consolidate if the number of components will exceed the allowed maximum by the current + // operation. + final int numComponents = components.size(); + if (numComponents > maxNumComponents) { + final int capacity = components.get(numComponents - 1).endOffset; + + ByteBuf consolidated = allocBuffer(capacity); + + // We're not using foreach to avoid creating an iterator. + for (int i = 0; i < numComponents; i ++) { + Component c = components.get(i); + ByteBuf b = c.buf; + consolidated.writeBytes(b); + c.freeIfNecessary(); + } + Component c = new Component(consolidated); + c.endOffset = c.length; + components.clear(); + components.add(c); + } + } + + private void checkComponentIndex(int cIndex) { + ensureAccessible(); + if (cIndex < 0 || cIndex > components.size()) { + throw new IndexOutOfBoundsException(String.format( + "cIndex: %d (expected: >= 0 && <= numComponents(%d))", + cIndex, components.size())); + } + } + + private void checkComponentIndex(int cIndex, int numComponents) { + ensureAccessible(); + if (cIndex < 0 || cIndex + numComponents > components.size()) { + throw new IndexOutOfBoundsException(String.format( + "cIndex: %d, numComponents: %d " + + "(expected: cIndex >= 0 && cIndex + numComponents <= totalNumComponents(%d))", + cIndex, numComponents, components.size())); + } + } + + private void updateComponentOffsets(int cIndex) { + int size = components.size(); + if (size <= cIndex) { + return; + } + + Component c = components.get(cIndex); + if (cIndex == 0) { + c.offset = 0; + c.endOffset = c.length; + cIndex ++; + } + + for (int i = cIndex; i < size; i ++) { + Component prev = components.get(i - 1); + Component cur = components.get(i); + cur.offset = prev.endOffset; + cur.endOffset = cur.offset + cur.length; + } + } + + /** + * Remove the {@link ByteBuf} from the given index. + * + * @param cIndex the index on from which the {@link ByteBuf} will be remove + */ + public CompositeByteBuf removeComponent(int cIndex) { + checkComponentIndex(cIndex); + components.remove(cIndex).freeIfNecessary(); + updateComponentOffsets(cIndex); + return this; + } + + /** + * Remove the number of {@link ByteBuf}s starting from the given index. + * + * @param cIndex the index on which the {@link ByteBuf}s will be started to removed + * @param numComponents the number of components to remove + */ + public CompositeByteBuf removeComponents(int cIndex, int numComponents) { + checkComponentIndex(cIndex, numComponents); + + List toRemove = components.subList(cIndex, cIndex + numComponents); + for (Component c: toRemove) { + c.freeIfNecessary(); + } + toRemove.clear(); + + updateComponentOffsets(cIndex); + return this; + } + + public Iterator iterator() { + ensureAccessible(); + List list = new ArrayList(components.size()); + for (Component c: components) { + list.add(c.buf); + } + return list.iterator(); + } + + /** + * Same with {@link #slice(int, int)} except that this method returns a list. + */ + public List decompose(int offset, int length) { + checkIndex(offset, length); + if (length == 0) { + return Collections.emptyList(); + } + + int componentId = toComponentIndex(offset); + List slice = new ArrayList(components.size()); + + // The first component + Component firstC = components.get(componentId); + ByteBuf first = firstC.buf.duplicate(); + first.readerIndex(offset - firstC.offset); + + ByteBuf buf = first; + int bytesToSlice = length; + do { + int readableBytes = buf.readableBytes(); + if (bytesToSlice <= readableBytes) { + // Last component + buf.writerIndex(buf.readerIndex() + bytesToSlice); + slice.add(buf); + break; + } else { + // Not the last component + slice.add(buf); + bytesToSlice -= readableBytes; + componentId ++; + + // Fetch the next component. + buf = components.get(componentId).buf.duplicate(); + } + } while (bytesToSlice > 0); + + // Slice all components because only readable bytes are interesting. + for (int i = 0; i < slice.size(); i ++) { + slice.set(i, slice.get(i).slice()); + } + + return slice; + } + + @Override + public boolean isDirect() { + int size = components.size(); + if (size == 0) { + return false; + } + for (int i = 0; i < size; i++) { + if (!components.get(i).buf.isDirect()) { + return false; + } + } + return true; + } + + @Override + public boolean hasArray() { + if (components.size() == 1) { + return components.get(0).buf.hasArray(); + } + return false; + } + + @Override + public byte[] array() { + if (components.size() == 1) { + return components.get(0).buf.array(); + } + throw new UnsupportedOperationException(); + } + + @Override + public int arrayOffset() { + if (components.size() == 1) { + return components.get(0).buf.arrayOffset(); + } + throw new UnsupportedOperationException(); + } + + @Override + public int capacity() { + if (components.isEmpty()) { + return 0; + } + return components.get(components.size() - 1).endOffset; + } + + @Override + public CompositeByteBuf capacity(int newCapacity) { + ensureAccessible(); + if (newCapacity < 0 || newCapacity > maxCapacity()) { + throw new IllegalArgumentException("newCapacity: " + newCapacity); + } + + int oldCapacity = capacity(); + if (newCapacity > oldCapacity) { + final int paddingLength = newCapacity - oldCapacity; + ByteBuf padding; + int nComponents = components.size(); + if (nComponents < maxNumComponents) { + padding = allocBuffer(paddingLength); + padding.setIndex(0, paddingLength); + addComponent0(components.size(), padding); + } else { + padding = allocBuffer(paddingLength); + padding.setIndex(0, paddingLength); + // FIXME: No need to create a padding buffer and consolidate. + // Just create a big single buffer and put the current content there. + addComponent0(components.size(), padding); + consolidateIfNeeded(); + } + } else if (newCapacity < oldCapacity) { + int bytesToTrim = oldCapacity - newCapacity; + for (ListIterator i = components.listIterator(components.size()); i.hasPrevious();) { + Component c = i.previous(); + if (bytesToTrim >= c.length) { + bytesToTrim -= c.length; + i.remove(); + continue; + } + + // Replace the last component with the trimmed slice. + Component newC = new Component(c.buf.slice(0, c.length - bytesToTrim)); + newC.offset = c.offset; + newC.endOffset = newC.offset + newC.length; + i.set(newC); + break; + } + + if (readerIndex() > newCapacity) { + setIndex(newCapacity, newCapacity); + } else if (writerIndex() > newCapacity) { + writerIndex(newCapacity); + } + } + return this; + } + + @Override + public ByteBufAllocator alloc() { + return alloc; + } + + @Override + public ByteOrder order() { + return ByteOrder.BIG_ENDIAN; + } + + /** + * Return the current number of {@link ByteBuf}'s that are composed in this instance + */ + public int numComponents() { + return components.size(); + } + + /** + * Return the max number of {@link ByteBuf}'s that are composed in this instance + */ + public int maxNumComponents() { + return maxNumComponents; + } + + /** + * Return the index for the given offset + */ + public int toComponentIndex(int offset) { + checkIndex(offset); + + for (int low = 0, high = components.size(); low <= high;) { + int mid = low + high >>> 1; + Component c = components.get(mid); + if (offset >= c.endOffset) { + low = mid + 1; + } else if (offset < c.offset) { + high = mid - 1; + } else { + return mid; + } + } + + throw new Error("should not reach here"); + } + + public int toByteIndex(int cIndex) { + checkComponentIndex(cIndex); + return components.get(cIndex).offset; + } + + @Override + public byte getByte(int index) { + return _getByte(index); + } + + @Override + protected byte _getByte(int index) { + Component c = findComponent(index); + return c.buf.getByte(index - c.offset); + } + + @Override + protected short _getShort(int index) { + Component c = findComponent(index); + if (index + 2 <= c.endOffset) { + return c.buf.getShort(index - c.offset); + } else if (order() == ByteOrder.BIG_ENDIAN) { + return (short) ((_getByte(index) & 0xff) << 8 | _getByte(index + 1) & 0xff); + } else { + return (short) (_getByte(index) & 0xff | (_getByte(index + 1) & 0xff) << 8); + } + } + + @Override + protected int _getUnsignedMedium(int index) { + Component c = findComponent(index); + if (index + 3 <= c.endOffset) { + return c.buf.getUnsignedMedium(index - c.offset); + } else if (order() == ByteOrder.BIG_ENDIAN) { + return (_getShort(index) & 0xffff) << 8 | _getByte(index + 2) & 0xff; + } else { + return _getShort(index) & 0xFFFF | (_getByte(index + 2) & 0xFF) << 16; + } + } + + @Override + protected int _getInt(int index) { + Component c = findComponent(index); + if (index + 4 <= c.endOffset) { + return c.buf.getInt(index - c.offset); + } else if (order() == ByteOrder.BIG_ENDIAN) { + return (_getShort(index) & 0xffff) << 16 | _getShort(index + 2) & 0xffff; + } else { + return _getShort(index) & 0xFFFF | (_getShort(index + 2) & 0xFFFF) << 16; + } + } + + @Override + protected long _getLong(int index) { + Component c = findComponent(index); + if (index + 8 <= c.endOffset) { + return c.buf.getLong(index - c.offset); + } else if (order() == ByteOrder.BIG_ENDIAN) { + return (_getInt(index) & 0xffffffffL) << 32 | _getInt(index + 4) & 0xffffffffL; + } else { + return _getInt(index) & 0xFFFFFFFFL | (_getInt(index + 4) & 0xFFFFFFFFL) << 32; + } + } + + @Override + public CompositeByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.length); + if (length == 0) { + return this; + } + + int i = toComponentIndex(index); + while (length > 0) { + Component c = components.get(i); + ByteBuf s = c.buf; + int adjustment = c.offset; + int localLength = Math.min(length, s.capacity() - (index - adjustment)); + s.getBytes(index - adjustment, dst, dstIndex, localLength); + index += localLength; + dstIndex += localLength; + length -= localLength; + i ++; + } + return this; + } + + @Override + public CompositeByteBuf getBytes(int index, ByteBuffer dst) { + int limit = dst.limit(); + int length = dst.remaining(); + + checkIndex(index, length); + if (length == 0) { + return this; + } + + int i = toComponentIndex(index); + try { + while (length > 0) { + Component c = components.get(i); + ByteBuf s = c.buf; + int adjustment = c.offset; + int localLength = Math.min(length, s.capacity() - (index - adjustment)); + dst.limit(dst.position() + localLength); + s.getBytes(index - adjustment, dst); + index += localLength; + length -= localLength; + i ++; + } + } finally { + dst.limit(limit); + } + return this; + } + + @Override + public CompositeByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.capacity()); + if (length == 0) { + return this; + } + + int i = toComponentIndex(index); + while (length > 0) { + Component c = components.get(i); + ByteBuf s = c.buf; + int adjustment = c.offset; + int localLength = Math.min(length, s.capacity() - (index - adjustment)); + s.getBytes(index - adjustment, dst, dstIndex, localLength); + index += localLength; + dstIndex += localLength; + length -= localLength; + i ++; + } + return this; + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) + throws IOException { + int count = nioBufferCount(); + if (count == 1) { + return out.write(internalNioBuffer(index, length)); + } else { + long writtenBytes = out.write(nioBuffers(index, length)); + if (writtenBytes > Integer.MAX_VALUE) { + return Integer.MAX_VALUE; + } else { + return (int) writtenBytes; + } + } + } + + @Override + public CompositeByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + checkIndex(index, length); + if (length == 0) { + return this; + } + + int i = toComponentIndex(index); + while (length > 0) { + Component c = components.get(i); + ByteBuf s = c.buf; + int adjustment = c.offset; + int localLength = Math.min(length, s.capacity() - (index - adjustment)); + s.getBytes(index - adjustment, out, localLength); + index += localLength; + length -= localLength; + i ++; + } + return this; + } + + @Override + public CompositeByteBuf setByte(int index, int value) { + Component c = findComponent(index); + c.buf.setByte(index - c.offset, value); + return this; + } + + @Override + protected void _setByte(int index, int value) { + setByte(index, value); + } + + @Override + public CompositeByteBuf setShort(int index, int value) { + return (CompositeByteBuf) super.setShort(index, value); + } + + @Override + protected void _setShort(int index, int value) { + Component c = findComponent(index); + if (index + 2 <= c.endOffset) { + c.buf.setShort(index - c.offset, value); + } else if (order() == ByteOrder.BIG_ENDIAN) { + _setByte(index, (byte) (value >>> 8)); + _setByte(index + 1, (byte) value); + } else { + _setByte(index, (byte) value); + _setByte(index + 1, (byte) (value >>> 8)); + } + } + + @Override + public CompositeByteBuf setMedium(int index, int value) { + return (CompositeByteBuf) super.setMedium(index, value); + } + + @Override + protected void _setMedium(int index, int value) { + Component c = findComponent(index); + if (index + 3 <= c.endOffset) { + c.buf.setMedium(index - c.offset, value); + } else if (order() == ByteOrder.BIG_ENDIAN) { + _setShort(index, (short) (value >> 8)); + _setByte(index + 2, (byte) value); + } else { + _setShort(index, (short) value); + _setByte(index + 2, (byte) (value >>> 16)); + } + } + + @Override + public CompositeByteBuf setInt(int index, int value) { + return (CompositeByteBuf) super.setInt(index, value); + } + + @Override + protected void _setInt(int index, int value) { + Component c = findComponent(index); + if (index + 4 <= c.endOffset) { + c.buf.setInt(index - c.offset, value); + } else if (order() == ByteOrder.BIG_ENDIAN) { + _setShort(index, (short) (value >>> 16)); + _setShort(index + 2, (short) value); + } else { + _setShort(index, (short) value); + _setShort(index + 2, (short) (value >>> 16)); + } + } + + @Override + public CompositeByteBuf setLong(int index, long value) { + return (CompositeByteBuf) super.setLong(index, value); + } + + @Override + protected void _setLong(int index, long value) { + Component c = findComponent(index); + if (index + 8 <= c.endOffset) { + c.buf.setLong(index - c.offset, value); + } else if (order() == ByteOrder.BIG_ENDIAN) { + _setInt(index, (int) (value >>> 32)); + _setInt(index + 4, (int) value); + } else { + _setInt(index, (int) value); + _setInt(index + 4, (int) (value >>> 32)); + } + } + + @Override + public CompositeByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + checkSrcIndex(index, length, srcIndex, src.length); + if (length == 0) { + return this; + } + + int i = toComponentIndex(index); + while (length > 0) { + Component c = components.get(i); + ByteBuf s = c.buf; + int adjustment = c.offset; + int localLength = Math.min(length, s.capacity() - (index - adjustment)); + s.setBytes(index - adjustment, src, srcIndex, localLength); + index += localLength; + srcIndex += localLength; + length -= localLength; + i ++; + } + return this; + } + + @Override + public CompositeByteBuf setBytes(int index, ByteBuffer src) { + int limit = src.limit(); + int length = src.remaining(); + + checkIndex(index, length); + if (length == 0) { + return this; + } + + int i = toComponentIndex(index); + try { + while (length > 0) { + Component c = components.get(i); + ByteBuf s = c.buf; + int adjustment = c.offset; + int localLength = Math.min(length, s.capacity() - (index - adjustment)); + src.limit(src.position() + localLength); + s.setBytes(index - adjustment, src); + index += localLength; + length -= localLength; + i ++; + } + } finally { + src.limit(limit); + } + return this; + } + + @Override + public CompositeByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + checkSrcIndex(index, length, srcIndex, src.capacity()); + if (length == 0) { + return this; + } + + int i = toComponentIndex(index); + while (length > 0) { + Component c = components.get(i); + ByteBuf s = c.buf; + int adjustment = c.offset; + int localLength = Math.min(length, s.capacity() - (index - adjustment)); + s.setBytes(index - adjustment, src, srcIndex, localLength); + index += localLength; + srcIndex += localLength; + length -= localLength; + i ++; + } + return this; + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + checkIndex(index, length); + if (length == 0) { + return in.read(EmptyArrays.EMPTY_BYTES); + } + + int i = toComponentIndex(index); + int readBytes = 0; + + do { + Component c = components.get(i); + ByteBuf s = c.buf; + int adjustment = c.offset; + int localLength = Math.min(length, s.capacity() - (index - adjustment)); + int localReadBytes = s.setBytes(index - adjustment, in, localLength); + if (localReadBytes < 0) { + if (readBytes == 0) { + return -1; + } else { + break; + } + } + + if (localReadBytes == localLength) { + index += localLength; + length -= localLength; + readBytes += localLength; + i ++; + } else { + index += localReadBytes; + length -= localReadBytes; + readBytes += localReadBytes; + } + } while (length > 0); + + return readBytes; + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + checkIndex(index, length); + if (length == 0) { + return in.read(FULL_BYTEBUFFER); + } + + int i = toComponentIndex(index); + int readBytes = 0; + do { + Component c = components.get(i); + ByteBuf s = c.buf; + int adjustment = c.offset; + int localLength = Math.min(length, s.capacity() - (index - adjustment)); + int localReadBytes = s.setBytes(index - adjustment, in, localLength); + + if (localReadBytes == 0) { + break; + } + + if (localReadBytes < 0) { + if (readBytes == 0) { + return -1; + } else { + break; + } + } + + if (localReadBytes == localLength) { + index += localLength; + length -= localLength; + readBytes += localLength; + i ++; + } else { + index += localReadBytes; + length -= localReadBytes; + readBytes += localReadBytes; + } + } while (length > 0); + + return readBytes; + } + + @Override + public ByteBuf copy(int index, int length) { + checkIndex(index, length); + ByteBuf dst = Unpooled.buffer(length); + if (length != 0) { + copyTo(index, length, toComponentIndex(index), dst); + } + return dst; + } + + private void copyTo(int index, int length, int componentId, ByteBuf dst) { + int dstIndex = 0; + int i = componentId; + + while (length > 0) { + Component c = components.get(i); + ByteBuf s = c.buf; + int adjustment = c.offset; + int localLength = Math.min(length, s.capacity() - (index - adjustment)); + s.getBytes(index - adjustment, dst, dstIndex, localLength); + index += localLength; + dstIndex += localLength; + length -= localLength; + i ++; + } + + dst.writerIndex(dst.capacity()); + } + + /** + * Return the {@link ByteBuf} on the specified index + * + * @param cIndex the index for which the {@link ByteBuf} should be returned + * @return buf the {@link ByteBuf} on the specified index + */ + public ByteBuf component(int cIndex) { + return internalComponent(cIndex).duplicate(); + } + + /** + * Return the {@link ByteBuf} on the specified index + * + * @param offset the offset for which the {@link ByteBuf} should be returned + * @return the {@link ByteBuf} on the specified index + */ + public ByteBuf componentAtOffset(int offset) { + return internalComponentAtOffset(offset).duplicate(); + } + + /** + * Return the internal {@link ByteBuf} on the specified index. Note that updating the indexes of the returned + * buffer will lead to an undefined behavior of this buffer. + * + * @param cIndex the index for which the {@link ByteBuf} should be returned + */ + public ByteBuf internalComponent(int cIndex) { + checkComponentIndex(cIndex); + return components.get(cIndex).buf; + } + + /** + * Return the internal {@link ByteBuf} on the specified offset. Note that updating the indexes of the returned + * buffer will lead to an undefined behavior of this buffer. + * + * @param offset the offset for which the {@link ByteBuf} should be returned + */ + public ByteBuf internalComponentAtOffset(int offset) { + return findComponent(offset).buf; + } + + private Component findComponent(int offset) { + checkIndex(offset); + + for (int low = 0, high = components.size(); low <= high;) { + int mid = low + high >>> 1; + Component c = components.get(mid); + if (offset >= c.endOffset) { + low = mid + 1; + } else if (offset < c.offset) { + high = mid - 1; + } else { + return c; + } + } + + throw new Error("should not reach here"); + } + + @Override + public int nioBufferCount() { + if (components.size() == 1) { + return components.get(0).buf.nioBufferCount(); + } else { + int count = 0; + int componentsCount = components.size(); + for (int i = 0; i < componentsCount; i++) { + Component c = components.get(i); + count += c.buf.nioBufferCount(); + } + return count; + } + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + if (components.size() == 1) { + return components.get(0).buf.internalNioBuffer(index, length); + } + throw new UnsupportedOperationException(); + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + if (components.size() == 1) { + ByteBuf buf = components.get(0).buf; + if (buf.nioBufferCount() == 1) { + return components.get(0).buf.nioBuffer(index, length); + } + } + ByteBuffer merged = ByteBuffer.allocate(length).order(order()); + ByteBuffer[] buffers = nioBuffers(index, length); + + //noinspection ForLoopReplaceableByForEach + for (int i = 0; i < buffers.length; i++) { + merged.put(buffers[i]); + } + + merged.flip(); + return merged; + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + checkIndex(index, length); + if (length == 0) { + return EmptyArrays.EMPTY_BYTE_BUFFERS; + } + + List buffers = new ArrayList(components.size()); + int i = toComponentIndex(index); + while (length > 0) { + Component c = components.get(i); + ByteBuf s = c.buf; + int adjustment = c.offset; + int localLength = Math.min(length, s.capacity() - (index - adjustment)); + switch (s.nioBufferCount()) { + case 0: + throw new UnsupportedOperationException(); + case 1: + buffers.add(s.nioBuffer(index - adjustment, localLength)); + break; + default: + Collections.addAll(buffers, s.nioBuffers(index - adjustment, localLength)); + } + + index += localLength; + length -= localLength; + i ++; + } + + return buffers.toArray(new ByteBuffer[buffers.size()]); + } + + /** + * Consolidate the composed {@link ByteBuf}s + */ + public CompositeByteBuf consolidate() { + ensureAccessible(); + final int numComponents = numComponents(); + if (numComponents <= 1) { + return this; + } + + final Component last = components.get(numComponents - 1); + final int capacity = last.endOffset; + final ByteBuf consolidated = allocBuffer(capacity); + + for (int i = 0; i < numComponents; i ++) { + Component c = components.get(i); + ByteBuf b = c.buf; + consolidated.writeBytes(b); + c.freeIfNecessary(); + } + + components.clear(); + components.add(new Component(consolidated)); + updateComponentOffsets(0); + return this; + } + + /** + * Consolidate the composed {@link ByteBuf}s + * + * @param cIndex the index on which to start to compose + * @param numComponents the number of components to compose + */ + public CompositeByteBuf consolidate(int cIndex, int numComponents) { + checkComponentIndex(cIndex, numComponents); + if (numComponents <= 1) { + return this; + } + + final int endCIndex = cIndex + numComponents; + final Component last = components.get(endCIndex - 1); + final int capacity = last.endOffset - components.get(cIndex).offset; + final ByteBuf consolidated = allocBuffer(capacity); + + for (int i = cIndex; i < endCIndex; i ++) { + Component c = components.get(i); + ByteBuf b = c.buf; + consolidated.writeBytes(b); + c.freeIfNecessary(); + } + + components.subList(cIndex + 1, endCIndex).clear(); + components.set(cIndex, new Component(consolidated)); + updateComponentOffsets(cIndex); + return this; + } + + /** + * Discard all {@link ByteBuf}s which are read. + */ + public CompositeByteBuf discardReadComponents() { + ensureAccessible(); + final int readerIndex = readerIndex(); + if (readerIndex == 0) { + return this; + } + + // Discard everything if (readerIndex = writerIndex = capacity). + int writerIndex = writerIndex(); + if (readerIndex == writerIndex && writerIndex == capacity()) { + for (Component c: components) { + c.freeIfNecessary(); + } + components.clear(); + setIndex(0, 0); + adjustMarkers(readerIndex); + return this; + } + + // Remove read components. + int firstComponentId = toComponentIndex(readerIndex); + for (int i = 0; i < firstComponentId; i ++) { + components.get(i).freeIfNecessary(); + } + components.subList(0, firstComponentId).clear(); + + // Update indexes and markers. + Component first = components.get(0); + int offset = first.offset; + updateComponentOffsets(0); + setIndex(readerIndex - offset, writerIndex - offset); + adjustMarkers(offset); + return this; + } + + @Override + public CompositeByteBuf discardReadBytes() { + ensureAccessible(); + final int readerIndex = readerIndex(); + if (readerIndex == 0) { + return this; + } + + // Discard everything if (readerIndex = writerIndex = capacity). + int writerIndex = writerIndex(); + if (readerIndex == writerIndex && writerIndex == capacity()) { + for (Component c: components) { + c.freeIfNecessary(); + } + components.clear(); + setIndex(0, 0); + adjustMarkers(readerIndex); + return this; + } + + // Remove read components. + int firstComponentId = toComponentIndex(readerIndex); + for (int i = 0; i < firstComponentId; i ++) { + components.get(i).freeIfNecessary(); + } + components.subList(0, firstComponentId).clear(); + + // Remove or replace the first readable component with a new slice. + Component c = components.get(0); + int adjustment = readerIndex - c.offset; + if (adjustment == c.length) { + // new slice would be empty, so remove instead + components.remove(0); + } else { + Component newC = new Component(c.buf.slice(adjustment, c.length - adjustment)); + components.set(0, newC); + } + + // Update indexes and markers. + updateComponentOffsets(0); + setIndex(0, writerIndex - readerIndex); + adjustMarkers(readerIndex); + return this; + } + + private ByteBuf allocBuffer(int capacity) { + if (direct) { + return alloc().directBuffer(capacity); + } + return alloc().heapBuffer(capacity); + } + + @Override + public String toString() { + String result = super.toString(); + result = result.substring(0, result.length() - 1); + return result + ", components=" + components.size() + ')'; + } + + private static final class Component { + final ByteBuf buf; + final int length; + int offset; + int endOffset; + + Component(ByteBuf buf) { + this.buf = buf; + length = buf.readableBytes(); + } + + void freeIfNecessary() { + // Unwrap so that we can free slices, too. + buf.release(); // We should not get a NPE here. If so, it must be a bug. + } + } + + @Override + public CompositeByteBuf readerIndex(int readerIndex) { + return (CompositeByteBuf) super.readerIndex(readerIndex); + } + + @Override + public CompositeByteBuf writerIndex(int writerIndex) { + return (CompositeByteBuf) super.writerIndex(writerIndex); + } + + @Override + public CompositeByteBuf setIndex(int readerIndex, int writerIndex) { + return (CompositeByteBuf) super.setIndex(readerIndex, writerIndex); + } + + @Override + public CompositeByteBuf clear() { + return (CompositeByteBuf) super.clear(); + } + + @Override + public CompositeByteBuf markReaderIndex() { + return (CompositeByteBuf) super.markReaderIndex(); + } + + @Override + public CompositeByteBuf resetReaderIndex() { + return (CompositeByteBuf) super.resetReaderIndex(); + } + + @Override + public CompositeByteBuf markWriterIndex() { + return (CompositeByteBuf) super.markWriterIndex(); + } + + @Override + public CompositeByteBuf resetWriterIndex() { + return (CompositeByteBuf) super.resetWriterIndex(); + } + + @Override + public CompositeByteBuf ensureWritable(int minWritableBytes) { + return (CompositeByteBuf) super.ensureWritable(minWritableBytes); + } + + @Override + public CompositeByteBuf getBytes(int index, ByteBuf dst) { + return (CompositeByteBuf) super.getBytes(index, dst); + } + + @Override + public CompositeByteBuf getBytes(int index, ByteBuf dst, int length) { + return (CompositeByteBuf) super.getBytes(index, dst, length); + } + + @Override + public CompositeByteBuf getBytes(int index, byte[] dst) { + return (CompositeByteBuf) super.getBytes(index, dst); + } + + @Override + public CompositeByteBuf setBoolean(int index, boolean value) { + return (CompositeByteBuf) super.setBoolean(index, value); + } + + @Override + public CompositeByteBuf setChar(int index, int value) { + return (CompositeByteBuf) super.setChar(index, value); + } + + @Override + public CompositeByteBuf setFloat(int index, float value) { + return (CompositeByteBuf) super.setFloat(index, value); + } + + @Override + public CompositeByteBuf setDouble(int index, double value) { + return (CompositeByteBuf) super.setDouble(index, value); + } + + @Override + public CompositeByteBuf setBytes(int index, ByteBuf src) { + return (CompositeByteBuf) super.setBytes(index, src); + } + + @Override + public CompositeByteBuf setBytes(int index, ByteBuf src, int length) { + return (CompositeByteBuf) super.setBytes(index, src, length); + } + + @Override + public CompositeByteBuf setBytes(int index, byte[] src) { + return (CompositeByteBuf) super.setBytes(index, src); + } + + @Override + public CompositeByteBuf setZero(int index, int length) { + return (CompositeByteBuf) super.setZero(index, length); + } + + @Override + public CompositeByteBuf readBytes(ByteBuf dst) { + return (CompositeByteBuf) super.readBytes(dst); + } + + @Override + public CompositeByteBuf readBytes(ByteBuf dst, int length) { + return (CompositeByteBuf) super.readBytes(dst, length); + } + + @Override + public CompositeByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { + return (CompositeByteBuf) super.readBytes(dst, dstIndex, length); + } + + @Override + public CompositeByteBuf readBytes(byte[] dst) { + return (CompositeByteBuf) super.readBytes(dst); + } + + @Override + public CompositeByteBuf readBytes(byte[] dst, int dstIndex, int length) { + return (CompositeByteBuf) super.readBytes(dst, dstIndex, length); + } + + @Override + public CompositeByteBuf readBytes(ByteBuffer dst) { + return (CompositeByteBuf) super.readBytes(dst); + } + + @Override + public CompositeByteBuf readBytes(OutputStream out, int length) throws IOException { + return (CompositeByteBuf) super.readBytes(out, length); + } + + @Override + public CompositeByteBuf skipBytes(int length) { + return (CompositeByteBuf) super.skipBytes(length); + } + + @Override + public CompositeByteBuf writeBoolean(boolean value) { + return (CompositeByteBuf) super.writeBoolean(value); + } + + @Override + public CompositeByteBuf writeByte(int value) { + return (CompositeByteBuf) super.writeByte(value); + } + + @Override + public CompositeByteBuf writeShort(int value) { + return (CompositeByteBuf) super.writeShort(value); + } + + @Override + public CompositeByteBuf writeMedium(int value) { + return (CompositeByteBuf) super.writeMedium(value); + } + + @Override + public CompositeByteBuf writeInt(int value) { + return (CompositeByteBuf) super.writeInt(value); + } + + @Override + public CompositeByteBuf writeLong(long value) { + return (CompositeByteBuf) super.writeLong(value); + } + + @Override + public CompositeByteBuf writeChar(int value) { + return (CompositeByteBuf) super.writeChar(value); + } + + @Override + public CompositeByteBuf writeFloat(float value) { + return (CompositeByteBuf) super.writeFloat(value); + } + + @Override + public CompositeByteBuf writeDouble(double value) { + return (CompositeByteBuf) super.writeDouble(value); + } + + @Override + public CompositeByteBuf writeBytes(ByteBuf src) { + return (CompositeByteBuf) super.writeBytes(src); + } + + @Override + public CompositeByteBuf writeBytes(ByteBuf src, int length) { + return (CompositeByteBuf) super.writeBytes(src, length); + } + + @Override + public CompositeByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { + return (CompositeByteBuf) super.writeBytes(src, srcIndex, length); + } + + @Override + public CompositeByteBuf writeBytes(byte[] src) { + return (CompositeByteBuf) super.writeBytes(src); + } + + @Override + public CompositeByteBuf writeBytes(byte[] src, int srcIndex, int length) { + return (CompositeByteBuf) super.writeBytes(src, srcIndex, length); + } + + @Override + public CompositeByteBuf writeBytes(ByteBuffer src) { + return (CompositeByteBuf) super.writeBytes(src); + } + + @Override + public CompositeByteBuf writeZero(int length) { + return (CompositeByteBuf) super.writeZero(length); + } + + @Override + public CompositeByteBuf retain(int increment) { + return (CompositeByteBuf) super.retain(increment); + } + + @Override + public CompositeByteBuf retain() { + return (CompositeByteBuf) super.retain(); + } + + @Override + public ByteBuffer[] nioBuffers() { + return nioBuffers(readerIndex(), readableBytes()); + } + + @Override + public CompositeByteBuf discardSomeReadBytes() { + return discardReadComponents(); + } + + @Override + protected void deallocate() { + if (freed) { + return; + } + + freed = true; + int size = components.size(); + // We're not using foreach to avoid creating an iterator. + // see https://github.com/netty/netty/issues/2642 + for (int i = 0; i < size; i++) { + components.get(i).freeIfNecessary(); + } + + if (leak != null) { + leak.close(); + } + } + + @Override + public ByteBuf unwrap() { + return null; + } +} diff --git a/common/src/main/java/common/net/buffer/DuplicatedByteBuf.java b/common/src/main/java/common/net/buffer/DuplicatedByteBuf.java new file mode 100644 index 0000000..a888cd6 --- /dev/null +++ b/common/src/main/java/common/net/buffer/DuplicatedByteBuf.java @@ -0,0 +1,295 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; + + +/** + * A derived buffer which simply forwards all data access requests to its + * parent. It is recommended to use {@link ByteBuf#duplicate()} instead + * of calling the constructor explicitly. + */ +public class DuplicatedByteBuf extends AbstractDerivedByteBuf { + + private final ByteBuf buffer; + + public DuplicatedByteBuf(ByteBuf buffer) { + super(buffer.maxCapacity()); + + if (buffer instanceof DuplicatedByteBuf) { + this.buffer = ((DuplicatedByteBuf) buffer).buffer; + } else { + this.buffer = buffer; + } + + setIndex(buffer.readerIndex(), buffer.writerIndex()); + } + + @Override + public ByteBuf unwrap() { + return buffer; + } + + @Override + public ByteBufAllocator alloc() { + return buffer.alloc(); + } + + @Override + public ByteOrder order() { + return buffer.order(); + } + + @Override + public boolean isDirect() { + return buffer.isDirect(); + } + + @Override + public int capacity() { + return buffer.capacity(); + } + + @Override + public ByteBuf capacity(int newCapacity) { + buffer.capacity(newCapacity); + return this; + } + + @Override + public boolean hasArray() { + return buffer.hasArray(); + } + + @Override + public byte[] array() { + return buffer.array(); + } + + @Override + public int arrayOffset() { + return buffer.arrayOffset(); + } + + @Override + public byte getByte(int index) { + return _getByte(index); + } + + @Override + protected byte _getByte(int index) { + return buffer.getByte(index); + } + + @Override + public short getShort(int index) { + return _getShort(index); + } + + @Override + protected short _getShort(int index) { + return buffer.getShort(index); + } + + @Override + public int getUnsignedMedium(int index) { + return _getUnsignedMedium(index); + } + + @Override + protected int _getUnsignedMedium(int index) { + return buffer.getUnsignedMedium(index); + } + + @Override + public int getInt(int index) { + return _getInt(index); + } + + @Override + protected int _getInt(int index) { + return buffer.getInt(index); + } + + @Override + public long getLong(int index) { + return _getLong(index); + } + + @Override + protected long _getLong(int index) { + return buffer.getLong(index); + } + + @Override + public ByteBuf copy(int index, int length) { + return buffer.copy(index, length); + } + + @Override + public ByteBuf slice(int index, int length) { + return buffer.slice(index, length); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + buffer.getBytes(index, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + buffer.getBytes(index, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + buffer.getBytes(index, dst); + return this; + } + + @Override + public ByteBuf setByte(int index, int value) { + _setByte(index, value); + return this; + } + + @Override + protected void _setByte(int index, int value) { + buffer.setByte(index, value); + } + + @Override + public ByteBuf setShort(int index, int value) { + _setShort(index, value); + return this; + } + + @Override + protected void _setShort(int index, int value) { + buffer.setShort(index, value); + } + + @Override + public ByteBuf setMedium(int index, int value) { + _setMedium(index, value); + return this; + } + + @Override + protected void _setMedium(int index, int value) { + buffer.setMedium(index, value); + } + + @Override + public ByteBuf setInt(int index, int value) { + _setInt(index, value); + return this; + } + + @Override + protected void _setInt(int index, int value) { + buffer.setInt(index, value); + } + + @Override + public ByteBuf setLong(int index, long value) { + _setLong(index, value); + return this; + } + + @Override + protected void _setLong(int index, long value) { + buffer.setLong(index, value); + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + buffer.setBytes(index, src, srcIndex, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + buffer.setBytes(index, src, srcIndex, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + buffer.setBytes(index, src); + return this; + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) + throws IOException { + buffer.getBytes(index, out, length); + return this; + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) + throws IOException { + return buffer.getBytes(index, out, length); + } + + @Override + public int setBytes(int index, InputStream in, int length) + throws IOException { + return buffer.setBytes(index, in, length); + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) + throws IOException { + return buffer.setBytes(index, in, length); + } + + @Override + public int nioBufferCount() { + return buffer.nioBufferCount(); + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + return buffer.nioBuffers(index, length); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + return nioBuffer(index, length); + } + + @Override + public int forEachByte(int index, int length, ByteBufProcessor processor) { + return buffer.forEachByte(index, length, processor); + } + + @Override + public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { + return buffer.forEachByteDesc(index, length, processor); + } +} + diff --git a/common/src/main/java/common/net/buffer/EmptyByteBuf.java b/common/src/main/java/common/net/buffer/EmptyByteBuf.java new file mode 100644 index 0000000..6c48eea --- /dev/null +++ b/common/src/main/java/common/net/buffer/EmptyByteBuf.java @@ -0,0 +1,842 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.ReadOnlyBufferException; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; +import java.nio.charset.Charset; + +import common.net.util.internal.EmptyArrays; +import common.net.util.internal.StringUtil; + +/** + * An empty {@link ByteBuf} whose capacity and maximum capacity are all {@code 0}. + */ +public final class EmptyByteBuf extends ByteBuf { + + private static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.allocateDirect(0); + + private final ByteBufAllocator alloc; + private final ByteOrder order; + private final String str; + private EmptyByteBuf swapped; + + public EmptyByteBuf(ByteBufAllocator alloc) { + this(alloc, ByteOrder.BIG_ENDIAN); + } + + private EmptyByteBuf(ByteBufAllocator alloc, ByteOrder order) { + if (alloc == null) { + throw new NullPointerException("alloc"); + } + + this.alloc = alloc; + this.order = order; + str = StringUtil.simpleClassName(this) + (order == ByteOrder.BIG_ENDIAN? "BE" : "LE"); + } + + @Override + public int capacity() { + return 0; + } + + @Override + public ByteBuf capacity(int newCapacity) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBufAllocator alloc() { + return alloc; + } + + @Override + public ByteOrder order() { + return order; + } + + @Override + public ByteBuf unwrap() { + return null; + } + + @Override + public boolean isDirect() { + return true; + } + + @Override + public int maxCapacity() { + return 0; + } + + @Override + public ByteBuf order(ByteOrder endianness) { + if (endianness == null) { + throw new NullPointerException("endianness"); + } + if (endianness == order()) { + return this; + } + + EmptyByteBuf swapped = this.swapped; + if (swapped != null) { + return swapped; + } + + this.swapped = swapped = new EmptyByteBuf(alloc(), endianness); + return swapped; + } + + @Override + public int readerIndex() { + return 0; + } + + @Override + public ByteBuf readerIndex(int readerIndex) { + return checkIndex(readerIndex); + } + + @Override + public int writerIndex() { + return 0; + } + + @Override + public ByteBuf writerIndex(int writerIndex) { + return checkIndex(writerIndex); + } + + @Override + public ByteBuf setIndex(int readerIndex, int writerIndex) { + checkIndex(readerIndex); + checkIndex(writerIndex); + return this; + } + + @Override + public int readableBytes() { + return 0; + } + + @Override + public int writableBytes() { + return 0; + } + + @Override + public int maxWritableBytes() { + return 0; + } + + @Override + public boolean isReadable() { + return false; + } + + @Override + public boolean isWritable() { + return false; + } + + @Override + public ByteBuf clear() { + return this; + } + + @Override + public ByteBuf markReaderIndex() { + return this; + } + + @Override + public ByteBuf resetReaderIndex() { + return this; + } + + @Override + public ByteBuf markWriterIndex() { + return this; + } + + @Override + public ByteBuf resetWriterIndex() { + return this; + } + + @Override + public ByteBuf discardReadBytes() { + return this; + } + + @Override + public ByteBuf discardSomeReadBytes() { + return this; + } + + @Override + public ByteBuf ensureWritable(int minWritableBytes) { + if (minWritableBytes < 0) { + throw new IllegalArgumentException("minWritableBytes: " + minWritableBytes + " (expected: >= 0)"); + } + if (minWritableBytes != 0) { + throw new IndexOutOfBoundsException(); + } + return this; + } + + @Override + public int ensureWritable(int minWritableBytes, boolean force) { + if (minWritableBytes < 0) { + throw new IllegalArgumentException("minWritableBytes: " + minWritableBytes + " (expected: >= 0)"); + } + + if (minWritableBytes == 0) { + return 0; + } + + return 1; + } + + @Override + public boolean getBoolean(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public byte getByte(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public short getUnsignedByte(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public short getShort(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public int getUnsignedShort(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public int getMedium(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public int getUnsignedMedium(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public int getInt(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public long getUnsignedInt(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public long getLong(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public char getChar(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public float getFloat(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public double getDouble(int index) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst) { + return checkIndex(index, dst.writableBytes()); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int length) { + return checkIndex(index, length); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + return checkIndex(index, length); + } + + @Override + public ByteBuf getBytes(int index, byte[] dst) { + return checkIndex(index, dst.length); + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + return checkIndex(index, length); + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + return checkIndex(index, dst.remaining()); + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) { + return checkIndex(index, length); + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) { + checkIndex(index, length); + return 0; + } + + @Override + public ByteBuf setBoolean(int index, boolean value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf setByte(int index, int value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf setShort(int index, int value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf setMedium(int index, int value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf setInt(int index, int value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf setLong(int index, long value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf setChar(int index, int value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf setFloat(int index, float value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf setDouble(int index, double value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int length) { + return checkIndex(index, length); + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + return checkIndex(index, length); + } + + @Override + public ByteBuf setBytes(int index, byte[] src) { + return checkIndex(index, src.length); + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + return checkIndex(index, length); + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + return checkIndex(index, src.remaining()); + } + + @Override + public int setBytes(int index, InputStream in, int length) { + checkIndex(index, length); + return 0; + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) { + checkIndex(index, length); + return 0; + } + + @Override + public ByteBuf setZero(int index, int length) { + return checkIndex(index, length); + } + + @Override + public boolean readBoolean() { + throw new IndexOutOfBoundsException(); + } + + @Override + public byte readByte() { + throw new IndexOutOfBoundsException(); + } + + @Override + public short readUnsignedByte() { + throw new IndexOutOfBoundsException(); + } + + @Override + public short readShort() { + throw new IndexOutOfBoundsException(); + } + + @Override + public int readUnsignedShort() { + throw new IndexOutOfBoundsException(); + } + + @Override + public int readMedium() { + throw new IndexOutOfBoundsException(); + } + + @Override + public int readUnsignedMedium() { + throw new IndexOutOfBoundsException(); + } + + @Override + public int readInt() { + throw new IndexOutOfBoundsException(); + } + + @Override + public long readUnsignedInt() { + throw new IndexOutOfBoundsException(); + } + + @Override + public long readLong() { + throw new IndexOutOfBoundsException(); + } + + @Override + public char readChar() { + throw new IndexOutOfBoundsException(); + } + + @Override + public float readFloat() { + throw new IndexOutOfBoundsException(); + } + + @Override + public double readDouble() { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf readBytes(int length) { + return checkLength(length); + } + + @Override + public ByteBuf readSlice(int length) { + return checkLength(length); + } + + @Override + public ByteBuf readBytes(ByteBuf dst) { + return checkLength(dst.writableBytes()); + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int length) { + return checkLength(length); + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { + return checkLength(length); + } + + @Override + public ByteBuf readBytes(byte[] dst) { + return checkLength(dst.length); + } + + @Override + public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { + return checkLength(length); + } + + @Override + public ByteBuf readBytes(ByteBuffer dst) { + return checkLength(dst.remaining()); + } + + @Override + public ByteBuf readBytes(OutputStream out, int length) { + return checkLength(length); + } + + @Override + public int readBytes(GatheringByteChannel out, int length) { + checkLength(length); + return 0; + } + + @Override + public ByteBuf skipBytes(int length) { + return checkLength(length); + } + + @Override + public ByteBuf writeBoolean(boolean value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf writeByte(int value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf writeShort(int value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf writeMedium(int value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf writeInt(int value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf writeLong(long value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf writeChar(int value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf writeFloat(float value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf writeDouble(double value) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf writeBytes(ByteBuf src) { + throw new IndexOutOfBoundsException(); + } + + @Override + public ByteBuf writeBytes(ByteBuf src, int length) { + return checkLength(length); + } + + @Override + public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { + return checkLength(length); + } + + @Override + public ByteBuf writeBytes(byte[] src) { + return checkLength(src.length); + } + + @Override + public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { + return checkLength(length); + } + + @Override + public ByteBuf writeBytes(ByteBuffer src) { + return checkLength(src.remaining()); + } + + @Override + public int writeBytes(InputStream in, int length) { + checkLength(length); + return 0; + } + + @Override + public int writeBytes(ScatteringByteChannel in, int length) { + checkLength(length); + return 0; + } + + @Override + public ByteBuf writeZero(int length) { + return checkLength(length); + } + + @Override + public int indexOf(int fromIndex, int toIndex, byte value) { + checkIndex(fromIndex); + checkIndex(toIndex); + return -1; + } + + @Override + public int bytesBefore(byte value) { + return -1; + } + + @Override + public int bytesBefore(int length, byte value) { + checkLength(length); + return -1; + } + + @Override + public int bytesBefore(int index, int length, byte value) { + checkIndex(index, length); + return -1; + } + + @Override + public int forEachByte(ByteBufProcessor processor) { + return -1; + } + + @Override + public int forEachByte(int index, int length, ByteBufProcessor processor) { + checkIndex(index, length); + return -1; + } + + @Override + public int forEachByteDesc(ByteBufProcessor processor) { + return -1; + } + + @Override + public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { + checkIndex(index, length); + return -1; + } + + @Override + public ByteBuf copy() { + return this; + } + + @Override + public ByteBuf copy(int index, int length) { + return checkIndex(index, length); + } + + @Override + public ByteBuf slice() { + return this; + } + + @Override + public ByteBuf slice(int index, int length) { + return checkIndex(index, length); + } + + @Override + public ByteBuf duplicate() { + return this; + } + + @Override + public int nioBufferCount() { + return 1; + } + + @Override + public ByteBuffer nioBuffer() { + return EMPTY_BYTE_BUFFER; + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + checkIndex(index, length); + return nioBuffer(); + } + + @Override + public ByteBuffer[] nioBuffers() { + return new ByteBuffer[] { EMPTY_BYTE_BUFFER }; + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + checkIndex(index, length); + return nioBuffers(); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + return EMPTY_BYTE_BUFFER; + } + + @Override + public boolean hasArray() { + return true; + } + + @Override + public byte[] array() { + return EmptyArrays.EMPTY_BYTES; + } + + @Override + public int arrayOffset() { + return 0; + } + + @Override + public String toString(Charset charset) { + return ""; + } + + @Override + public String toString(int index, int length, Charset charset) { + checkIndex(index, length); + return toString(charset); + } + + @Override + public int hashCode() { + return 0; + } + + @Override + public boolean equals(Object obj) { + return obj instanceof ByteBuf && !((ByteBuf) obj).isReadable(); + } + + @Override + public int compareTo(ByteBuf buffer) { + return buffer.isReadable()? -1 : 0; + } + + @Override + public String toString() { + return str; + } + + @Override + public boolean isReadable(int size) { + return false; + } + + @Override + public boolean isWritable(int size) { + return false; + } + + @Override + public int refCnt() { + return 1; + } + + @Override + public ByteBuf retain() { + return this; + } + + @Override + public ByteBuf retain(int increment) { + return this; + } + + @Override + public boolean release() { + return false; + } + + @Override + public boolean release(int decrement) { + return false; + } + + private ByteBuf checkIndex(int index) { + if (index != 0) { + throw new IndexOutOfBoundsException(); + } + return this; + } + + private ByteBuf checkIndex(int index, int length) { + if (length < 0) { + throw new IllegalArgumentException("length: " + length); + } + if (index != 0 || length != 0) { + throw new IndexOutOfBoundsException(); + } + return this; + } + + private ByteBuf checkLength(int length) { + if (length < 0) { + throw new IllegalArgumentException("length: " + length + " (expected: >= 0)"); + } + if (length != 0) { + throw new IndexOutOfBoundsException(); + } + return this; + } +} diff --git a/common/src/main/java/common/net/buffer/PoolArena.java b/common/src/main/java/common/net/buffer/PoolArena.java new file mode 100644 index 0000000..6752ab3 --- /dev/null +++ b/common/src/main/java/common/net/buffer/PoolArena.java @@ -0,0 +1,462 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import java.nio.ByteBuffer; + +import common.net.util.internal.StringUtil; + +abstract class PoolArena { + + static final int numTinySubpagePools = 512 >>> 4; + + final PooledByteBufAllocator parent; + + private final int maxOrder; + final int pageSize; + final int pageShifts; + final int chunkSize; + final int subpageOverflowMask; + final int numSmallSubpagePools; + private final PoolSubpage[] tinySubpagePools; + private final PoolSubpage[] smallSubpagePools; + + private final PoolChunkList q050; + private final PoolChunkList q025; + private final PoolChunkList q000; + private final PoolChunkList qInit; + private final PoolChunkList q075; + private final PoolChunkList q100; + + // TODO: Test if adding padding helps under contention + //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; + + protected PoolArena(PooledByteBufAllocator parent, int pageSize, int maxOrder, int pageShifts, int chunkSize) { + this.parent = parent; + this.pageSize = pageSize; + this.maxOrder = maxOrder; + this.pageShifts = pageShifts; + this.chunkSize = chunkSize; + subpageOverflowMask = ~(pageSize - 1); + tinySubpagePools = newSubpagePoolArray(numTinySubpagePools); + for (int i = 0; i < tinySubpagePools.length; i ++) { + tinySubpagePools[i] = newSubpagePoolHead(pageSize); + } + + numSmallSubpagePools = pageShifts - 9; + smallSubpagePools = newSubpagePoolArray(numSmallSubpagePools); + for (int i = 0; i < smallSubpagePools.length; i ++) { + smallSubpagePools[i] = newSubpagePoolHead(pageSize); + } + + q100 = new PoolChunkList(this, null, 100, Integer.MAX_VALUE); + q075 = new PoolChunkList(this, q100, 75, 100); + q050 = new PoolChunkList(this, q075, 50, 100); + q025 = new PoolChunkList(this, q050, 25, 75); + q000 = new PoolChunkList(this, q025, 1, 50); + qInit = new PoolChunkList(this, q000, Integer.MIN_VALUE, 25); + + q100.prevList = q075; + q075.prevList = q050; + q050.prevList = q025; + q025.prevList = q000; + q000.prevList = null; + qInit.prevList = qInit; + } + + private PoolSubpage newSubpagePoolHead(int pageSize) { + PoolSubpage head = new PoolSubpage(pageSize); + head.prev = head; + head.next = head; + return head; + } + + + private PoolSubpage[] newSubpagePoolArray(int size) { + return new PoolSubpage[size]; + } + + abstract boolean isDirect(); + + PooledByteBuf allocate(PoolThreadCache cache, int reqCapacity, int maxCapacity) { + PooledByteBuf buf = newByteBuf(maxCapacity); + allocate(cache, buf, reqCapacity); + return buf; + } + + static int tinyIdx(int normCapacity) { + return normCapacity >>> 4; + } + + static int smallIdx(int normCapacity) { + int tableIdx = 0; + int i = normCapacity >>> 10; + while (i != 0) { + i >>>= 1; + tableIdx ++; + } + return tableIdx; + } + + // capacity < pageSize + boolean isTinyOrSmall(int normCapacity) { + return (normCapacity & subpageOverflowMask) == 0; + } + + // normCapacity < 512 + static boolean isTiny(int normCapacity) { + return (normCapacity & 0xFFFFFE00) == 0; + } + + private void allocate(PoolThreadCache cache, PooledByteBuf buf, final int reqCapacity) { + final int normCapacity = normalizeCapacity(reqCapacity); + if (isTinyOrSmall(normCapacity)) { // capacity < pageSize + int tableIdx; + PoolSubpage[] table; + if (isTiny(normCapacity)) { // < 512 + if (cache.allocateTiny(this, buf, reqCapacity, normCapacity)) { + // was able to allocate out of the cache so move on + return; + } + tableIdx = tinyIdx(normCapacity); + table = tinySubpagePools; + } else { + if (cache.allocateSmall(this, buf, reqCapacity, normCapacity)) { + // was able to allocate out of the cache so move on + return; + } + tableIdx = smallIdx(normCapacity); + table = smallSubpagePools; + } + + synchronized (this) { + final PoolSubpage head = table[tableIdx]; + final PoolSubpage s = head.next; + if (s != head) { + assert s.doNotDestroy && s.elemSize == normCapacity; + long handle = s.allocate(); + assert handle >= 0; + s.chunk.initBufWithSubpage(buf, handle, reqCapacity); + return; + } + } + } else if (normCapacity <= chunkSize) { + if (cache.allocateNormal(this, buf, reqCapacity, normCapacity)) { + // was able to allocate out of the cache so move on + return; + } + } else { + // Huge allocations are never served via the cache so just call allocateHuge + allocateHuge(buf, reqCapacity); + return; + } + allocateNormal(buf, reqCapacity, normCapacity); + } + + private synchronized void allocateNormal(PooledByteBuf buf, int reqCapacity, int normCapacity) { + if (q050.allocate(buf, reqCapacity, normCapacity) || q025.allocate(buf, reqCapacity, normCapacity) || + q000.allocate(buf, reqCapacity, normCapacity) || qInit.allocate(buf, reqCapacity, normCapacity) || + q075.allocate(buf, reqCapacity, normCapacity) || q100.allocate(buf, reqCapacity, normCapacity)) { + return; + } + + // Add a new chunk. + PoolChunk c = newChunk(pageSize, maxOrder, pageShifts, chunkSize); + long handle = c.allocate(normCapacity); + assert handle > 0; + c.initBuf(buf, handle, reqCapacity); + qInit.add(c); + } + + private void allocateHuge(PooledByteBuf buf, int reqCapacity) { + buf.initUnpooled(newUnpooledChunk(reqCapacity), reqCapacity); + } + + void free(PoolChunk chunk, long handle, int normCapacity) { + if (chunk.unpooled) { + destroyChunk(chunk); + } else { + PoolThreadCache cache = parent.threadCache.get(); + if (cache.add(this, chunk, handle, normCapacity)) { + // cached so not free it. + return; + } + synchronized (this) { + chunk.parent.free(chunk, handle); + } + } + } + + PoolSubpage findSubpagePoolHead(int elemSize) { + int tableIdx; + PoolSubpage[] table; + if (isTiny(elemSize)) { // < 512 + tableIdx = elemSize >>> 4; + table = tinySubpagePools; + } else { + tableIdx = 0; + elemSize >>>= 10; + while (elemSize != 0) { + elemSize >>>= 1; + tableIdx ++; + } + table = smallSubpagePools; + } + + return table[tableIdx]; + } + + int normalizeCapacity(int reqCapacity) { + if (reqCapacity < 0) { + throw new IllegalArgumentException("capacity: " + reqCapacity + " (expected: 0+)"); + } + if (reqCapacity >= chunkSize) { + return reqCapacity; + } + + if (!isTiny(reqCapacity)) { // >= 512 + // Doubled + + int normalizedCapacity = reqCapacity; + normalizedCapacity --; + normalizedCapacity |= normalizedCapacity >>> 1; + normalizedCapacity |= normalizedCapacity >>> 2; + normalizedCapacity |= normalizedCapacity >>> 4; + normalizedCapacity |= normalizedCapacity >>> 8; + normalizedCapacity |= normalizedCapacity >>> 16; + normalizedCapacity ++; + + if (normalizedCapacity < 0) { + normalizedCapacity >>>= 1; + } + + return normalizedCapacity; + } + + // Quantum-spaced + if ((reqCapacity & 15) == 0) { + return reqCapacity; + } + + return (reqCapacity & ~15) + 16; + } + + void reallocate(PooledByteBuf buf, int newCapacity, boolean freeOldMemory) { + if (newCapacity < 0 || newCapacity > buf.maxCapacity()) { + throw new IllegalArgumentException("newCapacity: " + newCapacity); + } + + int oldCapacity = buf.length; + if (oldCapacity == newCapacity) { + return; + } + + PoolChunk oldChunk = buf.chunk; + long oldHandle = buf.handle; + T oldMemory = buf.memory; + int oldOffset = buf.offset; + int oldMaxLength = buf.maxLength; + int readerIndex = buf.readerIndex(); + int writerIndex = buf.writerIndex(); + + allocate(parent.threadCache.get(), buf, newCapacity); + if (newCapacity > oldCapacity) { + memoryCopy( + oldMemory, oldOffset, + buf.memory, buf.offset, oldCapacity); + } else if (newCapacity < oldCapacity) { + if (readerIndex < newCapacity) { + if (writerIndex > newCapacity) { + writerIndex = newCapacity; + } + memoryCopy( + oldMemory, oldOffset + readerIndex, + buf.memory, buf.offset + readerIndex, writerIndex - readerIndex); + } else { + readerIndex = writerIndex = newCapacity; + } + } + + buf.setIndex(readerIndex, writerIndex); + + if (freeOldMemory) { + free(oldChunk, oldHandle, oldMaxLength); + } + } + + protected abstract PoolChunk newChunk(int pageSize, int maxOrder, int pageShifts, int chunkSize); + protected abstract PoolChunk newUnpooledChunk(int capacity); + protected abstract PooledByteBuf newByteBuf(int maxCapacity); + protected abstract void memoryCopy(T src, int srcOffset, T dst, int dstOffset, int length); + protected abstract void destroyChunk(PoolChunk chunk); + + public synchronized String toString() { + StringBuilder buf = new StringBuilder(); + buf.append("Chunk(s) at 0~25%:"); + buf.append(StringUtil.NEWLINE); + buf.append(qInit); + buf.append(StringUtil.NEWLINE); + buf.append("Chunk(s) at 0~50%:"); + buf.append(StringUtil.NEWLINE); + buf.append(q000); + buf.append(StringUtil.NEWLINE); + buf.append("Chunk(s) at 25~75%:"); + buf.append(StringUtil.NEWLINE); + buf.append(q025); + buf.append(StringUtil.NEWLINE); + buf.append("Chunk(s) at 50~100%:"); + buf.append(StringUtil.NEWLINE); + buf.append(q050); + buf.append(StringUtil.NEWLINE); + buf.append("Chunk(s) at 75~100%:"); + buf.append(StringUtil.NEWLINE); + buf.append(q075); + buf.append(StringUtil.NEWLINE); + buf.append("Chunk(s) at 100%:"); + buf.append(StringUtil.NEWLINE); + buf.append(q100); + buf.append(StringUtil.NEWLINE); + buf.append("tiny subpages:"); + for (int i = 1; i < tinySubpagePools.length; i ++) { + PoolSubpage head = tinySubpagePools[i]; + if (head.next == head) { + continue; + } + + buf.append(StringUtil.NEWLINE); + buf.append(i); + buf.append(": "); + PoolSubpage s = head.next; + for (;;) { + buf.append(s); + s = s.next; + if (s == head) { + break; + } + } + } + buf.append(StringUtil.NEWLINE); + buf.append("small subpages:"); + for (int i = 1; i < smallSubpagePools.length; i ++) { + PoolSubpage head = smallSubpagePools[i]; + if (head.next == head) { + continue; + } + + buf.append(StringUtil.NEWLINE); + buf.append(i); + buf.append(": "); + PoolSubpage s = head.next; + for (;;) { + buf.append(s); + s = s.next; + if (s == head) { + break; + } + } + } + buf.append(StringUtil.NEWLINE); + + return buf.toString(); + } + + static final class HeapArena extends PoolArena { + + HeapArena(PooledByteBufAllocator parent, int pageSize, int maxOrder, int pageShifts, int chunkSize) { + super(parent, pageSize, maxOrder, pageShifts, chunkSize); + } + + @Override + boolean isDirect() { + return false; + } + + @Override + protected PoolChunk newChunk(int pageSize, int maxOrder, int pageShifts, int chunkSize) { + return new PoolChunk(this, new byte[chunkSize], pageSize, maxOrder, pageShifts, chunkSize); + } + + @Override + protected PoolChunk newUnpooledChunk(int capacity) { + return new PoolChunk(this, new byte[capacity], capacity); + } + + @Override + protected void destroyChunk(PoolChunk chunk) { + // Rely on GC. + } + + @Override + protected PooledByteBuf newByteBuf(int maxCapacity) { + return PooledHeapByteBuf.newInstance(maxCapacity); + } + + @Override + protected void memoryCopy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int length) { + if (length == 0) { + return; + } + + System.arraycopy(src, srcOffset, dst, dstOffset, length); + } + } + + static final class DirectArena extends PoolArena { + DirectArena(PooledByteBufAllocator parent, int pageSize, int maxOrder, int pageShifts, int chunkSize) { + super(parent, pageSize, maxOrder, pageShifts, chunkSize); + } + + @Override + boolean isDirect() { + return true; + } + + @Override + protected PoolChunk newChunk(int pageSize, int maxOrder, int pageShifts, int chunkSize) { + return new PoolChunk( + this, ByteBuffer.allocateDirect(chunkSize), pageSize, maxOrder, pageShifts, chunkSize); + } + + @Override + protected PoolChunk newUnpooledChunk(int capacity) { + return new PoolChunk(this, ByteBuffer.allocateDirect(capacity), capacity); + } + + @Override + protected void destroyChunk(PoolChunk chunk) { + } + + @Override + protected PooledByteBuf newByteBuf(int maxCapacity) { + return PooledDirectByteBuf.newInstance(maxCapacity); + } + + @Override + protected void memoryCopy(ByteBuffer src, int srcOffset, ByteBuffer dst, int dstOffset, int length) { + if (length == 0) { + return; + } + + // We must duplicate the NIO buffers because they may be accessed by other Netty buffers. + src = src.duplicate(); + dst = dst.duplicate(); + src.position(srcOffset).limit(srcOffset + length); + dst.position(dstOffset); + dst.put(src); + } + } +} diff --git a/common/src/main/java/common/net/buffer/PoolChunk.java b/common/src/main/java/common/net/buffer/PoolChunk.java new file mode 100644 index 0000000..87234ec --- /dev/null +++ b/common/src/main/java/common/net/buffer/PoolChunk.java @@ -0,0 +1,431 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +/** + * Description of algorithm for PageRun/PoolSubpage allocation from PoolChunk + * + * Notation: The following terms are important to understand the code + * > page - a page is the smallest unit of memory chunk that can be allocated + * > chunk - a chunk is a collection of pages + * > in this code chunkSize = 2^{maxOrder} * pageSize + * + * To begin we allocate a byte array of size = chunkSize + * Whenever a ByteBuf of given size needs to be created we search for the first position + * in the byte array that has enough empty space to accommodate the requested size and + * return a (long) handle that encodes this offset information, (this memory segment is then + * marked as reserved so it is always used by exactly one ByteBuf and no more) + * + * For simplicity all sizes are normalized according to PoolArena#normalizeCapacity method + * This ensures that when we request for memory segments of size >= pageSize the normalizedCapacity + * equals the next nearest power of 2 + * + * To search for the first offset in chunk that has at least requested size available we construct a + * complete balanced binary tree and store it in an array (just like heaps) - memoryMap + * + * The tree looks like this (the size of each node being mentioned in the parenthesis) + * + * depth=0 1 node (chunkSize) + * depth=1 2 nodes (chunkSize/2) + * .. + * .. + * depth=d 2^d nodes (chunkSize/2^d) + * .. + * depth=maxOrder 2^maxOrder nodes (chunkSize/2^{maxOrder} = pageSize) + * + * depth=maxOrder is the last level and the leafs consist of pages + * + * With this tree available searching in chunkArray translates like this: + * To allocate a memory segment of size chunkSize/2^k we search for the first node (from left) at height k + * which is unused + * + * Algorithm: + * ---------- + * Encode the tree in memoryMap with the notation + * memoryMap[id] = x => in the subtree rooted at id, the first node that is free to be allocated + * is at depth x (counted from depth=0) i.e., at depths [depth_of_id, x), there is no node that is free + * + * As we allocate & free nodes, we update values stored in memoryMap so that the property is maintained + * + * Initialization - + * In the beginning we construct the memoryMap array by storing the depth of a node at each node + * i.e., memoryMap[id] = depth_of_id + * + * Observations: + * ------------- + * 1) memoryMap[id] = depth_of_id => it is free / unallocated + * 2) memoryMap[id] > depth_of_id => at least one of its child nodes is allocated, so we cannot allocate it, but + * some of its children can still be allocated based on their availability + * 3) memoryMap[id] = maxOrder + 1 => the node is fully allocated & thus none of its children can be allocated, it + * is thus marked as unusable + * + * Algorithm: [allocateNode(d) => we want to find the first node (from left) at height h that can be allocated] + * ---------- + * 1) start at root (i.e., depth = 0 or id = 1) + * 2) if memoryMap[1] > d => cannot be allocated from this chunk + * 3) if left node value <= h; we can allocate from left subtree so move to left and repeat until found + * 4) else try in right subtree + * + * Algorithm: [allocateRun(size)] + * ---------- + * 1) Compute d = log_2(chunkSize/size) + * 2) Return allocateNode(d) + * + * Algorithm: [allocateSubpage(size)] + * ---------- + * 1) use allocateNode(maxOrder) to find an empty (i.e., unused) leaf (i.e., page) + * 2) use this handle to construct the PoolSubpage object or if it already exists just call init(normCapacity) + * note that this PoolSubpage object is added to subpagesPool in the PoolArena when we init() it + * + * Note: + * ----- + * In the implementation for improving cache coherence, + * we store 2 pieces of information (i.e, 2 byte vals) as a short value in memoryMap + * + * memoryMap[id]= (depth_of_id, x) + * where as per convention defined above + * the second value (i.e, x) indicates that the first node which is free to be allocated is at depth x (from root) + */ + +final class PoolChunk { + + final PoolArena arena; + final T memory; + final boolean unpooled; + + private final byte[] memoryMap; + private final byte[] depthMap; + private final PoolSubpage[] subpages; + /** Used to determine if the requested capacity is equal to or greater than pageSize. */ + private final int subpageOverflowMask; + private final int pageSize; + private final int pageShifts; + private final int maxOrder; + private final int chunkSize; + private final int log2ChunkSize; + private final int maxSubpageAllocs; + /** Used to mark memory as unusable */ + private final byte unusable; + + private int freeBytes; + + PoolChunkList parent; + PoolChunk prev; + PoolChunk next; + + // TODO: Test if adding padding helps under contention + //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; + + PoolChunk(PoolArena arena, T memory, int pageSize, int maxOrder, int pageShifts, int chunkSize) { + unpooled = false; + this.arena = arena; + this.memory = memory; + this.pageSize = pageSize; + this.pageShifts = pageShifts; + this.maxOrder = maxOrder; + this.chunkSize = chunkSize; + unusable = (byte) (maxOrder + 1); + log2ChunkSize = log2(chunkSize); + subpageOverflowMask = ~(pageSize - 1); + freeBytes = chunkSize; + + assert maxOrder < 30 : "maxOrder should be < 30, but is: " + maxOrder; + maxSubpageAllocs = 1 << maxOrder; + + // Generate the memory map. + memoryMap = new byte[maxSubpageAllocs << 1]; + depthMap = new byte[memoryMap.length]; + int memoryMapIndex = 1; + for (int d = 0; d <= maxOrder; ++ d) { // move down the tree one level at a time + int depth = 1 << d; + for (int p = 0; p < depth; ++ p) { + // in each level traverse left to right and set value to the depth of subtree + memoryMap[memoryMapIndex] = (byte) d; + depthMap[memoryMapIndex] = (byte) d; + memoryMapIndex ++; + } + } + + subpages = newSubpageArray(maxSubpageAllocs); + } + + /** Creates a special chunk that is not pooled. */ + PoolChunk(PoolArena arena, T memory, int size) { + unpooled = true; + this.arena = arena; + this.memory = memory; + memoryMap = null; + depthMap = null; + subpages = null; + subpageOverflowMask = 0; + pageSize = 0; + pageShifts = 0; + maxOrder = 0; + unusable = (byte) (maxOrder + 1); + chunkSize = size; + log2ChunkSize = log2(chunkSize); + maxSubpageAllocs = 0; + } + + + private PoolSubpage[] newSubpageArray(int size) { + return new PoolSubpage[size]; + } + + int usage() { + final int freeBytes = this.freeBytes; + if (freeBytes == 0) { + return 100; + } + + int freePercentage = (int) (freeBytes * 100L / chunkSize); + if (freePercentage == 0) { + return 99; + } + return 100 - freePercentage; + } + + long allocate(int normCapacity) { + if ((normCapacity & subpageOverflowMask) != 0) { // >= pageSize + return allocateRun(normCapacity); + } else { + return allocateSubpage(normCapacity); + } + } + + /** + * Update method used by allocate + * This is triggered only when a successor is allocated and all its predecessors + * need to update their state + * The minimal depth at which subtree rooted at id has some free space + * + * @param id id + */ + private void updateParentsAlloc(int id) { + while (id > 1) { + int parentId = id >>> 1; + byte val1 = value(id); + byte val2 = value(id ^ 1); + byte val = val1 < val2 ? val1 : val2; + setValue(parentId, val); + id = parentId; + } + } + + /** + * Update method used by free + * This needs to handle the special case when both children are completely free + * in which case parent be directly allocated on request of size = child-size * 2 + * + * @param id id + */ + private void updateParentsFree(int id) { + int logChild = depth(id) + 1; + while (id > 1) { + int parentId = id >>> 1; + byte val1 = value(id); + byte val2 = value(id ^ 1); + logChild -= 1; // in first iteration equals log, subsequently reduce 1 from logChild as we traverse up + + if (val1 == logChild && val2 == logChild) { + setValue(parentId, (byte) (logChild - 1)); + } else { + byte val = val1 < val2 ? val1 : val2; + setValue(parentId, val); + } + + id = parentId; + } + } + + /** + * Algorithm to allocate an index in memoryMap when we query for a free node + * at depth d + * + * @param d depth + * @return index in memoryMap + */ + private int allocateNode(int d) { + int id = 1; + int initial = - (1 << d); // has last d bits = 0 and rest all = 1 + byte val = value(id); + if (val > d) { // unusable + return -1; + } + while (val < d || (id & initial) == 0) { // id & initial == 1 << d for all ids at depth d, for < d it is 0 + id <<= 1; + val = value(id); + if (val > d) { + id ^= 1; + val = value(id); + } + } + byte value = value(id); + assert value == d && (id & initial) == 1 << d : String.format("val = %d, id & initial = %d, d = %d", + value, id & initial, d); + setValue(id, unusable); // mark as unusable + updateParentsAlloc(id); + return id; + } + + /** + * Allocate a run of pages (>=1) + * + * @param normCapacity normalized capacity + * @return index in memoryMap + */ + private long allocateRun(int normCapacity) { + int d = maxOrder - (log2(normCapacity) - pageShifts); + int id = allocateNode(d); + if (id < 0) { + return id; + } + freeBytes -= runLength(id); + return id; + } + + /** + * Create/ initialize a new PoolSubpage of normCapacity + * Any PoolSubpage created/ initialized here is added to subpage pool in the PoolArena that owns this PoolChunk + * + * @param normCapacity normalized capacity + * @return index in memoryMap + */ + private long allocateSubpage(int normCapacity) { + int d = maxOrder; // subpages are only be allocated from pages i.e., leaves + int id = allocateNode(d); + if (id < 0) { + return id; + } + + final PoolSubpage[] subpages = this.subpages; + final int pageSize = this.pageSize; + + freeBytes -= pageSize; + + int subpageIdx = subpageIdx(id); + PoolSubpage subpage = subpages[subpageIdx]; + if (subpage == null) { + subpage = new PoolSubpage(this, id, runOffset(id), pageSize, normCapacity); + subpages[subpageIdx] = subpage; + } else { + subpage.init(normCapacity); + } + return subpage.allocate(); + } + + /** + * Free a subpage or a run of pages + * When a subpage is freed from PoolSubpage, it might be added back to subpage pool of the owning PoolArena + * If the subpage pool in PoolArena has at least one other PoolSubpage of given elemSize, we can + * completely free the owning Page so it is available for subsequent allocations + * + * @param handle handle to free + */ + void free(long handle) { + int memoryMapIdx = (int) handle; + int bitmapIdx = (int) (handle >>> Integer.SIZE); + + if (bitmapIdx != 0) { // free a subpage + PoolSubpage subpage = subpages[subpageIdx(memoryMapIdx)]; + assert subpage != null && subpage.doNotDestroy; + if (subpage.free(bitmapIdx & 0x3FFFFFFF)) { + return; + } + } + freeBytes += runLength(memoryMapIdx); + setValue(memoryMapIdx, depth(memoryMapIdx)); + updateParentsFree(memoryMapIdx); + } + + void initBuf(PooledByteBuf buf, long handle, int reqCapacity) { + int memoryMapIdx = (int) handle; + int bitmapIdx = (int) (handle >>> Integer.SIZE); + if (bitmapIdx == 0) { + byte val = value(memoryMapIdx); + assert val == unusable : String.valueOf(val); + buf.init(this, handle, runOffset(memoryMapIdx), reqCapacity, runLength(memoryMapIdx)); + } else { + initBufWithSubpage(buf, handle, bitmapIdx, reqCapacity); + } + } + + void initBufWithSubpage(PooledByteBuf buf, long handle, int reqCapacity) { + initBufWithSubpage(buf, handle, (int) (handle >>> Integer.SIZE), reqCapacity); + } + + private void initBufWithSubpage(PooledByteBuf buf, long handle, int bitmapIdx, int reqCapacity) { + assert bitmapIdx != 0; + + int memoryMapIdx = (int) handle; + + PoolSubpage subpage = subpages[subpageIdx(memoryMapIdx)]; + assert subpage.doNotDestroy; + assert reqCapacity <= subpage.elemSize; + + buf.init( + this, handle, + runOffset(memoryMapIdx) + (bitmapIdx & 0x3FFFFFFF) * subpage.elemSize, reqCapacity, subpage.elemSize); + } + + private byte value(int id) { + return memoryMap[id]; + } + + private void setValue(int id, byte val) { + memoryMap[id] = val; + } + + private byte depth(int id) { + return depthMap[id]; + } + + private static int log2(int val) { + // compute the (0-based, with lsb = 0) position of highest set bit i.e, log2 + return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(val); + } + + private int runLength(int id) { + // represents the size in #bytes supported by node 'id' in the tree + return 1 << log2ChunkSize - depth(id); + } + + private int runOffset(int id) { + // represents the 0-based offset in #bytes from start of the byte-array chunk + int shift = id ^ 1 << depth(id); + return shift * runLength(id); + } + + private int subpageIdx(int memoryMapIdx) { + return memoryMapIdx ^ maxSubpageAllocs; // remove highest set bit, to get offset + } + + @Override + public String toString() { + StringBuilder buf = new StringBuilder(); + buf.append("Chunk("); + buf.append(Integer.toHexString(System.identityHashCode(this))); + buf.append(": "); + buf.append(usage()); + buf.append("%, "); + buf.append(chunkSize - freeBytes); + buf.append('/'); + buf.append(chunkSize); + buf.append(')'); + return buf.toString(); + } +} diff --git a/common/src/main/java/common/net/buffer/PoolChunkList.java b/common/src/main/java/common/net/buffer/PoolChunkList.java new file mode 100644 index 0000000..f0a5f40 --- /dev/null +++ b/common/src/main/java/common/net/buffer/PoolChunkList.java @@ -0,0 +1,129 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import common.net.util.internal.StringUtil; + +final class PoolChunkList { + private final PoolArena arena; + private final PoolChunkList nextList; + PoolChunkList prevList; + + private final int minUsage; + private final int maxUsage; + + private PoolChunk head; + + // TODO: Test if adding padding helps under contention + //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; + + PoolChunkList(PoolArena arena, PoolChunkList nextList, int minUsage, int maxUsage) { + this.arena = arena; + this.nextList = nextList; + this.minUsage = minUsage; + this.maxUsage = maxUsage; + } + + boolean allocate(PooledByteBuf buf, int reqCapacity, int normCapacity) { + if (head == null) { + return false; + } + + for (PoolChunk cur = head;;) { + long handle = cur.allocate(normCapacity); + if (handle < 0) { + cur = cur.next; + if (cur == null) { + return false; + } + } else { + cur.initBuf(buf, handle, reqCapacity); + if (cur.usage() >= maxUsage) { + remove(cur); + nextList.add(cur); + } + return true; + } + } + } + + void free(PoolChunk chunk, long handle) { + chunk.free(handle); + if (chunk.usage() < minUsage) { + remove(chunk); + if (prevList == null) { + assert chunk.usage() == 0; + arena.destroyChunk(chunk); + } else { + prevList.add(chunk); + } + } + } + + void add(PoolChunk chunk) { + if (chunk.usage() >= maxUsage) { + nextList.add(chunk); + return; + } + + chunk.parent = this; + if (head == null) { + head = chunk; + chunk.prev = null; + chunk.next = null; + } else { + chunk.prev = null; + chunk.next = head; + head.prev = chunk; + head = chunk; + } + } + + private void remove(PoolChunk cur) { + if (cur == head) { + head = cur.next; + if (head != null) { + head.prev = null; + } + } else { + PoolChunk next = cur.next; + cur.prev.next = next; + if (next != null) { + next.prev = cur.prev; + } + } + } + + @Override + public String toString() { + if (head == null) { + return "none"; + } + + StringBuilder buf = new StringBuilder(); + for (PoolChunk cur = head;;) { + buf.append(cur); + cur = cur.next; + if (cur == null) { + break; + } + buf.append(StringUtil.NEWLINE); + } + + return buf.toString(); + } +} diff --git a/common/src/main/java/common/net/buffer/PoolSubpage.java b/common/src/main/java/common/net/buffer/PoolSubpage.java new file mode 100644 index 0000000..ae643c7 --- /dev/null +++ b/common/src/main/java/common/net/buffer/PoolSubpage.java @@ -0,0 +1,213 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +final class PoolSubpage { + + final PoolChunk chunk; + private final int memoryMapIdx; + private final int runOffset; + private final int pageSize; + private final long[] bitmap; + + PoolSubpage prev; + PoolSubpage next; + + boolean doNotDestroy; + int elemSize; + private int maxNumElems; + private int bitmapLength; + private int nextAvail; + private int numAvail; + + // TODO: Test if adding padding helps under contention + //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; + + /** Special constructor that creates a linked list head */ + PoolSubpage(int pageSize) { + chunk = null; + memoryMapIdx = -1; + runOffset = -1; + elemSize = -1; + this.pageSize = pageSize; + bitmap = null; + } + + PoolSubpage(PoolChunk chunk, int memoryMapIdx, int runOffset, int pageSize, int elemSize) { + this.chunk = chunk; + this.memoryMapIdx = memoryMapIdx; + this.runOffset = runOffset; + this.pageSize = pageSize; + bitmap = new long[pageSize >>> 10]; // pageSize / 16 / 64 + init(elemSize); + } + + void init(int elemSize) { + doNotDestroy = true; + this.elemSize = elemSize; + if (elemSize != 0) { + maxNumElems = numAvail = pageSize / elemSize; + nextAvail = 0; + bitmapLength = maxNumElems >>> 6; + if ((maxNumElems & 63) != 0) { + bitmapLength ++; + } + + for (int i = 0; i < bitmapLength; i ++) { + bitmap[i] = 0; + } + } + + addToPool(); + } + + /** + * Returns the bitmap index of the subpage allocation. + */ + long allocate() { + if (elemSize == 0) { + return toHandle(0); + } + + if (numAvail == 0 || !doNotDestroy) { + return -1; + } + + final int bitmapIdx = getNextAvail(); + int q = bitmapIdx >>> 6; + int r = bitmapIdx & 63; + assert (bitmap[q] >>> r & 1) == 0; + bitmap[q] |= 1L << r; + + if (-- numAvail == 0) { + removeFromPool(); + } + + return toHandle(bitmapIdx); + } + + /** + * @return {@code true} if this subpage is in use. + * {@code false} if this subpage is not used by its chunk and thus it's OK to be released. + */ + boolean free(int bitmapIdx) { + + if (elemSize == 0) { + return true; + } + + int q = bitmapIdx >>> 6; + int r = bitmapIdx & 63; + assert (bitmap[q] >>> r & 1) != 0; + bitmap[q] ^= 1L << r; + + setNextAvail(bitmapIdx); + + if (numAvail ++ == 0) { + addToPool(); + return true; + } + + if (numAvail != maxNumElems) { + return true; + } else { + // Subpage not in use (numAvail == maxNumElems) + if (prev == next) { + // Do not remove if this subpage is the only one left in the pool. + return true; + } + + // Remove this subpage from the pool if there are other subpages left in the pool. + doNotDestroy = false; + removeFromPool(); + return false; + } + } + + private void addToPool() { + PoolSubpage head = chunk.arena.findSubpagePoolHead(elemSize); + assert prev == null && next == null; + prev = head; + next = head.next; + next.prev = this; + head.next = this; + } + + private void removeFromPool() { + assert prev != null && next != null; + prev.next = next; + next.prev = prev; + next = null; + prev = null; + } + + private void setNextAvail(int bitmapIdx) { + nextAvail = bitmapIdx; + } + + private int getNextAvail() { + int nextAvail = this.nextAvail; + if (nextAvail >= 0) { + this.nextAvail = -1; + return nextAvail; + } + return findNextAvail(); + } + + private int findNextAvail() { + final long[] bitmap = this.bitmap; + final int bitmapLength = this.bitmapLength; + for (int i = 0; i < bitmapLength; i ++) { + long bits = bitmap[i]; + if (~bits != 0) { + return findNextAvail0(i, bits); + } + } + return -1; + } + + private int findNextAvail0(int i, long bits) { + final int maxNumElems = this.maxNumElems; + final int baseVal = i << 6; + + for (int j = 0; j < 64; j ++) { + if ((bits & 1) == 0) { + int val = baseVal | j; + if (val < maxNumElems) { + return val; + } else { + break; + } + } + bits >>>= 1; + } + return -1; + } + + private long toHandle(int bitmapIdx) { + return 0x4000000000000000L | (long) bitmapIdx << 32 | memoryMapIdx; + } + + public String toString() { + if (!doNotDestroy) { + return "(" + memoryMapIdx + ": not in use)"; + } + + return String.valueOf('(') + memoryMapIdx + ": " + (maxNumElems - numAvail) + '/' + maxNumElems + + ", offset: " + runOffset + ", length: " + pageSize + ", elemSize: " + elemSize + ')'; + } +} diff --git a/common/src/main/java/common/net/buffer/PoolThreadCache.java b/common/src/main/java/common/net/buffer/PoolThreadCache.java new file mode 100644 index 0000000..1a41c18 --- /dev/null +++ b/common/src/main/java/common/net/buffer/PoolThreadCache.java @@ -0,0 +1,485 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + + +import java.nio.ByteBuffer; + +import common.net.util.ThreadDeathWatcher; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * Acts a Thread cache for allocations. This implementation is moduled after + * jemalloc and the descripted + * technics of Scalable memory allocation using jemalloc. + */ +final class PoolThreadCache { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(PoolThreadCache.class); + + final PoolArena heapArena; + final PoolArena directArena; + + // Hold the caches for the different size classes, which are tiny, small and normal. + private final MemoryRegionCache[] tinySubPageHeapCaches; + private final MemoryRegionCache[] smallSubPageHeapCaches; + private final MemoryRegionCache[] tinySubPageDirectCaches; + private final MemoryRegionCache[] smallSubPageDirectCaches; + private final MemoryRegionCache[] normalHeapCaches; + private final MemoryRegionCache[] normalDirectCaches; + + // Used for bitshifting when calculate the index of normal caches later + private final int numShiftsNormalDirect; + private final int numShiftsNormalHeap; + private final int freeSweepAllocationThreshold; + + private int allocations; + + private final Thread thread = Thread.currentThread(); + private final Runnable freeTask = new Runnable() { + @Override + public void run() { + free0(); + } + }; + + // TODO: Test if adding padding helps under contention + //private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; + + PoolThreadCache(PoolArena heapArena, PoolArena directArena, + int tinyCacheSize, int smallCacheSize, int normalCacheSize, + int maxCachedBufferCapacity, int freeSweepAllocationThreshold) { + if (maxCachedBufferCapacity < 0) { + throw new IllegalArgumentException("maxCachedBufferCapacity: " + + maxCachedBufferCapacity + " (expected: >= 0)"); + } + if (freeSweepAllocationThreshold < 1) { + throw new IllegalArgumentException("freeSweepAllocationThreshold: " + + maxCachedBufferCapacity + " (expected: > 0)"); + } + this.freeSweepAllocationThreshold = freeSweepAllocationThreshold; + this.heapArena = heapArena; + this.directArena = directArena; + if (directArena != null) { + tinySubPageDirectCaches = createSubPageCaches(tinyCacheSize, PoolArena.numTinySubpagePools); + smallSubPageDirectCaches = createSubPageCaches(smallCacheSize, directArena.numSmallSubpagePools); + + numShiftsNormalDirect = log2(directArena.pageSize); + normalDirectCaches = createNormalCaches( + normalCacheSize, maxCachedBufferCapacity, directArena); + } else { + // No directArea is configured so just null out all caches + tinySubPageDirectCaches = null; + smallSubPageDirectCaches = null; + normalDirectCaches = null; + numShiftsNormalDirect = -1; + } + if (heapArena != null) { + // Create the caches for the heap allocations + tinySubPageHeapCaches = createSubPageCaches(tinyCacheSize, PoolArena.numTinySubpagePools); + smallSubPageHeapCaches = createSubPageCaches(smallCacheSize, heapArena.numSmallSubpagePools); + + numShiftsNormalHeap = log2(heapArena.pageSize); + normalHeapCaches = createNormalCaches( + normalCacheSize, maxCachedBufferCapacity, heapArena); + } else { + // No heapArea is configured so just null out all caches + tinySubPageHeapCaches = null; + smallSubPageHeapCaches = null; + normalHeapCaches = null; + numShiftsNormalHeap = -1; + } + + // The thread-local cache will keep a list of pooled buffers which must be returned to + // the pool when the thread is not alive anymore. + ThreadDeathWatcher.watch(thread, freeTask); + } + + private static SubPageMemoryRegionCache[] createSubPageCaches(int cacheSize, int numCaches) { + if (cacheSize > 0) { + + SubPageMemoryRegionCache[] cache = new SubPageMemoryRegionCache[numCaches]; + for (int i = 0; i < cache.length; i++) { + // TODO: maybe use cacheSize / cache.length + cache[i] = new SubPageMemoryRegionCache(cacheSize); + } + return cache; + } else { + return null; + } + } + + private static NormalMemoryRegionCache[] createNormalCaches( + int cacheSize, int maxCachedBufferCapacity, PoolArena area) { + if (cacheSize > 0) { + int max = Math.min(area.chunkSize, maxCachedBufferCapacity); + int arraySize = Math.max(1, max / area.pageSize); + + + NormalMemoryRegionCache[] cache = new NormalMemoryRegionCache[arraySize]; + for (int i = 0; i < cache.length; i++) { + cache[i] = new NormalMemoryRegionCache(cacheSize); + } + return cache; + } else { + return null; + } + } + + private static int log2(int val) { + int res = 0; + while (val > 1) { + val >>= 1; + res++; + } + return res; + } + + /** + * Try to allocate a tiny buffer out of the cache. Returns {@code true} if successful {@code false} otherwise + */ + boolean allocateTiny(PoolArena area, PooledByteBuf buf, int reqCapacity, int normCapacity) { + return allocate(cacheForTiny(area, normCapacity), buf, reqCapacity); + } + + /** + * Try to allocate a small buffer out of the cache. Returns {@code true} if successful {@code false} otherwise + */ + boolean allocateSmall(PoolArena area, PooledByteBuf buf, int reqCapacity, int normCapacity) { + return allocate(cacheForSmall(area, normCapacity), buf, reqCapacity); + } + + /** + * Try to allocate a small buffer out of the cache. Returns {@code true} if successful {@code false} otherwise + */ + boolean allocateNormal(PoolArena area, PooledByteBuf buf, int reqCapacity, int normCapacity) { + return allocate(cacheForNormal(area, normCapacity), buf, reqCapacity); + } + + + private boolean allocate(MemoryRegionCache cache, PooledByteBuf buf, int reqCapacity) { + if (cache == null) { + // no cache found so just return false here + return false; + } + boolean allocated = cache.allocate(buf, reqCapacity); + if (++ allocations >= freeSweepAllocationThreshold) { + allocations = 0; + trim(); + } + return allocated; + } + + /** + * Add {@link PoolChunk} and {@code handle} to the cache if there is enough room. + * Returns {@code true} if it fit into the cache {@code false} otherwise. + */ + + boolean add(PoolArena area, PoolChunk chunk, long handle, int normCapacity) { + MemoryRegionCache cache; + if (area.isTinyOrSmall(normCapacity)) { + if (PoolArena.isTiny(normCapacity)) { + cache = cacheForTiny(area, normCapacity); + } else { + cache = cacheForSmall(area, normCapacity); + } + } else { + cache = cacheForNormal(area, normCapacity); + } + if (cache == null) { + return false; + } + return cache.add(chunk, handle); + } + + /** + * Should be called if the Thread that uses this cache is about to exist to release resources out of the cache + */ + void free() { + ThreadDeathWatcher.unwatch(thread, freeTask); + free0(); + } + + private void free0() { + int numFreed = free(tinySubPageDirectCaches) + + free(smallSubPageDirectCaches) + + free(normalDirectCaches) + + free(tinySubPageHeapCaches) + + free(smallSubPageHeapCaches) + + free(normalHeapCaches); + + if (numFreed > 0 && logger.isDebugEnabled()) { + logger.debug("Freed {} thread-local buffer(s) from thread: {}", numFreed, thread.getName()); + } + } + + private static int free(MemoryRegionCache[] caches) { + if (caches == null) { + return 0; + } + + int numFreed = 0; + for (MemoryRegionCache c: caches) { + numFreed += free(c); + } + return numFreed; + } + + private static int free(MemoryRegionCache cache) { + if (cache == null) { + return 0; + } + return cache.free(); + } + + void trim() { + trim(tinySubPageDirectCaches); + trim(smallSubPageDirectCaches); + trim(normalDirectCaches); + trim(tinySubPageHeapCaches); + trim(smallSubPageHeapCaches); + trim(normalHeapCaches); + } + + private static void trim(MemoryRegionCache[] caches) { + if (caches == null) { + return; + } + for (MemoryRegionCache c: caches) { + trim(c); + } + } + + private static void trim(MemoryRegionCache cache) { + if (cache == null) { + return; + } + cache.trim(); + } + + private MemoryRegionCache cacheForTiny(PoolArena area, int normCapacity) { + int idx = PoolArena.tinyIdx(normCapacity); + if (area.isDirect()) { + return cache(tinySubPageDirectCaches, idx); + } + return cache(tinySubPageHeapCaches, idx); + } + + private MemoryRegionCache cacheForSmall(PoolArena area, int normCapacity) { + int idx = PoolArena.smallIdx(normCapacity); + if (area.isDirect()) { + return cache(smallSubPageDirectCaches, idx); + } + return cache(smallSubPageHeapCaches, idx); + } + + private MemoryRegionCache cacheForNormal(PoolArena area, int normCapacity) { + if (area.isDirect()) { + int idx = log2(normCapacity >> numShiftsNormalDirect); + return cache(normalDirectCaches, idx); + } + int idx = log2(normCapacity >> numShiftsNormalHeap); + return cache(normalHeapCaches, idx); + } + + private static MemoryRegionCache cache(MemoryRegionCache[] cache, int idx) { + if (cache == null || idx > cache.length - 1) { + return null; + } + return cache[idx]; + } + + /** + * Cache used for buffers which are backed by TINY or SMALL size. + */ + private static final class SubPageMemoryRegionCache extends MemoryRegionCache { + SubPageMemoryRegionCache(int size) { + super(size); + } + + @Override + protected void initBuf( + PoolChunk chunk, long handle, PooledByteBuf buf, int reqCapacity) { + chunk.initBufWithSubpage(buf, handle, reqCapacity); + } + } + + /** + * Cache used for buffers which are backed by NORMAL size. + */ + private static final class NormalMemoryRegionCache extends MemoryRegionCache { + NormalMemoryRegionCache(int size) { + super(size); + } + + @Override + protected void initBuf( + PoolChunk chunk, long handle, PooledByteBuf buf, int reqCapacity) { + chunk.initBuf(buf, handle, reqCapacity); + } + } + + /** + * Cache of {@link PoolChunk} and handles which can be used to allocate a buffer without locking at all. + */ + private abstract static class MemoryRegionCache { + private final Entry[] entries; + private final int maxUnusedCached; + private int head; + private int tail; + private int maxEntriesInUse; + private int entriesInUse; + + + MemoryRegionCache(int size) { + entries = new Entry[powerOfTwo(size)]; + for (int i = 0; i < entries.length; i++) { + entries[i] = new Entry(); + } + maxUnusedCached = size / 2; + } + + private static int powerOfTwo(int res) { + if (res <= 2) { + return 2; + } + res--; + res |= res >> 1; + res |= res >> 2; + res |= res >> 4; + res |= res >> 8; + res |= res >> 16; + res++; + return res; + } + + /** + * Init the {@link PooledByteBuf} using the provided chunk and handle with the capacity restrictions. + */ + protected abstract void initBuf(PoolChunk chunk, long handle, + PooledByteBuf buf, int reqCapacity); + + /** + * Add to cache if not already full. + */ + public boolean add(PoolChunk chunk, long handle) { + Entry entry = entries[tail]; + if (entry.chunk != null) { + // cache is full + return false; + } + entriesInUse --; + + entry.chunk = chunk; + entry.handle = handle; + tail = nextIdx(tail); + return true; + } + + /** + * Allocate something out of the cache if possible and remove the entry from the cache. + */ + public boolean allocate(PooledByteBuf buf, int reqCapacity) { + Entry entry = entries[head]; + if (entry.chunk == null) { + return false; + } + + entriesInUse ++; + if (maxEntriesInUse < entriesInUse) { + maxEntriesInUse = entriesInUse; + } + initBuf(entry.chunk, entry.handle, buf, reqCapacity); + // only null out the chunk as we only use the chunk to check if the buffer is full or not. + entry.chunk = null; + head = nextIdx(head); + return true; + } + + /** + * Clear out this cache and free up all previous cached {@link PoolChunk}s and {@code handle}s. + */ + public int free() { + int numFreed = 0; + entriesInUse = 0; + maxEntriesInUse = 0; + for (int i = head;; i = nextIdx(i)) { + if (freeEntry(entries[i])) { + numFreed++; + } else { + // all cleared + return numFreed; + } + } + } + + /** + * Free up cached {@link PoolChunk}s if not allocated frequently enough. + */ + private void trim() { + int free = size() - maxEntriesInUse; + entriesInUse = 0; + maxEntriesInUse = 0; + + if (free <= maxUnusedCached) { + return; + } + + int i = head; + for (; free > 0; free--) { + if (!freeEntry(entries[i])) { + // all freed + return; + } + i = nextIdx(i); + } + } + + + private static boolean freeEntry(Entry entry) { + PoolChunk chunk = entry.chunk; + if (chunk == null) { + return false; + } + // need to synchronize on the area from which it was allocated before. + synchronized (chunk.arena) { + chunk.parent.free(chunk, entry.handle); + } + entry.chunk = null; + return true; + } + + /** + * Return the number of cached entries. + */ + private int size() { + return tail - head & entries.length - 1; + } + + private int nextIdx(int index) { + // use bitwise operation as this is faster as using modulo. + return index + 1 & entries.length - 1; + } + + private static final class Entry { + PoolChunk chunk; + long handle; + } + } +} diff --git a/common/src/main/java/common/net/buffer/PooledByteBuf.java b/common/src/main/java/common/net/buffer/PooledByteBuf.java new file mode 100644 index 0000000..34324d7 --- /dev/null +++ b/common/src/main/java/common/net/buffer/PooledByteBuf.java @@ -0,0 +1,160 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +import common.net.util.Recycler; + +abstract class PooledByteBuf extends AbstractReferenceCountedByteBuf { + + private final Recycler.Handle recyclerHandle; + + protected PoolChunk chunk; + protected long handle; + protected T memory; + protected int offset; + protected int length; + int maxLength; + + private ByteBuffer tmpNioBuf; + + protected PooledByteBuf(Recycler.Handle recyclerHandle, int maxCapacity) { + super(maxCapacity); + this.recyclerHandle = recyclerHandle; + } + + void init(PoolChunk chunk, long handle, int offset, int length, int maxLength) { + assert handle >= 0; + assert chunk != null; + + this.chunk = chunk; + this.handle = handle; + memory = chunk.memory; + this.offset = offset; + this.length = length; + this.maxLength = maxLength; + setIndex(0, 0); + tmpNioBuf = null; + } + + void initUnpooled(PoolChunk chunk, int length) { + assert chunk != null; + + this.chunk = chunk; + handle = 0; + memory = chunk.memory; + offset = 0; + this.length = maxLength = length; + setIndex(0, 0); + tmpNioBuf = null; + } + + @Override + public final int capacity() { + return length; + } + + @Override + public final ByteBuf capacity(int newCapacity) { + ensureAccessible(); + + // If the request capacity does not require reallocation, just update the length of the memory. + if (chunk.unpooled) { + if (newCapacity == length) { + return this; + } + } else { + if (newCapacity > length) { + if (newCapacity <= maxLength) { + length = newCapacity; + return this; + } + } else if (newCapacity < length) { + if (newCapacity > maxLength >>> 1) { + if (maxLength <= 512) { + if (newCapacity > maxLength - 16) { + length = newCapacity; + setIndex(Math.min(readerIndex(), newCapacity), Math.min(writerIndex(), newCapacity)); + return this; + } + } else { // > 512 (i.e. >= 1024) + length = newCapacity; + setIndex(Math.min(readerIndex(), newCapacity), Math.min(writerIndex(), newCapacity)); + return this; + } + } + } else { + return this; + } + } + + // Reallocation required. + chunk.arena.reallocate(this, newCapacity, true); + return this; + } + + @Override + public final ByteBufAllocator alloc() { + return chunk.arena.parent; + } + + @Override + public final ByteOrder order() { + return ByteOrder.BIG_ENDIAN; + } + + @Override + public final ByteBuf unwrap() { + return null; + } + + protected final ByteBuffer internalNioBuffer() { + ByteBuffer tmpNioBuf = this.tmpNioBuf; + if (tmpNioBuf == null) { + this.tmpNioBuf = tmpNioBuf = newInternalNioBuffer(memory); + } + return tmpNioBuf; + } + + protected abstract ByteBuffer newInternalNioBuffer(T memory); + + @Override + protected final void deallocate() { + if (handle >= 0) { + final long handle = this.handle; + this.handle = -1; + memory = null; + chunk.arena.free(chunk, handle, maxLength); + recycle(); + } + } + + private void recycle() { + Recycler.Handle recyclerHandle = this.recyclerHandle; + if (recyclerHandle != null) { + ((Recycler) recycler()).recycle(this, recyclerHandle); + } + } + + protected abstract Recycler recycler(); + + protected final int idx(int index) { + return offset + index; + } +} diff --git a/common/src/main/java/common/net/buffer/PooledByteBufAllocator.java b/common/src/main/java/common/net/buffer/PooledByteBufAllocator.java new file mode 100644 index 0000000..a0b0ca4 --- /dev/null +++ b/common/src/main/java/common/net/buffer/PooledByteBufAllocator.java @@ -0,0 +1,293 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import java.nio.ByteBuffer; +import java.util.concurrent.atomic.AtomicInteger; + +import common.net.util.concurrent.FastThreadLocal; +import common.net.util.internal.SystemPropertyUtil; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +public class PooledByteBufAllocator extends AbstractByteBufAllocator { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(PooledByteBufAllocator.class); + private static final int DEFAULT_NUM_HEAP_ARENA; + private static final int DEFAULT_NUM_DIRECT_ARENA; + + private static final int DEFAULT_PAGE_SIZE; + private static final int DEFAULT_MAX_ORDER; // 8192 << 11 = 16 MiB per chunk + private static final int DEFAULT_TINY_CACHE_SIZE; + private static final int DEFAULT_SMALL_CACHE_SIZE; + private static final int DEFAULT_NORMAL_CACHE_SIZE; + private static final int DEFAULT_MAX_CACHED_BUFFER_CAPACITY; + private static final int DEFAULT_CACHE_TRIM_INTERVAL; + + private static final int MIN_PAGE_SIZE = 4096; + private static final int MAX_CHUNK_SIZE = (int) (((long) Integer.MAX_VALUE + 1) / 2); + + static { + int defaultPageSize = SystemPropertyUtil.getInt("game.net.allocator.pageSize", 8192); + Throwable pageSizeFallbackCause = null; + try { + validateAndCalculatePageShifts(defaultPageSize); + } catch (Throwable t) { + pageSizeFallbackCause = t; + defaultPageSize = 8192; + } + DEFAULT_PAGE_SIZE = defaultPageSize; + + int defaultMaxOrder = SystemPropertyUtil.getInt("game.net.allocator.maxOrder", 11); + Throwable maxOrderFallbackCause = null; + try { + validateAndCalculateChunkSize(DEFAULT_PAGE_SIZE, defaultMaxOrder); + } catch (Throwable t) { + maxOrderFallbackCause = t; + defaultMaxOrder = 11; + } + DEFAULT_MAX_ORDER = defaultMaxOrder; + + // Determine reasonable default for nHeapArena and nDirectArena. + // Assuming each arena has 3 chunks, the pool should not consume more than 50% of max memory. + final Runtime runtime = Runtime.getRuntime(); + final int defaultChunkSize = DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER; + DEFAULT_NUM_HEAP_ARENA = Math.max(0, + SystemPropertyUtil.getInt( + "game.net.allocator.numHeapArenas", + (int) Math.min( + runtime.availableProcessors(), + Runtime.getRuntime().maxMemory() / defaultChunkSize / 2 / 3))); + DEFAULT_NUM_DIRECT_ARENA = Math.max(0, + SystemPropertyUtil.getInt( + "game.net.allocator.numDirectArenas", + (int) Math.min( + runtime.availableProcessors(), + Runtime.getRuntime().maxMemory() / defaultChunkSize / 2 / 3))); + + // cache sizes + DEFAULT_TINY_CACHE_SIZE = SystemPropertyUtil.getInt("game.net.allocator.tinyCacheSize", 512); + DEFAULT_SMALL_CACHE_SIZE = SystemPropertyUtil.getInt("game.net.allocator.smallCacheSize", 256); + DEFAULT_NORMAL_CACHE_SIZE = SystemPropertyUtil.getInt("game.net.allocator.normalCacheSize", 64); + + // 32 kb is the default maximum capacity of the cached buffer. Similar to what is explained in + // 'Scalable memory allocation using jemalloc' + DEFAULT_MAX_CACHED_BUFFER_CAPACITY = SystemPropertyUtil.getInt( + "game.net.allocator.maxCachedBufferCapacity", 32 * 1024); + + // the number of threshold of allocations when cached entries will be freed up if not frequently used + DEFAULT_CACHE_TRIM_INTERVAL = SystemPropertyUtil.getInt( + "game.net.allocator.cacheTrimInterval", 8192); + + if (logger.isDebugEnabled()) { + logger.debug("-Dgame.net.allocator.numHeapArenas: {}", DEFAULT_NUM_HEAP_ARENA); + logger.debug("-Dgame.net.allocator.numDirectArenas: {}", DEFAULT_NUM_DIRECT_ARENA); + if (pageSizeFallbackCause == null) { + logger.debug("-Dgame.net.allocator.pageSize: {}", DEFAULT_PAGE_SIZE); + } else { + logger.debug("-Dgame.net.allocator.pageSize: {}", DEFAULT_PAGE_SIZE, pageSizeFallbackCause); + } + if (maxOrderFallbackCause == null) { + logger.debug("-Dgame.net.allocator.maxOrder: {}", DEFAULT_MAX_ORDER); + } else { + logger.debug("-Dgame.net.allocator.maxOrder: {}", DEFAULT_MAX_ORDER, maxOrderFallbackCause); + } + logger.debug("-Dgame.net.allocator.chunkSize: {}", DEFAULT_PAGE_SIZE << DEFAULT_MAX_ORDER); + logger.debug("-Dgame.net.allocator.tinyCacheSize: {}", DEFAULT_TINY_CACHE_SIZE); + logger.debug("-Dgame.net.allocator.smallCacheSize: {}", DEFAULT_SMALL_CACHE_SIZE); + logger.debug("-Dgame.net.allocator.normalCacheSize: {}", DEFAULT_NORMAL_CACHE_SIZE); + logger.debug("-Dgame.net.allocator.maxCachedBufferCapacity: {}", DEFAULT_MAX_CACHED_BUFFER_CAPACITY); + logger.debug("-Dgame.net.allocator.cacheTrimInterval: {}", DEFAULT_CACHE_TRIM_INTERVAL); + } + } + + public static final PooledByteBufAllocator DEFAULT = new PooledByteBufAllocator(); + + private final PoolArena[] heapArenas; + private final PoolArena[] directArenas; + private final int tinyCacheSize; + private final int smallCacheSize; + private final int normalCacheSize; + + final PoolThreadLocalCache threadCache; + + public PooledByteBufAllocator() { + this(DEFAULT_NUM_HEAP_ARENA, DEFAULT_NUM_DIRECT_ARENA, DEFAULT_PAGE_SIZE, DEFAULT_MAX_ORDER); + } + + public PooledByteBufAllocator(int nHeapArena, int nDirectArena, int pageSize, int maxOrder) { + this(nHeapArena, nDirectArena, pageSize, maxOrder, + DEFAULT_TINY_CACHE_SIZE, DEFAULT_SMALL_CACHE_SIZE, DEFAULT_NORMAL_CACHE_SIZE); + } + + public PooledByteBufAllocator(int nHeapArena, int nDirectArena, int pageSize, int maxOrder, + int tinyCacheSize, int smallCacheSize, int normalCacheSize) { + threadCache = new PoolThreadLocalCache(); + this.tinyCacheSize = tinyCacheSize; + this.smallCacheSize = smallCacheSize; + this.normalCacheSize = normalCacheSize; + final int chunkSize = validateAndCalculateChunkSize(pageSize, maxOrder); + + if (nHeapArena < 0) { + throw new IllegalArgumentException("nHeapArena: " + nHeapArena + " (expected: >= 0)"); + } + if (nDirectArena < 0) { + throw new IllegalArgumentException("nDirectArea: " + nDirectArena + " (expected: >= 0)"); + } + + int pageShifts = validateAndCalculatePageShifts(pageSize); + + if (nHeapArena > 0) { + heapArenas = newArenaArray(nHeapArena); + for (int i = 0; i < heapArenas.length; i ++) { + heapArenas[i] = new PoolArena.HeapArena(this, pageSize, maxOrder, pageShifts, chunkSize); + } + } else { + heapArenas = null; + } + + if (nDirectArena > 0) { + directArenas = newArenaArray(nDirectArena); + for (int i = 0; i < directArenas.length; i ++) { + directArenas[i] = new PoolArena.DirectArena(this, pageSize, maxOrder, pageShifts, chunkSize); + } + } else { + directArenas = null; + } + } + + + private static PoolArena[] newArenaArray(int size) { + return new PoolArena[size]; + } + + private static int validateAndCalculatePageShifts(int pageSize) { + if (pageSize < MIN_PAGE_SIZE) { + throw new IllegalArgumentException("pageSize: " + pageSize + " (expected: " + MIN_PAGE_SIZE + "+)"); + } + + if ((pageSize & pageSize - 1) != 0) { + throw new IllegalArgumentException("pageSize: " + pageSize + " (expected: power of 2)"); + } + + // Logarithm base 2. At this point we know that pageSize is a power of two. + return Integer.SIZE - 1 - Integer.numberOfLeadingZeros(pageSize); + } + + private static int validateAndCalculateChunkSize(int pageSize, int maxOrder) { + if (maxOrder > 14) { + throw new IllegalArgumentException("maxOrder: " + maxOrder + " (expected: 0-14)"); + } + + // Ensure the resulting chunkSize does not overflow. + int chunkSize = pageSize; + for (int i = maxOrder; i > 0; i --) { + if (chunkSize > MAX_CHUNK_SIZE / 2) { + throw new IllegalArgumentException(String.format( + "pageSize (%d) << maxOrder (%d) must not exceed %d", pageSize, maxOrder, MAX_CHUNK_SIZE)); + } + chunkSize <<= 1; + } + return chunkSize; + } + + @Override + protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) { + PoolThreadCache cache = threadCache.get(); + PoolArena heapArena = cache.heapArena; + + ByteBuf buf; + if (heapArena != null) { + buf = heapArena.allocate(cache, initialCapacity, maxCapacity); + } else { + buf = new UnpooledHeapByteBuf(this, initialCapacity, maxCapacity); + } + + return toLeakAwareBuffer(buf); + } + + @Override + protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) { + PoolThreadCache cache = threadCache.get(); + PoolArena directArena = cache.directArena; + + ByteBuf buf; + if (directArena != null) { + buf = directArena.allocate(cache, initialCapacity, maxCapacity); + } else { + buf = new UnpooledDirectByteBuf(this, initialCapacity, maxCapacity); + } + + return toLeakAwareBuffer(buf); + } + + @Override + public boolean isDirectBufferPooled() { + return directArenas != null; + } + + final class PoolThreadLocalCache extends FastThreadLocal { + private final AtomicInteger index = new AtomicInteger(); + + @Override + protected PoolThreadCache initialValue() { + final int idx = index.getAndIncrement(); + final PoolArena heapArena; + final PoolArena directArena; + + if (heapArenas != null) { + heapArena = heapArenas[Math.abs(idx % heapArenas.length)]; + } else { + heapArena = null; + } + + if (directArenas != null) { + directArena = directArenas[Math.abs(idx % directArenas.length)]; + } else { + directArena = null; + } + + return new PoolThreadCache( + heapArena, directArena, tinyCacheSize, smallCacheSize, normalCacheSize, + DEFAULT_MAX_CACHED_BUFFER_CAPACITY, DEFAULT_CACHE_TRIM_INTERVAL); + } + + @Override + protected void onRemoval(PoolThreadCache value) { + value.free(); + } + } + +// Too noisy at the moment. +// +// public String toString() { +// StringBuilder buf = new StringBuilder(); +// buf.append(heapArenas.length); +// buf.append(" heap arena(s):"); +// buf.append(StringUtil.NEWLINE); +// for (PoolArena a: heapArenas) { +// buf.append(a); +// } +// buf.append(directArenas.length); +// buf.append(" direct arena(s):"); +// buf.append(StringUtil.NEWLINE); +// for (PoolArena a: directArenas) { +// buf.append(a); +// } +// return buf.toString(); +// } +} diff --git a/common/src/main/java/common/net/buffer/PooledDirectByteBuf.java b/common/src/main/java/common/net/buffer/PooledDirectByteBuf.java new file mode 100644 index 0000000..e8f4ec7 --- /dev/null +++ b/common/src/main/java/common/net/buffer/PooledDirectByteBuf.java @@ -0,0 +1,367 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; + +import common.net.util.Recycler; + +final class PooledDirectByteBuf extends PooledByteBuf { + + private static final Recycler RECYCLER = new Recycler() { + @Override + protected PooledDirectByteBuf newObject(Handle handle) { + return new PooledDirectByteBuf(handle, 0); + } + }; + + static PooledDirectByteBuf newInstance(int maxCapacity) { + PooledDirectByteBuf buf = RECYCLER.get(); + buf.setRefCnt(1); + buf.maxCapacity(maxCapacity); + return buf; + } + + private PooledDirectByteBuf(Recycler.Handle recyclerHandle, int maxCapacity) { + super(recyclerHandle, maxCapacity); + } + + @Override + protected ByteBuffer newInternalNioBuffer(ByteBuffer memory) { + return memory.duplicate(); + } + + @Override + public boolean isDirect() { + return true; + } + + @Override + protected byte _getByte(int index) { + return memory.get(idx(index)); + } + + @Override + protected short _getShort(int index) { + return memory.getShort(idx(index)); + } + + @Override + protected int _getUnsignedMedium(int index) { + index = idx(index); + return (memory.get(index) & 0xff) << 16 | (memory.get(index + 1) & 0xff) << 8 | memory.get(index + 2) & 0xff; + } + + @Override + protected int _getInt(int index) { + return memory.getInt(idx(index)); + } + + @Override + protected long _getLong(int index) { + return memory.getLong(idx(index)); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.capacity()); + if (dst.hasArray()) { + getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length); + } else if (dst.nioBufferCount() > 0) { + for (ByteBuffer bb: dst.nioBuffers(dstIndex, length)) { + int bbLen = bb.remaining(); + getBytes(index, bb); + index += bbLen; + } + } else { + dst.setBytes(dstIndex, this, index, length); + } + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + getBytes(index, dst, dstIndex, length, false); + return this; + } + + private void getBytes(int index, byte[] dst, int dstIndex, int length, boolean internal) { + checkDstIndex(index, length, dstIndex, dst.length); + ByteBuffer tmpBuf; + if (internal) { + tmpBuf = internalNioBuffer(); + } else { + tmpBuf = memory.duplicate(); + } + index = idx(index); + tmpBuf.clear().position(index).limit(index + length); + tmpBuf.get(dst, dstIndex, length); + } + + @Override + public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { + checkReadableBytes(length); + getBytes(readerIndex, dst, dstIndex, length, true); + readerIndex += length; + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + getBytes(index, dst, false); + return this; + } + + private void getBytes(int index, ByteBuffer dst, boolean internal) { + checkIndex(index); + int bytesToCopy = Math.min(capacity() - index, dst.remaining()); + ByteBuffer tmpBuf; + if (internal) { + tmpBuf = internalNioBuffer(); + } else { + tmpBuf = memory.duplicate(); + } + index = idx(index); + tmpBuf.clear().position(index).limit(index + bytesToCopy); + dst.put(tmpBuf); + } + + @Override + public ByteBuf readBytes(ByteBuffer dst) { + int length = dst.remaining(); + checkReadableBytes(length); + getBytes(readerIndex, dst, true); + readerIndex += length; + return this; + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + getBytes(index, out, length, false); + return this; + } + + private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException { + checkIndex(index, length); + if (length == 0) { + return; + } + + byte[] tmp = new byte[length]; + ByteBuffer tmpBuf; + if (internal) { + tmpBuf = internalNioBuffer(); + } else { + tmpBuf = memory.duplicate(); + } + tmpBuf.clear().position(idx(index)); + tmpBuf.get(tmp); + out.write(tmp); + } + + @Override + public ByteBuf readBytes(OutputStream out, int length) throws IOException { + checkReadableBytes(length); + getBytes(readerIndex, out, length, true); + readerIndex += length; + return this; + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { + return getBytes(index, out, length, false); + } + + private int getBytes(int index, GatheringByteChannel out, int length, boolean internal) throws IOException { + checkIndex(index, length); + if (length == 0) { + return 0; + } + + ByteBuffer tmpBuf; + if (internal) { + tmpBuf = internalNioBuffer(); + } else { + tmpBuf = memory.duplicate(); + } + index = idx(index); + tmpBuf.clear().position(index).limit(index + length); + return out.write(tmpBuf); + } + + @Override + public int readBytes(GatheringByteChannel out, int length) throws IOException { + checkReadableBytes(length); + int readBytes = getBytes(readerIndex, out, length, true); + readerIndex += readBytes; + return readBytes; + } + + @Override + protected void _setByte(int index, int value) { + memory.put(idx(index), (byte) value); + } + + @Override + protected void _setShort(int index, int value) { + memory.putShort(idx(index), (short) value); + } + + @Override + protected void _setMedium(int index, int value) { + index = idx(index); + memory.put(index, (byte) (value >>> 16)); + memory.put(index + 1, (byte) (value >>> 8)); + memory.put(index + 2, (byte) value); + } + + @Override + protected void _setInt(int index, int value) { + memory.putInt(idx(index), value); + } + + @Override + protected void _setLong(int index, long value) { + memory.putLong(idx(index), value); + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + checkSrcIndex(index, length, srcIndex, src.capacity()); + if (src.hasArray()) { + setBytes(index, src.array(), src.arrayOffset() + srcIndex, length); + } else if (src.nioBufferCount() > 0) { + for (ByteBuffer bb: src.nioBuffers(srcIndex, length)) { + int bbLen = bb.remaining(); + setBytes(index, bb); + index += bbLen; + } + } else { + src.getBytes(srcIndex, this, index, length); + } + return this; + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + checkSrcIndex(index, length, srcIndex, src.length); + ByteBuffer tmpBuf = internalNioBuffer(); + index = idx(index); + tmpBuf.clear().position(index).limit(index + length); + tmpBuf.put(src, srcIndex, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + checkIndex(index, src.remaining()); + ByteBuffer tmpBuf = internalNioBuffer(); + if (src == tmpBuf) { + src = src.duplicate(); + } + + index = idx(index); + tmpBuf.clear().position(index).limit(index + src.remaining()); + tmpBuf.put(src); + return this; + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + checkIndex(index, length); + byte[] tmp = new byte[length]; + int readBytes = in.read(tmp); + if (readBytes <= 0) { + return readBytes; + } + ByteBuffer tmpBuf = internalNioBuffer(); + tmpBuf.clear().position(idx(index)); + tmpBuf.put(tmp, 0, readBytes); + return readBytes; + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + checkIndex(index, length); + ByteBuffer tmpBuf = internalNioBuffer(); + index = idx(index); + tmpBuf.clear().position(index).limit(index + length); + try { + return in.read(tmpBuf); + } catch (ClosedChannelException ignored) { + return -1; + } + } + + @Override + public ByteBuf copy(int index, int length) { + checkIndex(index, length); + ByteBuf copy = alloc().directBuffer(length, maxCapacity()); + copy.writeBytes(this, index, length); + return copy; + } + + @Override + public int nioBufferCount() { + return 1; + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + checkIndex(index, length); + index = idx(index); + return ((ByteBuffer) memory.duplicate().position(index).limit(index + length)).slice(); + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + return new ByteBuffer[] { nioBuffer(index, length) }; + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + checkIndex(index, length); + index = idx(index); + return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); + } + + @Override + public boolean hasArray() { + return false; + } + + @Override + public byte[] array() { + throw new UnsupportedOperationException("direct buffer"); + } + + @Override + public int arrayOffset() { + throw new UnsupportedOperationException("direct buffer"); + } + + @Override + protected Recycler recycler() { + return RECYCLER; + } +} diff --git a/common/src/main/java/common/net/buffer/PooledHeapByteBuf.java b/common/src/main/java/common/net/buffer/PooledHeapByteBuf.java new file mode 100644 index 0000000..5f75f03 --- /dev/null +++ b/common/src/main/java/common/net/buffer/PooledHeapByteBuf.java @@ -0,0 +1,292 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file tothe License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; + +import common.net.util.Recycler; + +final class PooledHeapByteBuf extends PooledByteBuf { + + private static final Recycler RECYCLER = new Recycler() { + @Override + protected PooledHeapByteBuf newObject(Handle handle) { + return new PooledHeapByteBuf(handle, 0); + } + }; + + static PooledHeapByteBuf newInstance(int maxCapacity) { + PooledHeapByteBuf buf = RECYCLER.get(); + buf.setRefCnt(1); + buf.maxCapacity(maxCapacity); + return buf; + } + + private PooledHeapByteBuf(Recycler.Handle recyclerHandle, int maxCapacity) { + super(recyclerHandle, maxCapacity); + } + + @Override + public boolean isDirect() { + return false; + } + + @Override + protected byte _getByte(int index) { + return memory[idx(index)]; + } + + @Override + protected short _getShort(int index) { + index = idx(index); + return (short) (memory[index] << 8 | memory[index + 1] & 0xFF); + } + + @Override + protected int _getUnsignedMedium(int index) { + index = idx(index); + return (memory[index] & 0xff) << 16 | + (memory[index + 1] & 0xff) << 8 | + memory[index + 2] & 0xff; + } + + @Override + protected int _getInt(int index) { + index = idx(index); + return (memory[index] & 0xff) << 24 | + (memory[index + 1] & 0xff) << 16 | + (memory[index + 2] & 0xff) << 8 | + memory[index + 3] & 0xff; + } + + @Override + protected long _getLong(int index) { + index = idx(index); + return ((long) memory[index] & 0xff) << 56 | + ((long) memory[index + 1] & 0xff) << 48 | + ((long) memory[index + 2] & 0xff) << 40 | + ((long) memory[index + 3] & 0xff) << 32 | + ((long) memory[index + 4] & 0xff) << 24 | + ((long) memory[index + 5] & 0xff) << 16 | + ((long) memory[index + 6] & 0xff) << 8 | + (long) memory[index + 7] & 0xff; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.capacity()); + if (dst.hasArray()) { + getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length); + } else { + dst.setBytes(dstIndex, memory, idx(index), length); + } + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.length); + System.arraycopy(memory, idx(index), dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + checkIndex(index); + dst.put(memory, idx(index), Math.min(capacity() - index, dst.remaining())); + return this; + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + checkIndex(index, length); + out.write(memory, idx(index), length); + return this; + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { + return getBytes(index, out, length, false); + } + + private int getBytes(int index, GatheringByteChannel out, int length, boolean internal) throws IOException { + checkIndex(index, length); + index = idx(index); + ByteBuffer tmpBuf; + if (internal) { + tmpBuf = internalNioBuffer(); + } else { + tmpBuf = ByteBuffer.wrap(memory); + } + return out.write((ByteBuffer) tmpBuf.clear().position(index).limit(index + length)); + } + + @Override + public int readBytes(GatheringByteChannel out, int length) throws IOException { + checkReadableBytes(length); + int readBytes = getBytes(readerIndex, out, length, true); + readerIndex += readBytes; + return readBytes; + } + + @Override + protected void _setByte(int index, int value) { + memory[idx(index)] = (byte) value; + } + + @Override + protected void _setShort(int index, int value) { + index = idx(index); + memory[index] = (byte) (value >>> 8); + memory[index + 1] = (byte) value; + } + + @Override + protected void _setMedium(int index, int value) { + index = idx(index); + memory[index] = (byte) (value >>> 16); + memory[index + 1] = (byte) (value >>> 8); + memory[index + 2] = (byte) value; + } + + @Override + protected void _setInt(int index, int value) { + index = idx(index); + memory[index] = (byte) (value >>> 24); + memory[index + 1] = (byte) (value >>> 16); + memory[index + 2] = (byte) (value >>> 8); + memory[index + 3] = (byte) value; + } + + @Override + protected void _setLong(int index, long value) { + index = idx(index); + memory[index] = (byte) (value >>> 56); + memory[index + 1] = (byte) (value >>> 48); + memory[index + 2] = (byte) (value >>> 40); + memory[index + 3] = (byte) (value >>> 32); + memory[index + 4] = (byte) (value >>> 24); + memory[index + 5] = (byte) (value >>> 16); + memory[index + 6] = (byte) (value >>> 8); + memory[index + 7] = (byte) value; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + checkSrcIndex(index, length, srcIndex, src.capacity()); + if (src.hasArray()) { + setBytes(index, src.array(), src.arrayOffset() + srcIndex, length); + } else { + src.getBytes(srcIndex, memory, idx(index), length); + } + return this; + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + checkSrcIndex(index, length, srcIndex, src.length); + System.arraycopy(src, srcIndex, memory, idx(index), length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + int length = src.remaining(); + checkIndex(index, length); + src.get(memory, idx(index), length); + return this; + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + checkIndex(index, length); + return in.read(memory, idx(index), length); + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + checkIndex(index, length); + index = idx(index); + try { + return in.read((ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length)); + } catch (ClosedChannelException ignored) { + return -1; + } + } + + @Override + public ByteBuf copy(int index, int length) { + checkIndex(index, length); + ByteBuf copy = alloc().heapBuffer(length, maxCapacity()); + copy.writeBytes(memory, idx(index), length); + return copy; + } + + @Override + public int nioBufferCount() { + return 1; + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + return new ByteBuffer[] { nioBuffer(index, length) }; + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + checkIndex(index, length); + index = idx(index); + ByteBuffer buf = ByteBuffer.wrap(memory, index, length); + return buf.slice(); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + checkIndex(index, length); + index = idx(index); + return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); + } + + @Override + public boolean hasArray() { + return true; + } + + @Override + public byte[] array() { + return memory; + } + + @Override + public int arrayOffset() { + return offset; + } + + @Override + protected ByteBuffer newInternalNioBuffer(byte[] memory) { + return ByteBuffer.wrap(memory); + } + + @Override + protected Recycler recycler() { + return RECYCLER; + } +} diff --git a/common/src/main/java/common/net/buffer/ReadOnlyByteBuf.java b/common/src/main/java/common/net/buffer/ReadOnlyByteBuf.java new file mode 100644 index 0000000..810a1b4 --- /dev/null +++ b/common/src/main/java/common/net/buffer/ReadOnlyByteBuf.java @@ -0,0 +1,307 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.ReadOnlyBufferException; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; + +/** + * A derived buffer which forbids any write requests to its parent. It is + * recommended to use {@link Unpooled#unmodifiableBuffer(ByteBuf)} + * instead of calling the constructor explicitly. + */ +public class ReadOnlyByteBuf extends AbstractDerivedByteBuf { + + private final ByteBuf buffer; + + public ReadOnlyByteBuf(ByteBuf buffer) { + super(buffer.maxCapacity()); + + if (buffer instanceof ReadOnlyByteBuf || buffer instanceof DuplicatedByteBuf) { + this.buffer = buffer.unwrap(); + } else { + this.buffer = buffer; + } + setIndex(buffer.readerIndex(), buffer.writerIndex()); + } + + @Override + public boolean isWritable() { + return false; + } + + @Override + public boolean isWritable(int numBytes) { + return false; + } + + @Override + public ByteBuf unwrap() { + return buffer; + } + + @Override + public ByteBufAllocator alloc() { + return buffer.alloc(); + } + + @Override + public ByteOrder order() { + return buffer.order(); + } + + @Override + public boolean isDirect() { + return buffer.isDirect(); + } + + @Override + public boolean hasArray() { + return false; + } + + @Override + public byte[] array() { + throw new ReadOnlyBufferException(); + } + + @Override + public int arrayOffset() { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf discardReadBytes() { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setByte(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setByte(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setShort(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setShort(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setMedium(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setMedium(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setInt(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setInt(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setLong(int index, long value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setLong(int index, long value) { + throw new ReadOnlyBufferException(); + } + + @Override + public int setBytes(int index, InputStream in, int length) { + throw new ReadOnlyBufferException(); + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) { + throw new ReadOnlyBufferException(); + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) + throws IOException { + return buffer.getBytes(index, out, length); + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) + throws IOException { + buffer.getBytes(index, out, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + buffer.getBytes(index, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + buffer.getBytes(index, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + buffer.getBytes(index, dst); + return this; + } + + @Override + public ByteBuf duplicate() { + return new ReadOnlyByteBuf(this); + } + + @Override + public ByteBuf copy(int index, int length) { + return buffer.copy(index, length); + } + + @Override + public ByteBuf slice(int index, int length) { + return Unpooled.unmodifiableBuffer(buffer.slice(index, length)); + } + + @Override + public byte getByte(int index) { + return _getByte(index); + } + + @Override + protected byte _getByte(int index) { + return buffer.getByte(index); + } + + @Override + public short getShort(int index) { + return _getShort(index); + } + + @Override + protected short _getShort(int index) { + return buffer.getShort(index); + } + + @Override + public int getUnsignedMedium(int index) { + return _getUnsignedMedium(index); + } + + @Override + protected int _getUnsignedMedium(int index) { + return buffer.getUnsignedMedium(index); + } + + @Override + public int getInt(int index) { + return _getInt(index); + } + + @Override + protected int _getInt(int index) { + return buffer.getInt(index); + } + + @Override + public long getLong(int index) { + return _getLong(index); + } + + @Override + protected long _getLong(int index) { + return buffer.getLong(index); + } + + @Override + public int nioBufferCount() { + return buffer.nioBufferCount(); + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + return buffer.nioBuffer(index, length).asReadOnlyBuffer(); + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + return buffer.nioBuffers(index, length); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + return nioBuffer(index, length); + } + + @Override + public int forEachByte(int index, int length, ByteBufProcessor processor) { + return buffer.forEachByte(index, length, processor); + } + + @Override + public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { + return buffer.forEachByteDesc(index, length, processor); + } + + @Override + public int capacity() { + return buffer.capacity(); + } + + @Override + public ByteBuf capacity(int newCapacity) { + throw new ReadOnlyBufferException(); + } +} diff --git a/common/src/main/java/common/net/buffer/ReadOnlyByteBufferBuf.java b/common/src/main/java/common/net/buffer/ReadOnlyByteBufferBuf.java new file mode 100644 index 0000000..46bd366 --- /dev/null +++ b/common/src/main/java/common/net/buffer/ReadOnlyByteBufferBuf.java @@ -0,0 +1,325 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.ReadOnlyBufferException; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; + +import common.net.util.internal.StringUtil; + + +/** + * Read-only ByteBuf which wraps a read-only ByteBuffer. + */ +class ReadOnlyByteBufferBuf extends AbstractReferenceCountedByteBuf { + + protected final ByteBuffer buffer; + private final ByteBufAllocator allocator; + private ByteBuffer tmpNioBuf; + + ReadOnlyByteBufferBuf(ByteBufAllocator allocator, ByteBuffer buffer) { + super(buffer.remaining()); + if (!buffer.isReadOnly()) { + throw new IllegalArgumentException("must be a readonly buffer: " + StringUtil.simpleClassName(buffer)); + } + + this.allocator = allocator; + this.buffer = buffer.slice().order(ByteOrder.BIG_ENDIAN); + writerIndex(this.buffer.limit()); + } + + @Override + protected void deallocate() { } + + @Override + public byte getByte(int index) { + ensureAccessible(); + return _getByte(index); + } + + @Override + protected byte _getByte(int index) { + return buffer.get(index); + } + + @Override + public short getShort(int index) { + ensureAccessible(); + return _getShort(index); + } + + @Override + protected short _getShort(int index) { + return buffer.getShort(index); + } + + @Override + public int getUnsignedMedium(int index) { + ensureAccessible(); + return _getUnsignedMedium(index); + } + + @Override + protected int _getUnsignedMedium(int index) { + return (getByte(index) & 0xff) << 16 | (getByte(index + 1) & 0xff) << 8 | getByte(index + 2) & 0xff; + } + + @Override + public int getInt(int index) { + ensureAccessible(); + return _getInt(index); + } + + @Override + protected int _getInt(int index) { + return buffer.getInt(index); + } + + @Override + public long getLong(int index) { + ensureAccessible(); + return _getLong(index); + } + + @Override + protected long _getLong(int index) { + return buffer.getLong(index); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.capacity()); + if (dst.hasArray()) { + getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length); + } else if (dst.nioBufferCount() > 0) { + for (ByteBuffer bb: dst.nioBuffers(dstIndex, length)) { + int bbLen = bb.remaining(); + getBytes(index, bb); + index += bbLen; + } + } else { + dst.setBytes(dstIndex, this, index, length); + } + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.length); + + if (dstIndex < 0 || dstIndex > dst.length - length) { + throw new IndexOutOfBoundsException(String.format( + "dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dst.length)); + } + + ByteBuffer tmpBuf = internalNioBuffer(); + tmpBuf.clear().position(index).limit(index + length); + tmpBuf.get(dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + checkIndex(index); + if (dst == null) { + throw new NullPointerException("dst"); + } + + int bytesToCopy = Math.min(capacity() - index, dst.remaining()); + ByteBuffer tmpBuf = internalNioBuffer(); + tmpBuf.clear().position(index).limit(index + bytesToCopy); + dst.put(tmpBuf); + return this; + } + + @Override + protected void _setByte(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setShort(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setMedium(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setInt(int index, int value) { + throw new ReadOnlyBufferException(); + } + + @Override + protected void _setLong(int index, long value) { + throw new ReadOnlyBufferException(); + } + + @Override + public int capacity() { + return maxCapacity(); + } + + @Override + public ByteBuf capacity(int newCapacity) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBufAllocator alloc() { + return allocator; + } + + @Override + public ByteOrder order() { + return ByteOrder.BIG_ENDIAN; + } + + @Override + public ByteBuf unwrap() { + return null; + } + + @Override + public boolean isDirect() { + return buffer.isDirect(); + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + ensureAccessible(); + if (length == 0) { + return this; + } + + if (buffer.hasArray()) { + out.write(buffer.array(), index + buffer.arrayOffset(), length); + } else { + byte[] tmp = new byte[length]; + ByteBuffer tmpBuf = internalNioBuffer(); + tmpBuf.clear().position(index); + tmpBuf.get(tmp); + out.write(tmp); + } + return this; + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { + ensureAccessible(); + if (length == 0) { + return 0; + } + + ByteBuffer tmpBuf = internalNioBuffer(); + tmpBuf.clear().position(index).limit(index + length); + return out.write(tmpBuf); + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + throw new ReadOnlyBufferException(); + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + throw new ReadOnlyBufferException(); + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + throw new ReadOnlyBufferException(); + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + throw new ReadOnlyBufferException(); + } + + protected final ByteBuffer internalNioBuffer() { + ByteBuffer tmpNioBuf = this.tmpNioBuf; + if (tmpNioBuf == null) { + this.tmpNioBuf = tmpNioBuf = buffer.duplicate(); + } + return tmpNioBuf; + } + + @Override + public ByteBuf copy(int index, int length) { + ensureAccessible(); + ByteBuffer src; + try { + src = (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); + } catch (IllegalArgumentException ignored) { + throw new IndexOutOfBoundsException("Too many bytes to read - Need " + (index + length)); + } + + ByteBuffer dst = ByteBuffer.allocateDirect(length); + dst.put(src); + dst.order(order()); + dst.clear(); + return new UnpooledDirectByteBuf(alloc(), dst, maxCapacity()); + } + + @Override + public int nioBufferCount() { + return 1; + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + return new ByteBuffer[] { nioBuffer(index, length) }; + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + return (ByteBuffer) buffer.duplicate().position(index).limit(index + length); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + ensureAccessible(); + return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); + } + + @Override + public boolean hasArray() { + return buffer.hasArray(); + } + + @Override + public byte[] array() { + return buffer.array(); + } + + @Override + public int arrayOffset() { + return buffer.arrayOffset(); + } +} diff --git a/common/src/main/java/common/net/buffer/SimpleLeakAwareByteBuf.java b/common/src/main/java/common/net/buffer/SimpleLeakAwareByteBuf.java new file mode 100644 index 0000000..688af60 --- /dev/null +++ b/common/src/main/java/common/net/buffer/SimpleLeakAwareByteBuf.java @@ -0,0 +1,79 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import java.nio.ByteOrder; + +import common.net.util.ResourceLeak; + +final class SimpleLeakAwareByteBuf extends WrappedByteBuf { + + private final ResourceLeak leak; + + SimpleLeakAwareByteBuf(ByteBuf buf, ResourceLeak leak) { + super(buf); + this.leak = leak; + } + + @Override + public boolean release() { + boolean deallocated = super.release(); + if (deallocated) { + leak.close(); + } + return deallocated; + } + + @Override + public boolean release(int decrement) { + boolean deallocated = super.release(decrement); + if (deallocated) { + leak.close(); + } + return deallocated; + } + + @Override + public ByteBuf order(ByteOrder endianness) { + leak.record(); + if (order() == endianness) { + return this; + } else { + return new SimpleLeakAwareByteBuf(super.order(endianness), leak); + } + } + + @Override + public ByteBuf slice() { + return new SimpleLeakAwareByteBuf(super.slice(), leak); + } + + @Override + public ByteBuf slice(int index, int length) { + return new SimpleLeakAwareByteBuf(super.slice(index, length), leak); + } + + @Override + public ByteBuf duplicate() { + return new SimpleLeakAwareByteBuf(super.duplicate(), leak); + } + + @Override + public ByteBuf readSlice(int length) { + return new SimpleLeakAwareByteBuf(super.readSlice(length), leak); + } +} diff --git a/common/src/main/java/common/net/buffer/SlicedByteBuf.java b/common/src/main/java/common/net/buffer/SlicedByteBuf.java new file mode 100644 index 0000000..d0b26eb --- /dev/null +++ b/common/src/main/java/common/net/buffer/SlicedByteBuf.java @@ -0,0 +1,286 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; + + +/** + * A derived buffer which exposes its parent's sub-region only. It is + * recommended to use {@link ByteBuf#slice()} and + * {@link ByteBuf#slice(int, int)} instead of calling the constructor + * explicitly. + */ +public class SlicedByteBuf extends AbstractDerivedByteBuf { + + private final ByteBuf buffer; + private final int adjustment; + private final int length; + + public SlicedByteBuf(ByteBuf buffer, int index, int length) { + super(length); + if (index < 0 || index > buffer.capacity() - length) { + throw new IndexOutOfBoundsException(buffer + ".slice(" + index + ", " + length + ')'); + } + + if (buffer instanceof SlicedByteBuf) { + this.buffer = ((SlicedByteBuf) buffer).buffer; + adjustment = ((SlicedByteBuf) buffer).adjustment + index; + } else if (buffer instanceof DuplicatedByteBuf) { + this.buffer = buffer.unwrap(); + adjustment = index; + } else { + this.buffer = buffer; + adjustment = index; + } + this.length = length; + + writerIndex(length); + } + + @Override + public ByteBuf unwrap() { + return buffer; + } + + @Override + public ByteBufAllocator alloc() { + return buffer.alloc(); + } + + @Override + public ByteOrder order() { + return buffer.order(); + } + + @Override + public boolean isDirect() { + return buffer.isDirect(); + } + + @Override + public int capacity() { + return length; + } + + @Override + public ByteBuf capacity(int newCapacity) { + throw new UnsupportedOperationException("sliced buffer"); + } + + @Override + public boolean hasArray() { + return buffer.hasArray(); + } + + @Override + public byte[] array() { + return buffer.array(); + } + + @Override + public int arrayOffset() { + return buffer.arrayOffset() + adjustment; + } + + @Override + protected byte _getByte(int index) { + return buffer.getByte(index + adjustment); + } + + @Override + protected short _getShort(int index) { + return buffer.getShort(index + adjustment); + } + + @Override + protected int _getUnsignedMedium(int index) { + return buffer.getUnsignedMedium(index + adjustment); + } + + @Override + protected int _getInt(int index) { + return buffer.getInt(index + adjustment); + } + + @Override + protected long _getLong(int index) { + return buffer.getLong(index + adjustment); + } + + @Override + public ByteBuf duplicate() { + ByteBuf duplicate = buffer.slice(adjustment, length); + duplicate.setIndex(readerIndex(), writerIndex()); + return duplicate; + } + + @Override + public ByteBuf copy(int index, int length) { + checkIndex(index, length); + return buffer.copy(index + adjustment, length); + } + + @Override + public ByteBuf slice(int index, int length) { + checkIndex(index, length); + if (length == 0) { + return Unpooled.EMPTY_BUFFER; + } + return buffer.slice(index + adjustment, length); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + checkIndex(index, length); + buffer.getBytes(index + adjustment, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + checkIndex(index, length); + buffer.getBytes(index + adjustment, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + checkIndex(index, dst.remaining()); + buffer.getBytes(index + adjustment, dst); + return this; + } + + @Override + protected void _setByte(int index, int value) { + buffer.setByte(index + adjustment, value); + } + + @Override + protected void _setShort(int index, int value) { + buffer.setShort(index + adjustment, value); + } + + @Override + protected void _setMedium(int index, int value) { + buffer.setMedium(index + adjustment, value); + } + + @Override + protected void _setInt(int index, int value) { + buffer.setInt(index + adjustment, value); + } + + @Override + protected void _setLong(int index, long value) { + buffer.setLong(index + adjustment, value); + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + checkIndex(index, length); + buffer.setBytes(index + adjustment, src, srcIndex, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + checkIndex(index, length); + buffer.setBytes(index + adjustment, src, srcIndex, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + checkIndex(index, src.remaining()); + buffer.setBytes(index + adjustment, src); + return this; + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + checkIndex(index, length); + buffer.getBytes(index + adjustment, out, length); + return this; + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { + checkIndex(index, length); + return buffer.getBytes(index + adjustment, out, length); + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + checkIndex(index, length); + return buffer.setBytes(index + adjustment, in, length); + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + checkIndex(index, length); + return buffer.setBytes(index + adjustment, in, length); + } + + @Override + public int nioBufferCount() { + return buffer.nioBufferCount(); + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + checkIndex(index, length); + return buffer.nioBuffer(index + adjustment, length); + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + checkIndex(index, length); + return buffer.nioBuffers(index + adjustment, length); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + checkIndex(index, length); + return nioBuffer(index, length); + } + + @Override + public int forEachByte(int index, int length, ByteBufProcessor processor) { + int ret = buffer.forEachByte(index + adjustment, length, processor); + if (ret >= adjustment) { + return ret - adjustment; + } else { + return -1; + } + } + + @Override + public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { + int ret = buffer.forEachByteDesc(index + adjustment, length, processor); + if (ret >= adjustment) { + return ret - adjustment; + } else { + return -1; + } + } +} diff --git a/common/src/main/java/common/net/buffer/SwappedByteBuf.java b/common/src/main/java/common/net/buffer/SwappedByteBuf.java new file mode 100644 index 0000000..d5c0a96 --- /dev/null +++ b/common/src/main/java/common/net/buffer/SwappedByteBuf.java @@ -0,0 +1,842 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; +import java.nio.charset.Charset; + +/** + * Wrapper which swap the {@link ByteOrder} of a {@link ByteBuf}. + */ +public class SwappedByteBuf extends ByteBuf { + + private final ByteBuf buf; + private final ByteOrder order; + + public SwappedByteBuf(ByteBuf buf) { + if (buf == null) { + throw new NullPointerException("buf"); + } + this.buf = buf; + if (buf.order() == ByteOrder.BIG_ENDIAN) { + order = ByteOrder.LITTLE_ENDIAN; + } else { + order = ByteOrder.BIG_ENDIAN; + } + } + + @Override + public ByteOrder order() { + return order; + } + + @Override + public ByteBuf order(ByteOrder endianness) { + if (endianness == null) { + throw new NullPointerException("endianness"); + } + if (endianness == order) { + return this; + } + return buf; + } + + @Override + public ByteBuf unwrap() { + return buf.unwrap(); + } + + @Override + public ByteBufAllocator alloc() { + return buf.alloc(); + } + + @Override + public int capacity() { + return buf.capacity(); + } + + @Override + public ByteBuf capacity(int newCapacity) { + buf.capacity(newCapacity); + return this; + } + + @Override + public int maxCapacity() { + return buf.maxCapacity(); + } + + @Override + public boolean isDirect() { + return buf.isDirect(); + } + + @Override + public int readerIndex() { + return buf.readerIndex(); + } + + @Override + public ByteBuf readerIndex(int readerIndex) { + buf.readerIndex(readerIndex); + return this; + } + + @Override + public int writerIndex() { + return buf.writerIndex(); + } + + @Override + public ByteBuf writerIndex(int writerIndex) { + buf.writerIndex(writerIndex); + return this; + } + + @Override + public ByteBuf setIndex(int readerIndex, int writerIndex) { + buf.setIndex(readerIndex, writerIndex); + return this; + } + + @Override + public int readableBytes() { + return buf.readableBytes(); + } + + @Override + public int writableBytes() { + return buf.writableBytes(); + } + + @Override + public int maxWritableBytes() { + return buf.maxWritableBytes(); + } + + @Override + public boolean isReadable() { + return buf.isReadable(); + } + + @Override + public boolean isReadable(int size) { + return buf.isReadable(size); + } + + @Override + public boolean isWritable() { + return buf.isWritable(); + } + + @Override + public boolean isWritable(int size) { + return buf.isWritable(size); + } + + @Override + public ByteBuf clear() { + buf.clear(); + return this; + } + + @Override + public ByteBuf markReaderIndex() { + buf.markReaderIndex(); + return this; + } + + @Override + public ByteBuf resetReaderIndex() { + buf.resetReaderIndex(); + return this; + } + + @Override + public ByteBuf markWriterIndex() { + buf.markWriterIndex(); + return this; + } + + @Override + public ByteBuf resetWriterIndex() { + buf.resetWriterIndex(); + return this; + } + + @Override + public ByteBuf discardReadBytes() { + buf.discardReadBytes(); + return this; + } + + @Override + public ByteBuf discardSomeReadBytes() { + buf.discardSomeReadBytes(); + return this; + } + + @Override + public ByteBuf ensureWritable(int writableBytes) { + buf.ensureWritable(writableBytes); + return this; + } + + @Override + public int ensureWritable(int minWritableBytes, boolean force) { + return buf.ensureWritable(minWritableBytes, force); + } + + @Override + public boolean getBoolean(int index) { + return buf.getBoolean(index); + } + + @Override + public byte getByte(int index) { + return buf.getByte(index); + } + + @Override + public short getUnsignedByte(int index) { + return buf.getUnsignedByte(index); + } + + @Override + public short getShort(int index) { + return ByteBufUtil.swapShort(buf.getShort(index)); + } + + @Override + public int getUnsignedShort(int index) { + return getShort(index) & 0xFFFF; + } + + @Override + public int getMedium(int index) { + return ByteBufUtil.swapMedium(buf.getMedium(index)); + } + + @Override + public int getUnsignedMedium(int index) { + return getMedium(index) & 0xFFFFFF; + } + + @Override + public int getInt(int index) { + return ByteBufUtil.swapInt(buf.getInt(index)); + } + + @Override + public long getUnsignedInt(int index) { + return getInt(index) & 0xFFFFFFFFL; + } + + @Override + public long getLong(int index) { + return ByteBufUtil.swapLong(buf.getLong(index)); + } + + @Override + public char getChar(int index) { + return (char) getShort(index); + } + + @Override + public float getFloat(int index) { + return Float.intBitsToFloat(getInt(index)); + } + + @Override + public double getDouble(int index) { + return Double.longBitsToDouble(getLong(index)); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst) { + buf.getBytes(index, dst); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int length) { + buf.getBytes(index, dst, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + buf.getBytes(index, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst) { + buf.getBytes(index, dst); + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + buf.getBytes(index, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + buf.getBytes(index, dst); + return this; + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + buf.getBytes(index, out, length); + return this; + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { + return buf.getBytes(index, out, length); + } + + @Override + public ByteBuf setBoolean(int index, boolean value) { + buf.setBoolean(index, value); + return this; + } + + @Override + public ByteBuf setByte(int index, int value) { + buf.setByte(index, value); + return this; + } + + @Override + public ByteBuf setShort(int index, int value) { + buf.setShort(index, ByteBufUtil.swapShort((short) value)); + return this; + } + + @Override + public ByteBuf setMedium(int index, int value) { + buf.setMedium(index, ByteBufUtil.swapMedium(value)); + return this; + } + + @Override + public ByteBuf setInt(int index, int value) { + buf.setInt(index, ByteBufUtil.swapInt(value)); + return this; + } + + @Override + public ByteBuf setLong(int index, long value) { + buf.setLong(index, ByteBufUtil.swapLong(value)); + return this; + } + + @Override + public ByteBuf setChar(int index, int value) { + setShort(index, value); + return this; + } + + @Override + public ByteBuf setFloat(int index, float value) { + setInt(index, Float.floatToRawIntBits(value)); + return this; + } + + @Override + public ByteBuf setDouble(int index, double value) { + setLong(index, Double.doubleToRawLongBits(value)); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src) { + buf.setBytes(index, src); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int length) { + buf.setBytes(index, src, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + buf.setBytes(index, src, srcIndex, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, byte[] src) { + buf.setBytes(index, src); + return this; + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + buf.setBytes(index, src, srcIndex, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + buf.setBytes(index, src); + return this; + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + return buf.setBytes(index, in, length); + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + return buf.setBytes(index, in, length); + } + + @Override + public ByteBuf setZero(int index, int length) { + buf.setZero(index, length); + return this; + } + + @Override + public boolean readBoolean() { + return buf.readBoolean(); + } + + @Override + public byte readByte() { + return buf.readByte(); + } + + @Override + public short readUnsignedByte() { + return buf.readUnsignedByte(); + } + + @Override + public short readShort() { + return ByteBufUtil.swapShort(buf.readShort()); + } + + @Override + public int readUnsignedShort() { + return readShort() & 0xFFFF; + } + + @Override + public int readMedium() { + return ByteBufUtil.swapMedium(buf.readMedium()); + } + + @Override + public int readUnsignedMedium() { + return readMedium() & 0xFFFFFF; + } + + @Override + public int readInt() { + return ByteBufUtil.swapInt(buf.readInt()); + } + + @Override + public long readUnsignedInt() { + return readInt() & 0xFFFFFFFFL; + } + + @Override + public long readLong() { + return ByteBufUtil.swapLong(buf.readLong()); + } + + @Override + public char readChar() { + return (char) readShort(); + } + + @Override + public float readFloat() { + return Float.intBitsToFloat(readInt()); + } + + @Override + public double readDouble() { + return Double.longBitsToDouble(readLong()); + } + + @Override + public ByteBuf readBytes(int length) { + return buf.readBytes(length).order(order()); + } + + @Override + public ByteBuf readSlice(int length) { + return buf.readSlice(length).order(order); + } + + @Override + public ByteBuf readBytes(ByteBuf dst) { + buf.readBytes(dst); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int length) { + buf.readBytes(dst, length); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { + buf.readBytes(dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf readBytes(byte[] dst) { + buf.readBytes(dst); + return this; + } + + @Override + public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { + buf.readBytes(dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuffer dst) { + buf.readBytes(dst); + return this; + } + + @Override + public ByteBuf readBytes(OutputStream out, int length) throws IOException { + buf.readBytes(out, length); + return this; + } + + @Override + public int readBytes(GatheringByteChannel out, int length) throws IOException { + return buf.readBytes(out, length); + } + + @Override + public ByteBuf skipBytes(int length) { + buf.skipBytes(length); + return this; + } + + @Override + public ByteBuf writeBoolean(boolean value) { + buf.writeBoolean(value); + return this; + } + + @Override + public ByteBuf writeByte(int value) { + buf.writeByte(value); + return this; + } + + @Override + public ByteBuf writeShort(int value) { + buf.writeShort(ByteBufUtil.swapShort((short) value)); + return this; + } + + @Override + public ByteBuf writeMedium(int value) { + buf.writeMedium(ByteBufUtil.swapMedium(value)); + return this; + } + + @Override + public ByteBuf writeInt(int value) { + buf.writeInt(ByteBufUtil.swapInt(value)); + return this; + } + + @Override + public ByteBuf writeLong(long value) { + buf.writeLong(ByteBufUtil.swapLong(value)); + return this; + } + + @Override + public ByteBuf writeChar(int value) { + writeShort(value); + return this; + } + + @Override + public ByteBuf writeFloat(float value) { + writeInt(Float.floatToRawIntBits(value)); + return this; + } + + @Override + public ByteBuf writeDouble(double value) { + writeLong(Double.doubleToRawLongBits(value)); + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuf src) { + buf.writeBytes(src); + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuf src, int length) { + buf.writeBytes(src, length); + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { + buf.writeBytes(src, srcIndex, length); + return this; + } + + @Override + public ByteBuf writeBytes(byte[] src) { + buf.writeBytes(src); + return this; + } + + @Override + public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { + buf.writeBytes(src, srcIndex, length); + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuffer src) { + buf.writeBytes(src); + return this; + } + + @Override + public int writeBytes(InputStream in, int length) throws IOException { + return buf.writeBytes(in, length); + } + + @Override + public int writeBytes(ScatteringByteChannel in, int length) throws IOException { + return buf.writeBytes(in, length); + } + + @Override + public ByteBuf writeZero(int length) { + buf.writeZero(length); + return this; + } + + @Override + public int indexOf(int fromIndex, int toIndex, byte value) { + return buf.indexOf(fromIndex, toIndex, value); + } + + @Override + public int bytesBefore(byte value) { + return buf.bytesBefore(value); + } + + @Override + public int bytesBefore(int length, byte value) { + return buf.bytesBefore(length, value); + } + + @Override + public int bytesBefore(int index, int length, byte value) { + return buf.bytesBefore(index, length, value); + } + + @Override + public int forEachByte(ByteBufProcessor processor) { + return buf.forEachByte(processor); + } + + @Override + public int forEachByte(int index, int length, ByteBufProcessor processor) { + return buf.forEachByte(index, length, processor); + } + + @Override + public int forEachByteDesc(ByteBufProcessor processor) { + return buf.forEachByteDesc(processor); + } + + @Override + public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { + return buf.forEachByteDesc(index, length, processor); + } + + @Override + public ByteBuf copy() { + return buf.copy().order(order); + } + + @Override + public ByteBuf copy(int index, int length) { + return buf.copy(index, length).order(order); + } + + @Override + public ByteBuf slice() { + return buf.slice().order(order); + } + + @Override + public ByteBuf slice(int index, int length) { + return buf.slice(index, length).order(order); + } + + @Override + public ByteBuf duplicate() { + return buf.duplicate().order(order); + } + + @Override + public int nioBufferCount() { + return buf.nioBufferCount(); + } + + @Override + public ByteBuffer nioBuffer() { + return buf.nioBuffer().order(order); + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + return buf.nioBuffer(index, length).order(order); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + return nioBuffer(index, length); + } + + @Override + public ByteBuffer[] nioBuffers() { + ByteBuffer[] nioBuffers = buf.nioBuffers(); + for (int i = 0; i < nioBuffers.length; i++) { + nioBuffers[i] = nioBuffers[i].order(order); + } + return nioBuffers; + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + ByteBuffer[] nioBuffers = buf.nioBuffers(index, length); + for (int i = 0; i < nioBuffers.length; i++) { + nioBuffers[i] = nioBuffers[i].order(order); + } + return nioBuffers; + } + + @Override + public boolean hasArray() { + return buf.hasArray(); + } + + @Override + public byte[] array() { + return buf.array(); + } + + @Override + public int arrayOffset() { + return buf.arrayOffset(); + } + + @Override + public String toString(Charset charset) { + return buf.toString(charset); + } + + @Override + public String toString(int index, int length, Charset charset) { + return buf.toString(index, length, charset); + } + + @Override + public int refCnt() { + return buf.refCnt(); + } + + @Override + public ByteBuf retain() { + buf.retain(); + return this; + } + + @Override + public ByteBuf retain(int increment) { + buf.retain(increment); + return this; + } + + @Override + public boolean release() { + return buf.release(); + } + + @Override + public boolean release(int decrement) { + return buf.release(decrement); + } + + @Override + public int hashCode() { + return buf.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj instanceof ByteBuf) { + return ByteBufUtil.equals(this, (ByteBuf) obj); + } + return false; + } + + @Override + public int compareTo(ByteBuf buffer) { + return ByteBufUtil.compare(this, buffer); + } + + @Override + public String toString() { + return "Swapped(" + buf.toString() + ')'; + } +} diff --git a/common/src/main/java/common/net/buffer/Unpooled.java b/common/src/main/java/common/net/buffer/Unpooled.java new file mode 100644 index 0000000..ffd166e --- /dev/null +++ b/common/src/main/java/common/net/buffer/Unpooled.java @@ -0,0 +1,850 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.CharBuffer; +import java.nio.charset.Charset; +import java.util.ArrayList; +import java.util.List; + + +/** + * Creates a new {@link ByteBuf} by allocating new space or by wrapping + * or copying existing byte arrays, byte buffers and a string. + * + *

Use static import

+ * This classes is intended to be used with Java 5 static import statement: + * + *
+ * import static game.net.buffer.{@link Unpooled}.*;
+ *
+ * {@link ByteBuf} heapBuffer    = buffer(128);
+ * {@link ByteBuf} directBuffer  = directBuffer(256);
+ * {@link ByteBuf} wrappedBuffer = wrappedBuffer(new byte[128], new byte[256]);
+ * {@link ByteBuf} copiedBuffe r = copiedBuffer({@link ByteBuffer}.allocate(128));
+ * 
+ * + *

Allocating a new buffer

+ * + * Three buffer types are provided out of the box. + * + *
    + *
  • {@link #buffer(int)} allocates a new fixed-capacity heap buffer.
  • + *
  • {@link #directBuffer(int)} allocates a new fixed-capacity direct buffer.
  • + *
+ * + *

Creating a wrapped buffer

+ * + * Wrapped buffer is a buffer which is a view of one or more existing + * byte arrays and byte buffers. Any changes in the content of the original + * array or buffer will be visible in the wrapped buffer. Various wrapper + * methods are provided and their name is all {@code wrappedBuffer()}. + * You might want to take a look at the methods that accept varargs closely if + * you want to create a buffer which is composed of more than one array to + * reduce the number of memory copy. + * + *

Creating a copied buffer

+ * + * Copied buffer is a deep copy of one or more existing byte arrays, byte + * buffers or a string. Unlike a wrapped buffer, there's no shared data + * between the original data and the copied buffer. Various copy methods are + * provided and their name is all {@code copiedBuffer()}. It is also convenient + * to use this operation to merge multiple buffers into one buffer. + * + *

Miscellaneous utility methods

+ * + * This class also provides various utility methods to help implementation + * of a new buffer type, generation of hex dump and swapping an integer's + * byte order. + */ +public final class Unpooled { + + private static final ByteBufAllocator ALLOC = UnpooledByteBufAllocator.DEFAULT; + + /** + * Big endian byte order. + */ + public static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN; + + /** + * Little endian byte order. + */ + public static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN; + + /** + * A buffer whose capacity is {@code 0}. + */ + public static final ByteBuf EMPTY_BUFFER = ALLOC.buffer(0, 0); + + /** + * Creates a new big-endian Java heap buffer with reasonably small initial capacity, which + * expands its capacity boundlessly on demand. + */ + public static ByteBuf buffer() { + return ALLOC.heapBuffer(); + } + + /** + * Creates a new big-endian direct buffer with reasonably small initial capacity, which + * expands its capacity boundlessly on demand. + */ + public static ByteBuf directBuffer() { + return ALLOC.directBuffer(); + } + + /** + * Creates a new big-endian Java heap buffer with the specified {@code capacity}, which + * expands its capacity boundlessly on demand. The new buffer's {@code readerIndex} and + * {@code writerIndex} are {@code 0}. + */ + public static ByteBuf buffer(int initialCapacity) { + return ALLOC.heapBuffer(initialCapacity); + } + + /** + * Creates a new big-endian direct buffer with the specified {@code capacity}, which + * expands its capacity boundlessly on demand. The new buffer's {@code readerIndex} and + * {@code writerIndex} are {@code 0}. + */ + public static ByteBuf directBuffer(int initialCapacity) { + return ALLOC.directBuffer(initialCapacity); + } + + /** + * Creates a new big-endian Java heap buffer with the specified + * {@code initialCapacity}, that may grow up to {@code maxCapacity} + * The new buffer's {@code readerIndex} and {@code writerIndex} are + * {@code 0}. + */ + public static ByteBuf buffer(int initialCapacity, int maxCapacity) { + return ALLOC.heapBuffer(initialCapacity, maxCapacity); + } + + /** + * Creates a new big-endian direct buffer with the specified + * {@code initialCapacity}, that may grow up to {@code maxCapacity}. + * The new buffer's {@code readerIndex} and {@code writerIndex} are + * {@code 0}. + */ + public static ByteBuf directBuffer(int initialCapacity, int maxCapacity) { + return ALLOC.directBuffer(initialCapacity, maxCapacity); + } + + /** + * Creates a new big-endian buffer which wraps the specified {@code array}. + * A modification on the specified array's content will be visible to the + * returned buffer. + */ + public static ByteBuf wrappedBuffer(byte[] array) { + if (array.length == 0) { + return EMPTY_BUFFER; + } + return new UnpooledHeapByteBuf(ALLOC, array, array.length); + } + + /** + * Creates a new big-endian buffer which wraps the sub-region of the + * specified {@code array}. A modification on the specified array's + * content will be visible to the returned buffer. + */ + public static ByteBuf wrappedBuffer(byte[] array, int offset, int length) { + if (length == 0) { + return EMPTY_BUFFER; + } + + if (offset == 0 && length == array.length) { + return wrappedBuffer(array); + } + + return wrappedBuffer(array).slice(offset, length); + } + + /** + * Creates a new buffer which wraps the specified NIO buffer's current + * slice. A modification on the specified buffer's content will be + * visible to the returned buffer. + */ + public static ByteBuf wrappedBuffer(ByteBuffer buffer) { + if (!buffer.hasRemaining()) { + return EMPTY_BUFFER; + } + if (buffer.hasArray()) { + return wrappedBuffer( + buffer.array(), + buffer.arrayOffset() + buffer.position(), + buffer.remaining()).order(buffer.order()); + } + else { + if (buffer.isReadOnly()) { + return new ReadOnlyByteBufferBuf(ALLOC, buffer); + } else { + return new UnpooledDirectByteBuf(ALLOC, buffer, buffer.remaining()); + } + } + } + + /** + * Creates a new buffer which wraps the specified buffer's readable bytes. + * A modification on the specified buffer's content will be visible to the + * returned buffer. + */ + public static ByteBuf wrappedBuffer(ByteBuf buffer) { + if (buffer.isReadable()) { + return buffer.slice(); + } else { + return EMPTY_BUFFER; + } + } + + /** + * Creates a new big-endian composite buffer which wraps the specified + * arrays without copying them. A modification on the specified arrays' + * content will be visible to the returned buffer. + */ + public static ByteBuf wrappedBuffer(byte[]... arrays) { + return wrappedBuffer(16, arrays); + } + + /** + * Creates a new big-endian composite buffer which wraps the readable bytes of the + * specified buffers without copying them. A modification on the content + * of the specified buffers will be visible to the returned buffer. + */ + public static ByteBuf wrappedBuffer(ByteBuf... buffers) { + return wrappedBuffer(16, buffers); + } + + /** + * Creates a new big-endian composite buffer which wraps the slices of the specified + * NIO buffers without copying them. A modification on the content of the + * specified buffers will be visible to the returned buffer. + */ + public static ByteBuf wrappedBuffer(ByteBuffer... buffers) { + return wrappedBuffer(16, buffers); + } + + /** + * Creates a new big-endian composite buffer which wraps the specified + * arrays without copying them. A modification on the specified arrays' + * content will be visible to the returned buffer. + */ + public static ByteBuf wrappedBuffer(int maxNumComponents, byte[]... arrays) { + switch (arrays.length) { + case 0: + break; + case 1: + if (arrays[0].length != 0) { + return wrappedBuffer(arrays[0]); + } + break; + default: + // Get the list of the component, while guessing the byte order. + final List components = new ArrayList(arrays.length); + for (byte[] a: arrays) { + if (a == null) { + break; + } + if (a.length > 0) { + components.add(wrappedBuffer(a)); + } + } + + if (!components.isEmpty()) { + return new CompositeByteBuf(ALLOC, false, maxNumComponents, components); + } + } + + return EMPTY_BUFFER; + } + + /** + * Creates a new big-endian composite buffer which wraps the readable bytes of the + * specified buffers without copying them. A modification on the content + * of the specified buffers will be visible to the returned buffer. + */ + public static ByteBuf wrappedBuffer(int maxNumComponents, ByteBuf... buffers) { + switch (buffers.length) { + case 0: + break; + case 1: + if (buffers[0].isReadable()) { + return wrappedBuffer(buffers[0].order(BIG_ENDIAN)); + } + break; + default: + for (ByteBuf b: buffers) { + if (b.isReadable()) { + return new CompositeByteBuf(ALLOC, false, maxNumComponents, buffers); + } + } + } + return EMPTY_BUFFER; + } + + /** + * Creates a new big-endian composite buffer which wraps the slices of the specified + * NIO buffers without copying them. A modification on the content of the + * specified buffers will be visible to the returned buffer. + */ + public static ByteBuf wrappedBuffer(int maxNumComponents, ByteBuffer... buffers) { + switch (buffers.length) { + case 0: + break; + case 1: + if (buffers[0].hasRemaining()) { + return wrappedBuffer(buffers[0].order(BIG_ENDIAN)); + } + break; + default: + // Get the list of the component, while guessing the byte order. + final List components = new ArrayList(buffers.length); + for (ByteBuffer b: buffers) { + if (b == null) { + break; + } + if (b.remaining() > 0) { + components.add(wrappedBuffer(b.order(BIG_ENDIAN))); + } + } + + if (!components.isEmpty()) { + return new CompositeByteBuf(ALLOC, false, maxNumComponents, components); + } + } + + return EMPTY_BUFFER; + } + + /** + * Returns a new big-endian composite buffer with no components. + */ + public static CompositeByteBuf compositeBuffer() { + return compositeBuffer(16); + } + + /** + * Returns a new big-endian composite buffer with no components. + */ + public static CompositeByteBuf compositeBuffer(int maxNumComponents) { + return new CompositeByteBuf(ALLOC, false, maxNumComponents); + } + + /** + * Creates a new big-endian buffer whose content is a copy of the + * specified {@code array}. The new buffer's {@code readerIndex} and + * {@code writerIndex} are {@code 0} and {@code array.length} respectively. + */ + public static ByteBuf copiedBuffer(byte[] array) { + if (array.length == 0) { + return EMPTY_BUFFER; + } + return wrappedBuffer(array.clone()); + } + + /** + * Creates a new big-endian buffer whose content is a copy of the + * specified {@code array}'s sub-region. The new buffer's + * {@code readerIndex} and {@code writerIndex} are {@code 0} and + * the specified {@code length} respectively. + */ + public static ByteBuf copiedBuffer(byte[] array, int offset, int length) { + if (length == 0) { + return EMPTY_BUFFER; + } + byte[] copy = new byte[length]; + System.arraycopy(array, offset, copy, 0, length); + return wrappedBuffer(copy); + } + + /** + * Creates a new buffer whose content is a copy of the specified + * {@code buffer}'s current slice. The new buffer's {@code readerIndex} + * and {@code writerIndex} are {@code 0} and {@code buffer.remaining} + * respectively. + */ + public static ByteBuf copiedBuffer(ByteBuffer buffer) { + int length = buffer.remaining(); + if (length == 0) { + return EMPTY_BUFFER; + } + byte[] copy = new byte[length]; + int position = buffer.position(); + try { + buffer.get(copy); + } finally { + buffer.position(position); + } + return wrappedBuffer(copy).order(buffer.order()); + } + + /** + * Creates a new buffer whose content is a copy of the specified + * {@code buffer}'s readable bytes. The new buffer's {@code readerIndex} + * and {@code writerIndex} are {@code 0} and {@code buffer.readableBytes} + * respectively. + */ + public static ByteBuf copiedBuffer(ByteBuf buffer) { + int readable = buffer.readableBytes(); + if (readable > 0) { + ByteBuf copy = buffer(readable); + copy.writeBytes(buffer, buffer.readerIndex(), readable); + return copy; + } else { + return EMPTY_BUFFER; + } + } + + /** + * Creates a new big-endian buffer whose content is a merged copy of + * the specified {@code arrays}. The new buffer's {@code readerIndex} + * and {@code writerIndex} are {@code 0} and the sum of all arrays' + * {@code length} respectively. + */ + public static ByteBuf copiedBuffer(byte[]... arrays) { + switch (arrays.length) { + case 0: + return EMPTY_BUFFER; + case 1: + if (arrays[0].length == 0) { + return EMPTY_BUFFER; + } else { + return copiedBuffer(arrays[0]); + } + } + + // Merge the specified arrays into one array. + int length = 0; + for (byte[] a: arrays) { + if (Integer.MAX_VALUE - length < a.length) { + throw new IllegalArgumentException( + "The total length of the specified arrays is too big."); + } + length += a.length; + } + + if (length == 0) { + return EMPTY_BUFFER; + } + + byte[] mergedArray = new byte[length]; + for (int i = 0, j = 0; i < arrays.length; i ++) { + byte[] a = arrays[i]; + System.arraycopy(a, 0, mergedArray, j, a.length); + j += a.length; + } + + return wrappedBuffer(mergedArray); + } + + /** + * Creates a new buffer whose content is a merged copy of the specified + * {@code buffers}' readable bytes. The new buffer's {@code readerIndex} + * and {@code writerIndex} are {@code 0} and the sum of all buffers' + * {@code readableBytes} respectively. + * + * @throws IllegalArgumentException + * if the specified buffers' endianness are different from each + * other + */ + public static ByteBuf copiedBuffer(ByteBuf... buffers) { + switch (buffers.length) { + case 0: + return EMPTY_BUFFER; + case 1: + return copiedBuffer(buffers[0]); + } + + // Merge the specified buffers into one buffer. + ByteOrder order = null; + int length = 0; + for (ByteBuf b: buffers) { + int bLen = b.readableBytes(); + if (bLen <= 0) { + continue; + } + if (Integer.MAX_VALUE - length < bLen) { + throw new IllegalArgumentException( + "The total length of the specified buffers is too big."); + } + length += bLen; + if (order != null) { + if (!order.equals(b.order())) { + throw new IllegalArgumentException("inconsistent byte order"); + } + } else { + order = b.order(); + } + } + + if (length == 0) { + return EMPTY_BUFFER; + } + + byte[] mergedArray = new byte[length]; + for (int i = 0, j = 0; i < buffers.length; i ++) { + ByteBuf b = buffers[i]; + int bLen = b.readableBytes(); + b.getBytes(b.readerIndex(), mergedArray, j, bLen); + j += bLen; + } + + return wrappedBuffer(mergedArray).order(order); + } + + /** + * Creates a new buffer whose content is a merged copy of the specified + * {@code buffers}' slices. The new buffer's {@code readerIndex} and + * {@code writerIndex} are {@code 0} and the sum of all buffers' + * {@code remaining} respectively. + * + * @throws IllegalArgumentException + * if the specified buffers' endianness are different from each + * other + */ + public static ByteBuf copiedBuffer(ByteBuffer... buffers) { + switch (buffers.length) { + case 0: + return EMPTY_BUFFER; + case 1: + return copiedBuffer(buffers[0]); + } + + // Merge the specified buffers into one buffer. + ByteOrder order = null; + int length = 0; + for (ByteBuffer b: buffers) { + int bLen = b.remaining(); + if (bLen <= 0) { + continue; + } + if (Integer.MAX_VALUE - length < bLen) { + throw new IllegalArgumentException( + "The total length of the specified buffers is too big."); + } + length += bLen; + if (order != null) { + if (!order.equals(b.order())) { + throw new IllegalArgumentException("inconsistent byte order"); + } + } else { + order = b.order(); + } + } + + if (length == 0) { + return EMPTY_BUFFER; + } + + byte[] mergedArray = new byte[length]; + for (int i = 0, j = 0; i < buffers.length; i ++) { + ByteBuffer b = buffers[i]; + int bLen = b.remaining(); + int oldPos = b.position(); + b.get(mergedArray, j, bLen); + b.position(oldPos); + j += bLen; + } + + return wrappedBuffer(mergedArray).order(order); + } + + /** + * Creates a new big-endian buffer whose content is the specified + * {@code string} encoded in the specified {@code charset}. + * The new buffer's {@code readerIndex} and {@code writerIndex} are + * {@code 0} and the length of the encoded string respectively. + */ + public static ByteBuf copiedBuffer(CharSequence string, Charset charset) { + if (string == null) { + throw new NullPointerException("string"); + } + + if (string instanceof CharBuffer) { + return copiedBuffer((CharBuffer) string, charset); + } + + return copiedBuffer(CharBuffer.wrap(string), charset); + } + + /** + * Creates a new big-endian buffer whose content is a subregion of + * the specified {@code string} encoded in the specified {@code charset}. + * The new buffer's {@code readerIndex} and {@code writerIndex} are + * {@code 0} and the length of the encoded string respectively. + */ + public static ByteBuf copiedBuffer( + CharSequence string, int offset, int length, Charset charset) { + if (string == null) { + throw new NullPointerException("string"); + } + if (length == 0) { + return EMPTY_BUFFER; + } + + if (string instanceof CharBuffer) { + CharBuffer buf = (CharBuffer) string; + if (buf.hasArray()) { + return copiedBuffer( + buf.array(), + buf.arrayOffset() + buf.position() + offset, + length, charset); + } + + buf = buf.slice(); + buf.limit(length); + buf.position(offset); + return copiedBuffer(buf, charset); + } + + return copiedBuffer(CharBuffer.wrap(string, offset, offset + length), charset); + } + + /** + * Creates a new big-endian buffer whose content is the specified + * {@code array} encoded in the specified {@code charset}. + * The new buffer's {@code readerIndex} and {@code writerIndex} are + * {@code 0} and the length of the encoded string respectively. + */ + public static ByteBuf copiedBuffer(char[] array, Charset charset) { + if (array == null) { + throw new NullPointerException("array"); + } + return copiedBuffer(array, 0, array.length, charset); + } + + /** + * Creates a new big-endian buffer whose content is a subregion of + * the specified {@code array} encoded in the specified {@code charset}. + * The new buffer's {@code readerIndex} and {@code writerIndex} are + * {@code 0} and the length of the encoded string respectively. + */ + public static ByteBuf copiedBuffer(char[] array, int offset, int length, Charset charset) { + if (array == null) { + throw new NullPointerException("array"); + } + if (length == 0) { + return EMPTY_BUFFER; + } + return copiedBuffer(CharBuffer.wrap(array, offset, length), charset); + } + + private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset) { + return ByteBufUtil.encodeString0(ALLOC, true, buffer, charset); + } + + /** + * Creates a read-only buffer which disallows any modification operations + * on the specified {@code buffer}. The new buffer has the same + * {@code readerIndex} and {@code writerIndex} with the specified + * {@code buffer}. + */ + public static ByteBuf unmodifiableBuffer(ByteBuf buffer) { + ByteOrder endianness = buffer.order(); + if (endianness == BIG_ENDIAN) { + return new ReadOnlyByteBuf(buffer); + } + + return new ReadOnlyByteBuf(buffer.order(BIG_ENDIAN)).order(LITTLE_ENDIAN); + } + + /** + * Creates a new 4-byte big-endian buffer that holds the specified 32-bit integer. + */ + public static ByteBuf copyInt(int value) { + ByteBuf buf = buffer(4); + buf.writeInt(value); + return buf; + } + + /** + * Create a big-endian buffer that holds a sequence of the specified 32-bit integers. + */ + public static ByteBuf copyInt(int... values) { + if (values == null || values.length == 0) { + return EMPTY_BUFFER; + } + ByteBuf buffer = buffer(values.length * 4); + for (int v: values) { + buffer.writeInt(v); + } + return buffer; + } + + /** + * Creates a new 2-byte big-endian buffer that holds the specified 16-bit integer. + */ + public static ByteBuf copyShort(int value) { + ByteBuf buf = buffer(2); + buf.writeShort(value); + return buf; + } + + /** + * Create a new big-endian buffer that holds a sequence of the specified 16-bit integers. + */ + public static ByteBuf copyShort(short... values) { + if (values == null || values.length == 0) { + return EMPTY_BUFFER; + } + ByteBuf buffer = buffer(values.length * 2); + for (int v: values) { + buffer.writeShort(v); + } + return buffer; + } + + /** + * Create a new big-endian buffer that holds a sequence of the specified 16-bit integers. + */ + public static ByteBuf copyShort(int... values) { + if (values == null || values.length == 0) { + return EMPTY_BUFFER; + } + ByteBuf buffer = buffer(values.length * 2); + for (int v: values) { + buffer.writeShort(v); + } + return buffer; + } + + /** + * Creates a new 3-byte big-endian buffer that holds the specified 24-bit integer. + */ + public static ByteBuf copyMedium(int value) { + ByteBuf buf = buffer(3); + buf.writeMedium(value); + return buf; + } + + /** + * Create a new big-endian buffer that holds a sequence of the specified 24-bit integers. + */ + public static ByteBuf copyMedium(int... values) { + if (values == null || values.length == 0) { + return EMPTY_BUFFER; + } + ByteBuf buffer = buffer(values.length * 3); + for (int v: values) { + buffer.writeMedium(v); + } + return buffer; + } + + /** + * Creates a new 8-byte big-endian buffer that holds the specified 64-bit integer. + */ + public static ByteBuf copyLong(long value) { + ByteBuf buf = buffer(8); + buf.writeLong(value); + return buf; + } + + /** + * Create a new big-endian buffer that holds a sequence of the specified 64-bit integers. + */ + public static ByteBuf copyLong(long... values) { + if (values == null || values.length == 0) { + return EMPTY_BUFFER; + } + ByteBuf buffer = buffer(values.length * 8); + for (long v: values) { + buffer.writeLong(v); + } + return buffer; + } + + /** + * Creates a new single-byte big-endian buffer that holds the specified boolean value. + */ + public static ByteBuf copyBoolean(boolean value) { + ByteBuf buf = buffer(1); + buf.writeBoolean(value); + return buf; + } + + /** + * Create a new big-endian buffer that holds a sequence of the specified boolean values. + */ + public static ByteBuf copyBoolean(boolean... values) { + if (values == null || values.length == 0) { + return EMPTY_BUFFER; + } + ByteBuf buffer = buffer(values.length); + for (boolean v: values) { + buffer.writeBoolean(v); + } + return buffer; + } + + /** + * Creates a new 4-byte big-endian buffer that holds the specified 32-bit floating point number. + */ + public static ByteBuf copyFloat(float value) { + ByteBuf buf = buffer(4); + buf.writeFloat(value); + return buf; + } + + /** + * Create a new big-endian buffer that holds a sequence of the specified 32-bit floating point numbers. + */ + public static ByteBuf copyFloat(float... values) { + if (values == null || values.length == 0) { + return EMPTY_BUFFER; + } + ByteBuf buffer = buffer(values.length * 4); + for (float v: values) { + buffer.writeFloat(v); + } + return buffer; + } + + /** + * Creates a new 8-byte big-endian buffer that holds the specified 64-bit floating point number. + */ + public static ByteBuf copyDouble(double value) { + ByteBuf buf = buffer(8); + buf.writeDouble(value); + return buf; + } + + /** + * Create a new big-endian buffer that holds a sequence of the specified 64-bit floating point numbers. + */ + public static ByteBuf copyDouble(double... values) { + if (values == null || values.length == 0) { + return EMPTY_BUFFER; + } + ByteBuf buffer = buffer(values.length * 8); + for (double v: values) { + buffer.writeDouble(v); + } + return buffer; + } + + /** + * Return a unreleasable view on the given {@link ByteBuf} which will just ignore release and retain calls. + */ + public static ByteBuf unreleasableBuffer(ByteBuf buf) { + return new UnreleasableByteBuf(buf); + } + + private Unpooled() { + // Unused + } +} diff --git a/common/src/main/java/common/net/buffer/UnpooledByteBufAllocator.java b/common/src/main/java/common/net/buffer/UnpooledByteBufAllocator.java new file mode 100644 index 0000000..5d5d70d --- /dev/null +++ b/common/src/main/java/common/net/buffer/UnpooledByteBufAllocator.java @@ -0,0 +1,45 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +/** + * Simplistic {@link ByteBufAllocator} implementation that does not pool anything. + */ +public final class UnpooledByteBufAllocator extends AbstractByteBufAllocator { + + /** + * Default instance + */ + public static final UnpooledByteBufAllocator DEFAULT = new UnpooledByteBufAllocator(); + + @Override + protected ByteBuf newHeapBuffer(int initialCapacity, int maxCapacity) { + return new UnpooledHeapByteBuf(this, initialCapacity, maxCapacity); + } + + @Override + protected ByteBuf newDirectBuffer(int initialCapacity, int maxCapacity) { + ByteBuf buf; + buf = new UnpooledDirectByteBuf(this, initialCapacity, maxCapacity); + + return toLeakAwareBuffer(buf); + } + + @Override + public boolean isDirectBufferPooled() { + return false; + } +} diff --git a/common/src/main/java/common/net/buffer/UnpooledDirectByteBuf.java b/common/src/main/java/common/net/buffer/UnpooledDirectByteBuf.java new file mode 100644 index 0000000..22950dc --- /dev/null +++ b/common/src/main/java/common/net/buffer/UnpooledDirectByteBuf.java @@ -0,0 +1,591 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; + +/** + * A NIO {@link ByteBuffer} based buffer. It is recommended to use {@link Unpooled#directBuffer(int)} + * and {@link Unpooled#wrappedBuffer(ByteBuffer)} instead of calling the + * constructor explicitly. + */ +public class UnpooledDirectByteBuf extends AbstractReferenceCountedByteBuf { + + private final ByteBufAllocator alloc; + + private ByteBuffer buffer; + private ByteBuffer tmpNioBuf; + private int capacity; + private boolean doNotFree; + + /** + * Creates a new direct buffer. + * + * @param initialCapacity the initial capacity of the underlying direct buffer + * @param maxCapacity the maximum capacity of the underlying direct buffer + */ + protected UnpooledDirectByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) { + super(maxCapacity); + if (alloc == null) { + throw new NullPointerException("alloc"); + } + if (initialCapacity < 0) { + throw new IllegalArgumentException("initialCapacity: " + initialCapacity); + } + if (maxCapacity < 0) { + throw new IllegalArgumentException("maxCapacity: " + maxCapacity); + } + if (initialCapacity > maxCapacity) { + throw new IllegalArgumentException(String.format( + "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity)); + } + + this.alloc = alloc; + setByteBuffer(ByteBuffer.allocateDirect(initialCapacity)); + } + + /** + * Creates a new direct buffer by wrapping the specified initial buffer. + * + * @param maxCapacity the maximum capacity of the underlying direct buffer + */ + protected UnpooledDirectByteBuf(ByteBufAllocator alloc, ByteBuffer initialBuffer, int maxCapacity) { + super(maxCapacity); + if (alloc == null) { + throw new NullPointerException("alloc"); + } + if (initialBuffer == null) { + throw new NullPointerException("initialBuffer"); + } + if (!initialBuffer.isDirect()) { + throw new IllegalArgumentException("initialBuffer is not a direct buffer."); + } + if (initialBuffer.isReadOnly()) { + throw new IllegalArgumentException("initialBuffer is a read-only buffer."); + } + + int initialCapacity = initialBuffer.remaining(); + if (initialCapacity > maxCapacity) { + throw new IllegalArgumentException(String.format( + "initialCapacity(%d) > maxCapacity(%d)", initialCapacity, maxCapacity)); + } + + this.alloc = alloc; + doNotFree = true; + setByteBuffer(initialBuffer.slice().order(ByteOrder.BIG_ENDIAN)); + writerIndex(initialCapacity); + } + + /** + * Allocate a new direct {@link ByteBuffer} with the given initialCapacity. + */ + protected ByteBuffer allocateDirect(int initialCapacity) { + return ByteBuffer.allocateDirect(initialCapacity); + } + + /** + * Free a direct {@link ByteBuffer} + */ + protected void freeDirect(ByteBuffer buffer) { + } + + private void setByteBuffer(ByteBuffer buffer) { + ByteBuffer oldBuffer = this.buffer; + if (oldBuffer != null) { + if (doNotFree) { + doNotFree = false; + } else { + freeDirect(oldBuffer); + } + } + + this.buffer = buffer; + tmpNioBuf = null; + capacity = buffer.remaining(); + } + + @Override + public boolean isDirect() { + return true; + } + + @Override + public int capacity() { + return capacity; + } + + @Override + public ByteBuf capacity(int newCapacity) { + ensureAccessible(); + if (newCapacity < 0 || newCapacity > maxCapacity()) { + throw new IllegalArgumentException("newCapacity: " + newCapacity); + } + + int readerIndex = readerIndex(); + int writerIndex = writerIndex(); + + int oldCapacity = capacity; + if (newCapacity > oldCapacity) { + ByteBuffer oldBuffer = buffer; + ByteBuffer newBuffer = allocateDirect(newCapacity); + oldBuffer.position(0).limit(oldBuffer.capacity()); + newBuffer.position(0).limit(oldBuffer.capacity()); + newBuffer.put(oldBuffer); + newBuffer.clear(); + setByteBuffer(newBuffer); + } else if (newCapacity < oldCapacity) { + ByteBuffer oldBuffer = buffer; + ByteBuffer newBuffer = allocateDirect(newCapacity); + if (readerIndex < newCapacity) { + if (writerIndex > newCapacity) { + writerIndex(writerIndex = newCapacity); + } + oldBuffer.position(readerIndex).limit(writerIndex); + newBuffer.position(readerIndex).limit(writerIndex); + newBuffer.put(oldBuffer); + newBuffer.clear(); + } else { + setIndex(newCapacity, newCapacity); + } + setByteBuffer(newBuffer); + } + return this; + } + + @Override + public ByteBufAllocator alloc() { + return alloc; + } + + @Override + public ByteOrder order() { + return ByteOrder.BIG_ENDIAN; + } + + @Override + public boolean hasArray() { + return false; + } + + @Override + public byte[] array() { + throw new UnsupportedOperationException("direct buffer"); + } + + @Override + public int arrayOffset() { + throw new UnsupportedOperationException("direct buffer"); + } + + @Override + public byte getByte(int index) { + ensureAccessible(); + return _getByte(index); + } + + @Override + protected byte _getByte(int index) { + return buffer.get(index); + } + + @Override + public short getShort(int index) { + ensureAccessible(); + return _getShort(index); + } + + @Override + protected short _getShort(int index) { + return buffer.getShort(index); + } + + @Override + public int getUnsignedMedium(int index) { + ensureAccessible(); + return _getUnsignedMedium(index); + } + + @Override + protected int _getUnsignedMedium(int index) { + return (getByte(index) & 0xff) << 16 | (getByte(index + 1) & 0xff) << 8 | getByte(index + 2) & 0xff; + } + + @Override + public int getInt(int index) { + ensureAccessible(); + return _getInt(index); + } + + @Override + protected int _getInt(int index) { + return buffer.getInt(index); + } + + @Override + public long getLong(int index) { + ensureAccessible(); + return _getLong(index); + } + + @Override + protected long _getLong(int index) { + return buffer.getLong(index); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.capacity()); + if (dst.hasArray()) { + getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length); + } else if (dst.nioBufferCount() > 0) { + for (ByteBuffer bb: dst.nioBuffers(dstIndex, length)) { + int bbLen = bb.remaining(); + getBytes(index, bb); + index += bbLen; + } + } else { + dst.setBytes(dstIndex, this, index, length); + } + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + getBytes(index, dst, dstIndex, length, false); + return this; + } + + private void getBytes(int index, byte[] dst, int dstIndex, int length, boolean internal) { + checkDstIndex(index, length, dstIndex, dst.length); + + if (dstIndex < 0 || dstIndex > dst.length - length) { + throw new IndexOutOfBoundsException(String.format( + "dstIndex: %d, length: %d (expected: range(0, %d))", dstIndex, length, dst.length)); + } + + ByteBuffer tmpBuf; + if (internal) { + tmpBuf = internalNioBuffer(); + } else { + tmpBuf = buffer.duplicate(); + } + tmpBuf.clear().position(index).limit(index + length); + tmpBuf.get(dst, dstIndex, length); + } + + @Override + public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { + checkReadableBytes(length); + getBytes(readerIndex, dst, dstIndex, length, true); + readerIndex += length; + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + getBytes(index, dst, false); + return this; + } + + private void getBytes(int index, ByteBuffer dst, boolean internal) { + checkIndex(index); + if (dst == null) { + throw new NullPointerException("dst"); + } + + int bytesToCopy = Math.min(capacity() - index, dst.remaining()); + ByteBuffer tmpBuf; + if (internal) { + tmpBuf = internalNioBuffer(); + } else { + tmpBuf = buffer.duplicate(); + } + tmpBuf.clear().position(index).limit(index + bytesToCopy); + dst.put(tmpBuf); + } + + @Override + public ByteBuf readBytes(ByteBuffer dst) { + int length = dst.remaining(); + checkReadableBytes(length); + getBytes(readerIndex, dst, true); + readerIndex += length; + return this; + } + + @Override + public ByteBuf setByte(int index, int value) { + ensureAccessible(); + _setByte(index, value); + return this; + } + + @Override + protected void _setByte(int index, int value) { + buffer.put(index, (byte) value); + } + + @Override + public ByteBuf setShort(int index, int value) { + ensureAccessible(); + _setShort(index, value); + return this; + } + + @Override + protected void _setShort(int index, int value) { + buffer.putShort(index, (short) value); + } + + @Override + public ByteBuf setMedium(int index, int value) { + ensureAccessible(); + _setMedium(index, value); + return this; + } + + @Override + protected void _setMedium(int index, int value) { + setByte(index, (byte) (value >>> 16)); + setByte(index + 1, (byte) (value >>> 8)); + setByte(index + 2, (byte) value); + } + + @Override + public ByteBuf setInt(int index, int value) { + ensureAccessible(); + _setInt(index, value); + return this; + } + + @Override + protected void _setInt(int index, int value) { + buffer.putInt(index, value); + } + + @Override + public ByteBuf setLong(int index, long value) { + ensureAccessible(); + _setLong(index, value); + return this; + } + + @Override + protected void _setLong(int index, long value) { + buffer.putLong(index, value); + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + checkSrcIndex(index, length, srcIndex, src.capacity()); + if (src.nioBufferCount() > 0) { + for (ByteBuffer bb: src.nioBuffers(srcIndex, length)) { + int bbLen = bb.remaining(); + setBytes(index, bb); + index += bbLen; + } + } else { + src.getBytes(srcIndex, this, index, length); + } + return this; + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + checkSrcIndex(index, length, srcIndex, src.length); + ByteBuffer tmpBuf = internalNioBuffer(); + tmpBuf.clear().position(index).limit(index + length); + tmpBuf.put(src, srcIndex, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + ensureAccessible(); + ByteBuffer tmpBuf = internalNioBuffer(); + if (src == tmpBuf) { + src = src.duplicate(); + } + + tmpBuf.clear().position(index).limit(index + src.remaining()); + tmpBuf.put(src); + return this; + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + getBytes(index, out, length, false); + return this; + } + + private void getBytes(int index, OutputStream out, int length, boolean internal) throws IOException { + ensureAccessible(); + if (length == 0) { + return; + } + + if (buffer.hasArray()) { + out.write(buffer.array(), index + buffer.arrayOffset(), length); + } else { + byte[] tmp = new byte[length]; + ByteBuffer tmpBuf; + if (internal) { + tmpBuf = internalNioBuffer(); + } else { + tmpBuf = buffer.duplicate(); + } + tmpBuf.clear().position(index); + tmpBuf.get(tmp); + out.write(tmp); + } + } + + @Override + public ByteBuf readBytes(OutputStream out, int length) throws IOException { + checkReadableBytes(length); + getBytes(readerIndex, out, length, true); + readerIndex += length; + return this; + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { + return getBytes(index, out, length, false); + } + + private int getBytes(int index, GatheringByteChannel out, int length, boolean internal) throws IOException { + ensureAccessible(); + if (length == 0) { + return 0; + } + + ByteBuffer tmpBuf; + if (internal) { + tmpBuf = internalNioBuffer(); + } else { + tmpBuf = buffer.duplicate(); + } + tmpBuf.clear().position(index).limit(index + length); + return out.write(tmpBuf); + } + + @Override + public int readBytes(GatheringByteChannel out, int length) throws IOException { + checkReadableBytes(length); + int readBytes = getBytes(readerIndex, out, length, true); + readerIndex += readBytes; + return readBytes; + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + ensureAccessible(); + if (buffer.hasArray()) { + return in.read(buffer.array(), buffer.arrayOffset() + index, length); + } else { + byte[] tmp = new byte[length]; + int readBytes = in.read(tmp); + if (readBytes <= 0) { + return readBytes; + } + ByteBuffer tmpBuf = internalNioBuffer(); + tmpBuf.clear().position(index); + tmpBuf.put(tmp, 0, readBytes); + return readBytes; + } + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + ensureAccessible(); + ByteBuffer tmpBuf = internalNioBuffer(); + tmpBuf.clear().position(index).limit(index + length); + try { + return in.read(tmpNioBuf); + } catch (ClosedChannelException ignored) { + return -1; + } + } + + @Override + public int nioBufferCount() { + return 1; + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + return new ByteBuffer[] { nioBuffer(index, length) }; + } + + @Override + public ByteBuf copy(int index, int length) { + ensureAccessible(); + ByteBuffer src; + try { + src = (ByteBuffer) buffer.duplicate().clear().position(index).limit(index + length); + } catch (IllegalArgumentException ignored) { + throw new IndexOutOfBoundsException("Too many bytes to read - Need " + (index + length)); + } + + return alloc().directBuffer(length, maxCapacity()).writeBytes(src); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + checkIndex(index, length); + return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); + } + + private ByteBuffer internalNioBuffer() { + ByteBuffer tmpNioBuf = this.tmpNioBuf; + if (tmpNioBuf == null) { + this.tmpNioBuf = tmpNioBuf = buffer.duplicate(); + } + return tmpNioBuf; + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + checkIndex(index, length); + return ((ByteBuffer) buffer.duplicate().position(index).limit(index + length)).slice(); + } + + @Override + protected void deallocate() { + ByteBuffer buffer = this.buffer; + if (buffer == null) { + return; + } + + this.buffer = null; + + if (!doNotFree) { + freeDirect(buffer); + } + } + + @Override + public ByteBuf unwrap() { + return null; + } +} diff --git a/common/src/main/java/common/net/buffer/UnpooledHeapByteBuf.java b/common/src/main/java/common/net/buffer/UnpooledHeapByteBuf.java new file mode 100644 index 0000000..d94c172 --- /dev/null +++ b/common/src/main/java/common/net/buffer/UnpooledHeapByteBuf.java @@ -0,0 +1,433 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; + +/** + * Big endian Java heap buffer implementation. + */ +public class UnpooledHeapByteBuf extends AbstractReferenceCountedByteBuf { + + private final ByteBufAllocator alloc; + private byte[] array; + private ByteBuffer tmpNioBuf; + + /** + * Creates a new heap buffer with a newly allocated byte array. + * + * @param initialCapacity the initial capacity of the underlying byte array + * @param maxCapacity the max capacity of the underlying byte array + */ + protected UnpooledHeapByteBuf(ByteBufAllocator alloc, int initialCapacity, int maxCapacity) { + this(alloc, new byte[initialCapacity], 0, 0, maxCapacity); + } + + /** + * Creates a new heap buffer with an existing byte array. + * + * @param initialArray the initial underlying byte array + * @param maxCapacity the max capacity of the underlying byte array + */ + protected UnpooledHeapByteBuf(ByteBufAllocator alloc, byte[] initialArray, int maxCapacity) { + this(alloc, initialArray, 0, initialArray.length, maxCapacity); + } + + private UnpooledHeapByteBuf( + ByteBufAllocator alloc, byte[] initialArray, int readerIndex, int writerIndex, int maxCapacity) { + + super(maxCapacity); + + if (alloc == null) { + throw new NullPointerException("alloc"); + } + if (initialArray == null) { + throw new NullPointerException("initialArray"); + } + if (initialArray.length > maxCapacity) { + throw new IllegalArgumentException(String.format( + "initialCapacity(%d) > maxCapacity(%d)", initialArray.length, maxCapacity)); + } + + this.alloc = alloc; + setArray(initialArray); + setIndex(readerIndex, writerIndex); + } + + private void setArray(byte[] initialArray) { + array = initialArray; + tmpNioBuf = null; + } + + @Override + public ByteBufAllocator alloc() { + return alloc; + } + + @Override + public ByteOrder order() { + return ByteOrder.BIG_ENDIAN; + } + + @Override + public boolean isDirect() { + return false; + } + + @Override + public int capacity() { + ensureAccessible(); + return array.length; + } + + @Override + public ByteBuf capacity(int newCapacity) { + ensureAccessible(); + if (newCapacity < 0 || newCapacity > maxCapacity()) { + throw new IllegalArgumentException("newCapacity: " + newCapacity); + } + + int oldCapacity = array.length; + if (newCapacity > oldCapacity) { + byte[] newArray = new byte[newCapacity]; + System.arraycopy(array, 0, newArray, 0, array.length); + setArray(newArray); + } else if (newCapacity < oldCapacity) { + byte[] newArray = new byte[newCapacity]; + int readerIndex = readerIndex(); + if (readerIndex < newCapacity) { + int writerIndex = writerIndex(); + if (writerIndex > newCapacity) { + writerIndex(writerIndex = newCapacity); + } + System.arraycopy(array, readerIndex, newArray, readerIndex, writerIndex - readerIndex); + } else { + setIndex(newCapacity, newCapacity); + } + setArray(newArray); + } + return this; + } + + @Override + public boolean hasArray() { + return true; + } + + @Override + public byte[] array() { + ensureAccessible(); + return array; + } + + @Override + public int arrayOffset() { + return 0; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.capacity()); + if (dst.hasArray()) { + getBytes(index, dst.array(), dst.arrayOffset() + dstIndex, length); + } else { + dst.setBytes(dstIndex, array, index, length); + } + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + checkDstIndex(index, length, dstIndex, dst.length); + System.arraycopy(array, index, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + ensureAccessible(); + dst.put(array, index, Math.min(capacity() - index, dst.remaining())); + return this; + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + ensureAccessible(); + out.write(array, index, length); + return this; + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { + ensureAccessible(); + return getBytes(index, out, length, false); + } + + private int getBytes(int index, GatheringByteChannel out, int length, boolean internal) throws IOException { + ensureAccessible(); + ByteBuffer tmpBuf; + if (internal) { + tmpBuf = internalNioBuffer(); + } else { + tmpBuf = ByteBuffer.wrap(array); + } + return out.write((ByteBuffer) tmpBuf.clear().position(index).limit(index + length)); + } + + @Override + public int readBytes(GatheringByteChannel out, int length) throws IOException { + checkReadableBytes(length); + int readBytes = getBytes(readerIndex, out, length, true); + readerIndex += readBytes; + return readBytes; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + checkSrcIndex(index, length, srcIndex, src.capacity()); + if (src.hasArray()) { + setBytes(index, src.array(), src.arrayOffset() + srcIndex, length); + } else { + src.getBytes(srcIndex, array, index, length); + } + return this; + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + checkSrcIndex(index, length, srcIndex, src.length); + System.arraycopy(src, srcIndex, array, index, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + ensureAccessible(); + src.get(array, index, src.remaining()); + return this; + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + ensureAccessible(); + return in.read(array, index, length); + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + ensureAccessible(); + try { + return in.read((ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length)); + } catch (ClosedChannelException ignored) { + return -1; + } + } + + @Override + public int nioBufferCount() { + return 1; + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + ensureAccessible(); + return ByteBuffer.wrap(array, index, length).slice(); + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + return new ByteBuffer[] { nioBuffer(index, length) }; + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + checkIndex(index, length); + return (ByteBuffer) internalNioBuffer().clear().position(index).limit(index + length); + } + + @Override + public byte getByte(int index) { + ensureAccessible(); + return _getByte(index); + } + + @Override + protected byte _getByte(int index) { + return array[index]; + } + + @Override + public short getShort(int index) { + ensureAccessible(); + return _getShort(index); + } + + @Override + protected short _getShort(int index) { + return (short) (array[index] << 8 | array[index + 1] & 0xFF); + } + + @Override + public int getUnsignedMedium(int index) { + ensureAccessible(); + return _getUnsignedMedium(index); + } + + @Override + protected int _getUnsignedMedium(int index) { + return (array[index] & 0xff) << 16 | + (array[index + 1] & 0xff) << 8 | + array[index + 2] & 0xff; + } + + @Override + public int getInt(int index) { + ensureAccessible(); + return _getInt(index); + } + + @Override + protected int _getInt(int index) { + return (array[index] & 0xff) << 24 | + (array[index + 1] & 0xff) << 16 | + (array[index + 2] & 0xff) << 8 | + array[index + 3] & 0xff; + } + + @Override + public long getLong(int index) { + ensureAccessible(); + return _getLong(index); + } + + @Override + protected long _getLong(int index) { + return ((long) array[index] & 0xff) << 56 | + ((long) array[index + 1] & 0xff) << 48 | + ((long) array[index + 2] & 0xff) << 40 | + ((long) array[index + 3] & 0xff) << 32 | + ((long) array[index + 4] & 0xff) << 24 | + ((long) array[index + 5] & 0xff) << 16 | + ((long) array[index + 6] & 0xff) << 8 | + (long) array[index + 7] & 0xff; + } + + @Override + public ByteBuf setByte(int index, int value) { + ensureAccessible(); + _setByte(index, value); + return this; + } + + @Override + protected void _setByte(int index, int value) { + array[index] = (byte) value; + } + + @Override + public ByteBuf setShort(int index, int value) { + ensureAccessible(); + _setShort(index, value); + return this; + } + + @Override + protected void _setShort(int index, int value) { + array[index] = (byte) (value >>> 8); + array[index + 1] = (byte) value; + } + + @Override + public ByteBuf setMedium(int index, int value) { + ensureAccessible(); + _setMedium(index, value); + return this; + } + + @Override + protected void _setMedium(int index, int value) { + array[index] = (byte) (value >>> 16); + array[index + 1] = (byte) (value >>> 8); + array[index + 2] = (byte) value; + } + + @Override + public ByteBuf setInt(int index, int value) { + ensureAccessible(); + _setInt(index, value); + return this; + } + + @Override + protected void _setInt(int index, int value) { + array[index] = (byte) (value >>> 24); + array[index + 1] = (byte) (value >>> 16); + array[index + 2] = (byte) (value >>> 8); + array[index + 3] = (byte) value; + } + + @Override + public ByteBuf setLong(int index, long value) { + ensureAccessible(); + _setLong(index, value); + return this; + } + + @Override + protected void _setLong(int index, long value) { + array[index] = (byte) (value >>> 56); + array[index + 1] = (byte) (value >>> 48); + array[index + 2] = (byte) (value >>> 40); + array[index + 3] = (byte) (value >>> 32); + array[index + 4] = (byte) (value >>> 24); + array[index + 5] = (byte) (value >>> 16); + array[index + 6] = (byte) (value >>> 8); + array[index + 7] = (byte) value; + } + + @Override + public ByteBuf copy(int index, int length) { + checkIndex(index, length); + byte[] copiedArray = new byte[length]; + System.arraycopy(array, index, copiedArray, 0, length); + return new UnpooledHeapByteBuf(alloc(), copiedArray, maxCapacity()); + } + + private ByteBuffer internalNioBuffer() { + ByteBuffer tmpNioBuf = this.tmpNioBuf; + if (tmpNioBuf == null) { + this.tmpNioBuf = tmpNioBuf = ByteBuffer.wrap(array); + } + return tmpNioBuf; + } + + @Override + protected void deallocate() { + array = null; + } + + @Override + public ByteBuf unwrap() { + return null; + } +} diff --git a/common/src/main/java/common/net/buffer/UnreleasableByteBuf.java b/common/src/main/java/common/net/buffer/UnreleasableByteBuf.java new file mode 100644 index 0000000..3a677ba --- /dev/null +++ b/common/src/main/java/common/net/buffer/UnreleasableByteBuf.java @@ -0,0 +1,87 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.buffer; + +import java.nio.ByteOrder; + +/** + * A {@link ByteBuf} implementation that wraps another buffer to prevent a user from increasing or decreasing the + * wrapped buffer's reference count. + */ +final class UnreleasableByteBuf extends WrappedByteBuf { + + private SwappedByteBuf swappedBuf; + + UnreleasableByteBuf(ByteBuf buf) { + super(buf); + } + + @Override + public ByteBuf order(ByteOrder endianness) { + if (endianness == null) { + throw new NullPointerException("endianness"); + } + if (endianness == order()) { + return this; + } + + SwappedByteBuf swappedBuf = this.swappedBuf; + if (swappedBuf == null) { + this.swappedBuf = swappedBuf = new SwappedByteBuf(this); + } + return swappedBuf; + } + + @Override + public ByteBuf readSlice(int length) { + return new UnreleasableByteBuf(buf.readSlice(length)); + } + + @Override + public ByteBuf slice() { + return new UnreleasableByteBuf(buf.slice()); + } + + @Override + public ByteBuf slice(int index, int length) { + return new UnreleasableByteBuf(buf.slice(index, length)); + } + + @Override + public ByteBuf duplicate() { + return new UnreleasableByteBuf(buf.duplicate()); + } + + @Override + public ByteBuf retain(int increment) { + return this; + } + + @Override + public ByteBuf retain() { + return this; + } + + @Override + public boolean release() { + return false; + } + + @Override + public boolean release(int decrement) { + return false; + } +} diff --git a/common/src/main/java/common/net/buffer/WrappedByteBuf.java b/common/src/main/java/common/net/buffer/WrappedByteBuf.java new file mode 100644 index 0000000..8cbec40 --- /dev/null +++ b/common/src/main/java/common/net/buffer/WrappedByteBuf.java @@ -0,0 +1,817 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.buffer; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.GatheringByteChannel; +import java.nio.channels.ScatteringByteChannel; +import java.nio.charset.Charset; + +import common.net.util.internal.StringUtil; + +class WrappedByteBuf extends ByteBuf { + + protected final ByteBuf buf; + + protected WrappedByteBuf(ByteBuf buf) { + if (buf == null) { + throw new NullPointerException("buf"); + } + this.buf = buf; + } + + @Override + public int capacity() { + return buf.capacity(); + } + + @Override + public ByteBuf capacity(int newCapacity) { + buf.capacity(newCapacity); + return this; + } + + @Override + public int maxCapacity() { + return buf.maxCapacity(); + } + + @Override + public ByteBufAllocator alloc() { + return buf.alloc(); + } + + @Override + public ByteOrder order() { + return buf.order(); + } + + @Override + public ByteBuf order(ByteOrder endianness) { + return buf.order(endianness); + } + + @Override + public ByteBuf unwrap() { + return buf; + } + + @Override + public boolean isDirect() { + return buf.isDirect(); + } + + @Override + public int readerIndex() { + return buf.readerIndex(); + } + + @Override + public ByteBuf readerIndex(int readerIndex) { + buf.readerIndex(readerIndex); + return this; + } + + @Override + public int writerIndex() { + return buf.writerIndex(); + } + + @Override + public ByteBuf writerIndex(int writerIndex) { + buf.writerIndex(writerIndex); + return this; + } + + @Override + public ByteBuf setIndex(int readerIndex, int writerIndex) { + buf.setIndex(readerIndex, writerIndex); + return this; + } + + @Override + public int readableBytes() { + return buf.readableBytes(); + } + + @Override + public int writableBytes() { + return buf.writableBytes(); + } + + @Override + public int maxWritableBytes() { + return buf.maxWritableBytes(); + } + + @Override + public boolean isReadable() { + return buf.isReadable(); + } + + @Override + public boolean isWritable() { + return buf.isWritable(); + } + + @Override + public ByteBuf clear() { + buf.clear(); + return this; + } + + @Override + public ByteBuf markReaderIndex() { + buf.markReaderIndex(); + return this; + } + + @Override + public ByteBuf resetReaderIndex() { + buf.resetReaderIndex(); + return this; + } + + @Override + public ByteBuf markWriterIndex() { + buf.markWriterIndex(); + return this; + } + + @Override + public ByteBuf resetWriterIndex() { + buf.resetWriterIndex(); + return this; + } + + @Override + public ByteBuf discardReadBytes() { + buf.discardReadBytes(); + return this; + } + + @Override + public ByteBuf discardSomeReadBytes() { + buf.discardSomeReadBytes(); + return this; + } + + @Override + public ByteBuf ensureWritable(int minWritableBytes) { + buf.ensureWritable(minWritableBytes); + return this; + } + + @Override + public int ensureWritable(int minWritableBytes, boolean force) { + return buf.ensureWritable(minWritableBytes, force); + } + + @Override + public boolean getBoolean(int index) { + return buf.getBoolean(index); + } + + @Override + public byte getByte(int index) { + return buf.getByte(index); + } + + @Override + public short getUnsignedByte(int index) { + return buf.getUnsignedByte(index); + } + + @Override + public short getShort(int index) { + return buf.getShort(index); + } + + @Override + public int getUnsignedShort(int index) { + return buf.getUnsignedShort(index); + } + + @Override + public int getMedium(int index) { + return buf.getMedium(index); + } + + @Override + public int getUnsignedMedium(int index) { + return buf.getUnsignedMedium(index); + } + + @Override + public int getInt(int index) { + return buf.getInt(index); + } + + @Override + public long getUnsignedInt(int index) { + return buf.getUnsignedInt(index); + } + + @Override + public long getLong(int index) { + return buf.getLong(index); + } + + @Override + public char getChar(int index) { + return buf.getChar(index); + } + + @Override + public float getFloat(int index) { + return buf.getFloat(index); + } + + @Override + public double getDouble(int index) { + return buf.getDouble(index); + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst) { + buf.getBytes(index, dst); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int length) { + buf.getBytes(index, dst, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuf dst, int dstIndex, int length) { + buf.getBytes(index, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst) { + buf.getBytes(index, dst); + return this; + } + + @Override + public ByteBuf getBytes(int index, byte[] dst, int dstIndex, int length) { + buf.getBytes(index, dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf getBytes(int index, ByteBuffer dst) { + buf.getBytes(index, dst); + return this; + } + + @Override + public ByteBuf getBytes(int index, OutputStream out, int length) throws IOException { + buf.getBytes(index, out, length); + return this; + } + + @Override + public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { + return buf.getBytes(index, out, length); + } + + @Override + public ByteBuf setBoolean(int index, boolean value) { + buf.setBoolean(index, value); + return this; + } + + @Override + public ByteBuf setByte(int index, int value) { + buf.setByte(index, value); + return this; + } + + @Override + public ByteBuf setShort(int index, int value) { + buf.setShort(index, value); + return this; + } + + @Override + public ByteBuf setMedium(int index, int value) { + buf.setMedium(index, value); + return this; + } + + @Override + public ByteBuf setInt(int index, int value) { + buf.setInt(index, value); + return this; + } + + @Override + public ByteBuf setLong(int index, long value) { + buf.setLong(index, value); + return this; + } + + @Override + public ByteBuf setChar(int index, int value) { + buf.setChar(index, value); + return this; + } + + @Override + public ByteBuf setFloat(int index, float value) { + buf.setFloat(index, value); + return this; + } + + @Override + public ByteBuf setDouble(int index, double value) { + buf.setDouble(index, value); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src) { + buf.setBytes(index, src); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int length) { + buf.setBytes(index, src, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuf src, int srcIndex, int length) { + buf.setBytes(index, src, srcIndex, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, byte[] src) { + buf.setBytes(index, src); + return this; + } + + @Override + public ByteBuf setBytes(int index, byte[] src, int srcIndex, int length) { + buf.setBytes(index, src, srcIndex, length); + return this; + } + + @Override + public ByteBuf setBytes(int index, ByteBuffer src) { + buf.setBytes(index, src); + return this; + } + + @Override + public int setBytes(int index, InputStream in, int length) throws IOException { + return buf.setBytes(index, in, length); + } + + @Override + public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { + return buf.setBytes(index, in, length); + } + + @Override + public ByteBuf setZero(int index, int length) { + buf.setZero(index, length); + return this; + } + + @Override + public boolean readBoolean() { + return buf.readBoolean(); + } + + @Override + public byte readByte() { + return buf.readByte(); + } + + @Override + public short readUnsignedByte() { + return buf.readUnsignedByte(); + } + + @Override + public short readShort() { + return buf.readShort(); + } + + @Override + public int readUnsignedShort() { + return buf.readUnsignedShort(); + } + + @Override + public int readMedium() { + return buf.readMedium(); + } + + @Override + public int readUnsignedMedium() { + return buf.readUnsignedMedium(); + } + + @Override + public int readInt() { + return buf.readInt(); + } + + @Override + public long readUnsignedInt() { + return buf.readUnsignedInt(); + } + + @Override + public long readLong() { + return buf.readLong(); + } + + @Override + public char readChar() { + return buf.readChar(); + } + + @Override + public float readFloat() { + return buf.readFloat(); + } + + @Override + public double readDouble() { + return buf.readDouble(); + } + + @Override + public ByteBuf readBytes(int length) { + return buf.readBytes(length); + } + + @Override + public ByteBuf readSlice(int length) { + return buf.readSlice(length); + } + + @Override + public ByteBuf readBytes(ByteBuf dst) { + buf.readBytes(dst); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int length) { + buf.readBytes(dst, length); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuf dst, int dstIndex, int length) { + buf.readBytes(dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf readBytes(byte[] dst) { + buf.readBytes(dst); + return this; + } + + @Override + public ByteBuf readBytes(byte[] dst, int dstIndex, int length) { + buf.readBytes(dst, dstIndex, length); + return this; + } + + @Override + public ByteBuf readBytes(ByteBuffer dst) { + buf.readBytes(dst); + return this; + } + + @Override + public ByteBuf readBytes(OutputStream out, int length) throws IOException { + buf.readBytes(out, length); + return this; + } + + @Override + public int readBytes(GatheringByteChannel out, int length) throws IOException { + return buf.readBytes(out, length); + } + + @Override + public ByteBuf skipBytes(int length) { + buf.skipBytes(length); + return this; + } + + @Override + public ByteBuf writeBoolean(boolean value) { + buf.writeBoolean(value); + return this; + } + + @Override + public ByteBuf writeByte(int value) { + buf.writeByte(value); + return this; + } + + @Override + public ByteBuf writeShort(int value) { + buf.writeShort(value); + return this; + } + + @Override + public ByteBuf writeMedium(int value) { + buf.writeMedium(value); + return this; + } + + @Override + public ByteBuf writeInt(int value) { + buf.writeInt(value); + return this; + } + + @Override + public ByteBuf writeLong(long value) { + buf.writeLong(value); + return this; + } + + @Override + public ByteBuf writeChar(int value) { + buf.writeChar(value); + return this; + } + + @Override + public ByteBuf writeFloat(float value) { + buf.writeFloat(value); + return this; + } + + @Override + public ByteBuf writeDouble(double value) { + buf.writeDouble(value); + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuf src) { + buf.writeBytes(src); + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuf src, int length) { + buf.writeBytes(src, length); + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuf src, int srcIndex, int length) { + buf.writeBytes(src, srcIndex, length); + return this; + } + + @Override + public ByteBuf writeBytes(byte[] src) { + buf.writeBytes(src); + return this; + } + + @Override + public ByteBuf writeBytes(byte[] src, int srcIndex, int length) { + buf.writeBytes(src, srcIndex, length); + return this; + } + + @Override + public ByteBuf writeBytes(ByteBuffer src) { + buf.writeBytes(src); + return this; + } + + @Override + public int writeBytes(InputStream in, int length) throws IOException { + return buf.writeBytes(in, length); + } + + @Override + public int writeBytes(ScatteringByteChannel in, int length) throws IOException { + return buf.writeBytes(in, length); + } + + @Override + public ByteBuf writeZero(int length) { + buf.writeZero(length); + return this; + } + + @Override + public int indexOf(int fromIndex, int toIndex, byte value) { + return buf.indexOf(fromIndex, toIndex, value); + } + + @Override + public int bytesBefore(byte value) { + return buf.bytesBefore(value); + } + + @Override + public int bytesBefore(int length, byte value) { + return buf.bytesBefore(length, value); + } + + @Override + public int bytesBefore(int index, int length, byte value) { + return buf.bytesBefore(index, length, value); + } + + @Override + public int forEachByte(ByteBufProcessor processor) { + return buf.forEachByte(processor); + } + + @Override + public int forEachByte(int index, int length, ByteBufProcessor processor) { + return buf.forEachByte(index, length, processor); + } + + @Override + public int forEachByteDesc(ByteBufProcessor processor) { + return buf.forEachByteDesc(processor); + } + + @Override + public int forEachByteDesc(int index, int length, ByteBufProcessor processor) { + return buf.forEachByteDesc(index, length, processor); + } + + @Override + public ByteBuf copy() { + return buf.copy(); + } + + @Override + public ByteBuf copy(int index, int length) { + return buf.copy(index, length); + } + + @Override + public ByteBuf slice() { + return buf.slice(); + } + + @Override + public ByteBuf slice(int index, int length) { + return buf.slice(index, length); + } + + @Override + public ByteBuf duplicate() { + return buf.duplicate(); + } + + @Override + public int nioBufferCount() { + return buf.nioBufferCount(); + } + + @Override + public ByteBuffer nioBuffer() { + return buf.nioBuffer(); + } + + @Override + public ByteBuffer nioBuffer(int index, int length) { + return buf.nioBuffer(index, length); + } + + @Override + public ByteBuffer[] nioBuffers() { + return buf.nioBuffers(); + } + + @Override + public ByteBuffer[] nioBuffers(int index, int length) { + return buf.nioBuffers(index, length); + } + + @Override + public ByteBuffer internalNioBuffer(int index, int length) { + return buf.internalNioBuffer(index, length); + } + + @Override + public boolean hasArray() { + return buf.hasArray(); + } + + @Override + public byte[] array() { + return buf.array(); + } + + @Override + public int arrayOffset() { + return buf.arrayOffset(); + } + + @Override + public String toString(Charset charset) { + return buf.toString(charset); + } + + @Override + public String toString(int index, int length, Charset charset) { + return buf.toString(index, length, charset); + } + + @Override + public int hashCode() { + return buf.hashCode(); + } + + @Override + + public boolean equals(Object obj) { + return buf.equals(obj); + } + + @Override + public int compareTo(ByteBuf buffer) { + return buf.compareTo(buffer); + } + + @Override + public String toString() { + return StringUtil.simpleClassName(this) + '(' + buf.toString() + ')'; + } + + @Override + public ByteBuf retain(int increment) { + buf.retain(increment); + return this; + } + + @Override + public ByteBuf retain() { + buf.retain(); + return this; + } + + @Override + public boolean isReadable(int size) { + return buf.isReadable(size); + } + + @Override + public boolean isWritable(int size) { + return buf.isWritable(size); + } + + @Override + public int refCnt() { + return buf.refCnt(); + } + + @Override + public boolean release() { + return buf.release(); + } + + @Override + public boolean release(int decrement) { + return buf.release(decrement); + } +} diff --git a/common/src/main/java/common/net/channel/AbstractChannel.java b/common/src/main/java/common/net/channel/AbstractChannel.java new file mode 100644 index 0000000..2330ef8 --- /dev/null +++ b/common/src/main/java/common/net/channel/AbstractChannel.java @@ -0,0 +1,858 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.io.IOException; +import java.net.SocketAddress; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.NotYetConnectedException; +import java.util.concurrent.RejectedExecutionException; + +import common.net.buffer.ByteBufAllocator; +import common.net.util.DefaultAttributeMap; +import common.net.util.ReferenceCountUtil; +import common.net.util.internal.EmptyArrays; +import common.net.util.internal.OneTimeTask; +import common.net.util.internal.ThreadLocalRandom; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * A skeletal {@link Channel} implementation. + */ +public abstract class AbstractChannel extends DefaultAttributeMap implements Channel { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractChannel.class); + + static final ClosedChannelException CLOSED_CHANNEL_EXCEPTION = new ClosedChannelException(); + static final NotYetConnectedException NOT_YET_CONNECTED_EXCEPTION = new NotYetConnectedException(); + + static { + CLOSED_CHANNEL_EXCEPTION.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); + NOT_YET_CONNECTED_EXCEPTION.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); + } + + private MessageSizeEstimator.Handle estimatorHandle; + + private final Channel parent; + private final long hashCode = ThreadLocalRandom.current().nextLong(); + private final Unsafe unsafe; + private final DefaultChannelPipeline pipeline; + private final ChannelFuture succeededFuture = new SucceededChannelFuture(this, null); + private final VoidChannelPromise voidPromise = new VoidChannelPromise(this, true); + private final VoidChannelPromise unsafeVoidPromise = new VoidChannelPromise(this, false); + private final CloseFuture closeFuture = new CloseFuture(this); + + private volatile SocketAddress localAddress; + private volatile SocketAddress remoteAddress; + private volatile EventLoop eventLoop; + private volatile boolean registered; + + /** Cache for the string representation of this channel */ + private boolean strValActive; + private String strVal; + + /** + * Creates a new instance. + * + * @param parent + * the parent of this channel. {@code null} if there's no parent. + */ + protected AbstractChannel(Channel parent) { + this.parent = parent; + unsafe = newUnsafe(); + pipeline = new DefaultChannelPipeline(this); + } + + @Override + public boolean isWritable() { + ChannelOutboundBuffer buf = unsafe.outboundBuffer(); + return buf != null && buf.isWritable(); + } + + @Override + public Channel parent() { + return parent; + } + + @Override + public ChannelPipeline pipeline() { + return pipeline; + } + + @Override + public ByteBufAllocator alloc() { + return config().getAllocator(); + } + + @Override + public EventLoop eventLoop() { + EventLoop eventLoop = this.eventLoop; + if (eventLoop == null) { + throw new IllegalStateException("channel not registered to an event loop"); + } + return eventLoop; + } + + @Override + public SocketAddress localAddress() { + SocketAddress localAddress = this.localAddress; + if (localAddress == null) { + try { + this.localAddress = localAddress = unsafe().localAddress(); + } catch (Throwable t) { + // Sometimes fails on a closed socket in Windows. + return null; + } + } + return localAddress; + } + + protected void invalidateLocalAddress() { + localAddress = null; + } + + @Override + public SocketAddress remoteAddress() { + SocketAddress remoteAddress = this.remoteAddress; + if (remoteAddress == null) { + try { + this.remoteAddress = remoteAddress = unsafe().remoteAddress(); + } catch (Throwable t) { + // Sometimes fails on a closed socket in Windows. + return null; + } + } + return remoteAddress; + } + + /** + * Reset the stored remoteAddress + */ + protected void invalidateRemoteAddress() { + remoteAddress = null; + } + + @Override + public boolean isRegistered() { + return registered; + } + + @Override + public ChannelFuture bind(SocketAddress localAddress) { + return pipeline.bind(localAddress); + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress) { + return pipeline.connect(remoteAddress); + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { + return pipeline.connect(remoteAddress, localAddress); + } + + @Override + public ChannelFuture disconnect() { + return pipeline.disconnect(); + } + + @Override + public ChannelFuture close() { + return pipeline.close(); + } + + @Override + public ChannelFuture deregister() { + return pipeline.deregister(); + } + + @Override + public Channel flush() { + pipeline.flush(); + return this; + } + + @Override + public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { + return pipeline.bind(localAddress, promise); + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { + return pipeline.connect(remoteAddress, promise); + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { + return pipeline.connect(remoteAddress, localAddress, promise); + } + + @Override + public ChannelFuture disconnect(ChannelPromise promise) { + return pipeline.disconnect(promise); + } + + @Override + public ChannelFuture close(ChannelPromise promise) { + return pipeline.close(promise); + } + + @Override + public ChannelFuture deregister(ChannelPromise promise) { + return pipeline.deregister(promise); + } + + @Override + public Channel read() { + pipeline.read(); + return this; + } + + @Override + public ChannelFuture write(Object msg) { + return pipeline.write(msg); + } + + @Override + public ChannelFuture write(Object msg, ChannelPromise promise) { + return pipeline.write(msg, promise); + } + + @Override + public ChannelFuture writeAndFlush(Object msg) { + return pipeline.writeAndFlush(msg); + } + + @Override + public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { + return pipeline.writeAndFlush(msg, promise); + } + + @Override + public ChannelPromise newPromise() { + return new DefaultChannelPromise(this); + } + +// @Override +// public ChannelProgressivePromise newProgressivePromise() { +// return new DefaultChannelProgressivePromise(this); +// } + + @Override + public ChannelFuture newSucceededFuture() { + return succeededFuture; + } + + @Override + public ChannelFuture newFailedFuture(Throwable cause) { + return new FailedChannelFuture(this, null, cause); + } + + @Override + public ChannelFuture closeFuture() { + return closeFuture; + } + + @Override + public Unsafe unsafe() { + return unsafe; + } + + /** + * Create a new {@link AbstractUnsafe} instance which will be used for the life-time of the {@link Channel} + */ + protected abstract AbstractUnsafe newUnsafe(); + + /** + * Returns the ID of this channel. + */ + @Override + public final int hashCode() { + return (int) hashCode; + } + + /** + * Returns {@code true} if and only if the specified object is identical + * with this channel (i.e: {@code this == o}). + */ + @Override + public final boolean equals(Object o) { + return this == o; + } + + @Override + public final int compareTo(Channel o) { + if (this == o) { + return 0; + } + + long ret = hashCode - o.hashCode(); + if (ret > 0) { + return 1; + } + if (ret < 0) { + return -1; + } + + ret = System.identityHashCode(this) - System.identityHashCode(o); + if (ret != 0) { + return (int) ret; + } + + // Jackpot! - different objects with same hashes + throw new Error(); + } + + /** + * Returns the {@link String} representation of this channel. The returned + * string contains the {@linkplain #hashCode()} ID}, {@linkplain #localAddress() local address}, + * and {@linkplain #remoteAddress() remote address} of this channel for + * easier identification. + */ + @Override + public String toString() { + boolean active = isActive(); + if (strValActive == active && strVal != null) { + return strVal; + } + + SocketAddress remoteAddr = remoteAddress(); + SocketAddress localAddr = localAddress(); + if (remoteAddr != null) { + SocketAddress srcAddr; + SocketAddress dstAddr; + if (parent == null) { + srcAddr = localAddr; + dstAddr = remoteAddr; + } else { + srcAddr = remoteAddr; + dstAddr = localAddr; + } + strVal = String.format("[id: 0x%08x, %s %s %s]", (int) hashCode, srcAddr, active? "=>" : ":>", dstAddr); + } else if (localAddr != null) { + strVal = String.format("[id: 0x%08x, %s]", (int) hashCode, localAddr); + } else { + strVal = String.format("[id: 0x%08x]", (int) hashCode); + } + + strValActive = active; + return strVal; + } + + @Override + public final ChannelPromise voidPromise() { + return voidPromise; + } + + final MessageSizeEstimator.Handle estimatorHandle() { + if (estimatorHandle == null) { + estimatorHandle = config().getMessageSizeEstimator().newHandle(); + } + return estimatorHandle; + } + + /** + * {@link Unsafe} implementation which sub-classes must extend and use. + */ + protected abstract class AbstractUnsafe implements Unsafe { + + private ChannelOutboundBuffer outboundBuffer = new ChannelOutboundBuffer(AbstractChannel.this); + private boolean inFlush0; + + @Override + public final ChannelOutboundBuffer outboundBuffer() { + return outboundBuffer; + } + + @Override + public final SocketAddress localAddress() { + return localAddress0(); + } + + @Override + public final SocketAddress remoteAddress() { + return remoteAddress0(); + } + + @Override + public final void register(EventLoop eventLoop, final ChannelPromise promise) { + if (eventLoop == null) { + throw new NullPointerException("eventLoop"); + } + if (isRegistered()) { + promise.setFailure(new IllegalStateException("registered to an event loop already")); + return; + } + if (!isCompatible(eventLoop)) { + promise.setFailure( + new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName())); + return; + } + + AbstractChannel.this.eventLoop = eventLoop; + + if (eventLoop.inEventLoop()) { + register0(promise); + } else { + try { + eventLoop.execute(new OneTimeTask() { + @Override + public void run() { + register0(promise); + } + }); + } catch (Throwable t) { + logger.warn( + "Force-closing a channel whose registration task was not accepted by an event loop: {}", + AbstractChannel.this, t); + closeForcibly(); + closeFuture.setClosed(); + safeSetFailure(promise, t); + } + } + } + + private void register0(ChannelPromise promise) { + try { + // check if the channel is still open as it could be closed in the mean time when the register + // call was outside of the eventLoop + if (!promise.setUncancellable() || !ensureOpen(promise)) { + return; + } + doRegister(); + registered = true; + safeSetSuccess(promise); + pipeline.fireChannelRegistered(); + if (isActive()) { + pipeline.fireChannelActive(); + } + } catch (Throwable t) { + // Close the channel directly to avoid FD leak. + closeForcibly(); + closeFuture.setClosed(); + safeSetFailure(promise, t); + } + } + + @Override + public final void bind(final SocketAddress localAddress, final ChannelPromise promise) { + if (!promise.setUncancellable() || !ensureOpen(promise)) { + return; + } + + boolean wasActive = isActive(); + try { + doBind(localAddress); + } catch (Throwable t) { + safeSetFailure(promise, t); + closeIfClosed(); + return; + } + + if (!wasActive && isActive()) { + invokeLater(new OneTimeTask() { + @Override + public void run() { + pipeline.fireChannelActive(); + } + }); + } + + safeSetSuccess(promise); + } + + @Override + public final void disconnect(final ChannelPromise promise) { + if (!promise.setUncancellable()) { + return; + } + + boolean wasActive = isActive(); + try { + doDisconnect(); + } catch (Throwable t) { + safeSetFailure(promise, t); + closeIfClosed(); + return; + } + + if (wasActive && !isActive()) { + invokeLater(new OneTimeTask() { + @Override + public void run() { + pipeline.fireChannelInactive(); + } + }); + } + + safeSetSuccess(promise); + closeIfClosed(); // doDisconnect() might have closed the channel + } + + @Override + public final void close(final ChannelPromise promise) { + if (!promise.setUncancellable()) { + return; + } + + if (inFlush0) { + invokeLater(new OneTimeTask() { + @Override + public void run() { + close(promise); + } + }); + return; + } + + if (closeFuture.isDone()) { + // Closed already. + safeSetSuccess(promise); + return; + } + + boolean wasActive = isActive(); + ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; + this.outboundBuffer = null; // Disallow adding any messages and flushes to outboundBuffer. + + try { + doClose(); + closeFuture.setClosed(); + safeSetSuccess(promise); + } catch (Throwable t) { + closeFuture.setClosed(); + safeSetFailure(promise, t); + } + + // Fail all the queued messages + try { + outboundBuffer.failFlushed(CLOSED_CHANNEL_EXCEPTION); + outboundBuffer.close(CLOSED_CHANNEL_EXCEPTION); + } finally { + + if (wasActive && !isActive()) { + invokeLater(new OneTimeTask() { + @Override + public void run() { + pipeline.fireChannelInactive(); + } + }); + } + + deregister(voidPromise()); + } + } + + @Override + public final void closeForcibly() { + try { + doClose(); + } catch (Exception e) { + logger.warn("Failed to close a channel.", e); + } + } + + @Override + public final void deregister(final ChannelPromise promise) { + if (!promise.setUncancellable()) { + return; + } + + if (!registered) { + safeSetSuccess(promise); + return; + } + + try { + doDeregister(); + } catch (Throwable t) { + logger.warn("Unexpected exception occurred while deregistering a channel.", t); + } finally { + if (registered) { + registered = false; + invokeLater(new OneTimeTask() { + @Override + public void run() { + pipeline.fireChannelUnregistered(); + } + }); + safeSetSuccess(promise); + } else { + // Some transports like local and AIO does not allow the deregistration of + // an open channel. Their doDeregister() calls close(). Consequently, + // close() calls deregister() again - no need to fire channelUnregistered. + safeSetSuccess(promise); + } + } + } + + @Override + public final void beginRead() { + if (!isActive()) { + return; + } + + try { + doBeginRead(); + } catch (final Exception e) { + invokeLater(new OneTimeTask() { + @Override + public void run() { + pipeline.fireExceptionCaught(e); + } + }); + close(voidPromise()); + } + } + + @Override + public final void write(Object msg, ChannelPromise promise) { + ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; + if (outboundBuffer == null) { + // If the outboundBuffer is null we know the channel was closed and so + // need to fail the future right away. If it is not null the handling of the rest + // will be done in flush0() + // See https://github.com/netty/netty/issues/2362 + safeSetFailure(promise, CLOSED_CHANNEL_EXCEPTION); + // release message now to prevent resource-leak + ReferenceCountUtil.release(msg); + return; + } + + int size; + try { + msg = filterOutboundMessage(msg); + size = estimatorHandle().size(msg); + if (size < 0) { + size = 0; + } + } catch (Throwable t) { + safeSetFailure(promise, t); + ReferenceCountUtil.release(msg); + return; + } + + outboundBuffer.addMessage(msg, size, promise); + } + + @Override + public final void flush() { + ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; + if (outboundBuffer == null) { + return; + } + + outboundBuffer.addFlush(); + flush0(); + } + + protected void flush0() { + if (inFlush0) { + // Avoid re-entrance + return; + } + + final ChannelOutboundBuffer outboundBuffer = this.outboundBuffer; + if (outboundBuffer == null || outboundBuffer.isEmpty()) { + return; + } + + inFlush0 = true; + + // Mark all pending write requests as failure if the channel is inactive. + if (!isActive()) { + try { + if (isOpen()) { + outboundBuffer.failFlushed(NOT_YET_CONNECTED_EXCEPTION); + } else { + outboundBuffer.failFlushed(CLOSED_CHANNEL_EXCEPTION); + } + } finally { + inFlush0 = false; + } + return; + } + + try { + doWrite(outboundBuffer); + } catch (Throwable t) { + outboundBuffer.failFlushed(t); + if (t instanceof IOException) { + close(voidPromise()); + } + } finally { + inFlush0 = false; + } + } + + @Override + public final ChannelPromise voidPromise() { + return unsafeVoidPromise; + } + + protected final boolean ensureOpen(ChannelPromise promise) { + if (isOpen()) { + return true; + } + + safeSetFailure(promise, CLOSED_CHANNEL_EXCEPTION); + return false; + } + + /** + * Marks the specified {@code promise} as success. If the {@code promise} is done already, log a message. + */ + protected final void safeSetSuccess(ChannelPromise promise) { + if (!(promise instanceof VoidChannelPromise) && !promise.trySuccess()) { + logger.warn("Failed to mark a promise as success because it is done already: {}", promise); + } + } + + /** + * Marks the specified {@code promise} as failure. If the {@code promise} is done already, log a message. + */ + protected final void safeSetFailure(ChannelPromise promise, Throwable cause) { + if (!(promise instanceof VoidChannelPromise) && !promise.tryFailure(cause)) { + logger.warn("Failed to mark a promise as failure because it's done already: {}", promise, cause); + } + } + + protected final void closeIfClosed() { + if (isOpen()) { + return; + } + close(voidPromise()); + } + + private void invokeLater(Runnable task) { + try { + // This method is used by outbound operation implementations to trigger an inbound event later. + // They do not trigger an inbound event immediately because an outbound operation might have been + // triggered by another inbound event handler method. If fired immediately, the call stack + // will look like this for example: + // + // handlerA.inboundBufferUpdated() - (1) an inbound handler method closes a connection. + // -> handlerA.ctx.close() + // -> channel.unsafe.close() + // -> handlerA.channelInactive() - (2) another inbound handler method called while in (1) yet + // + // which means the execution of two inbound handler methods of the same handler overlap undesirably. + eventLoop().execute(task); + } catch (RejectedExecutionException e) { + logger.warn("Can't invoke task later as EventLoop rejected it", e); + } + } + } + + /** + * Return {@code true} if the given {@link EventLoop} is compatible with this instance. + */ + protected abstract boolean isCompatible(EventLoop loop); + + /** + * Returns the {@link SocketAddress} which is bound locally. + */ + protected abstract SocketAddress localAddress0(); + + /** + * Return the {@link SocketAddress} which the {@link Channel} is connected to. + */ + protected abstract SocketAddress remoteAddress0(); + + /** + * Is called after the {@link Channel} is registered with its {@link EventLoop} as part of the register process. + * + * Sub-classes may override this method + */ + protected void doRegister() throws Exception { + // NOOP + } + + /** + * Bind the {@link Channel} to the {@link SocketAddress} + */ + protected abstract void doBind(SocketAddress localAddress) throws Exception; + + /** + * Disconnect this {@link Channel} from its remote peer + */ + protected abstract void doDisconnect() throws Exception; + + /** + * Close the {@link Channel} + */ + protected abstract void doClose() throws Exception; + + /** + * Deregister the {@link Channel} from its {@link EventLoop}. + * + * Sub-classes may override this method + */ + protected void doDeregister() throws Exception { + // NOOP + } + + /** + * Schedule a read operation. + */ + protected abstract void doBeginRead() throws Exception; + + /** + * Flush the content of the given buffer to the remote peer. + */ + protected abstract void doWrite(ChannelOutboundBuffer in) throws Exception; + + /** + * Invoked when a new message is added to a {@link ChannelOutboundBuffer} of this {@link AbstractChannel}, so that + * the {@link Channel} implementation converts the message to another. (e.g. heap buffer -> direct buffer) + */ + protected Object filterOutboundMessage(Object msg) throws Exception { + return msg; + } + + static final class CloseFuture extends DefaultChannelPromise { + + CloseFuture(AbstractChannel ch) { + super(ch); + } + + @Override + public ChannelPromise setSuccess() { + throw new IllegalStateException(); + } + + @Override + public ChannelPromise setFailure(Throwable cause) { + throw new IllegalStateException(); + } + + @Override + public boolean trySuccess() { + throw new IllegalStateException(); + } + + @Override + public boolean tryFailure(Throwable cause) { + throw new IllegalStateException(); + } + + boolean setClosed() { + return super.trySuccess(); + } + } +} diff --git a/common/src/main/java/common/net/channel/AbstractChannelHandlerContext.java b/common/src/main/java/common/net/channel/AbstractChannelHandlerContext.java new file mode 100644 index 0000000..204bd7a --- /dev/null +++ b/common/src/main/java/common/net/channel/AbstractChannelHandlerContext.java @@ -0,0 +1,1000 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import static common.net.channel.DefaultChannelPipeline.logger; + +import java.net.SocketAddress; + +import common.net.buffer.ByteBufAllocator; +import common.net.util.DefaultAttributeMap; +import common.net.util.Recycler; +import common.net.util.ReferenceCountUtil; +import common.net.util.concurrent.EventExecutor; +import common.net.util.concurrent.EventExecutorGroup; +import common.net.util.internal.OneTimeTask; +import common.net.util.internal.RecyclableMpscLinkedQueueNode; +import common.net.util.internal.StringUtil; + +abstract class AbstractChannelHandlerContext extends DefaultAttributeMap implements ChannelHandlerContext { + + volatile AbstractChannelHandlerContext next; + volatile AbstractChannelHandlerContext prev; + + private final boolean inbound; + private final boolean outbound; + private final AbstractChannel channel; + private final DefaultChannelPipeline pipeline; + private final String name; + private boolean removed; + + // Will be set to null if no child executor should be used, otherwise it will be set to the + // child executor. + final EventExecutor executor; + private ChannelFuture succeededFuture; + + // Lazily instantiated tasks used to trigger events to a handler with different executor. + // These needs to be volatile as otherwise an other Thread may see an half initialized instance. + // See the JMM for more details + private volatile Runnable invokeChannelReadCompleteTask; + private volatile Runnable invokeReadTask; + private volatile Runnable invokeChannelWritableStateChangedTask; + private volatile Runnable invokeFlushTask; + + AbstractChannelHandlerContext(DefaultChannelPipeline pipeline, EventExecutorGroup group, String name, + boolean inbound, boolean outbound) { + + if (name == null) { + throw new NullPointerException("name"); + } + + channel = pipeline.channel; + this.pipeline = pipeline; + this.name = name; + + if (group != null) { + // Pin one of the child executors once and remember it so that the same child executor + // is used to fire events for the same channel. + EventExecutor childExecutor = pipeline.childExecutors.get(group); + if (childExecutor == null) { + childExecutor = group.next(); + pipeline.childExecutors.put(group, childExecutor); + } + executor = childExecutor; + } else { + executor = null; + } + + this.inbound = inbound; + this.outbound = outbound; + } + + /** Invocation initiated by {@link DefaultChannelPipeline#teardownAll()}}. */ + void teardown() { + EventExecutor executor = executor(); + if (executor.inEventLoop()) { + teardown0(); + } else { + executor.execute(new Runnable() { + @Override + public void run() { + teardown0(); + } + }); + } + } + + private void teardown0() { + AbstractChannelHandlerContext prev = this.prev; + if (prev != null) { + synchronized (pipeline) { + pipeline.remove0(this); + } + prev.teardown(); + } + } + + @Override + public Channel channel() { + return channel; + } + + @Override + public ChannelPipeline pipeline() { + return pipeline; + } + + @Override + public ByteBufAllocator alloc() { + return channel().config().getAllocator(); + } + + @Override + public EventExecutor executor() { + if (executor == null) { + return channel().eventLoop(); + } else { + return executor; + } + } + + @Override + public String name() { + return name; + } + + @Override + public ChannelHandlerContext fireChannelRegistered() { + final AbstractChannelHandlerContext next = findContextInbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeChannelRegistered(); + } else { + executor.execute(new OneTimeTask() { + @Override + public void run() { + next.invokeChannelRegistered(); + } + }); + } + return this; + } + + private void invokeChannelRegistered() { + try { + ((ChannelInboundHandler) handler()).channelRegistered(this); + } catch (Throwable t) { + notifyHandlerException(t); + } + } + + @Override + public ChannelHandlerContext fireChannelUnregistered() { + final AbstractChannelHandlerContext next = findContextInbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeChannelUnregistered(); + } else { + executor.execute(new OneTimeTask() { + @Override + public void run() { + next.invokeChannelUnregistered(); + } + }); + } + return this; + } + + private void invokeChannelUnregistered() { + try { + ((ChannelInboundHandler) handler()).channelUnregistered(this); + } catch (Throwable t) { + notifyHandlerException(t); + } + } + + @Override + public ChannelHandlerContext fireChannelActive() { + final AbstractChannelHandlerContext next = findContextInbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeChannelActive(); + } else { + executor.execute(new OneTimeTask() { + @Override + public void run() { + next.invokeChannelActive(); + } + }); + } + return this; + } + + private void invokeChannelActive() { + try { + ((ChannelInboundHandler) handler()).channelActive(this); + } catch (Throwable t) { + notifyHandlerException(t); + } + } + + @Override + public ChannelHandlerContext fireChannelInactive() { + final AbstractChannelHandlerContext next = findContextInbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeChannelInactive(); + } else { + executor.execute(new OneTimeTask() { + @Override + public void run() { + next.invokeChannelInactive(); + } + }); + } + return this; + } + + private void invokeChannelInactive() { + try { + ((ChannelInboundHandler) handler()).channelInactive(this); + } catch (Throwable t) { + notifyHandlerException(t); + } + } + + @Override + public ChannelHandlerContext fireExceptionCaught(final Throwable cause) { + if (cause == null) { + throw new NullPointerException("cause"); + } + + final AbstractChannelHandlerContext next = this.next; + + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeExceptionCaught(cause); + } else { + try { + executor.execute(new OneTimeTask() { + @Override + public void run() { + next.invokeExceptionCaught(cause); + } + }); + } catch (Throwable t) { + if (logger.isWarnEnabled()) { + logger.warn("Failed to submit an exceptionCaught() event.", t); + logger.warn("The exceptionCaught() event that was failed to submit was:", cause); + } + } + } + + return this; + } + + private void invokeExceptionCaught(final Throwable cause) { + try { + handler().exceptionCaught(this, cause); + } catch (Throwable t) { + if (logger.isWarnEnabled()) { + logger.warn( + "An exception was thrown by a user handler's " + + "exceptionCaught() method while handling the following exception:", cause); + } + } + } + + @Override + public ChannelHandlerContext fireUserEventTriggered(final Object event) { + if (event == null) { + throw new NullPointerException("event"); + } + + final AbstractChannelHandlerContext next = findContextInbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeUserEventTriggered(event); + } else { + executor.execute(new OneTimeTask() { + @Override + public void run() { + next.invokeUserEventTriggered(event); + } + }); + } + return this; + } + + private void invokeUserEventTriggered(Object event) { + try { + ((ChannelInboundHandler) handler()).userEventTriggered(this, event); + } catch (Throwable t) { + notifyHandlerException(t); + } + } + + @Override + public ChannelHandlerContext fireChannelRead(final Object msg) { + if (msg == null) { + throw new NullPointerException("msg"); + } + + final AbstractChannelHandlerContext next = findContextInbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeChannelRead(msg); + } else { + executor.execute(new OneTimeTask() { + @Override + public void run() { + next.invokeChannelRead(msg); + } + }); + } + return this; + } + + private void invokeChannelRead(Object msg) { + try { + ((ChannelInboundHandler) handler()).channelRead(this, msg); + } catch (Throwable t) { + notifyHandlerException(t); + } + } + + @Override + public ChannelHandlerContext fireChannelReadComplete() { + final AbstractChannelHandlerContext next = findContextInbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeChannelReadComplete(); + } else { + Runnable task = next.invokeChannelReadCompleteTask; + if (task == null) { + next.invokeChannelReadCompleteTask = task = new Runnable() { + @Override + public void run() { + next.invokeChannelReadComplete(); + } + }; + } + executor.execute(task); + } + return this; + } + + private void invokeChannelReadComplete() { + try { + ((ChannelInboundHandler) handler()).channelReadComplete(this); + } catch (Throwable t) { + notifyHandlerException(t); + } + } + + @Override + public ChannelHandlerContext fireChannelWritabilityChanged() { + final AbstractChannelHandlerContext next = findContextInbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeChannelWritabilityChanged(); + } else { + Runnable task = next.invokeChannelWritableStateChangedTask; + if (task == null) { + next.invokeChannelWritableStateChangedTask = task = new Runnable() { + @Override + public void run() { + next.invokeChannelWritabilityChanged(); + } + }; + } + executor.execute(task); + } + return this; + } + + private void invokeChannelWritabilityChanged() { + try { + ((ChannelInboundHandler) handler()).channelWritabilityChanged(this); + } catch (Throwable t) { + notifyHandlerException(t); + } + } + + @Override + public ChannelFuture bind(SocketAddress localAddress) { + return bind(localAddress, newPromise()); + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress) { + return connect(remoteAddress, newPromise()); + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { + return connect(remoteAddress, localAddress, newPromise()); + } + + @Override + public ChannelFuture disconnect() { + return disconnect(newPromise()); + } + + @Override + public ChannelFuture close() { + return close(newPromise()); + } + + @Override + public ChannelFuture deregister() { + return deregister(newPromise()); + } + + @Override + public ChannelFuture bind(final SocketAddress localAddress, final ChannelPromise promise) { + if (localAddress == null) { + throw new NullPointerException("localAddress"); + } + if (!validatePromise(promise, false)) { + // cancelled + return promise; + } + + final AbstractChannelHandlerContext next = findContextOutbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeBind(localAddress, promise); + } else { + safeExecute(executor, new OneTimeTask() { + @Override + public void run() { + next.invokeBind(localAddress, promise); + } + }, promise, null); + } + + return promise; + } + + private void invokeBind(SocketAddress localAddress, ChannelPromise promise) { + try { + ((ChannelOutboundHandler) handler()).bind(this, localAddress, promise); + } catch (Throwable t) { + notifyOutboundHandlerException(t, promise); + } + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { + return connect(remoteAddress, null, promise); + } + + @Override + public ChannelFuture connect( + final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) { + + if (remoteAddress == null) { + throw new NullPointerException("remoteAddress"); + } + if (!validatePromise(promise, false)) { + // cancelled + return promise; + } + + final AbstractChannelHandlerContext next = findContextOutbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeConnect(remoteAddress, localAddress, promise); + } else { + safeExecute(executor, new OneTimeTask() { + @Override + public void run() { + next.invokeConnect(remoteAddress, localAddress, promise); + } + }, promise, null); + } + + return promise; + } + + private void invokeConnect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { + try { + ((ChannelOutboundHandler) handler()).connect(this, remoteAddress, localAddress, promise); + } catch (Throwable t) { + notifyOutboundHandlerException(t, promise); + } + } + + @Override + public ChannelFuture disconnect(final ChannelPromise promise) { + if (!validatePromise(promise, false)) { + // cancelled + return promise; + } + + final AbstractChannelHandlerContext next = findContextOutbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + // Translate disconnect to close if the channel has no notion of disconnect-reconnect. + // So far, UDP/IP is the only transport that has such behavior. + if (!channel().metadata().hasDisconnect()) { + next.invokeClose(promise); + } else { + next.invokeDisconnect(promise); + } + } else { + safeExecute(executor, new OneTimeTask() { + @Override + public void run() { + if (!channel().metadata().hasDisconnect()) { + next.invokeClose(promise); + } else { + next.invokeDisconnect(promise); + } + } + }, promise, null); + } + + return promise; + } + + private void invokeDisconnect(ChannelPromise promise) { + try { + ((ChannelOutboundHandler) handler()).disconnect(this, promise); + } catch (Throwable t) { + notifyOutboundHandlerException(t, promise); + } + } + + @Override + public ChannelFuture close(final ChannelPromise promise) { + if (!validatePromise(promise, false)) { + // cancelled + return promise; + } + + final AbstractChannelHandlerContext next = findContextOutbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeClose(promise); + } else { + safeExecute(executor, new OneTimeTask() { + @Override + public void run() { + next.invokeClose(promise); + } + }, promise, null); + } + + return promise; + } + + private void invokeClose(ChannelPromise promise) { + try { + ((ChannelOutboundHandler) handler()).close(this, promise); + } catch (Throwable t) { + notifyOutboundHandlerException(t, promise); + } + } + + @Override + public ChannelFuture deregister(final ChannelPromise promise) { + if (!validatePromise(promise, false)) { + // cancelled + return promise; + } + + final AbstractChannelHandlerContext next = findContextOutbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeDeregister(promise); + } else { + safeExecute(executor, new OneTimeTask() { + @Override + public void run() { + next.invokeDeregister(promise); + } + }, promise, null); + } + + return promise; + } + + private void invokeDeregister(ChannelPromise promise) { + try { + ((ChannelOutboundHandler) handler()).deregister(this, promise); + } catch (Throwable t) { + notifyOutboundHandlerException(t, promise); + } + } + + @Override + public ChannelHandlerContext read() { + final AbstractChannelHandlerContext next = findContextOutbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeRead(); + } else { + Runnable task = next.invokeReadTask; + if (task == null) { + next.invokeReadTask = task = new Runnable() { + @Override + public void run() { + next.invokeRead(); + } + }; + } + executor.execute(task); + } + + return this; + } + + private void invokeRead() { + try { + ((ChannelOutboundHandler) handler()).read(this); + } catch (Throwable t) { + notifyHandlerException(t); + } + } + + @Override + public ChannelFuture write(Object msg) { + return write(msg, newPromise()); + } + + @Override + public ChannelFuture write(final Object msg, final ChannelPromise promise) { + if (msg == null) { + throw new NullPointerException("msg"); + } + + if (!validatePromise(promise, true)) { + ReferenceCountUtil.release(msg); + // cancelled + return promise; + } + write(msg, false, promise); + + return promise; + } + + private void invokeWrite(Object msg, ChannelPromise promise) { + try { + ((ChannelOutboundHandler) handler()).write(this, msg, promise); + } catch (Throwable t) { + notifyOutboundHandlerException(t, promise); + } + } + + @Override + public ChannelHandlerContext flush() { + final AbstractChannelHandlerContext next = findContextOutbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeFlush(); + } else { + Runnable task = next.invokeFlushTask; + if (task == null) { + next.invokeFlushTask = task = new Runnable() { + @Override + public void run() { + next.invokeFlush(); + } + }; + } + safeExecute(executor, task, channel.voidPromise(), null); + } + + return this; + } + + private void invokeFlush() { + try { + ((ChannelOutboundHandler) handler()).flush(this); + } catch (Throwable t) { + notifyHandlerException(t); + } + } + + @Override + public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { + if (msg == null) { + throw new NullPointerException("msg"); + } + + if (!validatePromise(promise, true)) { + ReferenceCountUtil.release(msg); + // cancelled + return promise; + } + + write(msg, true, promise); + + return promise; + } + + private void write(Object msg, boolean flush, ChannelPromise promise) { + + AbstractChannelHandlerContext next = findContextOutbound(); + EventExecutor executor = next.executor(); + if (executor.inEventLoop()) { + next.invokeWrite(msg, promise); + if (flush) { + next.invokeFlush(); + } + } else { + int size = channel.estimatorHandle().size(msg); + if (size > 0) { + ChannelOutboundBuffer buffer = channel.unsafe().outboundBuffer(); + // Check for null as it may be set to null if the channel is closed already + if (buffer != null) { + buffer.incrementPendingOutboundBytes(size); + } + } + Runnable task; + if (flush) { + task = WriteAndFlushTask.newInstance(next, msg, size, promise); + } else { + task = WriteTask.newInstance(next, msg, size, promise); + } + safeExecute(executor, task, promise, msg); + } + } + + @Override + public ChannelFuture writeAndFlush(Object msg) { + return writeAndFlush(msg, newPromise()); + } + + private static void notifyOutboundHandlerException(Throwable cause, ChannelPromise promise) { + // only try to fail the promise if its not a VoidChannelPromise, as + // the VoidChannelPromise would also fire the cause through the pipeline + if (promise instanceof VoidChannelPromise) { + return; + } + + if (!promise.tryFailure(cause)) { + if (logger.isWarnEnabled()) { + logger.warn("Failed to fail the promise because it's done already: {}", promise, cause); + } + } + } + + private void notifyHandlerException(Throwable cause) { + if (inExceptionCaught(cause)) { + if (logger.isWarnEnabled()) { + logger.warn( + "An exception was thrown by a user handler " + + "while handling an exceptionCaught event", cause); + } + return; + } + + invokeExceptionCaught(cause); + } + + private static boolean inExceptionCaught(Throwable cause) { + do { + StackTraceElement[] trace = cause.getStackTrace(); + if (trace != null) { + for (StackTraceElement t : trace) { + if (t == null) { + break; + } + if ("exceptionCaught".equals(t.getMethodName())) { + return true; + } + } + } + + cause = cause.getCause(); + } while (cause != null); + + return false; + } + + @Override + public ChannelPromise newPromise() { + return new DefaultChannelPromise(channel(), executor()); + } + +// @Override +// public ChannelProgressivePromise newProgressivePromise() { +// return new DefaultChannelProgressivePromise(channel(), executor()); +// } + + @Override + public ChannelFuture newSucceededFuture() { + ChannelFuture succeededFuture = this.succeededFuture; + if (succeededFuture == null) { + this.succeededFuture = succeededFuture = new SucceededChannelFuture(channel(), executor()); + } + return succeededFuture; + } + + @Override + public ChannelFuture newFailedFuture(Throwable cause) { + return new FailedChannelFuture(channel(), executor(), cause); + } + + private boolean validatePromise(ChannelPromise promise, boolean allowVoidPromise) { + if (promise == null) { + throw new NullPointerException("promise"); + } + + if (promise.isDone()) { + // Check if the promise was cancelled and if so signal that the processing of the operation + // should not be performed. + // + // See https://github.com/netty/netty/issues/2349 + if (promise.isCancelled()) { + return false; + } + throw new IllegalArgumentException("promise already done: " + promise); + } + + if (promise.channel() != channel()) { + throw new IllegalArgumentException(String.format( + "promise.channel does not match: %s (expected: %s)", promise.channel(), channel())); + } + + if (promise.getClass() == DefaultChannelPromise.class) { + return true; + } + + if (!allowVoidPromise && promise instanceof VoidChannelPromise) { + throw new IllegalArgumentException( + StringUtil.simpleClassName(VoidChannelPromise.class) + " not allowed for this operation"); + } + + if (promise instanceof AbstractChannel.CloseFuture) { + throw new IllegalArgumentException( + StringUtil.simpleClassName(AbstractChannel.CloseFuture.class) + " not allowed in a pipeline"); + } + return true; + } + + private AbstractChannelHandlerContext findContextInbound() { + AbstractChannelHandlerContext ctx = this; + do { + ctx = ctx.next; + } while (!ctx.inbound); + return ctx; + } + + private AbstractChannelHandlerContext findContextOutbound() { + AbstractChannelHandlerContext ctx = this; + do { + ctx = ctx.prev; + } while (!ctx.outbound); + return ctx; + } + + @Override + public ChannelPromise voidPromise() { + return channel.voidPromise(); + } + + void setRemoved() { + removed = true; + } + + @Override + public boolean isRemoved() { + return removed; + } + + private static void safeExecute(EventExecutor executor, Runnable runnable, ChannelPromise promise, Object msg) { + try { + executor.execute(runnable); + } catch (Throwable cause) { + try { + promise.setFailure(cause); + } finally { + if (msg != null) { + ReferenceCountUtil.release(msg); + } + } + } + } + + abstract static class AbstractWriteTask extends RecyclableMpscLinkedQueueNode implements Runnable { + private AbstractChannelHandlerContext ctx; + private Object msg; + private ChannelPromise promise; + private int size; + + private AbstractWriteTask(Recycler.Handle handle) { + super(handle); + } + + protected static void init(AbstractWriteTask task, AbstractChannelHandlerContext ctx, + Object msg, int size, ChannelPromise promise) { + task.ctx = ctx; + task.msg = msg; + task.promise = promise; + task.size = size; + } + + @Override + public final void run() { + try { + if (size > 0) { + ChannelOutboundBuffer buffer = ctx.channel.unsafe().outboundBuffer(); + // Check for null as it may be set to null if the channel is closed already + if (buffer != null) { + buffer.decrementPendingOutboundBytes(size); + } + } + write(ctx, msg, promise); + } finally { + // Set to null so the GC can collect them directly + ctx = null; + msg = null; + promise = null; + } + } + + @Override + public Runnable value() { + return this; + } + + protected void write(AbstractChannelHandlerContext ctx, Object msg, ChannelPromise promise) { + ctx.invokeWrite(msg, promise); + } + } + + static final class WriteTask extends AbstractWriteTask implements SingleThreadEventLoop.NonWakeupRunnable { + + private static final Recycler RECYCLER = new Recycler() { + @Override + protected WriteTask newObject(Handle handle) { + return new WriteTask(handle); + } + }; + + private static WriteTask newInstance( + AbstractChannelHandlerContext ctx, Object msg, int size, ChannelPromise promise) { + WriteTask task = RECYCLER.get(); + init(task, ctx, msg, size, promise); + return task; + } + + private WriteTask(Recycler.Handle handle) { + super(handle); + } + + @Override + protected void recycle(Recycler.Handle handle) { + RECYCLER.recycle(this, handle); + } + } + + static final class WriteAndFlushTask extends AbstractWriteTask { + + private static final Recycler RECYCLER = new Recycler() { + @Override + protected WriteAndFlushTask newObject(Handle handle) { + return new WriteAndFlushTask(handle); + } + }; + + private static WriteAndFlushTask newInstance( + AbstractChannelHandlerContext ctx, Object msg, int size, ChannelPromise promise) { + WriteAndFlushTask task = RECYCLER.get(); + init(task, ctx, msg, size, promise); + return task; + } + + private WriteAndFlushTask(Recycler.Handle handle) { + super(handle); + } + + @Override + public void write(AbstractChannelHandlerContext ctx, Object msg, ChannelPromise promise) { + super.write(ctx, msg, promise); + ctx.invokeFlush(); + } + + @Override + protected void recycle(Recycler.Handle handle) { + RECYCLER.recycle(this, handle); + } + } +} diff --git a/common/src/main/java/common/net/channel/AbstractServerChannel.java b/common/src/main/java/common/net/channel/AbstractServerChannel.java new file mode 100644 index 0000000..ae1bd45 --- /dev/null +++ b/common/src/main/java/common/net/channel/AbstractServerChannel.java @@ -0,0 +1,83 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.net.SocketAddress; + +/** + * A skeletal server-side {@link Channel} implementation. A server-side + * {@link Channel} does not allow the following operations: + *
    + *
  • {@link #connect(SocketAddress, ChannelPromise)}
  • + *
  • {@link #disconnect(ChannelPromise)}
  • + *
  • {@link #write(Object, ChannelPromise)}
  • + *
  • {@link #flush()}
  • + *
  • and the shortcut methods which calls the methods mentioned above + *
+ */ +public abstract class AbstractServerChannel extends AbstractChannel implements ServerChannel { + + private static final ChannelMetadata METADATA = new ChannelMetadata(false); + + /** + * Creates a new instance. + */ + protected AbstractServerChannel() { + super(null); + } + + @Override + public ChannelMetadata metadata() { + return METADATA; + } + + @Override + public SocketAddress remoteAddress() { + return null; + } + + @Override + protected SocketAddress remoteAddress0() { + return null; + } + + @Override + protected void doDisconnect() throws Exception { + throw new UnsupportedOperationException(); + } + + @Override + protected AbstractUnsafe newUnsafe() { + return new DefaultServerUnsafe(); + } + + @Override + protected void doWrite(ChannelOutboundBuffer in) throws Exception { + throw new UnsupportedOperationException(); + } + + @Override + protected final Object filterOutboundMessage(Object msg) { + throw new UnsupportedOperationException(); + } + + private final class DefaultServerUnsafe extends AbstractUnsafe { + @Override + public void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { + safeSetFailure(promise, new UnsupportedOperationException()); + } + } +} diff --git a/common/src/main/java/common/net/channel/AdaptiveRecvByteBufAllocator.java b/common/src/main/java/common/net/channel/AdaptiveRecvByteBufAllocator.java new file mode 100644 index 0000000..f1eb52d --- /dev/null +++ b/common/src/main/java/common/net/channel/AdaptiveRecvByteBufAllocator.java @@ -0,0 +1,182 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.util.ArrayList; +import java.util.List; + +import common.net.buffer.ByteBuf; +import common.net.buffer.ByteBufAllocator; + +/** + * The {@link RecvByteBufAllocator} that automatically increases and + * decreases the predicted buffer size on feed back. + *

+ * It gradually increases the expected number of readable bytes if the previous + * read fully filled the allocated buffer. It gradually decreases the expected + * number of readable bytes if the read operation was not able to fill a certain + * amount of the allocated buffer two times consecutively. Otherwise, it keeps + * returning the same prediction. + */ +public class AdaptiveRecvByteBufAllocator implements RecvByteBufAllocator { + + static final int DEFAULT_MINIMUM = 64; + static final int DEFAULT_INITIAL = 1024; + static final int DEFAULT_MAXIMUM = 65536; + + private static final int INDEX_INCREMENT = 4; + private static final int INDEX_DECREMENT = 1; + + private static final int[] SIZE_TABLE; + + static { + List sizeTable = new ArrayList(); + for (int i = 16; i < 512; i += 16) { + sizeTable.add(i); + } + + for (int i = 512; i > 0; i <<= 1) { + sizeTable.add(i); + } + + SIZE_TABLE = new int[sizeTable.size()]; + for (int i = 0; i < SIZE_TABLE.length; i ++) { + SIZE_TABLE[i] = sizeTable.get(i); + } + } + + public static final AdaptiveRecvByteBufAllocator DEFAULT = new AdaptiveRecvByteBufAllocator(); + + private static int getSizeTableIndex(final int size) { + for (int low = 0, high = SIZE_TABLE.length - 1;;) { + if (high < low) { + return low; + } + if (high == low) { + return high; + } + + int mid = low + high >>> 1; + int a = SIZE_TABLE[mid]; + int b = SIZE_TABLE[mid + 1]; + if (size > b) { + low = mid + 1; + } else if (size < a) { + high = mid - 1; + } else if (size == a) { + return mid; + } else { + return mid + 1; + } + } + } + + private static final class HandleImpl implements Handle { + private final int minIndex; + private final int maxIndex; + private int index; + private int nextReceiveBufferSize; + private boolean decreaseNow; + + HandleImpl(int minIndex, int maxIndex, int initial) { + this.minIndex = minIndex; + this.maxIndex = maxIndex; + + index = getSizeTableIndex(initial); + nextReceiveBufferSize = SIZE_TABLE[index]; + } + + @Override + public ByteBuf allocate(ByteBufAllocator alloc) { + return alloc.ioBuffer(nextReceiveBufferSize); + } + + @Override + public int guess() { + return nextReceiveBufferSize; + } + + @Override + public void record(int actualReadBytes) { + if (actualReadBytes <= SIZE_TABLE[Math.max(0, index - INDEX_DECREMENT - 1)]) { + if (decreaseNow) { + index = Math.max(index - INDEX_DECREMENT, minIndex); + nextReceiveBufferSize = SIZE_TABLE[index]; + decreaseNow = false; + } else { + decreaseNow = true; + } + } else if (actualReadBytes >= nextReceiveBufferSize) { + index = Math.min(index + INDEX_INCREMENT, maxIndex); + nextReceiveBufferSize = SIZE_TABLE[index]; + decreaseNow = false; + } + } + } + + private final int minIndex; + private final int maxIndex; + private final int initial; + + /** + * Creates a new predictor with the default parameters. With the default + * parameters, the expected buffer size starts from {@code 1024}, does not + * go down below {@code 64}, and does not go up above {@code 65536}. + */ + private AdaptiveRecvByteBufAllocator() { + this(DEFAULT_MINIMUM, DEFAULT_INITIAL, DEFAULT_MAXIMUM); + } + + /** + * Creates a new predictor with the specified parameters. + * + * @param minimum the inclusive lower bound of the expected buffer size + * @param initial the initial buffer size when no feed back was received + * @param maximum the inclusive upper bound of the expected buffer size + */ + public AdaptiveRecvByteBufAllocator(int minimum, int initial, int maximum) { + if (minimum <= 0) { + throw new IllegalArgumentException("minimum: " + minimum); + } + if (initial < minimum) { + throw new IllegalArgumentException("initial: " + initial); + } + if (maximum < initial) { + throw new IllegalArgumentException("maximum: " + maximum); + } + + int minIndex = getSizeTableIndex(minimum); + if (SIZE_TABLE[minIndex] < minimum) { + this.minIndex = minIndex + 1; + } else { + this.minIndex = minIndex; + } + + int maxIndex = getSizeTableIndex(maximum); + if (SIZE_TABLE[maxIndex] > maximum) { + this.maxIndex = maxIndex - 1; + } else { + this.maxIndex = maxIndex; + } + + this.initial = initial; + } + + @Override + public Handle newHandle() { + return new HandleImpl(minIndex, maxIndex, initial); + } +} diff --git a/common/src/main/java/common/net/channel/Channel.java b/common/src/main/java/common/net/channel/Channel.java new file mode 100644 index 0000000..464bbff --- /dev/null +++ b/common/src/main/java/common/net/channel/Channel.java @@ -0,0 +1,511 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.net.SocketAddress; + +import common.net.buffer.ByteBufAllocator; +import common.net.util.AttributeMap; + + +/** + * A nexus to a network socket or a component which is capable of I/O + * operations such as read, write, connect, and bind. + *

+ * A channel provides a user: + *

    + *
  • the current state of the channel (e.g. is it open? is it connected?),
  • + *
  • the {@linkplain ChannelConfig configuration parameters} of the channel (e.g. receive buffer size),
  • + *
  • the I/O operations that the channel supports (e.g. read, write, connect, and bind), and
  • + *
  • the {@link ChannelPipeline} which handles all I/O events and requests + * associated with the channel.
  • + *
+ * + *

All I/O operations are asynchronous.

+ *

+ * All I/O operations in Netty are asynchronous. It means any I/O calls will + * return immediately with no guarantee that the requested I/O operation has + * been completed at the end of the call. Instead, you will be returned with + * a {@link ChannelFuture} instance which will notify you when the requested I/O + * operation has succeeded, failed, or canceled. + * + *

Channels are hierarchical

+ *

+ * A {@link Channel} can have a {@linkplain #parent() parent} depending on + * how it was created. For instance, a {@link SocketChannel}, that was accepted + * by {@link ServerSocketChannel}, will return the {@link ServerSocketChannel} + * as its parent on {@link #parent()}. + *

+ * The semantics of the hierarchical structure depends on the transport + * implementation where the {@link Channel} belongs to. For example, you could + * write a new {@link Channel} implementation that creates the sub-channels that + * share one socket connection, as BEEP and + * SSH do. + * + *

Downcast to access transport-specific operations

+ *

+ * Some transports exposes additional operations that is specific to the + * transport. Down-cast the {@link Channel} to sub-type to invoke such + * operations. For example, with the old I/O datagram transport, multicast + * join / leave operations are provided by {@link DatagramChannel}. + * + *

Release resources

+ *

+ * It is important to call {@link #close()} or {@link #close(ChannelPromise)} to release all + * resources once you are done with the {@link Channel}. This ensures all resources are + * released in a proper way, i.e. filehandles. + */ +public interface Channel extends AttributeMap, Comparable { + + /** + * Return the {@link EventLoop} this {@link Channel} was registered too. + */ + EventLoop eventLoop(); + + /** + * Returns the parent of this channel. + * + * @return the parent channel. + * {@code null} if this channel does not have a parent channel. + */ + Channel parent(); + + /** + * Returns the configuration of this channel. + */ + ChannelConfig config(); + + /** + * Returns {@code true} if the {@link Channel} is open an may get active later + */ + boolean isOpen(); + + /** + * Returns {@code true} if the {@link Channel} is registered with an {@link EventLoop}. + */ + boolean isRegistered(); + + /** + * Return {@code true} if the {@link Channel} is active and so connected. + */ + boolean isActive(); + + /** + * Return the {@link ChannelMetadata} of the {@link Channel} which describe the nature of the {@link Channel}. + */ + ChannelMetadata metadata(); + + /** + * Returns the local address where this channel is bound to. The returned + * {@link SocketAddress} is supposed to be down-cast into more concrete + * type such as {@link InetSocketAddress} to retrieve the detailed + * information. + * + * @return the local address of this channel. + * {@code null} if this channel is not bound. + */ + SocketAddress localAddress(); + + /** + * Returns the remote address where this channel is connected to. The + * returned {@link SocketAddress} is supposed to be down-cast into more + * concrete type such as {@link InetSocketAddress} to retrieve the detailed + * information. + * + * @return the remote address of this channel. + * {@code null} if this channel is not connected. + * If this channel is not connected but it can receive messages + * from arbitrary remote addresses (e.g. {@link DatagramChannel}, + * use {@link DatagramPacket#recipient()} to determine + * the origination of the received message as this method will + * return {@code null}. + */ + SocketAddress remoteAddress(); + + /** + * Returns the {@link ChannelFuture} which will be notified when this + * channel is closed. This method always returns the same future instance. + */ + ChannelFuture closeFuture(); + + /** + * Returns {@code true} if and only if the I/O thread will perform the + * requested write operation immediately. Any write requests made when + * this method returns {@code false} are queued until the I/O thread is + * ready to process the queued write requests. + */ + boolean isWritable(); + + /** + * Returns an internal-use-only object that provides unsafe operations. + */ + Unsafe unsafe(); + + /** + * Return the assigned {@link ChannelPipeline} + */ + ChannelPipeline pipeline(); + + /** + * Return the assigned {@link ByteBufAllocator} which will be used to allocate {@link ByteBuf}s. + */ + ByteBufAllocator alloc(); + + /** + * Return a new {@link ChannelPromise}. + */ + ChannelPromise newPromise(); + + /** + * Return an new {@link ChannelProgressivePromise} + */ +// ChannelProgressivePromise newProgressivePromise(); + + /** + * Create a new {@link ChannelFuture} which is marked as succeeded already. So {@link ChannelFuture#isSuccess()} + * will return {@code true}. All {@link FutureListener} added to it will be notified directly. Also + * every call of blocking methods will just return without blocking. + */ + ChannelFuture newSucceededFuture(); + + /** + * Create a new {@link ChannelFuture} which is marked as failed already. So {@link ChannelFuture#isSuccess()} + * will return {@code false}. All {@link FutureListener} added to it will be notified directly. Also + * every call of blocking methods will just return without blocking. + */ + ChannelFuture newFailedFuture(Throwable cause); + + /** + * Return a special ChannelPromise which can be reused for different operations. + *

+ * It's only supported to use + * it for {@link Channel#write(Object, ChannelPromise)}. + *

+ *

+ * Be aware that the returned {@link ChannelPromise} will not support most operations and should only be used + * if you want to save an object allocation for every write operation. You will not be able to detect if the + * operation was complete, only if it failed as the implementation will call + * {@link ChannelPipeline#fireExceptionCaught(Throwable)} in this case. + *

+ * Be aware this is an expert feature and should be used with care! + */ + ChannelPromise voidPromise(); + + /** + * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method + * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture bind(SocketAddress localAddress); + + /** + * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + *

+ * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with + * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} + * will be used. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress); + + /** + * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the + * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of + * an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress); + + /** + * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, + * either because the operation was successful or because of an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture disconnect(); + + /** + * Request to close this {@link Channel} and notify the {@link ChannelFuture} once the operation completes, + * either because the operation was successful or because of + * an error. + * + * After it is closed it is not possible to reuse it again. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture close(); + + /** + * Request to deregister this {@link Channel} from the previous assigned {@link EventExecutor} and notify the + * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of + * an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + * + */ + ChannelFuture deregister(); + + /** + * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + * + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method + * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise); + + /** + * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + * + * The given {@link ChannelFuture} will be notified. + * + *

+ * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with + * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} + * will be used. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise); + + /** + * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the + * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of + * an error. + * + * The given {@link ChannelPromise} will be notified and also returned. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise); + + /** + * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, + * either because the operation was successful or because of an error. + * + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture disconnect(ChannelPromise promise); + + /** + * Request to close this {@link Channel} and notify the {@link ChannelFuture} once the operation completes, + * either because the operation was successful or because of + * an error. + * + * After it is closed it is not possible to reuse it again. + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture close(ChannelPromise promise); + + /** + * Request to deregister this {@link Channel} from the previous assigned {@link EventExecutor} and notify the + * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of + * an error. + * + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture deregister(ChannelPromise promise); + + /** + * Request to Read data from the {@link Channel} into the first inbound buffer, triggers an + * {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)} event if data was + * read, and triggers a + * {@link ChannelInboundHandler#channelReadComplete(ChannelHandlerContext) channelReadComplete} event so the + * handler can decide to continue reading. If there's a pending read operation already, this method does nothing. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#read(ChannelHandlerContext)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + Channel read(); + + /** + * Request to write a message via this {@link Channel} through the {@link ChannelPipeline}. + * This method will not request to actual flush, so be sure to call {@link #flush()} + * once you want to request to flush all pending data to the actual transport. + */ + ChannelFuture write(Object msg); + + /** + * Request to write a message via this {@link Channel} through the {@link ChannelPipeline}. + * This method will not request to actual flush, so be sure to call {@link #flush()} + * once you want to request to flush all pending data to the actual transport. + */ + ChannelFuture write(Object msg, ChannelPromise promise); + + /** + * Request to flush all pending messages. + */ + Channel flush(); + + /** + * Shortcut for call {@link #write(Object, ChannelPromise)} and {@link #flush()}. + */ + ChannelFuture writeAndFlush(Object msg, ChannelPromise promise); + + /** + * Shortcut for call {@link #write(Object)} and {@link #flush()}. + */ + ChannelFuture writeAndFlush(Object msg); + + /** + * Unsafe operations that should never be called from user-code. These methods + * are only provided to implement the actual transport, and must be invoked from an I/O thread except for the + * following methods: + *

    + *
  • {@link #localAddress()}
  • + *
  • {@link #remoteAddress()}
  • + *
  • {@link #closeForcibly()}
  • + *
  • {@link #register(EventLoop, ChannelPromise)}
  • + *
  • {@link #voidPromise()}
  • + *
+ */ + interface Unsafe { + /** + * Return the {@link SocketAddress} to which is bound local or + * {@code null} if none. + */ + SocketAddress localAddress(); + + /** + * Return the {@link SocketAddress} to which is bound remote or + * {@code null} if none is bound yet. + */ + SocketAddress remoteAddress(); + + /** + * Register the {@link Channel} of the {@link ChannelPromise} with the {@link EventLoop} and notify + * the {@link ChannelFuture} once the registration was complete. + */ + void register(EventLoop eventLoop, ChannelPromise promise); + + /** + * Bind the {@link SocketAddress} to the {@link Channel} of the {@link ChannelPromise} and notify + * it once its done. + */ + void bind(SocketAddress localAddress, ChannelPromise promise); + + /** + * Connect the {@link Channel} of the given {@link ChannelFuture} with the given remote {@link SocketAddress}. + * If a specific local {@link SocketAddress} should be used it need to be given as argument. Otherwise just + * pass {@code null} to it. + * + * The {@link ChannelPromise} will get notified once the connect operation was complete. + */ + void connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise); + + /** + * Disconnect the {@link Channel} of the {@link ChannelFuture} and notify the {@link ChannelPromise} once the + * operation was complete. + */ + void disconnect(ChannelPromise promise); + + /** + * Close the {@link Channel} of the {@link ChannelPromise} and notify the {@link ChannelPromise} once the + * operation was complete. + */ + void close(ChannelPromise promise); + + /** + * Closes the {@link Channel} immediately without firing any events. Probably only useful + * when registration attempt failed. + */ + void closeForcibly(); + + /** + * Deregister the {@link Channel} of the {@link ChannelPromise} from {@link EventLoop} and notify the + * {@link ChannelPromise} once the operation was complete. + */ + void deregister(ChannelPromise promise); + + /** + * Schedules a read operation that fills the inbound buffer of the first {@link ChannelInboundHandler} in the + * {@link ChannelPipeline}. If there's already a pending read operation, this method does nothing. + */ + void beginRead(); + + /** + * Schedules a write operation. + */ + void write(Object msg, ChannelPromise promise); + + /** + * Flush out all write operations scheduled via {@link #write(Object, ChannelPromise)}. + */ + void flush(); + + /** + * Return a special ChannelPromise which can be reused and passed to the operations in {@link Unsafe}. + * It will never be notified of a success or error and so is only a placeholder for operations + * that take a {@link ChannelPromise} as argument but for which you not want to get notified. + */ + ChannelPromise voidPromise(); + + /** + * Returns the {@link ChannelOutboundBuffer} of the {@link Channel} where the pending write requests are stored. + */ + ChannelOutboundBuffer outboundBuffer(); + } +} diff --git a/common/src/main/java/common/net/channel/ChannelConfig.java b/common/src/main/java/common/net/channel/ChannelConfig.java new file mode 100644 index 0000000..50e300f --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelConfig.java @@ -0,0 +1,231 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.util.Map; + +import common.net.buffer.ByteBufAllocator; + +/** + * A set of configuration properties of a {@link Channel}. + *

+ * Please down-cast to more specific configuration type such as + * {@link SocketChannelConfig} or use {@link #setOptions(Map)} to set the + * transport-specific properties: + *

+ * {@link Channel} ch = ...;
+ * {@link SocketChannelConfig} cfg = ({@link SocketChannelConfig}) ch.getConfig();
+ * cfg.setTcpNoDelay(false);
+ * 
+ * + *

Option map

+ * + * An option map property is a dynamic write-only property which allows + * the configuration of a {@link Channel} without down-casting its associated + * {@link ChannelConfig}. To update an option map, please call {@link #setOptions(Map)}. + *

+ * All {@link ChannelConfig} has the following options: + * + * + * + * + * + * + * + * + * + * + * + * + * + *
NameAssociated setter method
{@link ChannelOption#CONNECT_TIMEOUT_MILLIS}{@link #setConnectTimeoutMillis(int)}
{@link ChannelOption#WRITE_SPIN_COUNT}{@link #setWriteSpinCount(int)}
{@link ChannelOption#ALLOCATOR}{@link #setAllocator(ByteBufAllocator)}
{@link ChannelOption#AUTO_READ}{@link #setAutoRead(boolean)}
+ *

+ * More options are available in the sub-types of {@link ChannelConfig}. For + * example, you can configure the parameters which are specific to a TCP/IP + * socket as explained in {@link SocketChannelConfig}. + */ +public interface ChannelConfig { + + /** + * Return all set {@link ChannelOption}'s. + */ + Map, Object> getOptions(); + + /** + * Sets the configuration properties from the specified {@link Map}. + */ + boolean setOptions(Map, ?> options); + + /** + * Return the value of the given {@link ChannelOption} + */ + T getOption(ChannelOption option); + + /** + * Sets a configuration property with the specified name and value. + * To override this method properly, you must call the super class: + *

+     * public boolean setOption(ChannelOption<T> option, T value) {
+     *     if (super.setOption(option, value)) {
+     *         return true;
+     *     }
+     *
+     *     if (option.equals(additionalOption)) {
+     *         ....
+     *         return true;
+     *     }
+     *
+     *     return false;
+     * }
+     * 
+ * + * @return {@code true} if and only if the property has been set + */ + boolean setOption(ChannelOption option, T value); + + /** + * Returns the connect timeout of the channel in milliseconds. If the + * {@link Channel} does not support connect operation, this property is not + * used at all, and therefore will be ignored. + * + * @return the connect timeout in milliseconds. {@code 0} if disabled. + */ + int getConnectTimeoutMillis(); + + /** + * Sets the connect timeout of the channel in milliseconds. If the + * {@link Channel} does not support connect operation, this property is not + * used at all, and therefore will be ignored. + * + * @param connectTimeoutMillis the connect timeout in milliseconds. + * {@code 0} to disable. + */ + ChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis); + + /** + * Returns the maximum number of messages to read per read loop. + * a {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object) channelRead()} event. + * If this value is greater than 1, an event loop might attempt to read multiple times to procure multiple messages. + */ + int getMaxMessagesPerRead(); + + /** + * Sets the maximum number of messages to read per read loop. + * If this value is greater than 1, an event loop might attempt to read multiple times to procure multiple messages. + */ + ChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead); + + /** + * Returns the maximum loop count for a write operation until + * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. + * It is similar to what a spin lock is used for in concurrency programming. + * It improves memory utilization and write throughput depending on + * the platform that JVM runs on. The default value is {@code 16}. + */ + int getWriteSpinCount(); + + /** + * Sets the maximum loop count for a write operation until + * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. + * It is similar to what a spin lock is used for in concurrency programming. + * It improves memory utilization and write throughput depending on + * the platform that JVM runs on. The default value is {@code 16}. + * + * @throws IllegalArgumentException + * if the specified value is {@code 0} or less than {@code 0} + */ + ChannelConfig setWriteSpinCount(int writeSpinCount); + + /** + * Returns {@link ByteBufAllocator} which is used for the channel + * to allocate buffers. + */ + ByteBufAllocator getAllocator(); + + /** + * Set the {@link ByteBufAllocator} which is used for the channel + * to allocate buffers. + */ + ChannelConfig setAllocator(ByteBufAllocator allocator); + + /** + * Returns {@link RecvByteBufAllocator} which is used for the channel + * to allocate receive buffers. + */ + RecvByteBufAllocator getRecvByteBufAllocator(); + + /** + * Set the {@link ByteBufAllocator} which is used for the channel + * to allocate receive buffers. + */ + ChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator); + + /** + * Returns {@code true} if and only if {@link ChannelHandlerContext#read()} will be invoked automatically so that + * a user application doesn't need to call it at all. The default value is {@code true}. + */ + boolean isAutoRead(); + + /** + * Sets if {@link ChannelHandlerContext#read()} will be invoked automatically so that a user application doesn't + * need to call it at all. The default value is {@code true}. + */ + ChannelConfig setAutoRead(boolean autoRead); + + /** + * Returns the high water mark of the write buffer. If the number of bytes + * queued in the write buffer exceeds this value, {@link Channel#isWritable()} + * will start to return {@code false}. + */ + int getWriteBufferHighWaterMark(); + + /** + * Sets the high water mark of the write buffer. If the number of bytes + * queued in the write buffer exceeds this value, {@link Channel#isWritable()} + * will start to return {@code false}. + */ + ChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark); + + /** + * Returns the low water mark of the write buffer. Once the number of bytes + * queued in the write buffer exceeded the + * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then + * dropped down below this value, {@link Channel#isWritable()} will start to return + * {@code true} again. + */ + int getWriteBufferLowWaterMark(); + + /** + * Sets the low water mark of the write buffer. Once the number of bytes + * queued in the write buffer exceeded the + * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then + * dropped down below this value, {@link Channel#isWritable()} will start to return + * {@code true} again. + */ + ChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark); + + /** + * Returns {@link MessageSizeEstimator} which is used for the channel + * to detect the size of a message. + */ + MessageSizeEstimator getMessageSizeEstimator(); + + /** + * Set the {@link ByteBufAllocator} which is used for the channel + * to detect the size of a message. + */ + ChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator); +} diff --git a/common/src/main/java/common/net/channel/ChannelException.java b/common/src/main/java/common/net/channel/ChannelException.java new file mode 100644 index 0000000..721d03f --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelException.java @@ -0,0 +1,51 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +/** + * A {@link RuntimeException} which is thrown when an I/O operation fails. + */ +public class ChannelException extends RuntimeException { + + private static final long serialVersionUID = 2908618315971075004L; + + /** + * Creates a new exception. + */ + public ChannelException() { + } + + /** + * Creates a new exception. + */ + public ChannelException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Creates a new exception. + */ + public ChannelException(String message) { + super(message); + } + + /** + * Creates a new exception. + */ + public ChannelException(Throwable cause) { + super(cause); + } +} diff --git a/common/src/main/java/common/net/channel/ChannelFuture.java b/common/src/main/java/common/net/channel/ChannelFuture.java new file mode 100644 index 0000000..e849ad5 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelFuture.java @@ -0,0 +1,192 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; + + +/** + * The result of an asynchronous {@link Channel} I/O operation. + *

+ * All I/O operations in Netty are asynchronous. It means any I/O calls will + * return immediately with no guarantee that the requested I/O operation has + * been completed at the end of the call. Instead, you will be returned with + * a {@link ChannelFuture} instance which gives you the information about the + * result or status of the I/O operation. + *

+ * A {@link ChannelFuture} is either uncompleted or completed. + * When an I/O operation begins, a new future object is created. The new future + * is uncompleted initially - it is neither succeeded, failed, nor cancelled + * because the I/O operation is not finished yet. If the I/O operation is + * finished either successfully, with failure, or by cancellation, the future is + * marked as completed with more specific information, such as the cause of the + * failure. Please note that even failure and cancellation belong to the + * completed state. + *

+ *                                      +---------------------------+
+ *                                      | Completed successfully    |
+ *                                      +---------------------------+
+ *                                 +---->      isDone() = true      |
+ * +--------------------------+    |    |   isSuccess() = true      |
+ * |        Uncompleted       |    |    +===========================+
+ * +--------------------------+    |    | Completed with failure    |
+ * |      isDone() = false    |    |    +---------------------------+
+ * |   isSuccess() = false    |----+---->   isDone() = true         |
+ * | isCancelled() = false    |    |    | cause() = non-null     |
+ * |    cause() = null     |    |    +===========================+
+ * +--------------------------+    |    | Completed by cancellation |
+ *                                 |    +---------------------------+
+ *                                 +---->      isDone() = true      |
+ *                                      | isCancelled() = true      |
+ *                                      +---------------------------+
+ * 
+ * + * Various methods are provided to let you check if the I/O operation has been + * completed, wait for the completion, and retrieve the result of the I/O + * operation. It also allows you to add {@link ChannelFutureListener}s so you + * can get notified when the I/O operation is completed. + * + *

Prefer {@link #addListener(GenericFutureListener)} to {@link #await()}

+ * + * It is recommended to prefer {@link #addListener(GenericFutureListener)} to + * {@link #await()} wherever possible to get notified when an I/O operation is + * done and to do any follow-up tasks. + *

+ * {@link #addListener(GenericFutureListener)} is non-blocking. It simply adds + * the specified {@link ChannelFutureListener} to the {@link ChannelFuture}, and + * I/O thread will notify the listeners when the I/O operation associated with + * the future is done. {@link ChannelFutureListener} yields the best + * performance and resource utilization because it does not block at all, but + * it could be tricky to implement a sequential logic if you are not used to + * event-driven programming. + *

+ * By contrast, {@link #await()} is a blocking operation. Once called, the + * caller thread blocks until the operation is done. It is easier to implement + * a sequential logic with {@link #await()}, but the caller thread blocks + * unnecessarily until the I/O operation is done and there's relatively + * expensive cost of inter-thread notification. Moreover, there's a chance of + * dead lock in a particular circumstance, which is described below. + * + *

Do not call {@link #await()} inside {@link ChannelHandler}

+ *

+ * The event handler methods in {@link ChannelHandler} is usually called by + * an I/O thread. If {@link #await()} is called by an event handler + * method, which is called by the I/O thread, the I/O operation it is waiting + * for might never be complete because {@link #await()} can block the I/O + * operation it is waiting for, which is a dead lock. + *

+ * // BAD - NEVER DO THIS
+ * {@code @Override}
+ * public void channelRead({@link ChannelHandlerContext} ctx, GoodByeMessage msg) {
+ *     {@link ChannelFuture} future = ctx.channel().close();
+ *     future.awaitUninterruptibly();
+ *     // Perform post-closure operation
+ *     // ...
+ * }
+ *
+ * // GOOD
+ * {@code @Override}
+ * public void channelRead({@link ChannelHandlerContext} ctx,  GoodByeMessage msg) {
+ *     {@link ChannelFuture} future = ctx.channel().close();
+ *     future.addListener(new {@link ChannelFutureListener}() {
+ *         public void operationComplete({@link ChannelFuture} future) {
+ *             // Perform post-closure operation
+ *             // ...
+ *         }
+ *     });
+ * }
+ * 
+ *

+ * In spite of the disadvantages mentioned above, there are certainly the cases + * where it is more convenient to call {@link #await()}. In such a case, please + * make sure you do not call {@link #await()} in an I/O thread. Otherwise, + * {@link BlockingOperationException} will be raised to prevent a dead lock. + * + *

Do not confuse I/O timeout and await timeout

+ * + * The timeout value you specify with {@link #await(long)}, + * {@link #await(long, TimeUnit)}, {@link #awaitUninterruptibly(long)}, or + * {@link #awaitUninterruptibly(long, TimeUnit)} are not related with I/O + * timeout at all. If an I/O operation times out, the future will be marked as + * 'completed with failure,' as depicted in the diagram above. For example, + * connect timeout should be configured via a transport-specific option: + *
+ * // BAD - NEVER DO THIS
+ * {@link Bootstrap} b = ...;
+ * {@link ChannelFuture} f = b.connect(...);
+ * f.awaitUninterruptibly(10, TimeUnit.SECONDS);
+ * if (f.isCancelled()) {
+ *     // Connection attempt cancelled by user
+ * } else if (!f.isSuccess()) {
+ *     // You might get a NullPointerException here because the future
+ *     // might not be completed yet.
+ *     f.cause().printStackTrace();
+ * } else {
+ *     // Connection established successfully
+ * }
+ *
+ * // GOOD
+ * {@link Bootstrap} b = ...;
+ * // Configure the connect timeout option.
+ * b.option({@link ChannelOption}.CONNECT_TIMEOUT_MILLIS, 10000);
+ * {@link ChannelFuture} f = b.connect(...);
+ * f.awaitUninterruptibly();
+ *
+ * // Now we are sure the future is completed.
+ * assert f.isDone();
+ *
+ * if (f.isCancelled()) {
+ *     // Connection attempt cancelled by user
+ * } else if (!f.isSuccess()) {
+ *     f.cause().printStackTrace();
+ * } else {
+ *     // Connection established successfully
+ * }
+ * 
+ */ +public interface ChannelFuture extends Future { + + /** + * Returns a channel where the I/O operation associated with this + * future takes place. + */ + Channel channel(); + + @Override + ChannelFuture addListener(GenericFutureListener> listener); + + @Override + ChannelFuture addListeners(GenericFutureListener>... listeners); + + @Override + ChannelFuture removeListener(GenericFutureListener> listener); + + @Override + ChannelFuture removeListeners(GenericFutureListener>... listeners); + + @Override + ChannelFuture sync() throws InterruptedException; + + @Override + ChannelFuture syncUninterruptibly(); + + @Override + ChannelFuture await() throws InterruptedException; + + @Override + ChannelFuture awaitUninterruptibly(); +} diff --git a/common/src/main/java/common/net/channel/ChannelFutureListener.java b/common/src/main/java/common/net/channel/ChannelFutureListener.java new file mode 100644 index 0000000..ec088b6 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelFutureListener.java @@ -0,0 +1,74 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.util.concurrent.GenericFutureListener; + + +/** + * Listens to the result of a {@link ChannelFuture}. The result of the + * asynchronous {@link Channel} I/O operation is notified once this listener + * is added by calling {@link ChannelFuture#addListener(GenericFutureListener)}. + * + *

Return the control to the caller quickly

+ * + * {@link #operationComplete(Future)} is directly called by an I/O + * thread. Therefore, performing a time consuming task or a blocking operation + * in the handler method can cause an unexpected pause during I/O. If you need + * to perform a blocking operation on I/O completion, try to execute the + * operation in a different thread using a thread pool. + */ +public interface ChannelFutureListener extends GenericFutureListener { + + /** + * A {@link ChannelFutureListener} that closes the {@link Channel} which is + * associated with the specified {@link ChannelFuture}. + */ + ChannelFutureListener CLOSE = new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) { + future.channel().close(); + } + }; + + /** + * A {@link ChannelFutureListener} that closes the {@link Channel} when the + * operation ended up with a failure or cancellation rather than a success. + */ + ChannelFutureListener CLOSE_ON_FAILURE = new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) { + if (!future.isSuccess()) { + future.channel().close(); + } + } + }; + + /** + * A {@link ChannelFutureListener} that forwards the {@link Throwable} of the {@link ChannelFuture} into the + * {@link ChannelPipeline}. This mimics the old behavior of Netty 3. + */ + ChannelFutureListener FIRE_EXCEPTION_ON_FAILURE = new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) { + if (!future.isSuccess()) { + future.channel().pipeline().fireExceptionCaught(future.cause()); + } + } + }; + + // Just a type alias +} diff --git a/common/src/main/java/common/net/channel/ChannelHandler.java b/common/src/main/java/common/net/channel/ChannelHandler.java new file mode 100644 index 0000000..4b78cde --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelHandler.java @@ -0,0 +1,211 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.lang.annotation.Documented; +import java.lang.annotation.ElementType; +import java.lang.annotation.Inherited; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +/** + * Handles or intercepts a {@link ChannelInboundInvoker} or {@link ChannelOutboundInvoker} operation, and forwards it + * to the next handler in a {@link ChannelPipeline}. + * + *

Sub-types

+ *

+ * {@link ChannelHandler} itself does not provide many methods. To handle a + * a {@link ChannelInboundInvoker} or {@link ChannelOutboundInvoker} operation + * you need to implement its sub-interfaces. There are many different sub-interfaces + * which handles inbound and outbound operations. + * + * But the most useful for developers may be: + *

    + *
  • {@link ChannelInboundHandlerAdapter} handles and intercepts inbound operations
  • + *
  • {@link ChannelOutboundHandlerAdapter} handles and intercepts outbound operations
  • + *
+ * + * You will also find more detailed explanation from the documentation of + * each sub-interface on how an event is interpreted when it goes upstream and + * downstream respectively. + * + *

The context object

+ *

+ * A {@link ChannelHandler} is provided with a {@link ChannelHandlerContext} + * object. A {@link ChannelHandler} is supposed to interact with the + * {@link ChannelPipeline} it belongs to via a context object. Using the + * context object, the {@link ChannelHandler} can pass events upstream or + * downstream, modify the pipeline dynamically, or store the information + * (using {@link AttributeKey}s) which is specific to the handler. + * + *

State management

+ * + * A {@link ChannelHandler} often needs to store some stateful information. + * The simplest and recommended approach is to use member variables: + *
+ * public interface Message {
+ *     // your methods here
+ * }
+ *
+ * public class DataServerHandler extends {@link SimpleChannelInboundHandler}<Message> {
+ *
+ *     private boolean loggedIn;
+ *
+ *     {@code @Override}
+ *     public void channelRead0({@link ChannelHandlerContext} ctx, Message message) {
+ *         {@link Channel} ch = e.getChannel();
+ *         if (message instanceof LoginMessage) {
+ *             authenticate((LoginMessage) message);
+ *             loggedIn = true;
+ *         } else (message instanceof GetDataMessage) {
+ *             if (loggedIn) {
+ *                 ch.write(fetchSecret((GetDataMessage) message));
+ *             } else {
+ *                 fail();
+ *             }
+ *         }
+ *     }
+ *     ...
+ * }
+ * 
+ * Because the handler instance has a state variable which is dedicated to + * one connection, you have to create a new handler instance for each new + * channel to avoid a race condition where a unauthenticated client can get + * the confidential information: + *
+ * // Create a new handler instance per channel.
+ * // See {@link ChannelInitializer#initChannel(Channel)}.
+ * public class DataServerInitializer extends {@link ChannelInitializer}<{@link Channel}> {
+ *     {@code @Override}
+ *     public void initChannel({@link Channel} channel) {
+ *         channel.pipeline().addLast("handler", new DataServerHandler());
+ *     }
+ * }
+ *
+ * 
+ * + *

Using {@link AttributeKey}

+ * + * Although it's recommended to use member variables to store the state of a + * handler, for some reason you might not want to create many handler instances. + * In such a case, you can use {@link AttributeKey}s which is provided by + * {@link ChannelHandlerContext}: + *
+ * public interface Message {
+ *     // your methods here
+ * }
+ *
+ * {@code @Sharable}
+ * public class DataServerHandler extends {@link SimpleChannelInboundHandler}<Message> {
+ *     private final {@link AttributeKey}<{@link Boolean}> auth =
+ *           {@link AttributeKey#valueOf(String) AttributeKey.valueOf("auth")};
+ *
+ *     {@code @Override}
+ *     public void channelRead({@link ChannelHandlerContext} ctx, Message message) {
+ *         {@link Attribute}<{@link Boolean}> attr = ctx.attr(auth);
+ *         {@link Channel} ch = ctx.channel();
+ *         if (message instanceof LoginMessage) {
+ *             authenticate((LoginMessage) o);
+ *             attr.set(true);
+ *         } else (message instanceof GetDataMessage) {
+ *             if (Boolean.TRUE.equals(attr.get())) {
+ *                 ch.write(fetchSecret((GetDataMessage) o));
+ *             } else {
+ *                 fail();
+ *             }
+ *         }
+ *     }
+ *     ...
+ * }
+ * 
+ * Now that the state of the handler isattached to the {@link ChannelHandlerContext}, you can add the + * same handler instance to different pipelines: + *
+ * public class DataServerInitializer extends {@link ChannelInitializer}<{@link Channel}> {
+ *
+ *     private static final DataServerHandler SHARED = new DataServerHandler();
+ *
+ *     {@code @Override}
+ *     public void initChannel({@link Channel} channel) {
+ *         channel.pipeline().addLast("handler", SHARED);
+ *     }
+ * }
+ * 
+ * + * + *

The {@code @Sharable} annotation

+ *

+ * In the example above which used an {@link AttributeKey}, + * you might have noticed the {@code @Sharable} annotation. + *

+ * If a {@link ChannelHandler} is annotated with the {@code @Sharable} + * annotation, it means you can create an instance of the handler just once and + * add it to one or more {@link ChannelPipeline}s multiple times without + * a race condition. + *

+ * If this annotation is not specified, you have to create a new handler + * instance every time you add it to a pipeline because it has unshared state + * such as member variables. + *

+ * This annotation is provided for documentation purpose, just like + * the JCIP annotations. + * + *

Additional resources worth reading

+ *

+ * Please refer to the {@link ChannelHandler}, and + * {@link ChannelPipeline} to find out more about inbound and outbound operations, + * what fundamental differences they have, how they flow in a pipeline, and how to handle + * the operation in your application. + */ +public interface ChannelHandler { + + /** + * Gets called after the {@link ChannelHandler} was added to the actual context and it's ready to handle events. + */ + void handlerAdded(ChannelHandlerContext ctx) throws Exception; + + /** + * Gets called after the {@link ChannelHandler} was removed from the actual context and it doesn't handle events + * anymore. + */ + void handlerRemoved(ChannelHandlerContext ctx) throws Exception; + + /** + * Gets called if a {@link Throwable} was thrown. + */ + void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception; + + /** + * Indicates that the same instance of the annotated {@link ChannelHandler} + * can be added to one or more {@link ChannelPipeline}s multiple times + * without a race condition. + *

+ * If this annotation is not specified, you have to create a new handler + * instance every time you add it to a pipeline because it has unshared + * state such as member variables. + *

+ * This annotation is provided for documentation purpose, just like + * the JCIP annotations. + */ + @Inherited + @Documented + @Target(ElementType.TYPE) + @Retention(RetentionPolicy.RUNTIME) + @interface Sharable { + // no value + } +} diff --git a/common/src/main/java/common/net/channel/ChannelHandlerAdapter.java b/common/src/main/java/common/net/channel/ChannelHandlerAdapter.java new file mode 100644 index 0000000..7137333 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelHandlerAdapter.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.channel; + +import java.util.Map; + +import common.net.util.internal.InternalThreadLocalMap; + +/** + * Skelton implementation of a {@link ChannelHandler}. + */ +public abstract class ChannelHandlerAdapter implements ChannelHandler { + + // Not using volatile because it's used only for a sanity check. + boolean added; + + /** + * Return {@code true} if the implementation is {@link Sharable} and so can be added + * to different {@link ChannelPipeline}s. + */ + public boolean isSharable() { + /** + * Cache the result of {@link Sharable} annotation detection to workaround a condition. We use a + * {@link ThreadLocal} and {@link WeakHashMap} to eliminate the volatile write/reads. Using different + * {@link WeakHashMap} instances per {@link Thread} is good enough for us and the number of + * {@link Thread}s are quite limited anyway. + * + * See #2289. + */ + Class clazz = getClass(); + Map, Boolean> cache = InternalThreadLocalMap.get().handlerSharableCache(); + Boolean sharable = cache.get(clazz); + if (sharable == null) { + sharable = clazz.isAnnotationPresent(Sharable.class); + cache.put(clazz, sharable); + } + return sharable; + } + + /** + * Do nothing by default, sub-classes may override this method. + */ + @Override + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { + // NOOP + } + + /** + * Do nothing by default, sub-classes may override this method. + */ + @Override + public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { + // NOOP + } + + /** + * Calls {@link ChannelHandlerContext#fireExceptionCaught(Throwable)} to forward + * to the next {@link ChannelHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + ctx.fireExceptionCaught(cause); + } +} diff --git a/common/src/main/java/common/net/channel/ChannelHandlerContext.java b/common/src/main/java/common/net/channel/ChannelHandlerContext.java new file mode 100644 index 0000000..81da8c7 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelHandlerContext.java @@ -0,0 +1,489 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + + +import java.net.SocketAddress; + +import common.net.buffer.ByteBufAllocator; +import common.net.util.AttributeMap; +import common.net.util.concurrent.EventExecutor; + +/** + * Enables a {@link ChannelHandler} to interact with its {@link ChannelPipeline} + * and other handlers. A handler can notify the next {@link ChannelHandler} in the {@link ChannelPipeline}, + * modify the {@link ChannelPipeline} it belongs to dynamically. + * + *

Notify

+ * + * You can notify the closest handler in the + * same {@link ChannelPipeline} by calling one of the various methods provided here. + * Please refer to {@link ChannelPipeline} to understand how an event flows. + * + *

Modifying a pipeline

+ * + * You can get the {@link ChannelPipeline} your handler belongs to by calling + * {@link #pipeline()}. A non-trivial application could insert, remove, or + * replace handlers in the pipeline dynamically at runtime. + * + *

Retrieving for later use

+ * + * You can keep the {@link ChannelHandlerContext} for later use, such as + * triggering an event outside the handler methods, even from a different thread. + *
+ * public class MyHandler extends {@link ChannelDuplexHandler} {
+ *
+ *     private {@link ChannelHandlerContext} ctx;
+ *
+ *     public void beforeAdd({@link ChannelHandlerContext} ctx) {
+ *         this.ctx = ctx;
+ *     }
+ *
+ *     public void login(String username, password) {
+ *         ctx.write(new LoginMessage(username, password));
+ *     }
+ *     ...
+ * }
+ * 
+ * + *

Storing stateful information

+ * + * {@link #attr(AttributeKey)} allow you to + * store and access stateful information that is related with a handler and its + * context. Please refer to {@link ChannelHandler} to learn various recommended + * ways to manage stateful information. + * + *

A handler can have more than one context

+ * + * Please note that a {@link ChannelHandler} instance can be added to more than + * one {@link ChannelPipeline}. It means a single {@link ChannelHandler} + * instance can have more than one {@link ChannelHandlerContext} and therefore + * the single instance can be invoked with different + * {@link ChannelHandlerContext}s if it is added to one or more + * {@link ChannelPipeline}s more than once. + *

+ * For example, the following handler will have as many independent {@link AttributeKey}s + * as how many times it is added to pipelines, regardless if it is added to the + * same pipeline multiple times or added to different pipelines multiple times: + *

+ * public class FactorialHandler extends {@link ChannelInboundHandlerAdapter}<{@link Integer}> {
+ *
+ *   private final {@link AttributeKey}<{@link Integer}> counter =
+ *           new {@link AttributeKey}<{@link Integer}>("counter");
+ *
+ *   // This handler will receive a sequence of increasing integers starting
+ *   // from 1.
+ *   {@code @Override}
+ *   public void channelRead({@link ChannelHandlerContext} ctx, {@link Integer} integer) {
+ *     {@link Attribute}<{@link Integer}> attr = ctx.getAttr(counter);
+ *     Integer a = ctx.getAttr(counter).get();
+ *
+ *     if (a == null) {
+ *       a = 1;
+ *     }
+ *
+ *     attr.set(a * integer));
+ *   }
+ * }
+ *
+ * // Different context objects are given to "f1", "f2", "f3", and "f4" even if
+ * // they refer to the same handler instance.  Because the FactorialHandler
+ * // stores its state in a context object (as an (using an {@link AttributeKey}), the factorial is
+ * // calculated correctly 4 times once the two pipelines (p1 and p2) are active.
+ * FactorialHandler fh = new FactorialHandler();
+ *
+ * {@link ChannelPipeline} p1 = {@link Channels}.pipeline();
+ * p1.addLast("f1", fh);
+ * p1.addLast("f2", fh);
+ *
+ * {@link ChannelPipeline} p2 = {@link Channels}.pipeline();
+ * p2.addLast("f3", fh);
+ * p2.addLast("f4", fh);
+ * 
+ * + *

Additional resources worth reading

+ *

+ * Please refer to the {@link ChannelHandler}, and + * {@link ChannelPipeline} to find out more about inbound and outbound operations, + * what fundamental differences they have, how they flow in a pipeline, and how to handle + * the operation in your application. + */ +public interface ChannelHandlerContext + extends AttributeMap { + + /** + * Return the {@link Channel} which is bound to the {@link ChannelHandlerContext}. + */ + Channel channel(); + + /** + * The {@link EventExecutor} that is used to dispatch the events. This can also be used to directly + * submit tasks that get executed in the event loop. For more information please refer to the + * {@link EventExecutor} javadoc. + */ + EventExecutor executor(); + + /** + * The unique name of the {@link ChannelHandlerContext}.The name was used when then {@link ChannelHandler} + * was added to the {@link ChannelPipeline}. This name can also be used to access the registered + * {@link ChannelHandler} from the {@link ChannelPipeline}. + */ + String name(); + + /** + * The {@link ChannelHandler} that is bound this {@link ChannelHandlerContext}. + */ + ChannelHandler handler(); + + /** + * Return {@code true} if the {@link ChannelHandler} which belongs to this {@link ChannelHandler} was removed + * from the {@link ChannelPipeline}. Note that this method is only meant to be called from with in the + * {@link EventLoop}. + */ + boolean isRemoved(); + + /** + * A {@link Channel} was registered to its {@link EventLoop}. + * + * This will result in having the {@link ChannelInboundHandler#channelRegistered(ChannelHandlerContext)} method + * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelHandlerContext fireChannelRegistered(); + + /** + * A {@link Channel} was unregistered from its {@link EventLoop}. + * + * This will result in having the {@link ChannelInboundHandler#channelUnregistered(ChannelHandlerContext)} method + * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelHandlerContext fireChannelUnregistered(); + + /** + * A {@link Channel} is active now, which means it is connected. + * + * This will result in having the {@link ChannelInboundHandler#channelActive(ChannelHandlerContext)} method + * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelHandlerContext fireChannelActive(); + + /** + * A {@link Channel} is inactive now, which means it is closed. + * + * This will result in having the {@link ChannelInboundHandler#channelInactive(ChannelHandlerContext)} method + * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelHandlerContext fireChannelInactive(); + + /** + * A {@link Channel} received an {@link Throwable} in one of its inbound operations. + * + * This will result in having the {@link ChannelInboundHandler#exceptionCaught(ChannelHandlerContext, Throwable)} + * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelHandlerContext fireExceptionCaught(Throwable cause); + + /** + * A {@link Channel} received an user defined event. + * + * This will result in having the {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)} + * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelHandlerContext fireUserEventTriggered(Object event); + + /** + * A {@link Channel} received a message. + * + * This will result in having the {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)} + * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelHandlerContext fireChannelRead(Object msg); + + /** + * Triggers an {@link ChannelInboundHandler#channelWritabilityChanged(ChannelHandlerContext)} + * event to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + */ + ChannelHandlerContext fireChannelReadComplete(); + + /** + * Triggers an {@link ChannelInboundHandler#channelWritabilityChanged(ChannelHandlerContext)} + * event to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + */ + ChannelHandlerContext fireChannelWritabilityChanged(); + + /** + * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method + * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture bind(SocketAddress localAddress); + + /** + * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + *

+ * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with + * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} + * will be used. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress); + + /** + * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the + * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of + * an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress); + + /** + * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, + * either because the operation was successful or because of an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture disconnect(); + + /** + * Request to close the {@link Channel} and notify the {@link ChannelFuture} once the operation completes, + * either because the operation was successful or because of + * an error. + * + * After it is closed it is not possible to reuse it again. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture close(); + + /** + * Request to deregister from the previous assigned {@link EventExecutor} and notify the + * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of + * an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + * + */ + ChannelFuture deregister(); + + /** + * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + * + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method + * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise); + + /** + * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + * + * The given {@link ChannelFuture} will be notified. + * + *

+ * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with + * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} + * will be used. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise); + + /** + * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the + * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of + * an error. + * + * The given {@link ChannelPromise} will be notified and also returned. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise); + + /** + * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, + * either because the operation was successful or because of an error. + * + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture disconnect(ChannelPromise promise); + + /** + * Request to close the {@link Channel} and notify the {@link ChannelFuture} once the operation completes, + * either because the operation was successful or because of + * an error. + * + * After it is closed it is not possible to reuse it again. + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture close(ChannelPromise promise); + + /** + * Request to deregister from the previous assigned {@link EventExecutor} and notify the + * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of + * an error. + * + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture deregister(ChannelPromise promise); + + /** + * Request to Read data from the {@link Channel} into the first inbound buffer, triggers an + * {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)} event if data was + * read, and triggers a + * {@link ChannelInboundHandler#channelReadComplete(ChannelHandlerContext) channelReadComplete} event so the + * handler can decide to continue reading. If there's a pending read operation already, this method does nothing. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#read(ChannelHandlerContext)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelHandlerContext read(); + + /** + * Request to write a message via this {@link ChannelHandlerContext} through the {@link ChannelPipeline}. + * This method will not request to actual flush, so be sure to call {@link #flush()} + * once you want to request to flush all pending data to the actual transport. + */ + ChannelFuture write(Object msg); + + /** + * Request to write a message via this {@link ChannelHandlerContext} through the {@link ChannelPipeline}. + * This method will not request to actual flush, so be sure to call {@link #flush()} + * once you want to request to flush all pending data to the actual transport. + */ + ChannelFuture write(Object msg, ChannelPromise promise); + + /** + * Request to flush all pending messages via this ChannelOutboundInvoker. + */ + ChannelHandlerContext flush(); + + /** + * Shortcut for call {@link #write(Object, ChannelPromise)} and {@link #flush()}. + */ + ChannelFuture writeAndFlush(Object msg, ChannelPromise promise); + + /** + * Shortcut for call {@link #write(Object)} and {@link #flush()}. + */ + ChannelFuture writeAndFlush(Object msg); + + /** + * Return the assigned {@link ChannelPipeline} + */ + ChannelPipeline pipeline(); + + /** + * Return the assigned {@link ByteBufAllocator} which will be used to allocate {@link ByteBuf}s. + */ + ByteBufAllocator alloc(); + + /** + * Return a new {@link ChannelPromise}. + */ + ChannelPromise newPromise(); + + /** + * Return an new {@link ChannelProgressivePromise} + */ +// ChannelProgressivePromise newProgressivePromise(); + + /** + * Create a new {@link ChannelFuture} which is marked as succeeded already. So {@link ChannelFuture#isSuccess()} + * will return {@code true}. All {@link FutureListener} added to it will be notified directly. Also + * every call of blocking methods will just return without blocking. + */ + ChannelFuture newSucceededFuture(); + + /** + * Create a new {@link ChannelFuture} which is marked as failed already. So {@link ChannelFuture#isSuccess()} + * will return {@code false}. All {@link FutureListener} added to it will be notified directly. Also + * every call of blocking methods will just return without blocking. + */ + ChannelFuture newFailedFuture(Throwable cause); + + /** + * Return a special ChannelPromise which can be reused for different operations. + *

+ * It's only supported to use + * it for {@link ChannelHandlerContext#write(Object, ChannelPromise)}. + *

+ *

+ * Be aware that the returned {@link ChannelPromise} will not support most operations and should only be used + * if you want to save an object allocation for every write operation. You will not be able to detect if the + * operation was complete, only if it failed as the implementation will call + * {@link ChannelPipeline#fireExceptionCaught(Throwable)} in this case. + *

+ * Be aware this is an expert feature and should be used with care! + */ + ChannelPromise voidPromise(); + +} diff --git a/common/src/main/java/common/net/channel/ChannelInboundHandler.java b/common/src/main/java/common/net/channel/ChannelInboundHandler.java new file mode 100644 index 0000000..97c9691 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelInboundHandler.java @@ -0,0 +1,74 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +/** + * {@link ChannelHandler} which adds callbacks for state changes. This allows the user + * to hook in to state changes easily. + */ +public interface ChannelInboundHandler extends ChannelHandler { + + /** + * The {@link Channel} of the {@link ChannelHandlerContext} was registered with its {@link EventLoop} + */ + void channelRegistered(ChannelHandlerContext ctx) throws Exception; + + /** + * The {@link Channel} of the {@link ChannelHandlerContext} was unregistered from its {@link EventLoop} + */ + void channelUnregistered(ChannelHandlerContext ctx) throws Exception; + + /** + * The {@link Channel} of the {@link ChannelHandlerContext} is now active + */ + void channelActive(ChannelHandlerContext ctx) throws Exception; + + /** + * The {@link Channel} of the {@link ChannelHandlerContext} was registered is now inactive and reached its + * end of lifetime. + */ + void channelInactive(ChannelHandlerContext ctx) throws Exception; + + /** + * Invoked when the current {@link Channel} has read a message from the peer. + */ + void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception; + + /** + * Invoked when the last message read by the current read operation has been consumed by + * {@link #channelRead(ChannelHandlerContext, Object)}. If {@link ChannelOption#AUTO_READ} is off, no further + * attempt to read an inbound data from the current {@link Channel} will be made until + * {@link ChannelHandlerContext#read()} is called. + */ + void channelReadComplete(ChannelHandlerContext ctx) throws Exception; + + /** + * Gets called if an user event was triggered. + */ + void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception; + + /** + * Gets called once the writable state of a {@link Channel} changed. You can check the state with + * {@link Channel#isWritable()}. + */ + void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception; + + /** + * Gets called if a {@link Throwable} was thrown. + */ + @Override + void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception; +} diff --git a/common/src/main/java/common/net/channel/ChannelInboundHandlerAdapter.java b/common/src/main/java/common/net/channel/ChannelInboundHandlerAdapter.java new file mode 100644 index 0000000..7f6e8a2 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelInboundHandlerAdapter.java @@ -0,0 +1,133 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +/** + * Abstract base class for {@link ChannelInboundHandler} implementations which provide + * implementations of all of their methods. + * + *

+ * This implementation just forward the operation to the next {@link ChannelHandler} in the + * {@link ChannelPipeline}. Sub-classes may override a method implementation to change this. + *

+ *

+ * Be aware that messages are not released after the {@link #channelRead(ChannelHandlerContext, Object)} + * method returns automatically. If you are looking for a {@link ChannelInboundHandler} implementation that + * releases the received messages automatically, please see {@link SimpleChannelInboundHandler}. + *

+ */ +public class ChannelInboundHandlerAdapter extends ChannelHandlerAdapter implements ChannelInboundHandler { + + /** + * Calls {@link ChannelHandlerContext#fireChannelRegistered()} to forward + * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void channelRegistered(ChannelHandlerContext ctx) throws Exception { + ctx.fireChannelRegistered(); + } + + /** + * Calls {@link ChannelHandlerContext#fireChannelUnregistered()} to forward + * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { + ctx.fireChannelUnregistered(); + } + + /** + * Calls {@link ChannelHandlerContext#fireChannelActive()} to forward + * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + ctx.fireChannelActive(); + } + + /** + * Calls {@link ChannelHandlerContext#fireChannelInactive()} to forward + * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + ctx.fireChannelInactive(); + } + + /** + * Calls {@link ChannelHandlerContext#fireChannelRead(Object)} to forward + * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + ctx.fireChannelRead(msg); + } + + /** + * Calls {@link ChannelHandlerContext#fireChannelReadComplete()} to forward + * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + ctx.fireChannelReadComplete(); + } + + /** + * Calls {@link ChannelHandlerContext#fireUserEventTriggered(Object)} to forward + * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { + ctx.fireUserEventTriggered(evt); + } + + /** + * Calls {@link ChannelHandlerContext#fireChannelWritabilityChanged()} to forward + * to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { + ctx.fireChannelWritabilityChanged(); + } + + /** + * Calls {@link ChannelHandlerContext#fireExceptionCaught(Throwable)} to forward + * to the next {@link ChannelHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) + throws Exception { + ctx.fireExceptionCaught(cause); + } +} diff --git a/common/src/main/java/common/net/channel/ChannelInitializer.java b/common/src/main/java/common/net/channel/ChannelInitializer.java new file mode 100644 index 0000000..31ad3ab --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelInitializer.java @@ -0,0 +1,82 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.channel.ChannelHandler.Sharable; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * A special {@link ChannelInboundHandler} which offers an easy way to initialize a {@link Channel} once it was + * registered to its {@link EventLoop}. + * + * Implementations are most often used in the context of {@link Bootstrap#handler(ChannelHandler)} , + * {@link ServerBootstrap#handler(ChannelHandler)} and {@link ServerBootstrap#childHandler(ChannelHandler)} to + * setup the {@link ChannelPipeline} of a {@link Channel}. + * + *
+ *
+ * public class MyChannelInitializer extends {@link ChannelInitializer} {
+ *     public void initChannel({@link Channel} channel) {
+ *         channel.pipeline().addLast("myHandler", new MyHandler());
+ *     }
+ * }
+ *
+ * {@link ServerBootstrap} bootstrap = ...;
+ * ...
+ * bootstrap.childHandler(new MyChannelInitializer());
+ * ...
+ * 
+ * Be aware that this class is marked as {@link Sharable} and so the implementation must be safe to be re-used. + * + * @param A sub-type of {@link Channel} + */ +@Sharable +public abstract class ChannelInitializer extends ChannelInboundHandlerAdapter { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(ChannelInitializer.class); + + /** + * This method will be called once the {@link Channel} was registered. After the method returns this instance + * will be removed from the {@link ChannelPipeline} of the {@link Channel}. + * + * @param ch the {@link Channel} which was registered. + * @throws Exception is thrown if an error occurs. In that case the {@link Channel} will be closed. + */ + protected abstract void initChannel(C ch) throws Exception; + + @Override + + public final void channelRegistered(ChannelHandlerContext ctx) throws Exception { + ChannelPipeline pipeline = ctx.pipeline(); + boolean success = false; + try { + initChannel((C) ctx.channel()); + pipeline.remove(this); + ctx.fireChannelRegistered(); + success = true; + } catch (Throwable t) { + logger.warn("Failed to initialize a channel. Closing: " + ctx.channel(), t); + } finally { + if (pipeline.context(this) != null) { + pipeline.remove(this); + } + if (!success) { + ctx.close(); + } + } + } +} diff --git a/common/src/main/java/common/net/channel/ChannelMetadata.java b/common/src/main/java/common/net/channel/ChannelMetadata.java new file mode 100644 index 0000000..375acb9 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelMetadata.java @@ -0,0 +1,44 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +/** + * Represents the properties of a {@link Channel} implementation. + */ +public final class ChannelMetadata { + + private final boolean hasDisconnect; + + /** + * Create a new instance + * + * @param hasDisconnect {@code true} if and only if the channel has the {@code disconnect()} operation + * that allows a user to disconnect and then call {@link Channel#connect(SocketAddress)} + * again, such as UDP/IP. + */ + public ChannelMetadata(boolean hasDisconnect) { + this.hasDisconnect = hasDisconnect; + } + + /** + * Returns {@code true} if and only if the channel has the {@code disconnect()} operation + * that allows a user to disconnect and then call {@link Channel#connect(SocketAddress)} again, + * such as UDP/IP. + */ + public boolean hasDisconnect() { + return hasDisconnect; + } +} diff --git a/common/src/main/java/common/net/channel/ChannelOption.java b/common/src/main/java/common/net/channel/ChannelOption.java new file mode 100644 index 0000000..629d2fe --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelOption.java @@ -0,0 +1,89 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import common.net.buffer.ByteBufAllocator; +import common.net.util.UniqueName; + +/** + * A {@link ChannelOption} allows to configure a {@link ChannelConfig} in a type-safe + * way. Which {@link ChannelOption} is supported depends on the actual implementation + * of {@link ChannelConfig} and may depend on the nature of the transport it belongs + * to. + * + * @param the type of the value which is valid for the {@link ChannelOption} + */ + +public class ChannelOption extends UniqueName { + + private static final ConcurrentMap names = new ConcurrentHashMap(); + + public static final ChannelOption ALLOCATOR = valueOf("ALLOCATOR"); + public static final ChannelOption RCVBUF_ALLOCATOR = valueOf("RCVBUF_ALLOCATOR"); + public static final ChannelOption MESSAGE_SIZE_ESTIMATOR = valueOf("MESSAGE_SIZE_ESTIMATOR"); + + public static final ChannelOption CONNECT_TIMEOUT_MILLIS = valueOf("CONNECT_TIMEOUT_MILLIS"); + public static final ChannelOption MAX_MESSAGES_PER_READ = valueOf("MAX_MESSAGES_PER_READ"); + public static final ChannelOption WRITE_SPIN_COUNT = valueOf("WRITE_SPIN_COUNT"); + public static final ChannelOption WRITE_BUFFER_HIGH_WATER_MARK = valueOf("WRITE_BUFFER_HIGH_WATER_MARK"); + public static final ChannelOption WRITE_BUFFER_LOW_WATER_MARK = valueOf("WRITE_BUFFER_LOW_WATER_MARK"); + + public static final ChannelOption ALLOW_HALF_CLOSURE = valueOf("ALLOW_HALF_CLOSURE"); + public static final ChannelOption AUTO_READ = valueOf("AUTO_READ"); + + public static final ChannelOption SO_BROADCAST = valueOf("SO_BROADCAST"); + public static final ChannelOption SO_KEEPALIVE = valueOf("SO_KEEPALIVE"); + public static final ChannelOption SO_SNDBUF = valueOf("SO_SNDBUF"); + public static final ChannelOption SO_RCVBUF = valueOf("SO_RCVBUF"); + public static final ChannelOption SO_REUSEADDR = valueOf("SO_REUSEADDR"); + public static final ChannelOption SO_LINGER = valueOf("SO_LINGER"); + public static final ChannelOption SO_BACKLOG = valueOf("SO_BACKLOG"); + public static final ChannelOption SO_TIMEOUT = valueOf("SO_TIMEOUT"); + + public static final ChannelOption IP_TOS = valueOf("IP_TOS"); + public static final ChannelOption IP_MULTICAST_ADDR = valueOf("IP_MULTICAST_ADDR"); + public static final ChannelOption IP_MULTICAST_IF = valueOf("IP_MULTICAST_IF"); + public static final ChannelOption IP_MULTICAST_TTL = valueOf("IP_MULTICAST_TTL"); + public static final ChannelOption IP_MULTICAST_LOOP_DISABLED = valueOf("IP_MULTICAST_LOOP_DISABLED"); + + public static final ChannelOption TCP_NODELAY = valueOf("TCP_NODELAY"); + + /** + * Creates a new {@link ChannelOption} with the specified {@code name}. + */ + public static ChannelOption valueOf(String name) { + return new ChannelOption(name); + } + + private ChannelOption(String name) { + super(names, name); + } + + /** + * Validate the value which is set for the {@link ChannelOption}. Sub-classes + * may override this for special checks. + */ + public void validate(T value) { + if (value == null) { + throw new NullPointerException("value"); + } + } +} diff --git a/common/src/main/java/common/net/channel/ChannelOutboundBuffer.java b/common/src/main/java/common/net/channel/ChannelOutboundBuffer.java new file mode 100644 index 0000000..e362114 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelOutboundBuffer.java @@ -0,0 +1,644 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.nio.ByteBuffer; +import java.nio.channels.ClosedChannelException; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicLongFieldUpdater; + +import common.net.buffer.ByteBuf; +import common.net.buffer.Unpooled; +import common.net.util.Recycler; +import common.net.util.ReferenceCountUtil; +import common.net.util.Recycler.Handle; +import common.net.util.concurrent.FastThreadLocal; +import common.net.util.internal.InternalThreadLocalMap; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * (Transport implementors only) an internal data structure used by {@link AbstractChannel} to store its pending + * outbound write requests. + * + * All the methods should only be called by the {@link EventLoop} of the {@link Channel}. + */ +public final class ChannelOutboundBuffer { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(ChannelOutboundBuffer.class); + + private static final FastThreadLocal NIO_BUFFERS = new FastThreadLocal() { + @Override + protected ByteBuffer[] initialValue() throws Exception { + return new ByteBuffer[1024]; + } + }; + + private final Channel channel; + + // Entry(flushedEntry) --> ... Entry(unflushedEntry) --> ... Entry(tailEntry) + // + // The Entry that is the first in the linked-list structure that was flushed + private Entry flushedEntry; + // The Entry which is the first unflushed in the linked-list structure + private Entry unflushedEntry; + // The Entry which represents the tail of the buffer + private Entry tailEntry; + // The number of flushed entries that are not written yet + private int flushed; + + private int nioBufferCount; + private long nioBufferSize; + + private boolean inFail; + + private static final AtomicLongFieldUpdater TOTAL_PENDING_SIZE_UPDATER; + + + private volatile long totalPendingSize; + + private static final AtomicIntegerFieldUpdater WRITABLE_UPDATER; + + + private volatile int writable = 1; + + static { + AtomicIntegerFieldUpdater writableUpdater = + null; + if (writableUpdater == null) { + writableUpdater = AtomicIntegerFieldUpdater.newUpdater(ChannelOutboundBuffer.class, "writable"); + } + WRITABLE_UPDATER = writableUpdater; + + AtomicLongFieldUpdater pendingSizeUpdater = + null; + if (pendingSizeUpdater == null) { + pendingSizeUpdater = AtomicLongFieldUpdater.newUpdater(ChannelOutboundBuffer.class, "totalPendingSize"); + } + TOTAL_PENDING_SIZE_UPDATER = pendingSizeUpdater; + } + + ChannelOutboundBuffer(AbstractChannel channel) { + this.channel = channel; + } + + /** + * Add given message to this {@link ChannelOutboundBuffer}. The given {@link ChannelPromise} will be notified once + * the message was written. + */ + public void addMessage(Object msg, int size, ChannelPromise promise) { + Entry entry = Entry.newInstance(msg, size, total(msg), promise); + if (tailEntry == null) { + flushedEntry = null; + tailEntry = entry; + } else { + Entry tail = tailEntry; + tail.next = entry; + tailEntry = entry; + } + if (unflushedEntry == null) { + unflushedEntry = entry; + } + + // increment pending bytes after adding message to the unflushed arrays. + // See https://github.com/netty/netty/issues/1619 + incrementPendingOutboundBytes(size); + } + + /** + * Add a flush to this {@link ChannelOutboundBuffer}. This means all previous added messages are marked as flushed + * and so you will be able to handle them. + */ + public void addFlush() { + // There is no need to process all entries if there was already a flush before and no new messages + // where added in the meantime. + // + // See https://github.com/netty/netty/issues/2577 + Entry entry = unflushedEntry; + if (entry != null) { + if (flushedEntry == null) { + // there is no flushedEntry yet, so start with the entry + flushedEntry = entry; + } + do { + flushed ++; + if (!entry.promise.setUncancellable()) { + // Was cancelled so make sure we free up memory and notify about the freed bytes + int pending = entry.cancel(); + decrementPendingOutboundBytes(pending); + } + entry = entry.next; + } while (entry != null); + + // All flushed so reset unflushedEntry + unflushedEntry = null; + } + } + + /** + * Increment the pending bytes which will be written at some point. + * This method is thread-safe! + */ + void incrementPendingOutboundBytes(long size) { + if (size == 0) { + return; + } + + long newWriteBufferSize = TOTAL_PENDING_SIZE_UPDATER.addAndGet(this, size); + if (newWriteBufferSize > channel.config().getWriteBufferHighWaterMark()) { + if (WRITABLE_UPDATER.compareAndSet(this, 1, 0)) { + channel.pipeline().fireChannelWritabilityChanged(); + } + } + } + + /** + * Decrement the pending bytes which will be written at some point. + * This method is thread-safe! + */ + void decrementPendingOutboundBytes(long size) { + if (size == 0) { + return; + } + + long newWriteBufferSize = TOTAL_PENDING_SIZE_UPDATER.addAndGet(this, -size); + if (newWriteBufferSize == 0 || newWriteBufferSize < channel.config().getWriteBufferLowWaterMark()) { + if (WRITABLE_UPDATER.compareAndSet(this, 0, 1)) { + channel.pipeline().fireChannelWritabilityChanged(); + } + } + } + + private static long total(Object msg) { + if (msg instanceof ByteBuf) { + return ((ByteBuf) msg).readableBytes(); + } +// if (msg instanceof FileRegion) { +// return ((FileRegion) msg).count(); +// } +// if (msg instanceof ByteBufHolder) { +// return ((ByteBufHolder) msg).content().readableBytes(); +// } + return -1; + } + + /** + * Return the current message to write or {@code null} if nothing was flushed before and so is ready to be written. + */ + public Object current() { + Entry entry = flushedEntry; + if (entry == null) { + return null; + } + + return entry.msg; + } + + /** + * Notify the {@link ChannelPromise} of the current message about writing progress. + */ + public void progress(long amount) { + Entry e = flushedEntry; + assert e != null; + ChannelPromise p = e.promise; + if (p instanceof ChannelProgressivePromise) { + long progress = e.progress + amount; + e.progress = progress; + ((ChannelProgressivePromise) p).tryProgress(progress, e.total); + } + } + + /** + * Will remove the current message, mark its {@link ChannelPromise} as success and return {@code true}. If no + * flushed message exists at the time this method is called it will return {@code false} to signal that no more + * messages are ready to be handled. + */ + public boolean remove() { + Entry e = flushedEntry; + if (e == null) { + return false; + } + Object msg = e.msg; + + ChannelPromise promise = e.promise; + int size = e.pendingSize; + + removeEntry(e); + + if (!e.cancelled) { + // only release message, notify and decrement if it was not canceled before. + ReferenceCountUtil.safeRelease(msg); + safeSuccess(promise); + decrementPendingOutboundBytes(size); + } + + // recycle the entry + e.recycle(); + + return true; + } + + /** + * Will remove the current message, mark its {@link ChannelPromise} as failure using the given {@link Throwable} + * and return {@code true}. If no flushed message exists at the time this method is called it will return + * {@code false} to signal that no more messages are ready to be handled. + */ + public boolean remove(Throwable cause) { + Entry e = flushedEntry; + if (e == null) { + return false; + } + Object msg = e.msg; + + ChannelPromise promise = e.promise; + int size = e.pendingSize; + + removeEntry(e); + + if (!e.cancelled) { + // only release message, fail and decrement if it was not canceled before. + ReferenceCountUtil.safeRelease(msg); + + safeFail(promise, cause); + decrementPendingOutboundBytes(size); + } + + // recycle the entry + e.recycle(); + + return true; + } + + private void removeEntry(Entry e) { + if (-- flushed == 0) { + // processed everything + flushedEntry = null; + if (e == tailEntry) { + tailEntry = null; + unflushedEntry = null; + } + } else { + flushedEntry = e.next; + } + } + + /** + * Removes the fully written entries and update the reader index of the partially written entry. + * This operation assumes all messages in this buffer is {@link ByteBuf}. + */ + public void removeBytes(long writtenBytes) { + for (;;) { + Object msg = current(); + if (!(msg instanceof ByteBuf)) { + assert writtenBytes == 0; + break; + } + + final ByteBuf buf = (ByteBuf) msg; + final int readerIndex = buf.readerIndex(); + final int readableBytes = buf.writerIndex() - readerIndex; + + if (readableBytes <= writtenBytes) { + if (writtenBytes != 0) { + progress(readableBytes); + writtenBytes -= readableBytes; + } + remove(); + } else { // readableBytes > writtenBytes + if (writtenBytes != 0) { + buf.readerIndex(readerIndex + (int) writtenBytes); + progress(writtenBytes); + } + break; + } + } + } + + /** + * Returns an array of direct NIO buffers if the currently pending messages are made of {@link ByteBuf} only. + * {@link #nioBufferCount()} and {@link #nioBufferSize()} will return the number of NIO buffers in the returned + * array and the total number of readable bytes of the NIO buffers respectively. + *

+ * Note that the returned array is reused and thus should not escape + * {@link AbstractChannel#doWrite(ChannelOutboundBuffer)}. + * Refer to {@link NioSocketChannel#doWrite(ChannelOutboundBuffer)} for an example. + *

+ */ + public ByteBuffer[] nioBuffers() { + long nioBufferSize = 0; + int nioBufferCount = 0; + final InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.get(); + ByteBuffer[] nioBuffers = NIO_BUFFERS.get(threadLocalMap); + Entry entry = flushedEntry; + while (isFlushedEntry(entry) && entry.msg instanceof ByteBuf) { + if (!entry.cancelled) { + ByteBuf buf = (ByteBuf) entry.msg; + final int readerIndex = buf.readerIndex(); + final int readableBytes = buf.writerIndex() - readerIndex; + + if (readableBytes > 0) { + nioBufferSize += readableBytes; + int count = entry.count; + if (count == -1) { + //noinspection ConstantValueVariableUse + entry.count = count = buf.nioBufferCount(); + } + int neededSpace = nioBufferCount + count; + if (neededSpace > nioBuffers.length) { + nioBuffers = expandNioBufferArray(nioBuffers, neededSpace, nioBufferCount); + NIO_BUFFERS.set(threadLocalMap, nioBuffers); + } + if (count == 1) { + ByteBuffer nioBuf = entry.buf; + if (nioBuf == null) { + // cache ByteBuffer as it may need to create a new ByteBuffer instance if its a + // derived buffer + entry.buf = nioBuf = buf.internalNioBuffer(readerIndex, readableBytes); + } + nioBuffers[nioBufferCount ++] = nioBuf; + } else { + ByteBuffer[] nioBufs = entry.bufs; + if (nioBufs == null) { + // cached ByteBuffers as they may be expensive to create in terms + // of Object allocation + entry.bufs = nioBufs = buf.nioBuffers(); + } + nioBufferCount = fillBufferArray(nioBufs, nioBuffers, nioBufferCount); + } + } + } + entry = entry.next; + } + this.nioBufferCount = nioBufferCount; + this.nioBufferSize = nioBufferSize; + + return nioBuffers; + } + + private static int fillBufferArray(ByteBuffer[] nioBufs, ByteBuffer[] nioBuffers, int nioBufferCount) { + for (ByteBuffer nioBuf: nioBufs) { + if (nioBuf == null) { + break; + } + nioBuffers[nioBufferCount ++] = nioBuf; + } + return nioBufferCount; + } + + private static ByteBuffer[] expandNioBufferArray(ByteBuffer[] array, int neededSpace, int size) { + int newCapacity = array.length; + do { + // double capacity until it is big enough + // See https://github.com/netty/netty/issues/1890 + newCapacity <<= 1; + + if (newCapacity < 0) { + throw new IllegalStateException(); + } + + } while (neededSpace > newCapacity); + + ByteBuffer[] newArray = new ByteBuffer[newCapacity]; + System.arraycopy(array, 0, newArray, 0, size); + + return newArray; + } + + /** + * Returns the number of {@link ByteBuffer} that can be written out of the {@link ByteBuffer} array that was + * obtained via {@link #nioBuffers()}. This method MUST be called after {@link #nioBuffers()} + * was called. + */ + public int nioBufferCount() { + return nioBufferCount; + } + + /** + * Returns the number of bytes that can be written out of the {@link ByteBuffer} array that was + * obtained via {@link #nioBuffers()}. This method MUST be called after {@link #nioBuffers()} + * was called. + */ + public long nioBufferSize() { + return nioBufferSize; + } + + boolean isWritable() { + return writable != 0; + } + + /** + * Returns the number of flushed messages in this {@link ChannelOutboundBuffer}. + */ + public int size() { + return flushed; + } + + /** + * Returns {@code true} if there are flushed messages in this {@link ChannelOutboundBuffer} or {@code false} + * otherwise. + */ + public boolean isEmpty() { + return flushed == 0; + } + + void failFlushed(Throwable cause) { + // Make sure that this method does not reenter. A listener added to the current promise can be notified by the + // current thread in the tryFailure() call of the loop below, and the listener can trigger another fail() call + // indirectly (usually by closing the channel.) + // + // See https://github.com/netty/netty/issues/1501 + if (inFail) { + return; + } + + try { + inFail = true; + for (;;) { + if (!remove(cause)) { + break; + } + } + } finally { + inFail = false; + } + } + + void close(final ClosedChannelException cause) { + if (inFail) { + channel.eventLoop().execute(new Runnable() { + @Override + public void run() { + close(cause); + } + }); + return; + } + + inFail = true; + + if (channel.isOpen()) { + throw new IllegalStateException("close() must be invoked after the channel is closed."); + } + + if (!isEmpty()) { + throw new IllegalStateException("close() must be invoked after all flushed writes are handled."); + } + + // Release all unflushed messages. + try { + Entry e = unflushedEntry; + while (e != null) { + // Just decrease; do not trigger any events via decrementPendingOutboundBytes() + int size = e.pendingSize; + TOTAL_PENDING_SIZE_UPDATER.addAndGet(this, -size); + + if (!e.cancelled) { + ReferenceCountUtil.safeRelease(e.msg); + safeFail(e.promise, cause); + } + e = e.recycleAndGetNext(); + } + } finally { + inFail = false; + } + } + + private static void safeSuccess(ChannelPromise promise) { + if (!(promise instanceof VoidChannelPromise) && !promise.trySuccess()) { + logger.warn("Failed to mark a promise as success because it is done already: {}", promise); + } + } + + private static void safeFail(ChannelPromise promise, Throwable cause) { + if (!(promise instanceof VoidChannelPromise) && !promise.tryFailure(cause)) { + logger.warn("Failed to mark a promise as failure because it's done already: {}", promise, cause); + } + } + + public long totalPendingWriteBytes() { + return totalPendingSize; + } + + /** + * Call {@link MessageProcessor#processMessage(Object)} for each flushed message + * in this {@link ChannelOutboundBuffer} until {@link MessageProcessor#processMessage(Object)} + * returns {@code false} or there are no more flushed messages to process. + */ + public void forEachFlushedMessage(MessageProcessor processor) throws Exception { + if (processor == null) { + throw new NullPointerException("processor"); + } + + Entry entry = flushedEntry; + if (entry == null) { + return; + } + + do { + if (!entry.cancelled) { + if (!processor.processMessage(entry.msg)) { + return; + } + } + entry = entry.next; + } while (isFlushedEntry(entry)); + } + + private boolean isFlushedEntry(Entry e) { + return e != null && e != unflushedEntry; + } + + public interface MessageProcessor { + /** + * Will be called for each flushed message until it either there are no more flushed messages or this + * method returns {@code false}. + */ + boolean processMessage(Object msg) throws Exception; + } + + static final class Entry { + private static final Recycler RECYCLER = new Recycler() { + @Override + protected Entry newObject(Handle handle) { + return new Entry(handle); + } + }; + + private final Handle handle; + Entry next; + Object msg; + ByteBuffer[] bufs; + ByteBuffer buf; + ChannelPromise promise; + long progress; + long total; + int pendingSize; + int count = -1; + boolean cancelled; + + private Entry(Handle handle) { + this.handle = handle; + } + + static Entry newInstance(Object msg, int size, long total, ChannelPromise promise) { + Entry entry = RECYCLER.get(); + entry.msg = msg; + entry.pendingSize = size; + entry.total = total; + entry.promise = promise; + return entry; + } + + int cancel() { + if (!cancelled) { + cancelled = true; + int pSize = pendingSize; + + // release message and replace with an empty buffer + ReferenceCountUtil.safeRelease(msg); + msg = Unpooled.EMPTY_BUFFER; + + pendingSize = 0; + total = 0; + progress = 0; + bufs = null; + buf = null; + return pSize; + } + return 0; + } + + void recycle() { + next = null; + bufs = null; + buf = null; + msg = null; + promise = null; + progress = 0; + total = 0; + pendingSize = 0; + count = -1; + cancelled = false; + RECYCLER.recycle(this, handle); + } + + Entry recycleAndGetNext() { + Entry next = this.next; + recycle(); + return next; + } + } +} diff --git a/common/src/main/java/common/net/channel/ChannelOutboundHandler.java b/common/src/main/java/common/net/channel/ChannelOutboundHandler.java new file mode 100644 index 0000000..9cce0d7 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelOutboundHandler.java @@ -0,0 +1,99 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.net.SocketAddress; + +/** + * {@link ChannelHandler} which will get notified for IO-outbound-operations. + */ +public interface ChannelOutboundHandler extends ChannelHandler { + /** + * Called once a bind operation is made. + * + * @param ctx the {@link ChannelHandlerContext} for which the bind operation is made + * @param localAddress the {@link SocketAddress} to which it should bound + * @param promise the {@link ChannelPromise} to notify once the operation completes + * @throws Exception thrown if an error accour + */ + void bind(ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) throws Exception; + + /** + * Called once a connect operation is made. + * + * @param ctx the {@link ChannelHandlerContext} for which the connect operation is made + * @param remoteAddress the {@link SocketAddress} to which it should connect + * @param localAddress the {@link SocketAddress} which is used as source on connect + * @param promise the {@link ChannelPromise} to notify once the operation completes + * @throws Exception thrown if an error accour + */ + void connect( + ChannelHandlerContext ctx, SocketAddress remoteAddress, + SocketAddress localAddress, ChannelPromise promise) throws Exception; + + /** + * Called once a disconnect operation is made. + * + * @param ctx the {@link ChannelHandlerContext} for which the disconnect operation is made + * @param promise the {@link ChannelPromise} to notify once the operation completes + * @throws Exception thrown if an error accour + */ + void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception; + + /** + * Called once a close operation is made. + * + * @param ctx the {@link ChannelHandlerContext} for which the close operation is made + * @param promise the {@link ChannelPromise} to notify once the operation completes + * @throws Exception thrown if an error accour + */ + void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception; + + /** + * Called once a deregister operation is made from the current registered {@link EventLoop}. + * + * @param ctx the {@link ChannelHandlerContext} for which the close operation is made + * @param promise the {@link ChannelPromise} to notify once the operation completes + * @throws Exception thrown if an error accour + */ + void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception; + + /** + * Intercepts {@link ChannelHandlerContext#read()}. + */ + void read(ChannelHandlerContext ctx) throws Exception; + + /** + * Called once a write operation is made. The write operation will write the messages through the + * {@link ChannelPipeline}. Those are then ready to be flushed to the actual {@link Channel} once + * {@link Channel#flush()} is called + * + * @param ctx the {@link ChannelHandlerContext} for which the write operation is made + * @param msg the message to write + * @param promise the {@link ChannelPromise} to notify once the operation completes + * @throws Exception thrown if an error accour + */ + void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception; + + /** + * Called once a flush operation is made. The flush operation will try to flush out all previous written messages + * that are pending. + * + * @param ctx the {@link ChannelHandlerContext} for which the flush operation is made + * @throws Exception thrown if an error accour + */ + void flush(ChannelHandlerContext ctx) throws Exception; +} diff --git a/common/src/main/java/common/net/channel/ChannelOutboundHandlerAdapter.java b/common/src/main/java/common/net/channel/ChannelOutboundHandlerAdapter.java new file mode 100644 index 0000000..0ce2ac8 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelOutboundHandlerAdapter.java @@ -0,0 +1,117 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.net.SocketAddress; + +/** + * Skelton implementation of a {@link ChannelOutboundHandler}. This implementation just forwards each method call via + * the {@link ChannelHandlerContext}. + */ +public class ChannelOutboundHandlerAdapter extends ChannelHandlerAdapter implements ChannelOutboundHandler { + + /** + * Calls {@link ChannelHandlerContext#bind(SocketAddress, ChannelPromise)} to forward + * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void bind(ChannelHandlerContext ctx, SocketAddress localAddress, + ChannelPromise promise) throws Exception { + ctx.bind(localAddress, promise); + } + + /** + * Calls {@link ChannelHandlerContext#connect(SocketAddress, SocketAddress, ChannelPromise)} to forward + * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void connect(ChannelHandlerContext ctx, SocketAddress remoteAddress, + SocketAddress localAddress, ChannelPromise promise) throws Exception { + ctx.connect(remoteAddress, localAddress, promise); + } + + /** + * Calls {@link ChannelHandlerContext#disconnect(ChannelPromise)} to forward + * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) + throws Exception { + ctx.disconnect(promise); + } + + /** + * Calls {@link ChannelHandlerContext#close(ChannelPromise)} to forward + * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void close(ChannelHandlerContext ctx, ChannelPromise promise) + throws Exception { + ctx.close(promise); + } + + /** + * Calls {@link ChannelHandlerContext#close(ChannelPromise)} to forward + * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { + ctx.deregister(promise); + } + + /** + * Calls {@link ChannelHandlerContext#read()} to forward + * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void read(ChannelHandlerContext ctx) throws Exception { + ctx.read(); + } + + /** + * Calls {@link ChannelHandlerContext#write(Object)} to forward + * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + ctx.write(msg, promise); + } + + /** + * Calls {@link ChannelHandlerContext#flush()} to forward + * to the next {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. + * + * Sub-classes may override this method to change behavior. + */ + @Override + public void flush(ChannelHandlerContext ctx) throws Exception { + ctx.flush(); + } +} diff --git a/common/src/main/java/common/net/channel/ChannelPipeline.java b/common/src/main/java/common/net/channel/ChannelPipeline.java new file mode 100644 index 0000000..ed5ac6f --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelPipeline.java @@ -0,0 +1,872 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.net.SocketAddress; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import common.net.util.concurrent.EventExecutorGroup; + + +/** + * A list of {@link ChannelHandler}s which handles or intercepts inbound events and outbound operations of a + * {@link Channel}. {@link ChannelPipeline} implements an advanced form of the + * Intercepting Filter pattern + * to give a user full control over how an event is handled and how the {@link ChannelHandler}s in a pipeline + * interact with each other. + * + *

Creation of a pipeline

+ * + * Each channel has its own pipeline and it is created automatically when a new channel is created. + * + *

How an event flows in a pipeline

+ * + * The following diagram describes how I/O events are processed by {@link ChannelHandler}s in a {@link ChannelPipeline} + * typically. An I/O event is handled by either a {@link ChannelInboundHandler} or a {@link ChannelOutboundHandler} + * and be forwarded to its closest handler by calling the event propagation methods defined in + * {@link ChannelHandlerContext}, such as {@link ChannelHandlerContext#fireChannelRead(Object)} and + * {@link ChannelHandlerContext#write(Object)}. + * + *
+ *                                                 I/O Request
+ *                                            via {@link Channel} or
+ *                                        {@link ChannelHandlerContext}
+ *                                                      |
+ *  +---------------------------------------------------+---------------+
+ *  |                           ChannelPipeline         |               |
+ *  |                                                  \|/              |
+ *  |    +---------------------+            +-----------+----------+    |
+ *  |    | Inbound Handler  N  |            | Outbound Handler  1  |    |
+ *  |    +----------+----------+            +-----------+----------+    |
+ *  |              /|\                                  |               |
+ *  |               |                                  \|/              |
+ *  |    +----------+----------+            +-----------+----------+    |
+ *  |    | Inbound Handler N-1 |            | Outbound Handler  2  |    |
+ *  |    +----------+----------+            +-----------+----------+    |
+ *  |              /|\                                  .               |
+ *  |               .                                   .               |
+ *  | ChannelHandlerContext.fireIN_EVT() ChannelHandlerContext.OUT_EVT()|
+ *  |        [ method call]                       [method call]         |
+ *  |               .                                   .               |
+ *  |               .                                  \|/              |
+ *  |    +----------+----------+            +-----------+----------+    |
+ *  |    | Inbound Handler  2  |            | Outbound Handler M-1 |    |
+ *  |    +----------+----------+            +-----------+----------+    |
+ *  |              /|\                                  |               |
+ *  |               |                                  \|/              |
+ *  |    +----------+----------+            +-----------+----------+    |
+ *  |    | Inbound Handler  1  |            | Outbound Handler  M  |    |
+ *  |    +----------+----------+            +-----------+----------+    |
+ *  |              /|\                                  |               |
+ *  +---------------+-----------------------------------+---------------+
+ *                  |                                  \|/
+ *  +---------------+-----------------------------------+---------------+
+ *  |               |                                   |               |
+ *  |       [ Socket.read() ]                    [ Socket.write() ]     |
+ *  |                                                                   |
+ *  |  Netty Internal I/O Threads (Transport Implementation)            |
+ *  +-------------------------------------------------------------------+
+ * 
+ * An inbound event is handled by the inbound handlers in the bottom-up direction as shown on the left side of the + * diagram. An inbound handler usually handles the inbound data generated by the I/O thread on the bottom of the + * diagram. The inbound data is often read from a remote peer via the actual input operation such as + * {@link SocketChannel#read(ByteBuffer)}. If an inbound event goes beyond the top inbound handler, it is discarded + * silently, or logged if it needs your attention. + *

+ * An outbound event is handled by the outbound handler in the top-down direction as shown on the right side of the + * diagram. An outbound handler usually generates or transforms the outbound traffic such as write requests. + * If an outbound event goes beyond the bottom outbound handler, it is handled by an I/O thread associated with the + * {@link Channel}. The I/O thread often performs the actual output operation such as + * {@link SocketChannel#write(ByteBuffer)}. + *

+ * For example, let us assume that we created the following pipeline: + *

+ * {@link ChannelPipeline} p = ...;
+ * p.addLast("1", new InboundHandlerA());
+ * p.addLast("2", new InboundHandlerB());
+ * p.addLast("3", new OutboundHandlerA());
+ * p.addLast("4", new OutboundHandlerB());
+ * p.addLast("5", new InboundOutboundHandlerX());
+ * 
+ * In the example above, the class whose name starts with {@code Inbound} means it is an inbound handler. + * The class whose name starts with {@code Outbound} means it is a outbound handler. + *

+ * In the given example configuration, the handler evaluation order is 1, 2, 3, 4, 5 when an event goes inbound. + * When an event goes outbound, the order is 5, 4, 3, 2, 1. On top of this principle, {@link ChannelPipeline} skips + * the evaluation of certain handlers to shorten the stack depth: + *

    + *
  • 3 and 4 don't implement {@link ChannelInboundHandler}, and therefore the actual evaluation order of an inbound + * event will be: 1, 2, and 5.
  • + *
  • 1 and 2 don't implement {@link ChannelOutboundHandler}, and therefore the actual evaluation order of a + * outbound event will be: 5, 4, and 3.
  • + *
  • If 5 implements both {@link ChannelInboundHandler} and {@link ChannelOutboundHandler}, the evaluation order of + * an inbound and a outbound event could be 125 and 543 respectively.
  • + *
+ * + *

Forwarding an event to the next handler

+ * + * As you might noticed in the diagram shows, a handler has to invoke the event propagation methods in + * {@link ChannelHandlerContext} to forward an event to its next handler. Those methods include: + *
    + *
  • Inbound event propagation methods: + *
      + *
    • {@link ChannelHandlerContext#fireChannelRegistered()}
    • + *
    • {@link ChannelHandlerContext#fireChannelActive()}
    • + *
    • {@link ChannelHandlerContext#fireChannelRead(Object)}
    • + *
    • {@link ChannelHandlerContext#fireChannelReadComplete()}
    • + *
    • {@link ChannelHandlerContext#fireExceptionCaught(Throwable)}
    • + *
    • {@link ChannelHandlerContext#fireUserEventTriggered(Object)}
    • + *
    • {@link ChannelHandlerContext#fireChannelWritabilityChanged()}
    • + *
    • {@link ChannelHandlerContext#fireChannelInactive()}
    • + *
    • {@link ChannelHandlerContext#fireChannelUnregistered()}
    • + *
    + *
  • + *
  • Outbound event propagation methods: + *
      + *
    • {@link ChannelHandlerContext#bind(SocketAddress, ChannelPromise)}
    • + *
    • {@link ChannelHandlerContext#connect(SocketAddress, SocketAddress, ChannelPromise)}
    • + *
    • {@link ChannelHandlerContext#write(Object, ChannelPromise)}
    • + *
    • {@link ChannelHandlerContext#flush()}
    • + *
    • {@link ChannelHandlerContext#read()}
    • + *
    • {@link ChannelHandlerContext#disconnect(ChannelPromise)}
    • + *
    • {@link ChannelHandlerContext#close(ChannelPromise)}
    • + *
    • {@link ChannelHandlerContext#deregister(ChannelPromise)}
    • + *
    + *
  • + *
+ * + * and the following example shows how the event propagation is usually done: + * + *
+ * public class MyInboundHandler extends {@link ChannelInboundHandlerAdapter} {
+ *     {@code @Override}
+ *     public void channelActive({@link ChannelHandlerContext} ctx) {
+ *         System.out.println("Connected!");
+ *         ctx.fireChannelActive();
+ *     }
+ * }
+ *
+ * public clas MyOutboundHandler extends {@link ChannelOutboundHandlerAdapter} {
+ *     {@code @Override}
+ *     public void close({@link ChannelHandlerContext} ctx, {@link ChannelPromise} promise) {
+ *         System.out.println("Closing ..");
+ *         ctx.close(promise);
+ *     }
+ * }
+ * 
+ * + *

Building a pipeline

+ *

+ * A user is supposed to have one or more {@link ChannelHandler}s in a pipeline to receive I/O events (e.g. read) and + * to request I/O operations (e.g. write and close). For example, a typical server will have the following handlers + * in each channel's pipeline, but your mileage may vary depending on the complexity and characteristics of the + * protocol and business logic: + * + *

    + *
  1. Protocol Decoder - translates binary data (e.g. {@link ByteBuf}) into a Java object.
  2. + *
  3. Protocol Encoder - translates a Java object into binary data.
  4. + *
  5. Business Logic Handler - performs the actual business logic (e.g. database access).
  6. + *
+ * + * and it could be represented as shown in the following example: + * + *
+ * static final {@link EventExecutorGroup} group = new {@link DefaultEventExecutorGroup}(16);
+ * ...
+ *
+ * {@link ChannelPipeline} pipeline = ch.pipeline();
+ *
+ * pipeline.addLast("decoder", new MyProtocolDecoder());
+ * pipeline.addLast("encoder", new MyProtocolEncoder());
+ *
+ * // Tell the pipeline to run MyBusinessLogicHandler's event handler methods
+ * // in a different thread than an I/O thread so that the I/O thread is not blocked by
+ * // a time-consuming task.
+ * // If your business logic is fully asynchronous or finished very quickly, you don't
+ * // need to specify a group.
+ * pipeline.addLast(group, "handler", new MyBusinessLogicHandler());
+ * 
+ * + *

Thread safety

+ *

+ * A {@link ChannelHandler} can be added or removed at any time because a {@link ChannelPipeline} is thread safe. + * For example, you can insert an encryption handler when sensitive information is about to be exchanged, and remove it + * after the exchange. + */ +public interface ChannelPipeline + extends Iterable> { + + /** + * Inserts a {@link ChannelHandler} at the first position of this pipeline. + * + * @param name the name of the handler to insert first + * @param handler the handler to insert first + * + * @throws IllegalArgumentException + * if there's an entry with the same name already in the pipeline + * @throws NullPointerException + * if the specified name or handler is {@code null} + */ + ChannelPipeline addFirst(String name, ChannelHandler handler); + + /** + * Inserts a {@link ChannelHandler} at the first position of this pipeline. + * + * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler} + * methods + * @param name the name of the handler to insert first + * @param handler the handler to insert first + * + * @throws IllegalArgumentException + * if there's an entry with the same name already in the pipeline + * @throws NullPointerException + * if the specified name or handler is {@code null} + */ + ChannelPipeline addFirst(EventExecutorGroup group, String name, ChannelHandler handler); + + /** + * Appends a {@link ChannelHandler} at the last position of this pipeline. + * + * @param name the name of the handler to append + * @param handler the handler to append + * + * @throws IllegalArgumentException + * if there's an entry with the same name already in the pipeline + * @throws NullPointerException + * if the specified name or handler is {@code null} + */ + ChannelPipeline addLast(String name, ChannelHandler handler); + + /** + * Appends a {@link ChannelHandler} at the last position of this pipeline. + * + * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler} + * methods + * @param name the name of the handler to append + * @param handler the handler to append + * + * @throws IllegalArgumentException + * if there's an entry with the same name already in the pipeline + * @throws NullPointerException + * if the specified name or handler is {@code null} + */ + ChannelPipeline addLast(EventExecutorGroup group, String name, ChannelHandler handler); + + /** + * Inserts a {@link ChannelHandler} before an existing handler of this + * pipeline. + * + * @param baseName the name of the existing handler + * @param name the name of the handler to insert before + * @param handler the handler to insert before + * + * @throws NoSuchElementException + * if there's no such entry with the specified {@code baseName} + * @throws IllegalArgumentException + * if there's an entry with the same name already in the pipeline + * @throws NullPointerException + * if the specified baseName, name, or handler is {@code null} + */ + ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler); + + /** + * Inserts a {@link ChannelHandler} before an existing handler of this + * pipeline. + * + * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler} + * methods + * @param baseName the name of the existing handler + * @param name the name of the handler to insert before + * @param handler the handler to insert before + * + * @throws NoSuchElementException + * if there's no such entry with the specified {@code baseName} + * @throws IllegalArgumentException + * if there's an entry with the same name already in the pipeline + * @throws NullPointerException + * if the specified baseName, name, or handler is {@code null} + */ + ChannelPipeline addBefore(EventExecutorGroup group, String baseName, String name, ChannelHandler handler); + + /** + * Inserts a {@link ChannelHandler} after an existing handler of this + * pipeline. + * + * @param baseName the name of the existing handler + * @param name the name of the handler to insert after + * @param handler the handler to insert after + * + * @throws NoSuchElementException + * if there's no such entry with the specified {@code baseName} + * @throws IllegalArgumentException + * if there's an entry with the same name already in the pipeline + * @throws NullPointerException + * if the specified baseName, name, or handler is {@code null} + */ + ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler); + + /** + * Inserts a {@link ChannelHandler} after an existing handler of this + * pipeline. + * + * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler} + * methods + * @param baseName the name of the existing handler + * @param name the name of the handler to insert after + * @param handler the handler to insert after + * + * @throws NoSuchElementException + * if there's no such entry with the specified {@code baseName} + * @throws IllegalArgumentException + * if there's an entry with the same name already in the pipeline + * @throws NullPointerException + * if the specified baseName, name, or handler is {@code null} + */ + ChannelPipeline addAfter(EventExecutorGroup group, String baseName, String name, ChannelHandler handler); + + /** + * Inserts a {@link ChannelHandler}s at the first position of this pipeline. + * + * @param handlers the handlers to insert first + * + */ + ChannelPipeline addFirst(ChannelHandler... handlers); + + /** + * Inserts a {@link ChannelHandler}s at the first position of this pipeline. + * + * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler}s + * methods. + * @param handlers the handlers to insert first + * + */ + ChannelPipeline addFirst(EventExecutorGroup group, ChannelHandler... handlers); + + /** + * Inserts a {@link ChannelHandler}s at the last position of this pipeline. + * + * @param handlers the handlers to insert last + * + */ + ChannelPipeline addLast(ChannelHandler... handlers); + + /** + * Inserts a {@link ChannelHandler}s at the last position of this pipeline. + * + * @param group the {@link EventExecutorGroup} which will be used to execute the {@link ChannelHandler}s + * methods. + * @param handlers the handlers to insert last + * + */ + ChannelPipeline addLast(EventExecutorGroup group, ChannelHandler... handlers); + + /** + * Removes the specified {@link ChannelHandler} from this pipeline. + * + * @param handler the {@link ChannelHandler} to remove + * + * @throws NoSuchElementException + * if there's no such handler in this pipeline + * @throws NullPointerException + * if the specified handler is {@code null} + */ + ChannelPipeline remove(ChannelHandler handler); + + /** + * Removes the {@link ChannelHandler} with the specified name from this pipeline. + * + * @param name the name under which the {@link ChannelHandler} was stored. + * + * @return the removed handler + * + * @throws NoSuchElementException + * if there's no such handler with the specified name in this pipeline + * @throws NullPointerException + * if the specified name is {@code null} + */ + ChannelHandler remove(String name); + + /** + * Removes the {@link ChannelHandler} of the specified type from this pipeline. + * + * @param the type of the handler + * @param handlerType the type of the handler + * + * @return the removed handler + * + * @throws NoSuchElementException + * if there's no such handler of the specified type in this pipeline + * @throws NullPointerException + * if the specified handler type is {@code null} + */ + T remove(Class handlerType); + + /** + * Removes the first {@link ChannelHandler} in this pipeline. + * + * @return the removed handler + * + * @throws NoSuchElementException + * if this pipeline is empty + */ + ChannelHandler removeFirst(); + + /** + * Removes the last {@link ChannelHandler} in this pipeline. + * + * @return the removed handler + * + * @throws NoSuchElementException + * if this pipeline is empty + */ + ChannelHandler removeLast(); + + /** + * Replaces the specified {@link ChannelHandler} with a new handler in this pipeline. + * + * @param oldHandler the {@link ChannelHandler} to be replaced + * @param newName the name under which the replacement should be added + * @param newHandler the {@link ChannelHandler} which is used as replacement + * + * @return itself + + * @throws NoSuchElementException + * if the specified old handler does not exist in this pipeline + * @throws IllegalArgumentException + * if a handler with the specified new name already exists in this + * pipeline, except for the handler to be replaced + * @throws NullPointerException + * if the specified old handler, new name, or new handler is + * {@code null} + */ + ChannelPipeline replace(ChannelHandler oldHandler, String newName, ChannelHandler newHandler); + + /** + * Replaces the {@link ChannelHandler} of the specified name with a new handler in this pipeline. + * + * @param oldName the name of the {@link ChannelHandler} to be replaced + * @param newName the name under which the replacement should be added + * @param newHandler the {@link ChannelHandler} which is used as replacement + * + * @return the removed handler + * + * @throws NoSuchElementException + * if the handler with the specified old name does not exist in this pipeline + * @throws IllegalArgumentException + * if a handler with the specified new name already exists in this + * pipeline, except for the handler to be replaced + * @throws NullPointerException + * if the specified old handler, new name, or new handler is + * {@code null} + */ + ChannelHandler replace(String oldName, String newName, ChannelHandler newHandler); + + /** + * Replaces the {@link ChannelHandler} of the specified type with a new handler in this pipeline. + * + * @param oldHandlerType the type of the handler to be removed + * @param newName the name under which the replacement should be added + * @param newHandler the {@link ChannelHandler} which is used as replacement + * + * @return the removed handler + * + * @throws NoSuchElementException + * if the handler of the specified old handler type does not exist + * in this pipeline + * @throws IllegalArgumentException + * if a handler with the specified new name already exists in this + * pipeline, except for the handler to be replaced + * @throws NullPointerException + * if the specified old handler, new name, or new handler is + * {@code null} + */ + T replace(Class oldHandlerType, String newName, + ChannelHandler newHandler); + + /** + * Returns the first {@link ChannelHandler} in this pipeline. + * + * @return the first handler. {@code null} if this pipeline is empty. + */ + ChannelHandler first(); + + /** + * Returns the context of the first {@link ChannelHandler} in this pipeline. + * + * @return the context of the first handler. {@code null} if this pipeline is empty. + */ + ChannelHandlerContext firstContext(); + + /** + * Returns the last {@link ChannelHandler} in this pipeline. + * + * @return the last handler. {@code null} if this pipeline is empty. + */ + ChannelHandler last(); + + /** + * Returns the context of the last {@link ChannelHandler} in this pipeline. + * + * @return the context of the last handler. {@code null} if this pipeline is empty. + */ + ChannelHandlerContext lastContext(); + + /** + * Returns the {@link ChannelHandler} with the specified name in this + * pipeline. + * + * @return the handler with the specified name. + * {@code null} if there's no such handler in this pipeline. + */ + ChannelHandler get(String name); + + /** + * Returns the {@link ChannelHandler} of the specified type in this + * pipeline. + * + * @return the handler of the specified handler type. + * {@code null} if there's no such handler in this pipeline. + */ + T get(Class handlerType); + + /** + * Returns the context object of the specified {@link ChannelHandler} in + * this pipeline. + * + * @return the context object of the specified handler. + * {@code null} if there's no such handler in this pipeline. + */ + ChannelHandlerContext context(ChannelHandler handler); + + /** + * Returns the context object of the {@link ChannelHandler} with the + * specified name in this pipeline. + * + * @return the context object of the handler with the specified name. + * {@code null} if there's no such handler in this pipeline. + */ + ChannelHandlerContext context(String name); + + /** + * Returns the context object of the {@link ChannelHandler} of the + * specified type in this pipeline. + * + * @return the context object of the handler of the specified type. + * {@code null} if there's no such handler in this pipeline. + */ + ChannelHandlerContext context(Class handlerType); + + /** + * Returns the {@link Channel} that this pipeline is attached to. + * + * @return the channel. {@code null} if this pipeline is not attached yet. + */ + Channel channel(); + + /** + * Returns the {@link List} of the handler names. + */ + List names(); + + /** + * Converts this pipeline into an ordered {@link Map} whose keys are + * handler names and whose values are handlers. + */ + Map toMap(); + + /** + * A {@link Channel} was registered to its {@link EventLoop}. + * + * This will result in having the {@link ChannelInboundHandler#channelRegistered(ChannelHandlerContext)} method + * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelPipeline fireChannelRegistered(); + + /** + * A {@link Channel} was unregistered from its {@link EventLoop}. + * + * This will result in having the {@link ChannelInboundHandler#channelUnregistered(ChannelHandlerContext)} method + * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelPipeline fireChannelUnregistered(); + + /** + * A {@link Channel} is active now, which means it is connected. + * + * This will result in having the {@link ChannelInboundHandler#channelActive(ChannelHandlerContext)} method + * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelPipeline fireChannelActive(); + + /** + * A {@link Channel} is inactive now, which means it is closed. + * + * This will result in having the {@link ChannelInboundHandler#channelInactive(ChannelHandlerContext)} method + * called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelPipeline fireChannelInactive(); + + /** + * A {@link Channel} received an {@link Throwable} in one of its inbound operations. + * + * This will result in having the {@link ChannelInboundHandler#exceptionCaught(ChannelHandlerContext, Throwable)} + * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelPipeline fireExceptionCaught(Throwable cause); + + /** + * A {@link Channel} received an user defined event. + * + * This will result in having the {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)} + * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelPipeline fireUserEventTriggered(Object event); + + /** + * A {@link Channel} received a message. + * + * This will result in having the {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)} + * method called of the next {@link ChannelInboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelPipeline fireChannelRead(Object msg); + + /** + * Triggers an {@link ChannelInboundHandler#channelWritabilityChanged(ChannelHandlerContext)} + * event to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + */ + ChannelPipeline fireChannelReadComplete(); + + /** + * Triggers an {@link ChannelInboundHandler#channelWritabilityChanged(ChannelHandlerContext)} + * event to the next {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + */ + ChannelPipeline fireChannelWritabilityChanged(); + + /** + * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method + * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture bind(SocketAddress localAddress); + + /** + * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + *

+ * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with + * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} + * will be used. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress); + + /** + * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the + * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of + * an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress); + + /** + * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, + * either because the operation was successful or because of an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture disconnect(); + + /** + * Request to close the {@link Channel} and notify the {@link ChannelFuture} once the operation completes, + * either because the operation was successful or because of + * an error. + * + * After it is closed it is not possible to reuse it again. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture close(); + + /** + * Request to deregister the {@link Channel} from the previous assigned {@link EventExecutor} and notify the + * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of + * an error. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + * + */ + ChannelFuture deregister(); + + /** + * Request to bind to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + * + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#bind(ChannelHandlerContext, SocketAddress, ChannelPromise)} method + * called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise); + + /** + * Request to connect to the given {@link SocketAddress} and notify the {@link ChannelFuture} once the operation + * completes, either because the operation was successful or because of an error. + * + * The given {@link ChannelFuture} will be notified. + * + *

+ * If the connection fails because of a connection timeout, the {@link ChannelFuture} will get failed with + * a {@link ConnectTimeoutException}. If it fails because of connection refused a {@link ConnectException} + * will be used. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise); + + /** + * Request to connect to the given {@link SocketAddress} while bind to the localAddress and notify the + * {@link ChannelFuture} once the operation completes, either because the operation was successful or because of + * an error. + * + * The given {@link ChannelPromise} will be notified and also returned. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#connect(ChannelHandlerContext, SocketAddress, SocketAddress, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise); + + /** + * Request to disconnect from the remote peer and notify the {@link ChannelFuture} once the operation completes, + * either because the operation was successful or because of an error. + * + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#disconnect(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture disconnect(ChannelPromise promise); + + /** + * Request to close the {@link Channel} bound to this {@link ChannelPipeline} and notify the {@link ChannelFuture} + * once the operation completes, either because the operation was successful or because of + * an error. + * + * After it is closed it is not possible to reuse it again. + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#close(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture close(ChannelPromise promise); + + /** + * Request to deregister the {@link Channel} bound this {@link ChannelPipeline} from the previous assigned + * {@link EventExecutor} and notify the {@link ChannelFuture} once the operation completes, either because the + * operation was successful or because of an error. + * + * The given {@link ChannelPromise} will be notified. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#deregister(ChannelHandlerContext, ChannelPromise)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelFuture deregister(ChannelPromise promise); + + /** + * Request to Read data from the {@link Channel} into the first inbound buffer, triggers an + * {@link ChannelInboundHandler#channelRead(ChannelHandlerContext, Object)} event if data was + * read, and triggers a + * {@link ChannelInboundHandler#channelReadComplete(ChannelHandlerContext) channelReadComplete} event so the + * handler can decide to continue reading. If there's a pending read operation already, this method does nothing. + *

+ * This will result in having the + * {@link ChannelOutboundHandler#read(ChannelHandlerContext)} + * method called of the next {@link ChannelOutboundHandler} contained in the {@link ChannelPipeline} of the + * {@link Channel}. + */ + ChannelPipeline read(); + + /** + * Request to write a message via this {@link ChannelPipeline}. + * This method will not request to actual flush, so be sure to call {@link #flush()} + * once you want to request to flush all pending data to the actual transport. + */ + ChannelFuture write(Object msg); + + /** + * Request to write a message via this {@link ChannelPipeline}. + * This method will not request to actual flush, so be sure to call {@link #flush()} + * once you want to request to flush all pending data to the actual transport. + */ + ChannelFuture write(Object msg, ChannelPromise promise); + + /** + * Request to flush all pending messages. + */ + ChannelPipeline flush(); + + /** + * Shortcut for call {@link #write(Object, ChannelPromise)} and {@link #flush()}. + */ + ChannelFuture writeAndFlush(Object msg, ChannelPromise promise); + + /** + * Shortcut for call {@link #write(Object)} and {@link #flush()}. + */ + ChannelFuture writeAndFlush(Object msg); +} diff --git a/common/src/main/java/common/net/channel/ChannelPipelineException.java b/common/src/main/java/common/net/channel/ChannelPipelineException.java new file mode 100644 index 0000000..d1f8628 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelPipelineException.java @@ -0,0 +1,52 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +/** + * A {@link ChannelException} which is thrown when a {@link ChannelPipeline} + * failed to execute an operation. + */ +public class ChannelPipelineException extends ChannelException { + + private static final long serialVersionUID = 3379174210419885980L; + + /** + * Creates a new instance. + */ + public ChannelPipelineException() { + } + + /** + * Creates a new instance. + */ + public ChannelPipelineException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Creates a new instance. + */ + public ChannelPipelineException(String message) { + super(message); + } + + /** + * Creates a new instance. + */ + public ChannelPipelineException(Throwable cause) { + super(cause); + } +} diff --git a/common/src/main/java/common/net/channel/ChannelProgressivePromise.java b/common/src/main/java/common/net/channel/ChannelProgressivePromise.java new file mode 100644 index 0000000..530e252 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelProgressivePromise.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; +import common.net.util.concurrent.ProgressiveFuture; +import common.net.util.concurrent.ProgressivePromise; + +/** + * Special {@link ChannelPromise} which will be notified once the associated bytes is transferring. + */ +public interface ChannelProgressivePromise extends ProgressivePromise, ChannelFuture, ProgressiveFuture, ChannelPromise { +// @Override +// ChannelProgressiveFuture addListener(GenericFutureListener> listener); +// +// @Override +// ChannelProgressiveFuture addListeners(GenericFutureListener>... listeners); +// +// @Override +// ChannelProgressiveFuture removeListener(GenericFutureListener> listener); +// +// @Override +// ChannelProgressiveFuture removeListeners(GenericFutureListener>... listeners); +// +// @Override +// ChannelProgressiveFuture sync() throws InterruptedException; +// +// @Override +// ChannelProgressiveFuture syncUninterruptibly(); +// +// @Override +// ChannelProgressiveFuture await() throws InterruptedException; +// +// @Override +// ChannelProgressiveFuture awaitUninterruptibly(); + + @Override + ChannelProgressivePromise addListener(GenericFutureListener> listener); + + @Override + ChannelProgressivePromise addListeners(GenericFutureListener>... listeners); + + @Override + ChannelProgressivePromise removeListener(GenericFutureListener> listener); + + @Override + ChannelProgressivePromise removeListeners(GenericFutureListener>... listeners); + + @Override + ChannelProgressivePromise sync() throws InterruptedException; + + @Override + ChannelProgressivePromise syncUninterruptibly(); + + @Override + ChannelProgressivePromise await() throws InterruptedException; + + @Override + ChannelProgressivePromise awaitUninterruptibly(); + + @Override + ChannelProgressivePromise setSuccess(Void result); + + @Override + ChannelProgressivePromise setSuccess(); + + @Override + ChannelProgressivePromise setFailure(Throwable cause); + + @Override + ChannelProgressivePromise setProgress(long progress, long total); +} diff --git a/common/src/main/java/common/net/channel/ChannelPromise.java b/common/src/main/java/common/net/channel/ChannelPromise.java new file mode 100644 index 0000000..fda7072 --- /dev/null +++ b/common/src/main/java/common/net/channel/ChannelPromise.java @@ -0,0 +1,63 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; +import common.net.util.concurrent.Promise; + +/** + * Special {@link ChannelFuture} which is writable. + */ +public interface ChannelPromise extends ChannelFuture, Promise { + + @Override + Channel channel(); + + @Override + ChannelPromise setSuccess(Void result); + + ChannelPromise setSuccess(); + + boolean trySuccess(); + + @Override + ChannelPromise setFailure(Throwable cause); + + @Override + ChannelPromise addListener(GenericFutureListener> listener); + + @Override + ChannelPromise addListeners(GenericFutureListener>... listeners); + + @Override + ChannelPromise removeListener(GenericFutureListener> listener); + + @Override + ChannelPromise removeListeners(GenericFutureListener>... listeners); + + @Override + ChannelPromise sync() throws InterruptedException; + + @Override + ChannelPromise syncUninterruptibly(); + + @Override + ChannelPromise await() throws InterruptedException; + + @Override + ChannelPromise awaitUninterruptibly(); +} diff --git a/common/src/main/java/common/net/channel/CompleteChannelFuture.java b/common/src/main/java/common/net/channel/CompleteChannelFuture.java new file mode 100644 index 0000000..2e8dac6 --- /dev/null +++ b/common/src/main/java/common/net/channel/CompleteChannelFuture.java @@ -0,0 +1,107 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.util.concurrent.CompleteFuture; +import common.net.util.concurrent.EventExecutor; +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; + +/** + * A skeletal {@link ChannelFuture} implementation which represents a + * {@link ChannelFuture} which has been completed already. + */ +abstract class CompleteChannelFuture extends CompleteFuture implements ChannelFuture { + + private final Channel channel; + + /** + * Creates a new instance. + * + * @param channel the {@link Channel} associated with this future + */ + protected CompleteChannelFuture(Channel channel, EventExecutor executor) { + super(executor); + if (channel == null) { + throw new NullPointerException("channel"); + } + this.channel = channel; + } + + @Override + protected EventExecutor executor() { + EventExecutor e = super.executor(); + if (e == null) { + return channel().eventLoop(); + } else { + return e; + } + } + + @Override + public ChannelFuture addListener(GenericFutureListener> listener) { + super.addListener(listener); + return this; + } + + @Override + public ChannelFuture addListeners(GenericFutureListener>... listeners) { + super.addListeners(listeners); + return this; + } + + @Override + public ChannelFuture removeListener(GenericFutureListener> listener) { + super.removeListener(listener); + return this; + } + + @Override + public ChannelFuture removeListeners(GenericFutureListener>... listeners) { + super.removeListeners(listeners); + return this; + } + + @Override + public ChannelFuture syncUninterruptibly() { + return this; + } + + @Override + public ChannelFuture sync() throws InterruptedException { + return this; + } + + @Override + public ChannelFuture await() throws InterruptedException { + return this; + } + + @Override + public ChannelFuture awaitUninterruptibly() { + return this; + } + + @Override + public Channel channel() { + return channel; + } + + @Override + public Void getNow() { + return null; + } +} diff --git a/common/src/main/java/common/net/channel/ConnectTimeoutException.java b/common/src/main/java/common/net/channel/ConnectTimeoutException.java new file mode 100644 index 0000000..831cbe6 --- /dev/null +++ b/common/src/main/java/common/net/channel/ConnectTimeoutException.java @@ -0,0 +1,33 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.net.ConnectException; + +/** + * {@link ConnectException} which will be thrown if a connection could + * not be established because of a connection timeout. + */ +public class ConnectTimeoutException extends ConnectException { + private static final long serialVersionUID = 2317065249988317463L; + + public ConnectTimeoutException(String msg) { + super(msg); + } + + public ConnectTimeoutException() { + } +} diff --git a/common/src/main/java/common/net/channel/DefaultChannelConfig.java b/common/src/main/java/common/net/channel/DefaultChannelConfig.java new file mode 100644 index 0000000..5d94a1c --- /dev/null +++ b/common/src/main/java/common/net/channel/DefaultChannelConfig.java @@ -0,0 +1,337 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import static common.net.channel.ChannelOption.ALLOCATOR; +import static common.net.channel.ChannelOption.AUTO_READ; +import static common.net.channel.ChannelOption.CONNECT_TIMEOUT_MILLIS; +import static common.net.channel.ChannelOption.MAX_MESSAGES_PER_READ; +import static common.net.channel.ChannelOption.MESSAGE_SIZE_ESTIMATOR; +import static common.net.channel.ChannelOption.RCVBUF_ALLOCATOR; +import static common.net.channel.ChannelOption.WRITE_BUFFER_HIGH_WATER_MARK; +import static common.net.channel.ChannelOption.WRITE_BUFFER_LOW_WATER_MARK; +import static common.net.channel.ChannelOption.WRITE_SPIN_COUNT; + +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.Map.Entry; + +import common.net.buffer.ByteBufAllocator; +import common.net.channel.nio.AbstractNioByteChannel; + +/** + * The default {@link SocketChannelConfig} implementation. + */ +public class DefaultChannelConfig implements ChannelConfig { + + private static final RecvByteBufAllocator DEFAULT_RCVBUF_ALLOCATOR = AdaptiveRecvByteBufAllocator.DEFAULT; + private static final MessageSizeEstimator DEFAULT_MSG_SIZE_ESTIMATOR = DefaultMessageSizeEstimator.DEFAULT; + + private static final int DEFAULT_CONNECT_TIMEOUT = 30000; + + protected final Channel channel; + + private volatile ByteBufAllocator allocator = ByteBufAllocator.DEFAULT; + private volatile RecvByteBufAllocator rcvBufAllocator = DEFAULT_RCVBUF_ALLOCATOR; + private volatile MessageSizeEstimator msgSizeEstimator = DEFAULT_MSG_SIZE_ESTIMATOR; + + private volatile int connectTimeoutMillis = DEFAULT_CONNECT_TIMEOUT; + private volatile int maxMessagesPerRead; + private volatile int writeSpinCount = 16; + private volatile boolean autoRead = true; + private volatile int writeBufferHighWaterMark = 64 * 1024; + private volatile int writeBufferLowWaterMark = 32 * 1024; + + public DefaultChannelConfig(Channel channel) { + if (channel == null) { + throw new NullPointerException("channel"); + } + this.channel = channel; + + if (channel instanceof ServerChannel || channel instanceof AbstractNioByteChannel) { + // Server channels: Accept as many incoming connections as possible. + // NIO byte channels: Implemented to reduce unnecessary system calls even if it's > 1. + // See https://github.com/netty/netty/issues/2079 + // TODO: Add some property to ChannelMetadata so we can remove the ugly instanceof + maxMessagesPerRead = 16; + } else { + maxMessagesPerRead = 1; + } + } + + @Override + + public Map, Object> getOptions() { + return getOptions( + null, + CONNECT_TIMEOUT_MILLIS, MAX_MESSAGES_PER_READ, WRITE_SPIN_COUNT, + ALLOCATOR, AUTO_READ, RCVBUF_ALLOCATOR, WRITE_BUFFER_HIGH_WATER_MARK, + WRITE_BUFFER_LOW_WATER_MARK, MESSAGE_SIZE_ESTIMATOR); + } + + protected Map, Object> getOptions( + Map, Object> result, ChannelOption... options) { + if (result == null) { + result = new IdentityHashMap, Object>(); + } + for (ChannelOption o: options) { + result.put(o, getOption(o)); + } + return result; + } + + + @Override + public boolean setOptions(Map, ?> options) { + if (options == null) { + throw new NullPointerException("options"); + } + + boolean setAllOptions = true; + for (Entry, ?> e: options.entrySet()) { + if (!setOption((ChannelOption) e.getKey(), e.getValue())) { + setAllOptions = false; + } + } + + return setAllOptions; + } + + @Override + + public T getOption(ChannelOption option) { + if (option == null) { + throw new NullPointerException("option"); + } + + if (option == CONNECT_TIMEOUT_MILLIS) { + return (T) Integer.valueOf(getConnectTimeoutMillis()); + } + if (option == MAX_MESSAGES_PER_READ) { + return (T) Integer.valueOf(getMaxMessagesPerRead()); + } + if (option == WRITE_SPIN_COUNT) { + return (T) Integer.valueOf(getWriteSpinCount()); + } + if (option == ALLOCATOR) { + return (T) getAllocator(); + } + if (option == RCVBUF_ALLOCATOR) { + return (T) getRecvByteBufAllocator(); + } + if (option == AUTO_READ) { + return (T) Boolean.valueOf(isAutoRead()); + } + if (option == WRITE_BUFFER_HIGH_WATER_MARK) { + return (T) Integer.valueOf(getWriteBufferHighWaterMark()); + } + if (option == WRITE_BUFFER_LOW_WATER_MARK) { + return (T) Integer.valueOf(getWriteBufferLowWaterMark()); + } + if (option == MESSAGE_SIZE_ESTIMATOR) { + return (T) getMessageSizeEstimator(); + } + return null; + } + + @Override + + public boolean setOption(ChannelOption option, T value) { + validate(option, value); + + if (option == CONNECT_TIMEOUT_MILLIS) { + setConnectTimeoutMillis((Integer) value); + } else if (option == MAX_MESSAGES_PER_READ) { + setMaxMessagesPerRead((Integer) value); + } else if (option == WRITE_SPIN_COUNT) { + setWriteSpinCount((Integer) value); + } else if (option == ALLOCATOR) { + setAllocator((ByteBufAllocator) value); + } else if (option == RCVBUF_ALLOCATOR) { + setRecvByteBufAllocator((RecvByteBufAllocator) value); + } else if (option == AUTO_READ) { + setAutoRead((Boolean) value); + } else if (option == WRITE_BUFFER_HIGH_WATER_MARK) { + setWriteBufferHighWaterMark((Integer) value); + } else if (option == WRITE_BUFFER_LOW_WATER_MARK) { + setWriteBufferLowWaterMark((Integer) value); + } else if (option == MESSAGE_SIZE_ESTIMATOR) { + setMessageSizeEstimator((MessageSizeEstimator) value); + } else { + return false; + } + + return true; + } + + protected void validate(ChannelOption option, T value) { + if (option == null) { + throw new NullPointerException("option"); + } + option.validate(value); + } + + @Override + public int getConnectTimeoutMillis() { + return connectTimeoutMillis; + } + + @Override + public ChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) { + if (connectTimeoutMillis < 0) { + throw new IllegalArgumentException(String.format( + "connectTimeoutMillis: %d (expected: >= 0)", connectTimeoutMillis)); + } + this.connectTimeoutMillis = connectTimeoutMillis; + return this; + } + + @Override + public int getMaxMessagesPerRead() { + return maxMessagesPerRead; + } + + @Override + public ChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) { + if (maxMessagesPerRead <= 0) { + throw new IllegalArgumentException("maxMessagesPerRead: " + maxMessagesPerRead + " (expected: > 0)"); + } + this.maxMessagesPerRead = maxMessagesPerRead; + return this; + } + + @Override + public int getWriteSpinCount() { + return writeSpinCount; + } + + @Override + public ChannelConfig setWriteSpinCount(int writeSpinCount) { + if (writeSpinCount <= 0) { + throw new IllegalArgumentException( + "writeSpinCount must be a positive integer."); + } + this.writeSpinCount = writeSpinCount; + return this; + } + + @Override + public ByteBufAllocator getAllocator() { + return allocator; + } + + @Override + public ChannelConfig setAllocator(ByteBufAllocator allocator) { + if (allocator == null) { + throw new NullPointerException("allocator"); + } + this.allocator = allocator; + return this; + } + + @Override + public RecvByteBufAllocator getRecvByteBufAllocator() { + return rcvBufAllocator; + } + + @Override + public ChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) { + if (allocator == null) { + throw new NullPointerException("allocator"); + } + rcvBufAllocator = allocator; + return this; + } + + @Override + public boolean isAutoRead() { + return autoRead; + } + + @Override + public ChannelConfig setAutoRead(boolean autoRead) { + boolean oldAutoRead = this.autoRead; + this.autoRead = autoRead; + if (autoRead && !oldAutoRead) { + channel.read(); + } else if (!autoRead && oldAutoRead) { + autoReadCleared(); + } + return this; + } + + /** + * Is called once {@link #setAutoRead(boolean)} is called with {@code false} and {@link #isAutoRead()} was + * {@code true} before. + */ + protected void autoReadCleared() { } + + @Override + public int getWriteBufferHighWaterMark() { + return writeBufferHighWaterMark; + } + + @Override + public ChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark) { + if (writeBufferHighWaterMark < getWriteBufferLowWaterMark()) { + throw new IllegalArgumentException( + "writeBufferHighWaterMark cannot be less than " + + "writeBufferLowWaterMark (" + getWriteBufferLowWaterMark() + "): " + + writeBufferHighWaterMark); + } + if (writeBufferHighWaterMark < 0) { + throw new IllegalArgumentException( + "writeBufferHighWaterMark must be >= 0"); + } + this.writeBufferHighWaterMark = writeBufferHighWaterMark; + return this; + } + + @Override + public int getWriteBufferLowWaterMark() { + return writeBufferLowWaterMark; + } + + @Override + public ChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark) { + if (writeBufferLowWaterMark > getWriteBufferHighWaterMark()) { + throw new IllegalArgumentException( + "writeBufferLowWaterMark cannot be greater than " + + "writeBufferHighWaterMark (" + getWriteBufferHighWaterMark() + "): " + + writeBufferLowWaterMark); + } + if (writeBufferLowWaterMark < 0) { + throw new IllegalArgumentException( + "writeBufferLowWaterMark must be >= 0"); + } + this.writeBufferLowWaterMark = writeBufferLowWaterMark; + return this; + } + + @Override + public MessageSizeEstimator getMessageSizeEstimator() { + return msgSizeEstimator; + } + + @Override + public ChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) { + if (estimator == null) { + throw new NullPointerException("estimator"); + } + msgSizeEstimator = estimator; + return this; + } +} diff --git a/common/src/main/java/common/net/channel/DefaultChannelHandlerContext.java b/common/src/main/java/common/net/channel/DefaultChannelHandlerContext.java new file mode 100644 index 0000000..9c24e1e --- /dev/null +++ b/common/src/main/java/common/net/channel/DefaultChannelHandlerContext.java @@ -0,0 +1,45 @@ +/* +* Copyright 2014 The Netty Project +* +* The Netty Project licenses this file to you under the Apache License, +* version 2.0 (the "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at: +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +* License for the specific language governing permissions and limitations +* under the License. +*/ +package common.net.channel; + +import common.net.util.concurrent.EventExecutorGroup; + +final class DefaultChannelHandlerContext extends AbstractChannelHandlerContext { + + private final ChannelHandler handler; + + DefaultChannelHandlerContext( + DefaultChannelPipeline pipeline, EventExecutorGroup group, String name, ChannelHandler handler) { + super(pipeline, group, name, isInbound(handler), isOutbound(handler)); + if (handler == null) { + throw new NullPointerException("handler"); + } + this.handler = handler; + } + + @Override + public ChannelHandler handler() { + return handler; + } + + private static boolean isInbound(ChannelHandler handler) { + return handler instanceof ChannelInboundHandler; + } + + private static boolean isOutbound(ChannelHandler handler) { + return handler instanceof ChannelOutboundHandler; + } +} diff --git a/common/src/main/java/common/net/channel/DefaultChannelPipeline.java b/common/src/main/java/common/net/channel/DefaultChannelPipeline.java new file mode 100644 index 0000000..86d549c --- /dev/null +++ b/common/src/main/java/common/net/channel/DefaultChannelPipeline.java @@ -0,0 +1,1067 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.net.SocketAddress; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.IdentityHashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.NoSuchElementException; +import java.util.WeakHashMap; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.Future; + +import common.net.channel.Channel.Unsafe; +import common.net.util.ReferenceCountUtil; +import common.net.util.concurrent.EventExecutor; +import common.net.util.concurrent.EventExecutorGroup; +import common.net.util.internal.StringUtil; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; +import common.util.Util; + +/** + * The default {@link ChannelPipeline} implementation. It is usually created + * by a {@link Channel} implementation when the {@link Channel} is created. + */ +final class DefaultChannelPipeline implements ChannelPipeline { + + static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelPipeline.class); + + + private static final WeakHashMap, String>[] nameCaches = + new WeakHashMap[Runtime.getRuntime().availableProcessors()]; + + static { + for (int i = 0; i < nameCaches.length; i ++) { + nameCaches[i] = new WeakHashMap, String>(); + } + } + + final AbstractChannel channel; + + final AbstractChannelHandlerContext head; + final AbstractChannelHandlerContext tail; + + private final Map name2ctx = + new HashMap(4); + + final Map childExecutors = + new IdentityHashMap(); + + public DefaultChannelPipeline(AbstractChannel channel) { + if (channel == null) { + throw new NullPointerException("channel"); + } + this.channel = channel; + + tail = new TailContext(this); + head = new HeadContext(this); + + head.next = tail; + tail.prev = head; + } + + @Override + public Channel channel() { + return channel; + } + + @Override + public ChannelPipeline addFirst(String name, ChannelHandler handler) { + return addFirst(null, name, handler); + } + + @Override + public ChannelPipeline addFirst(EventExecutorGroup group, final String name, ChannelHandler handler) { + synchronized (this) { + checkDuplicateName(name); + AbstractChannelHandlerContext newCtx = new DefaultChannelHandlerContext(this, group, name, handler); + addFirst0(name, newCtx); + } + + return this; + } + + private void addFirst0(String name, AbstractChannelHandlerContext newCtx) { + checkMultiplicity(newCtx); + + AbstractChannelHandlerContext nextCtx = head.next; + newCtx.prev = head; + newCtx.next = nextCtx; + head.next = newCtx; + nextCtx.prev = newCtx; + + name2ctx.put(name, newCtx); + + callHandlerAdded(newCtx); + } + + @Override + public ChannelPipeline addLast(String name, ChannelHandler handler) { + return addLast(null, name, handler); + } + + @Override + public ChannelPipeline addLast(EventExecutorGroup group, final String name, ChannelHandler handler) { + synchronized (this) { + checkDuplicateName(name); + + AbstractChannelHandlerContext newCtx = new DefaultChannelHandlerContext(this, group, name, handler); + addLast0(name, newCtx); + } + + return this; + } + + private void addLast0(final String name, AbstractChannelHandlerContext newCtx) { + checkMultiplicity(newCtx); + + AbstractChannelHandlerContext prev = tail.prev; + newCtx.prev = prev; + newCtx.next = tail; + prev.next = newCtx; + tail.prev = newCtx; + + name2ctx.put(name, newCtx); + + callHandlerAdded(newCtx); + } + + @Override + public ChannelPipeline addBefore(String baseName, String name, ChannelHandler handler) { + return addBefore(null, baseName, name, handler); + } + + @Override + public ChannelPipeline addBefore( + EventExecutorGroup group, String baseName, final String name, ChannelHandler handler) { + synchronized (this) { + AbstractChannelHandlerContext ctx = getContextOrDie(baseName); + checkDuplicateName(name); + AbstractChannelHandlerContext newCtx = new DefaultChannelHandlerContext(this, group, name, handler); + addBefore0(name, ctx, newCtx); + } + return this; + } + + private void addBefore0( + final String name, AbstractChannelHandlerContext ctx, AbstractChannelHandlerContext newCtx) { + checkMultiplicity(newCtx); + + newCtx.prev = ctx.prev; + newCtx.next = ctx; + ctx.prev.next = newCtx; + ctx.prev = newCtx; + + name2ctx.put(name, newCtx); + + callHandlerAdded(newCtx); + } + + @Override + public ChannelPipeline addAfter(String baseName, String name, ChannelHandler handler) { + return addAfter(null, baseName, name, handler); + } + + @Override + public ChannelPipeline addAfter( + EventExecutorGroup group, String baseName, final String name, ChannelHandler handler) { + synchronized (this) { + AbstractChannelHandlerContext ctx = getContextOrDie(baseName); + checkDuplicateName(name); + AbstractChannelHandlerContext newCtx = new DefaultChannelHandlerContext(this, group, name, handler); + + addAfter0(name, ctx, newCtx); + } + + return this; + } + + private void addAfter0(final String name, AbstractChannelHandlerContext ctx, AbstractChannelHandlerContext newCtx) { + checkDuplicateName(name); + checkMultiplicity(newCtx); + + newCtx.prev = ctx; + newCtx.next = ctx.next; + ctx.next.prev = newCtx; + ctx.next = newCtx; + + name2ctx.put(name, newCtx); + + callHandlerAdded(newCtx); + } + + @Override + public ChannelPipeline addFirst(ChannelHandler... handlers) { + return addFirst(null, handlers); + } + + @Override + public ChannelPipeline addFirst(EventExecutorGroup executor, ChannelHandler... handlers) { + if (handlers == null) { + throw new NullPointerException("handlers"); + } + if (handlers.length == 0 || handlers[0] == null) { + return this; + } + + int size; + for (size = 1; size < handlers.length; size ++) { + if (handlers[size] == null) { + break; + } + } + + for (int i = size - 1; i >= 0; i --) { + ChannelHandler h = handlers[i]; + addFirst(executor, generateName(h), h); + } + + return this; + } + + @Override + public ChannelPipeline addLast(ChannelHandler... handlers) { + return addLast(null, handlers); + } + + @Override + public ChannelPipeline addLast(EventExecutorGroup executor, ChannelHandler... handlers) { + if (handlers == null) { + throw new NullPointerException("handlers"); + } + + for (ChannelHandler h: handlers) { + if (h == null) { + break; + } + addLast(executor, generateName(h), h); + } + + return this; + } + + private String generateName(ChannelHandler handler) { + WeakHashMap, String> cache = nameCaches[(int) (Thread.currentThread().threadId() % nameCaches.length)]; + Class handlerType = handler.getClass(); + String name; + synchronized (cache) { + name = cache.get(handlerType); + if (name == null) { + name = generateName0(handlerType); + cache.put(handlerType, name); + } + } + + synchronized (this) { + // It's not very likely for a user to put more than one handler of the same type, but make sure to avoid + // any name conflicts. Note that we don't cache the names generated here. + if (name2ctx.containsKey(name)) { + String baseName = name.substring(0, name.length() - 1); // Strip the trailing '0'. + for (int i = 1;; i ++) { + String newName = baseName + i; + if (!name2ctx.containsKey(newName)) { + name = newName; + break; + } + } + } + } + + return name; + } + + private static String generateName0(Class handlerType) { + return StringUtil.simpleClassName(handlerType) + "#0"; + } + + @Override + public ChannelPipeline remove(ChannelHandler handler) { + remove(getContextOrDie(handler)); + return this; + } + + @Override + public ChannelHandler remove(String name) { + return remove(getContextOrDie(name)).handler(); + } + + + @Override + public T remove(Class handlerType) { + return (T) remove(getContextOrDie(handlerType)).handler(); + } + + private AbstractChannelHandlerContext remove(final AbstractChannelHandlerContext ctx) { + assert ctx != head && ctx != tail; + + AbstractChannelHandlerContext context; + Future future; + + synchronized (this) { + if (!ctx.channel().isRegistered() || ctx.executor().inEventLoop()) { + remove0(ctx); + return ctx; + } else { + future = ctx.executor().submit(new Runnable() { + @Override + public void run() { + synchronized (DefaultChannelPipeline.this) { + remove0(ctx); + } + } + }); + context = ctx; + } + } + + // Run the following 'waiting' code outside of the above synchronized block + // in order to avoid deadlock + + waitForFuture(future); + + return context; + } + + void remove0(AbstractChannelHandlerContext ctx) { + AbstractChannelHandlerContext prev = ctx.prev; + AbstractChannelHandlerContext next = ctx.next; + prev.next = next; + next.prev = prev; + name2ctx.remove(ctx.name()); + callHandlerRemoved(ctx); + } + + @Override + public ChannelHandler removeFirst() { + if (head.next == tail) { + throw new NoSuchElementException(); + } + return remove(head.next).handler(); + } + + @Override + public ChannelHandler removeLast() { + if (head.next == tail) { + throw new NoSuchElementException(); + } + return remove(tail.prev).handler(); + } + + @Override + public ChannelPipeline replace(ChannelHandler oldHandler, String newName, ChannelHandler newHandler) { + replace(getContextOrDie(oldHandler), newName, newHandler); + return this; + } + + @Override + public ChannelHandler replace(String oldName, String newName, ChannelHandler newHandler) { + return replace(getContextOrDie(oldName), newName, newHandler); + } + + @Override + + public T replace( + Class oldHandlerType, String newName, ChannelHandler newHandler) { + return (T) replace(getContextOrDie(oldHandlerType), newName, newHandler); + } + + private ChannelHandler replace( + final AbstractChannelHandlerContext ctx, final String newName, + ChannelHandler newHandler) { + + assert ctx != head && ctx != tail; + + Future future; + synchronized (this) { + boolean sameName = ctx.name().equals(newName); + if (!sameName) { + checkDuplicateName(newName); + } + + final AbstractChannelHandlerContext newCtx = + new DefaultChannelHandlerContext(this, ctx.executor, newName, newHandler); + + if (!newCtx.channel().isRegistered() || newCtx.executor().inEventLoop()) { + replace0(ctx, newName, newCtx); + return ctx.handler(); + } else { + future = newCtx.executor().submit(new Runnable() { + @Override + public void run() { + synchronized (DefaultChannelPipeline.this) { + replace0(ctx, newName, newCtx); + } + } + }); + } + } + + // Run the following 'waiting' code outside of the above synchronized block + // in order to avoid deadlock + + waitForFuture(future); + + return ctx.handler(); + } + + private void replace0(AbstractChannelHandlerContext oldCtx, String newName, + AbstractChannelHandlerContext newCtx) { + checkMultiplicity(newCtx); + + AbstractChannelHandlerContext prev = oldCtx.prev; + AbstractChannelHandlerContext next = oldCtx.next; + newCtx.prev = prev; + newCtx.next = next; + + // Finish the replacement of oldCtx with newCtx in the linked list. + // Note that this doesn't mean events will be sent to the new handler immediately + // because we are currently at the event handler thread and no more than one handler methods can be invoked + // at the same time (we ensured that in replace().) + prev.next = newCtx; + next.prev = newCtx; + + if (!oldCtx.name().equals(newName)) { + name2ctx.remove(oldCtx.name()); + } + name2ctx.put(newName, newCtx); + + // update the reference to the replacement so forward of buffered content will work correctly + oldCtx.prev = newCtx; + oldCtx.next = newCtx; + + // Invoke newHandler.handlerAdded() first (i.e. before oldHandler.handlerRemoved() is invoked) + // because callHandlerRemoved() will trigger inboundBufferUpdated() or flush() on newHandler and those + // event handlers must be called after handlerAdded(). + callHandlerAdded(newCtx); + callHandlerRemoved(oldCtx); + } + + private static void checkMultiplicity(ChannelHandlerContext ctx) { + ChannelHandler handler = ctx.handler(); + if (handler instanceof ChannelHandlerAdapter) { + ChannelHandlerAdapter h = (ChannelHandlerAdapter) handler; + if (!h.isSharable() && h.added) { + throw new ChannelPipelineException( + h.getClass().getName() + + " is not a @Sharable handler, so can't be added or removed multiple times."); + } + h.added = true; + } + } + + private void callHandlerAdded(final ChannelHandlerContext ctx) { + if (ctx.channel().isRegistered() && !ctx.executor().inEventLoop()) { + ctx.executor().execute(new Runnable() { + @Override + public void run() { + callHandlerAdded0(ctx); + } + }); + return; + } + callHandlerAdded0(ctx); + } + + private void callHandlerAdded0(final ChannelHandlerContext ctx) { + try { + ctx.handler().handlerAdded(ctx); + } catch (Throwable t) { + boolean removed = false; + try { + remove((AbstractChannelHandlerContext) ctx); + removed = true; + } catch (Throwable t2) { + if (logger.isWarnEnabled()) { + logger.warn("Failed to remove a handler: " + ctx.name(), t2); + } + } + + if (removed) { + fireExceptionCaught(new ChannelPipelineException( + ctx.handler().getClass().getName() + + ".handlerAdded() has thrown an exception; removed.", t)); + } else { + fireExceptionCaught(new ChannelPipelineException( + ctx.handler().getClass().getName() + + ".handlerAdded() has thrown an exception; also failed to remove.", t)); + } + } + } + + private void callHandlerRemoved(final AbstractChannelHandlerContext ctx) { + if (ctx.channel().isRegistered() && !ctx.executor().inEventLoop()) { + ctx.executor().execute(new Runnable() { + @Override + public void run() { + callHandlerRemoved0(ctx); + } + }); + return; + } + callHandlerRemoved0(ctx); + } + + private void callHandlerRemoved0(final AbstractChannelHandlerContext ctx) { + // Notify the complete removal. + try { + ctx.handler().handlerRemoved(ctx); + ctx.setRemoved(); + } catch (Throwable t) { + fireExceptionCaught(new ChannelPipelineException( + ctx.handler().getClass().getName() + ".handlerRemoved() has thrown an exception.", t)); + } + } + + /** + * Waits for a future to finish. If the task is interrupted, then the current thread will be interrupted. + * It is expected that the task performs any appropriate locking. + *

+ * If the internal call throws a {@link Throwable}, but it is not an instance of {@link Error} or + * {@link RuntimeException}, then it is wrapped inside a {@link ChannelPipelineException} and that is + * thrown instead.

+ * + * @param future wait for this future + * @see Future#get() + * @throws Error if the task threw this. + * @throws RuntimeException if the task threw this. + * @throws ChannelPipelineException with a {@link Throwable} as a cause, if the task threw another type of + * {@link Throwable}. + */ + private static void waitForFuture(Future future) { + try { + future.get(); + } catch (ExecutionException ex) { + // In the arbitrary case, we can throw Error, RuntimeException, and Exception + Util.throwUnchecked(ex.getCause()); + } catch (InterruptedException ex) { + // Interrupt the calling thread (note that this method is not called from the event loop) + Thread.currentThread().interrupt(); + } + } + + @Override + public ChannelHandler first() { + ChannelHandlerContext first = firstContext(); + if (first == null) { + return null; + } + return first.handler(); + } + + @Override + public ChannelHandlerContext firstContext() { + AbstractChannelHandlerContext first = head.next; + if (first == tail) { + return null; + } + return head.next; + } + + @Override + public ChannelHandler last() { + AbstractChannelHandlerContext last = tail.prev; + if (last == head) { + return null; + } + return last.handler(); + } + + @Override + public ChannelHandlerContext lastContext() { + AbstractChannelHandlerContext last = tail.prev; + if (last == head) { + return null; + } + return last; + } + + @Override + public ChannelHandler get(String name) { + ChannelHandlerContext ctx = context(name); + if (ctx == null) { + return null; + } else { + return ctx.handler(); + } + } + + + @Override + public T get(Class handlerType) { + ChannelHandlerContext ctx = context(handlerType); + if (ctx == null) { + return null; + } else { + return (T) ctx.handler(); + } + } + + @Override + public ChannelHandlerContext context(String name) { + if (name == null) { + throw new NullPointerException("name"); + } + + synchronized (this) { + return name2ctx.get(name); + } + } + + @Override + public ChannelHandlerContext context(ChannelHandler handler) { + if (handler == null) { + throw new NullPointerException("handler"); + } + + AbstractChannelHandlerContext ctx = head.next; + for (;;) { + + if (ctx == null) { + return null; + } + + if (ctx.handler() == handler) { + return ctx; + } + + ctx = ctx.next; + } + } + + @Override + public ChannelHandlerContext context(Class handlerType) { + if (handlerType == null) { + throw new NullPointerException("handlerType"); + } + + AbstractChannelHandlerContext ctx = head.next; + for (;;) { + if (ctx == null) { + return null; + } + if (handlerType.isAssignableFrom(ctx.handler().getClass())) { + return ctx; + } + ctx = ctx.next; + } + } + + @Override + public List names() { + List list = new ArrayList(); + AbstractChannelHandlerContext ctx = head.next; + for (;;) { + if (ctx == null) { + return list; + } + list.add(ctx.name()); + ctx = ctx.next; + } + } + + @Override + public Map toMap() { + Map map = new LinkedHashMap(); + AbstractChannelHandlerContext ctx = head.next; + for (;;) { + if (ctx == tail) { + return map; + } + map.put(ctx.name(), ctx.handler()); + ctx = ctx.next; + } + } + + @Override + public Iterator> iterator() { + return toMap().entrySet().iterator(); + } + + /** + * Returns the {@link String} representation of this pipeline. + */ + @Override + public String toString() { + StringBuilder buf = new StringBuilder(); + buf.append(StringUtil.simpleClassName(this)); + buf.append('{'); + AbstractChannelHandlerContext ctx = head.next; + for (;;) { + if (ctx == tail) { + break; + } + + buf.append('('); + buf.append(ctx.name()); + buf.append(" = "); + buf.append(ctx.handler().getClass().getName()); + buf.append(')'); + + ctx = ctx.next; + if (ctx == tail) { + break; + } + + buf.append(", "); + } + buf.append('}'); + return buf.toString(); + } + + @Override + public ChannelPipeline fireChannelRegistered() { + head.fireChannelRegistered(); + return this; + } + + @Override + public ChannelPipeline fireChannelUnregistered() { + head.fireChannelUnregistered(); + + // Remove all handlers sequentially if channel is closed and unregistered. + if (!channel.isOpen()) { + teardownAll(); + } + return this; + } + + /** + * Removes all handlers from the pipeline one by one from tail (exclusive) to head (inclusive) to trigger + * handlerRemoved(). Note that the tail handler is excluded because it's neither an outbound handler nor it + * does anything in handlerRemoved(). + */ + private void teardownAll() { + tail.prev.teardown(); + } + + @Override + public ChannelPipeline fireChannelActive() { + head.fireChannelActive(); + + if (channel.config().isAutoRead()) { + channel.read(); + } + + return this; + } + + @Override + public ChannelPipeline fireChannelInactive() { + head.fireChannelInactive(); + return this; + } + + @Override + public ChannelPipeline fireExceptionCaught(Throwable cause) { + head.fireExceptionCaught(cause); + return this; + } + + @Override + public ChannelPipeline fireUserEventTriggered(Object event) { + head.fireUserEventTriggered(event); + return this; + } + + @Override + public ChannelPipeline fireChannelRead(Object msg) { + head.fireChannelRead(msg); + return this; + } + + @Override + public ChannelPipeline fireChannelReadComplete() { + head.fireChannelReadComplete(); + if (channel.config().isAutoRead()) { + read(); + } + return this; + } + + @Override + public ChannelPipeline fireChannelWritabilityChanged() { + head.fireChannelWritabilityChanged(); + return this; + } + + @Override + public ChannelFuture bind(SocketAddress localAddress) { + return tail.bind(localAddress); + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress) { + return tail.connect(remoteAddress); + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress) { + return tail.connect(remoteAddress, localAddress); + } + + @Override + public ChannelFuture disconnect() { + return tail.disconnect(); + } + + @Override + public ChannelFuture close() { + return tail.close(); + } + + @Override + public ChannelFuture deregister() { + return tail.deregister(); + } + + @Override + public ChannelPipeline flush() { + tail.flush(); + return this; + } + + @Override + public ChannelFuture bind(SocketAddress localAddress, ChannelPromise promise) { + return tail.bind(localAddress, promise); + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress, ChannelPromise promise) { + return tail.connect(remoteAddress, promise); + } + + @Override + public ChannelFuture connect(SocketAddress remoteAddress, SocketAddress localAddress, ChannelPromise promise) { + return tail.connect(remoteAddress, localAddress, promise); + } + + @Override + public ChannelFuture disconnect(ChannelPromise promise) { + return tail.disconnect(promise); + } + + @Override + public ChannelFuture close(ChannelPromise promise) { + return tail.close(promise); + } + + @Override + public ChannelFuture deregister(final ChannelPromise promise) { + return tail.deregister(promise); + } + + @Override + public ChannelPipeline read() { + tail.read(); + return this; + } + + @Override + public ChannelFuture write(Object msg) { + return tail.write(msg); + } + + @Override + public ChannelFuture write(Object msg, ChannelPromise promise) { + return tail.write(msg, promise); + } + + @Override + public ChannelFuture writeAndFlush(Object msg, ChannelPromise promise) { + return tail.writeAndFlush(msg, promise); + } + + @Override + public ChannelFuture writeAndFlush(Object msg) { + return tail.writeAndFlush(msg); + } + + private void checkDuplicateName(String name) { + if (name2ctx.containsKey(name)) { + throw new IllegalArgumentException("Duplicate handler name: " + name); + } + } + + private AbstractChannelHandlerContext getContextOrDie(String name) { + AbstractChannelHandlerContext ctx = (AbstractChannelHandlerContext) context(name); + if (ctx == null) { + throw new NoSuchElementException(name); + } else { + return ctx; + } + } + + private AbstractChannelHandlerContext getContextOrDie(ChannelHandler handler) { + AbstractChannelHandlerContext ctx = (AbstractChannelHandlerContext) context(handler); + if (ctx == null) { + throw new NoSuchElementException(handler.getClass().getName()); + } else { + return ctx; + } + } + + private AbstractChannelHandlerContext getContextOrDie(Class handlerType) { + AbstractChannelHandlerContext ctx = (AbstractChannelHandlerContext) context(handlerType); + if (ctx == null) { + throw new NoSuchElementException(handlerType.getName()); + } else { + return ctx; + } + } + + // A special catch-all handler that handles both bytes and messages. + static final class TailContext extends AbstractChannelHandlerContext implements ChannelInboundHandler { + + private static final String TAIL_NAME = generateName0(TailContext.class); + + TailContext(DefaultChannelPipeline pipeline) { + super(pipeline, null, TAIL_NAME, true, false); + } + + @Override + public ChannelHandler handler() { + return this; + } + + @Override + public void channelRegistered(ChannelHandlerContext ctx) throws Exception { } + + @Override + public void channelUnregistered(ChannelHandlerContext ctx) throws Exception { } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { } + + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { } + + @Override + public void channelWritabilityChanged(ChannelHandlerContext ctx) throws Exception { } + + @Override + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { } + + @Override + public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { } + + @Override + public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception { } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + logger.warn( + "An exceptionCaught() event was fired, and it reached at the tail of the pipeline. " + + "It usually means the last handler in the pipeline did not handle the exception.", cause); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + try { + logger.debug( + "Discarded inbound message {} that reached at the tail of the pipeline. " + + "Please check your pipeline configuration.", msg); + } finally { + ReferenceCountUtil.release(msg); + } + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { } + } + + static final class HeadContext extends AbstractChannelHandlerContext implements ChannelOutboundHandler { + + private static final String HEAD_NAME = generateName0(HeadContext.class); + + protected final Unsafe unsafe; + + HeadContext(DefaultChannelPipeline pipeline) { + super(pipeline, null, HEAD_NAME, false, true); + unsafe = pipeline.channel().unsafe(); + } + + @Override + public ChannelHandler handler() { + return this; + } + + @Override + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { + // NOOP + } + + @Override + public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { + // NOOP + } + + @Override + public void bind( + ChannelHandlerContext ctx, SocketAddress localAddress, ChannelPromise promise) + throws Exception { + unsafe.bind(localAddress, promise); + } + + @Override + public void connect( + ChannelHandlerContext ctx, + SocketAddress remoteAddress, SocketAddress localAddress, + ChannelPromise promise) throws Exception { + unsafe.connect(remoteAddress, localAddress, promise); + } + + @Override + public void disconnect(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { + unsafe.disconnect(promise); + } + + @Override + public void close(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { + unsafe.close(promise); + } + + @Override + public void deregister(ChannelHandlerContext ctx, ChannelPromise promise) throws Exception { + unsafe.deregister(promise); + } + + @Override + public void read(ChannelHandlerContext ctx) { + unsafe.beginRead(); + } + + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + unsafe.write(msg, promise); + } + + @Override + public void flush(ChannelHandlerContext ctx) throws Exception { + unsafe.flush(); + } + + @Override + public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { + ctx.fireExceptionCaught(cause); + } + } +} diff --git a/common/src/main/java/common/net/channel/DefaultChannelPromise.java b/common/src/main/java/common/net/channel/DefaultChannelPromise.java new file mode 100644 index 0000000..02cc235 --- /dev/null +++ b/common/src/main/java/common/net/channel/DefaultChannelPromise.java @@ -0,0 +1,159 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.util.concurrent.DefaultPromise; +import common.net.util.concurrent.EventExecutor; +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; + +/** + * The default {@link ChannelPromise} implementation. It is recommended to use {@link Channel#newPromise()} to create + * a new {@link ChannelPromise} rather than calling the constructor explicitly. + */ +public class DefaultChannelPromise extends DefaultPromise implements ChannelPromise { + + private final Channel channel; +// private long checkpoint; + + /** + * Creates a new instance. + * + * @param channel + * the {@link Channel} associated with this future + */ + public DefaultChannelPromise(Channel channel) { + this.channel = channel; + } + + /** + * Creates a new instance. + * + * @param channel + * the {@link Channel} associated with this future + */ + public DefaultChannelPromise(Channel channel, EventExecutor executor) { + super(executor); + this.channel = channel; + } + + @Override + protected EventExecutor executor() { + EventExecutor e = super.executor(); + if (e == null) { + return channel().eventLoop(); + } else { + return e; + } + } + + @Override + public Channel channel() { + return channel; + } + + @Override + public ChannelPromise setSuccess() { + return setSuccess(null); + } + + @Override + public ChannelPromise setSuccess(Void result) { + super.setSuccess(result); + return this; + } + + @Override + public boolean trySuccess() { + return trySuccess(null); + } + + @Override + public ChannelPromise setFailure(Throwable cause) { + super.setFailure(cause); + return this; + } + + @Override + public ChannelPromise addListener(GenericFutureListener> listener) { + super.addListener(listener); + return this; + } + + @Override + public ChannelPromise addListeners(GenericFutureListener>... listeners) { + super.addListeners(listeners); + return this; + } + + @Override + public ChannelPromise removeListener(GenericFutureListener> listener) { + super.removeListener(listener); + return this; + } + + @Override + public ChannelPromise removeListeners(GenericFutureListener>... listeners) { + super.removeListeners(listeners); + return this; + } + + @Override + public ChannelPromise sync() throws InterruptedException { + super.sync(); + return this; + } + + @Override + public ChannelPromise syncUninterruptibly() { + super.syncUninterruptibly(); + return this; + } + + @Override + public ChannelPromise await() throws InterruptedException { + super.await(); + return this; + } + + @Override + public ChannelPromise awaitUninterruptibly() { + super.awaitUninterruptibly(); + return this; + } + +// @Override +// public long flushCheckpoint() { +// return checkpoint; +// } + +// @Override +// public void flushCheckpoint(long checkpoint) { +// this.checkpoint = checkpoint; +// } + +// @Override +// public ChannelPromise promise() { +// return this; +// } + + @Override + protected void checkDeadLock() { + if (channel().isRegistered()) { + super.checkDeadLock(); + } + } +} diff --git a/common/src/main/java/common/net/channel/DefaultMessageSizeEstimator.java b/common/src/main/java/common/net/channel/DefaultMessageSizeEstimator.java new file mode 100644 index 0000000..0862e96 --- /dev/null +++ b/common/src/main/java/common/net/channel/DefaultMessageSizeEstimator.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.buffer.ByteBuf; + +/** + * Default {@link MessageSizeEstimator} implementation which supports the estimation of the size of + * {@link ByteBuf}, {@link ByteBufHolder} and {@link FileRegion}. + */ +public final class DefaultMessageSizeEstimator implements MessageSizeEstimator { + + private static final class HandleImpl implements Handle { + private final int unknownSize; + + private HandleImpl(int unknownSize) { + this.unknownSize = unknownSize; + } + + @Override + public int size(Object msg) { + if (msg instanceof ByteBuf) { + return ((ByteBuf) msg).readableBytes(); + } +// if (msg instanceof ByteBufHolder) { +// return ((ByteBufHolder) msg).content().readableBytes(); +// } +// if (msg instanceof FileRegion) { +// return 0; +// } + return unknownSize; + } + } + + /** + * Return the default implementation which returns {@code -1} for unknown messages. + */ + public static final MessageSizeEstimator DEFAULT = new DefaultMessageSizeEstimator(0); + + private final Handle handle; + + /** + * Create a new instance + * + * @param unknownSize The size which is returned for unknown messages. + */ + public DefaultMessageSizeEstimator(int unknownSize) { + if (unknownSize < 0) { + throw new IllegalArgumentException("unknownSize: " + unknownSize + " (expected: >= 0)"); + } + handle = new HandleImpl(unknownSize); + } + + @Override + public Handle newHandle() { + return handle; + } +} diff --git a/common/src/main/java/common/net/channel/EventLoop.java b/common/src/main/java/common/net/channel/EventLoop.java new file mode 100644 index 0000000..8daea7a --- /dev/null +++ b/common/src/main/java/common/net/channel/EventLoop.java @@ -0,0 +1,30 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.util.concurrent.EventExecutor; + +/** + * Will handle all the I/O-Operations for a {@link Channel} once it was registered. + * + * One {@link EventLoop} instance will usually handle more then one {@link Channel} but this may depend on + * implementation details and internals. + * + */ +public interface EventLoop extends EventExecutor, EventLoopGroup { + @Override + EventLoopGroup parent(); +} diff --git a/common/src/main/java/common/net/channel/EventLoopException.java b/common/src/main/java/common/net/channel/EventLoopException.java new file mode 100644 index 0000000..02f9ffa --- /dev/null +++ b/common/src/main/java/common/net/channel/EventLoopException.java @@ -0,0 +1,41 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +/** + * Special {@link ChannelException} which will be thrown by {@link EventLoop} and {@link EventLoopGroup} + * implementations when an error occurs. + */ +public class EventLoopException extends ChannelException { + + private static final long serialVersionUID = -8969100344583703616L; + + public EventLoopException() { + } + + public EventLoopException(String message, Throwable cause) { + super(message, cause); + } + + public EventLoopException(String message) { + super(message); + } + + public EventLoopException(Throwable cause) { + super(cause); + } + +} diff --git a/common/src/main/java/common/net/channel/EventLoopGroup.java b/common/src/main/java/common/net/channel/EventLoopGroup.java new file mode 100644 index 0000000..e058491 --- /dev/null +++ b/common/src/main/java/common/net/channel/EventLoopGroup.java @@ -0,0 +1,43 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.util.concurrent.EventExecutorGroup; + +/** + * Special {@link EventExecutorGroup} which allows to register {@link Channel}'s that get + * processed for later selection during the event loop. + * + */ +public interface EventLoopGroup extends EventExecutorGroup { + /** + * Return the next {@link EventLoop} to use + */ + @Override + EventLoop next(); + + /** + * Register a {@link Channel} with this {@link EventLoop}. The returned {@link ChannelFuture} + * will get notified once the registration was complete. + */ + ChannelFuture register(Channel channel); + + /** + * Register a {@link Channel} with this {@link EventLoop}. The passed {@link ChannelFuture} + * will get notified once the registration was complete and also will get returned. + */ + ChannelFuture register(Channel channel, ChannelPromise promise); +} diff --git a/common/src/main/java/common/net/channel/FailedChannelFuture.java b/common/src/main/java/common/net/channel/FailedChannelFuture.java new file mode 100644 index 0000000..f357ae5 --- /dev/null +++ b/common/src/main/java/common/net/channel/FailedChannelFuture.java @@ -0,0 +1,65 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.util.concurrent.EventExecutor; +import common.util.Util; + +/** + * The {@link CompleteChannelFuture} which is failed already. It is + * recommended to use {@link Channel#newFailedFuture(Throwable)} + * instead of calling the constructor of this future. + */ +final class FailedChannelFuture extends CompleteChannelFuture { + + private final Throwable cause; + + /** + * Creates a new instance. + * + * @param channel the {@link Channel} associated with this future + * @param cause the cause of failure + */ + FailedChannelFuture(Channel channel, EventExecutor executor, Throwable cause) { + super(channel, executor); + if (cause == null) { + throw new NullPointerException("cause"); + } + this.cause = cause; + } + + @Override + public Throwable cause() { + return cause; + } + + @Override + public boolean isSuccess() { + return false; + } + + @Override + public ChannelFuture sync() { + Util.throwUnchecked(cause); + return this; + } + + @Override + public ChannelFuture syncUninterruptibly() { + Util.throwUnchecked(cause); + return this; + } +} diff --git a/common/src/main/java/common/net/channel/MessageSizeEstimator.java b/common/src/main/java/common/net/channel/MessageSizeEstimator.java new file mode 100644 index 0000000..cdefc87 --- /dev/null +++ b/common/src/main/java/common/net/channel/MessageSizeEstimator.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +/** + * Responsible to estimate size of a message. The size represent how much memory the message will ca. reserve in + * memory. + */ +public interface MessageSizeEstimator { + + /** + * Creates a new handle. The handle provides the actual operations. + */ + Handle newHandle(); + + interface Handle { + + /** + * Calculate the size of the given message. + * + * @param msg The message for which the size should be calculated + * @return size The size in bytes. The returned size must be >= 0 + */ + int size(Object msg); + } +} diff --git a/common/src/main/java/common/net/channel/MultithreadEventLoopGroup.java b/common/src/main/java/common/net/channel/MultithreadEventLoopGroup.java new file mode 100644 index 0000000..0a5f4e1 --- /dev/null +++ b/common/src/main/java/common/net/channel/MultithreadEventLoopGroup.java @@ -0,0 +1,71 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.util.concurrent.ThreadFactory; + +import common.net.util.concurrent.DefaultThreadFactory; +import common.net.util.concurrent.MultithreadEventExecutorGroup; +import common.net.util.internal.SystemPropertyUtil; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * Abstract base class for {@link EventLoopGroup} implementations that handles their tasks with multiple threads at + * the same time. + */ +public abstract class MultithreadEventLoopGroup extends MultithreadEventExecutorGroup implements EventLoopGroup { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(MultithreadEventLoopGroup.class); + + private static final int DEFAULT_EVENT_LOOP_THREADS; + + static { + DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt( + "game.net.eventLoopThreads", Runtime.getRuntime().availableProcessors() * 2)); + + if (logger.isDebugEnabled()) { + logger.debug("-Dgame.net.eventLoopThreads: {}", DEFAULT_EVENT_LOOP_THREADS); + } + } + + /** + * @see {@link MultithreadEventExecutorGroup#MultithreadEventExecutorGroup(int, ThreadFactory, Object...)} + */ + protected MultithreadEventLoopGroup(int nThreads, ThreadFactory threadFactory, Object... args) { + super(nThreads == 0? DEFAULT_EVENT_LOOP_THREADS : nThreads, threadFactory, args); + } + + @Override + protected ThreadFactory newDefaultThreadFactory() { + return new DefaultThreadFactory(getClass(), Thread.MAX_PRIORITY); + } + + @Override + public EventLoop next() { + return (EventLoop) super.next(); + } + + @Override + public ChannelFuture register(Channel channel) { + return next().register(channel); + } + + @Override + public ChannelFuture register(Channel channel, ChannelPromise promise) { + return next().register(channel, promise); + } +} diff --git a/common/src/main/java/common/net/channel/RecvByteBufAllocator.java b/common/src/main/java/common/net/channel/RecvByteBufAllocator.java new file mode 100644 index 0000000..f90ff3f --- /dev/null +++ b/common/src/main/java/common/net/channel/RecvByteBufAllocator.java @@ -0,0 +1,54 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.buffer.ByteBuf; +import common.net.buffer.ByteBufAllocator; + +/** + * Allocates a new receive buffer whose capacity is probably large enough to read all inbound data and small enough + * not to waste its space. + */ +public interface RecvByteBufAllocator { + + /** + * Creates a new handle. The handle provides the actual operations and keeps the internal information which is + * required for predicting an optimal buffer capacity. + */ + Handle newHandle(); + + interface Handle { + /** + * Creates a new receive buffer whose capacity is probably large enough to read all inbound data and small + * enough not to waste its space. + */ + ByteBuf allocate(ByteBufAllocator alloc); + + /** + * Similar to {@link #allocate(ByteBufAllocator)} except that it does not allocate anything but just tells the + * capacity. + */ + int guess(); + + /** + * Records the the actual number of read bytes in the previous read operation so that the allocator allocates + * the buffer with potentially more correct capacity. + * + * @param actualReadBytes the actual number of read bytes in the previous read operation + */ + void record(int actualReadBytes); + } +} diff --git a/common/src/main/java/common/net/channel/ServerChannel.java b/common/src/main/java/common/net/channel/ServerChannel.java new file mode 100644 index 0000000..7dedcaa --- /dev/null +++ b/common/src/main/java/common/net/channel/ServerChannel.java @@ -0,0 +1,25 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +/** + * A {@link Channel} that accepts an incoming connection attempt and creates + * its child {@link Channel}s by accepting them. {@link ServerSocketChannel} is + * a good example. + */ +public interface ServerChannel extends Channel { + // This is a tag interface. +} diff --git a/common/src/main/java/common/net/channel/SimpleChannelInboundHandler.java b/common/src/main/java/common/net/channel/SimpleChannelInboundHandler.java new file mode 100644 index 0000000..68b003e --- /dev/null +++ b/common/src/main/java/common/net/channel/SimpleChannelInboundHandler.java @@ -0,0 +1,129 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.util.ReferenceCountUtil; +import common.net.util.internal.TypeParameterMatcher; + +/** + * {@link ChannelInboundHandlerAdapter} which allows to explicit only handle a specific type of messages. + * + * For example here is an implementation which only handle {@link String} messages. + * + *
+ *     public class StringHandler extends
+ *             {@link SimpleChannelInboundHandler}<{@link String}> {
+ *
+ *         {@code @Override}
+ *         protected void channelRead0({@link ChannelHandlerContext} ctx, {@link String} message)
+ *                 throws {@link Exception} {
+ *             System.out.println(message);
+ *         }
+ *     }
+ * 
+ * + * Be aware that depending of the constructor parameters it will release all handled messages by pass them to + * {@link ReferenceCountUtil#release(Object)}. In this case you may need to use + * {@link ReferenceCountUtil#retain(Object)} if you pass the object to the next handler in the {@link ChannelPipeline}. + * + *

Forward compatibility notice

+ *

+ * Please keep in mind that {@link #channelRead0(ChannelHandlerContext, I)} will be renamed to + * {@code messageReceived(ChannelHandlerContext, I)} in 5.0. + *

+ */ +public abstract class SimpleChannelInboundHandler extends ChannelInboundHandlerAdapter { + + private final TypeParameterMatcher matcher; + private final boolean autoRelease; + + /** + * @see {@link #SimpleChannelInboundHandler(boolean)} with {@code true} as boolean parameter. + */ + protected SimpleChannelInboundHandler() { + this(true); + } + + /** + * Create a new instance which will try to detect the types to match out of the type parameter of the class. + * + * @param autoRelease {@code true} if handled messages should be released automatically by pass them to + * {@link ReferenceCountUtil#release(Object)}. + */ + protected SimpleChannelInboundHandler(boolean autoRelease) { + matcher = TypeParameterMatcher.find(this, SimpleChannelInboundHandler.class, "I"); + this.autoRelease = autoRelease; + } + + /** + * @see {@link #SimpleChannelInboundHandler(Class, boolean)} with {@code true} as boolean value. + */ + protected SimpleChannelInboundHandler(Class inboundMessageType) { + this(inboundMessageType, true); + } + + /** + * Create a new instance + * + * @param inboundMessageType The type of messages to match + * @param autoRelease {@code true} if handled messages should be released automatically by pass them to + * {@link ReferenceCountUtil#release(Object)}. + */ + protected SimpleChannelInboundHandler(Class inboundMessageType, boolean autoRelease) { + matcher = TypeParameterMatcher.get(inboundMessageType); + this.autoRelease = autoRelease; + } + + /** + * Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next + * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + */ + public boolean acceptInboundMessage(Object msg) throws Exception { + return matcher.match(msg); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + boolean release = true; + try { + if (acceptInboundMessage(msg)) { + + I imsg = (I) msg; + channelRead0(ctx, imsg); + } else { + release = false; + ctx.fireChannelRead(msg); + } + } finally { + if (autoRelease && release) { + ReferenceCountUtil.release(msg); + } + } + } + + /** + * Please keep in mind that this method will be renamed to + * {@code messageReceived(ChannelHandlerContext, I)} in 5.0. + * + * Is called for each message of type {@link I}. + * + * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler} + * belongs to + * @param msg the message to handle + * @throws Exception is thrown if an error occurred + */ + protected abstract void channelRead0(ChannelHandlerContext ctx, I msg) throws Exception; +} diff --git a/common/src/main/java/common/net/channel/SingleThreadEventLoop.java b/common/src/main/java/common/net/channel/SingleThreadEventLoop.java new file mode 100644 index 0000000..ed45956 --- /dev/null +++ b/common/src/main/java/common/net/channel/SingleThreadEventLoop.java @@ -0,0 +1,72 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.util.concurrent.ThreadFactory; + +import common.net.util.concurrent.SingleThreadEventExecutor; + +/** + * Abstract base class for {@link EventLoop}'s that execute all its submitted tasks in a single thread. + * + */ +public abstract class SingleThreadEventLoop extends SingleThreadEventExecutor implements EventLoop { + + /** + * @see {@link SingleThreadEventExecutor#SingleThreadEventExecutor(EventExecutorGroup, ThreadFactory, boolean)} + */ + protected SingleThreadEventLoop(EventLoopGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp) { + super(parent, threadFactory, addTaskWakesUp); + } + + @Override + public EventLoopGroup parent() { + return (EventLoopGroup) super.parent(); + } + + @Override + public EventLoop next() { + return (EventLoop) super.next(); + } + + @Override + public ChannelFuture register(Channel channel) { + return register(channel, new DefaultChannelPromise(channel, this)); + } + + @Override + public ChannelFuture register(final Channel channel, final ChannelPromise promise) { + if (channel == null) { + throw new NullPointerException("channel"); + } + if (promise == null) { + throw new NullPointerException("promise"); + } + + channel.unsafe().register(this, promise); + return promise; + } + + @Override + protected boolean wakesUpForTask(Runnable task) { + return !(task instanceof NonWakeupRunnable); + } + + /** + * Marker interface for {@linkRunnable} that will not trigger an {@link #wakeup(boolean)} in all cases. + */ + interface NonWakeupRunnable extends Runnable { } +} diff --git a/common/src/main/java/common/net/channel/SucceededChannelFuture.java b/common/src/main/java/common/net/channel/SucceededChannelFuture.java new file mode 100644 index 0000000..f2fafea --- /dev/null +++ b/common/src/main/java/common/net/channel/SucceededChannelFuture.java @@ -0,0 +1,45 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import common.net.util.concurrent.EventExecutor; + +/** + * The {@link CompleteChannelFuture} which is succeeded already. It is + * recommended to use {@link Channel#newSucceededFuture()} instead of + * calling the constructor of this future. + */ +final class SucceededChannelFuture extends CompleteChannelFuture { + + /** + * Creates a new instance. + * + * @param channel the {@link Channel} associated with this future + */ + SucceededChannelFuture(Channel channel, EventExecutor executor) { + super(channel, executor); + } + + @Override + public Throwable cause() { + return null; + } + + @Override + public boolean isSuccess() { + return true; + } +} diff --git a/common/src/main/java/common/net/channel/VoidChannelPromise.java b/common/src/main/java/common/net/channel/VoidChannelPromise.java new file mode 100644 index 0000000..1fcbb12 --- /dev/null +++ b/common/src/main/java/common/net/channel/VoidChannelPromise.java @@ -0,0 +1,205 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel; + +import java.util.concurrent.TimeUnit; + +import common.net.util.concurrent.AbstractFuture; +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; + +final class VoidChannelPromise extends AbstractFuture implements ChannelPromise { + + private final Channel channel; + private final boolean fireException; + + /** + * Creates a new instance. + * + * @param channel the {@link Channel} associated with this future + */ + VoidChannelPromise(Channel channel, boolean fireException) { + if (channel == null) { + throw new NullPointerException("channel"); + } + this.channel = channel; + this.fireException = fireException; + } + + @Override + public VoidChannelPromise addListener(GenericFutureListener> listener) { + fail(); + return this; + } + + @Override + public VoidChannelPromise addListeners(GenericFutureListener>... listeners) { + fail(); + return this; + } + + @Override + public VoidChannelPromise removeListener(GenericFutureListener> listener) { + // NOOP + return this; + } + + @Override + public VoidChannelPromise removeListeners(GenericFutureListener>... listeners) { + // NOOP + return this; + } + + @Override + public VoidChannelPromise await() throws InterruptedException { + if (Thread.interrupted()) { + throw new InterruptedException(); + } + return this; + } + + @Override + public boolean await(long timeout, TimeUnit unit) { + fail(); + return false; + } + + @Override + public boolean await(long timeoutMillis) { + fail(); + return false; + } + + @Override + public VoidChannelPromise awaitUninterruptibly() { + fail(); + return this; + } + + @Override + public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { + fail(); + return false; + } + + @Override + public boolean awaitUninterruptibly(long timeoutMillis) { + fail(); + return false; + } + + @Override + public Channel channel() { + return channel; + } + + @Override + public boolean isDone() { + return false; + } + + @Override + public boolean isSuccess() { + return false; + } + + @Override + public boolean setUncancellable() { + return true; + } + + @Override + public boolean isCancellable() { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public Throwable cause() { + return null; + } + + @Override + public VoidChannelPromise sync() { + fail(); + return this; + } + + @Override + public VoidChannelPromise syncUninterruptibly() { + fail(); + return this; + } + @Override + public VoidChannelPromise setFailure(Throwable cause) { + fireException(cause); + return this; + } + + @Override + public VoidChannelPromise setSuccess() { + return this; + } + + @Override + public boolean tryFailure(Throwable cause) { + fireException(cause); + return false; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } + + @Override + public boolean trySuccess() { + return false; + } + + private static void fail() { + throw new IllegalStateException("void future"); + } + + @Override + public VoidChannelPromise setSuccess(Void result) { + return this; + } + + @Override + public boolean trySuccess(Void result) { + return false; + } + + @Override + public Void getNow() { + return null; + } + + private void fireException(Throwable cause) { + // Only fire the exception if the channel is open and registered + // if not the pipeline is not setup and so it would hit the tail + // of the pipeline. + // See https://github.com/netty/netty/issues/1517 + if (fireException && channel.isRegistered()) { + channel.pipeline().fireExceptionCaught(cause); + } + } +} diff --git a/common/src/main/java/common/net/channel/local/LocalAddress.java b/common/src/main/java/common/net/channel/local/LocalAddress.java new file mode 100644 index 0000000..95f6e43 --- /dev/null +++ b/common/src/main/java/common/net/channel/local/LocalAddress.java @@ -0,0 +1,94 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.local; + +import java.net.SocketAddress; + +import common.net.channel.Channel; + +/** + * An endpoint in the local transport. Each endpoint is identified by a unique + * case-insensitive string. + */ +public final class LocalAddress extends SocketAddress implements Comparable { + + private static final long serialVersionUID = 4644331421130916435L; + + public static final LocalAddress ANY = new LocalAddress("ANY"); + + private final String id; + private final String strVal; + + /** + * Creates a new ephemeral port based on the ID of the specified channel. + * Note that we prepend an upper-case character so that it never conflicts with + * the addresses created by a user, which are always lower-cased on construction time. + */ + LocalAddress(Channel channel) { + StringBuilder buf = new StringBuilder(16); + buf.append("local:E"); + buf.append(Long.toHexString(channel.hashCode() & 0xFFFFFFFFL | 0x100000000L)); + buf.setCharAt(7, ':'); + id = buf.substring(6); + strVal = buf.toString(); + } + + /** + * Creates a new instance with the specified ID. + */ + public LocalAddress(String id) { + if (id == null) { + throw new NullPointerException("id"); + } + id = id.trim().toLowerCase(); + if (id.isEmpty()) { + throw new IllegalArgumentException("empty id"); + } + this.id = id; + strVal = "local:" + id; + } + + /** + * Returns the ID of this address. + */ + public String id() { + return id; + } + + @Override + public int hashCode() { + return id.hashCode(); + } + + @Override + public boolean equals(Object o) { + if (!(o instanceof LocalAddress)) { + return false; + } + + return id.equals(((LocalAddress) o).id); + } + + @Override + public int compareTo(LocalAddress o) { + return id.compareTo(o.id); + } + + @Override + public String toString() { + return strVal; + } +} diff --git a/common/src/main/java/common/net/channel/local/LocalChannel.java b/common/src/main/java/common/net/channel/local/LocalChannel.java new file mode 100644 index 0000000..c5590c9 --- /dev/null +++ b/common/src/main/java/common/net/channel/local/LocalChannel.java @@ -0,0 +1,383 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.local; + +import java.net.SocketAddress; +import java.nio.channels.AlreadyConnectedException; +import java.nio.channels.ClosedChannelException; +import java.nio.channels.ConnectionPendingException; +import java.nio.channels.NotYetConnectedException; +import java.util.ArrayDeque; +import java.util.Collections; +import java.util.Queue; + +import common.net.channel.AbstractChannel; +import common.net.channel.Channel; +import common.net.channel.ChannelConfig; +import common.net.channel.ChannelException; +import common.net.channel.ChannelMetadata; +import common.net.channel.ChannelOutboundBuffer; +import common.net.channel.ChannelPipeline; +import common.net.channel.ChannelPromise; +import common.net.channel.DefaultChannelConfig; +import common.net.channel.EventLoop; +import common.net.channel.SingleThreadEventLoop; +import common.net.util.ReferenceCountUtil; +import common.net.util.concurrent.SingleThreadEventExecutor; +import common.net.util.internal.InternalThreadLocalMap; + +/** + * A {@link Channel} for the local transport. + */ +public class LocalChannel extends AbstractChannel { + + private static final ChannelMetadata METADATA = new ChannelMetadata(false); + + private static final int MAX_READER_STACK_DEPTH = 8; + + private final ChannelConfig config = new DefaultChannelConfig(this); + private final Queue inboundBuffer = new ArrayDeque(); + private final Runnable readTask = new Runnable() { + @Override + public void run() { + ChannelPipeline pipeline = pipeline(); + for (;;) { + Object m = inboundBuffer.poll(); + if (m == null) { + break; + } + pipeline.fireChannelRead(m); + } + pipeline.fireChannelReadComplete(); + } + }; + + private final Runnable shutdownHook = new Runnable() { + @Override + public void run() { + unsafe().close(unsafe().voidPromise()); + } + }; + + private volatile int state; // 0 - open, 1 - bound, 2 - connected, 3 - closed + private volatile LocalChannel peer; + private volatile LocalAddress localAddress; + private volatile LocalAddress remoteAddress; + private volatile ChannelPromise connectPromise; + private volatile boolean readInProgress; + private volatile boolean registerInProgress; + + public LocalChannel() { + super(null); + } + + LocalChannel(LocalServerChannel parent, LocalChannel peer) { + super(parent); + this.peer = peer; + localAddress = parent.localAddress(); + remoteAddress = peer.localAddress(); + } + + @Override + public ChannelMetadata metadata() { + return METADATA; + } + + @Override + public ChannelConfig config() { + return config; + } + + @Override + public LocalServerChannel parent() { + return (LocalServerChannel) super.parent(); + } + + @Override + public LocalAddress localAddress() { + return (LocalAddress) super.localAddress(); + } + + @Override + public LocalAddress remoteAddress() { + return (LocalAddress) super.remoteAddress(); + } + + @Override + public boolean isOpen() { + return state < 3; + } + + @Override + public boolean isActive() { + return state == 2; + } + + @Override + protected AbstractUnsafe newUnsafe() { + return new LocalUnsafe(); + } + + @Override + protected boolean isCompatible(EventLoop loop) { + return loop instanceof SingleThreadEventLoop; + } + + @Override + protected SocketAddress localAddress0() { + return localAddress; + } + + @Override + protected SocketAddress remoteAddress0() { + return remoteAddress; + } + + @Override + protected void doRegister() throws Exception { + // Check if both peer and parent are non-null because this channel was created by a LocalServerChannel. + // This is needed as a peer may not be null also if a LocalChannel was connected before and + // deregistered / registered later again. + // + // See https://github.com/netty/netty/issues/2400 + if (peer != null && parent() != null) { + // Store the peer in a local variable as it may be set to null if doClose() is called. + // Because of this we also set registerInProgress to true as we check for this in doClose() and make sure + // we delay the fireChannelInactive() to be fired after the fireChannelActive() and so keep the correct + // order of events. + // + // See https://github.com/netty/netty/issues/2144 + final LocalChannel peer = this.peer; + registerInProgress = true; + state = 2; + + peer.remoteAddress = parent().localAddress(); + peer.state = 2; + + // Always call peer.eventLoop().execute() even if peer.eventLoop().inEventLoop() is true. + // This ensures that if both channels are on the same event loop, the peer's channelActive + // event is triggered *after* this channel's channelRegistered event, so that this channel's + // pipeline is fully initialized by ChannelInitializer before any channelRead events. + peer.eventLoop().execute(new Runnable() { + @Override + public void run() { + registerInProgress = false; + peer.pipeline().fireChannelActive(); + peer.connectPromise.setSuccess(); + } + }); + } + ((SingleThreadEventExecutor) eventLoop()).addShutdownHook(shutdownHook); + } + + @Override + protected void doBind(SocketAddress localAddress) throws Exception { + this.localAddress = + LocalChannelRegistry.register(this, this.localAddress, + localAddress); + state = 1; + } + + @Override + protected void doDisconnect() throws Exception { + doClose(); + } + + @Override + protected void doClose() throws Exception { + if (state <= 2) { + // Update all internal state before the closeFuture is notified. + if (localAddress != null) { + if (parent() == null) { + LocalChannelRegistry.unregister(localAddress); + } + localAddress = null; + } + state = 3; + } + + final LocalChannel peer = this.peer; + if (peer != null && peer.isActive()) { + // Need to execute the close in the correct EventLoop + // See https://github.com/netty/netty/issues/1777 + EventLoop eventLoop = peer.eventLoop(); + + // Also check if the registration was not done yet. In this case we submit the close to the EventLoop + // to make sure it is run after the registration completes. + // + // See https://github.com/netty/netty/issues/2144 + if (eventLoop.inEventLoop() && !registerInProgress) { + peer.unsafe().close(unsafe().voidPromise()); + } else { + peer.eventLoop().execute(new Runnable() { + @Override + public void run() { + peer.unsafe().close(unsafe().voidPromise()); + } + }); + } + this.peer = null; + } + } + + @Override + protected void doDeregister() throws Exception { + // Just remove the shutdownHook as this Channel may be closed later or registered to another EventLoop + ((SingleThreadEventExecutor) eventLoop()).removeShutdownHook(shutdownHook); + } + + @Override + protected void doBeginRead() throws Exception { + if (readInProgress) { + return; + } + + ChannelPipeline pipeline = pipeline(); + Queue inboundBuffer = this.inboundBuffer; + if (inboundBuffer.isEmpty()) { + readInProgress = true; + return; + } + + final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get(); + final Integer stackDepth = threadLocals.localChannelReaderStackDepth(); + if (stackDepth < MAX_READER_STACK_DEPTH) { + threadLocals.setLocalChannelReaderStackDepth(stackDepth + 1); + try { + for (;;) { + Object received = inboundBuffer.poll(); + if (received == null) { + break; + } + pipeline.fireChannelRead(received); + } + pipeline.fireChannelReadComplete(); + } finally { + threadLocals.setLocalChannelReaderStackDepth(stackDepth); + } + } else { + eventLoop().execute(readTask); + } + } + + @Override + protected void doWrite(ChannelOutboundBuffer in) throws Exception { + if (state < 2) { + throw new NotYetConnectedException(); + } + if (state > 2) { + throw new ClosedChannelException(); + } + + final LocalChannel peer = this.peer; + final ChannelPipeline peerPipeline = peer.pipeline(); + final EventLoop peerLoop = peer.eventLoop(); + + if (peerLoop == eventLoop()) { + for (;;) { + Object msg = in.current(); + if (msg == null) { + break; + } + peer.inboundBuffer.add(msg); + ReferenceCountUtil.retain(msg); + in.remove(); + } + finishPeerRead(peer, peerPipeline); + } else { + // Use a copy because the original msgs will be recycled by AbstractChannel. + final Object[] msgsCopy = new Object[in.size()]; + for (int i = 0; i < msgsCopy.length; i ++) { + msgsCopy[i] = ReferenceCountUtil.retain(in.current()); + in.remove(); + } + + peerLoop.execute(new Runnable() { + @Override + public void run() { + Collections.addAll(peer.inboundBuffer, msgsCopy); + finishPeerRead(peer, peerPipeline); + } + }); + } + } + + private static void finishPeerRead(LocalChannel peer, ChannelPipeline peerPipeline) { + if (peer.readInProgress) { + peer.readInProgress = false; + for (;;) { + Object received = peer.inboundBuffer.poll(); + if (received == null) { + break; + } + peerPipeline.fireChannelRead(received); + } + peerPipeline.fireChannelReadComplete(); + } + } + + private class LocalUnsafe extends AbstractUnsafe { + + @Override + public void connect(final SocketAddress remoteAddress, + SocketAddress localAddress, final ChannelPromise promise) { + if (!promise.setUncancellable() || !ensureOpen(promise)) { + return; + } + + if (state == 2) { + Exception cause = new AlreadyConnectedException(); + safeSetFailure(promise, cause); + pipeline().fireExceptionCaught(cause); + return; + } + + if (connectPromise != null) { + throw new ConnectionPendingException(); + } + + connectPromise = promise; + + if (state != 1) { + // Not bound yet and no localAddress specified - get one. + if (localAddress == null) { + localAddress = new LocalAddress(LocalChannel.this); + } + } + + if (localAddress != null) { + try { + doBind(localAddress); + } catch (Throwable t) { + safeSetFailure(promise, t); + close(voidPromise()); + return; + } + } + + Channel boundChannel = LocalChannelRegistry.get(remoteAddress); + if (!(boundChannel instanceof LocalServerChannel)) { + Exception cause = new ChannelException("connection refused"); + safeSetFailure(promise, cause); + close(voidPromise()); + return; + } + + LocalServerChannel serverChannel = (LocalServerChannel) boundChannel; + peer = serverChannel.serve(LocalChannel.this); + } + } +} diff --git a/common/src/main/java/common/net/channel/local/LocalChannelRegistry.java b/common/src/main/java/common/net/channel/local/LocalChannelRegistry.java new file mode 100644 index 0000000..4fc5b82 --- /dev/null +++ b/common/src/main/java/common/net/channel/local/LocalChannelRegistry.java @@ -0,0 +1,62 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.local; + +import java.net.SocketAddress; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +import common.net.channel.Channel; +import common.net.channel.ChannelException; +import common.net.util.internal.StringUtil; + +final class LocalChannelRegistry { + + private static final ConcurrentMap boundChannels = new ConcurrentHashMap(); + + static LocalAddress register( + Channel channel, LocalAddress oldLocalAddress, SocketAddress localAddress) { + if (oldLocalAddress != null) { + throw new ChannelException("already bound"); + } + if (!(localAddress instanceof LocalAddress)) { + throw new ChannelException("unsupported address type: " + StringUtil.simpleClassName(localAddress)); + } + + LocalAddress addr = (LocalAddress) localAddress; + if (LocalAddress.ANY.equals(addr)) { + addr = new LocalAddress(channel); + } + + Channel boundChannel = boundChannels.putIfAbsent(addr, channel); + if (boundChannel != null) { + throw new ChannelException("address already in use by: " + boundChannel); + } + return addr; + } + + static Channel get(SocketAddress localAddress) { + return boundChannels.get(localAddress); + } + + static void unregister(LocalAddress localAddress) { + boundChannels.remove(localAddress); + } + + private LocalChannelRegistry() { + // Unused + } +} diff --git a/common/src/main/java/common/net/channel/local/LocalEventLoop.java b/common/src/main/java/common/net/channel/local/LocalEventLoop.java new file mode 100644 index 0000000..4bf1b89 --- /dev/null +++ b/common/src/main/java/common/net/channel/local/LocalEventLoop.java @@ -0,0 +1,42 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.local; + +import java.util.concurrent.ThreadFactory; + +import common.net.channel.SingleThreadEventLoop; + +final class LocalEventLoop extends SingleThreadEventLoop { + + LocalEventLoop(LocalEventLoopGroup parent, ThreadFactory threadFactory) { + super(parent, threadFactory, true); + } + + @Override + protected void run() { + for (;;) { + Runnable task = takeTask(); + if (task != null) { + task.run(); + updateLastExecutionTime(); + } + + if (confirmShutdown()) { + break; + } + } + } +} diff --git a/common/src/main/java/common/net/channel/local/LocalEventLoopGroup.java b/common/src/main/java/common/net/channel/local/LocalEventLoopGroup.java new file mode 100644 index 0000000..7f58c98 --- /dev/null +++ b/common/src/main/java/common/net/channel/local/LocalEventLoopGroup.java @@ -0,0 +1,59 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.local; + +import java.util.concurrent.ThreadFactory; + +import common.net.channel.MultithreadEventLoopGroup; +import common.net.util.concurrent.EventExecutor; + +/** + * {@link MultithreadEventLoopGroup} which must be used for the local transport. + */ +public class LocalEventLoopGroup extends MultithreadEventLoopGroup { + + /** + * Create a new instance with the default number of threads. + */ + public LocalEventLoopGroup() { + this(0); + } + + /** + * Create a new instance + * + * @param nThreads the number of threads to use + */ + public LocalEventLoopGroup(int nThreads) { + this(nThreads, null); + } + + /** + * Create a new instance + * + * @param nThreads the number of threads to use + * @param threadFactory the {@link ThreadFactory} or {@code null} to use the default + */ + public LocalEventLoopGroup(int nThreads, ThreadFactory threadFactory) { + super(nThreads, threadFactory); + } + + @Override + protected EventExecutor newChild( + ThreadFactory threadFactory, Object... args) throws Exception { + return new LocalEventLoop(this, threadFactory); + } +} diff --git a/common/src/main/java/common/net/channel/local/LocalServerChannel.java b/common/src/main/java/common/net/channel/local/LocalServerChannel.java new file mode 100644 index 0000000..557f526 --- /dev/null +++ b/common/src/main/java/common/net/channel/local/LocalServerChannel.java @@ -0,0 +1,164 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.local; + +import java.net.SocketAddress; +import java.util.ArrayDeque; +import java.util.Queue; + +import common.net.channel.AbstractServerChannel; +import common.net.channel.ChannelConfig; +import common.net.channel.ChannelPipeline; +import common.net.channel.DefaultChannelConfig; +import common.net.channel.EventLoop; +import common.net.channel.SingleThreadEventLoop; +import common.net.util.concurrent.SingleThreadEventExecutor; + +/** + * A {@link ServerChannel} for the local transport which allows in VM communication. + */ +public class LocalServerChannel extends AbstractServerChannel { + + private final ChannelConfig config = new DefaultChannelConfig(this); + private final Queue inboundBuffer = new ArrayDeque(); + private final Runnable shutdownHook = new Runnable() { + @Override + public void run() { + unsafe().close(unsafe().voidPromise()); + } + }; + + private volatile int state; // 0 - open, 1 - active, 2 - closed + private volatile LocalAddress localAddress; + private volatile boolean acceptInProgress; + + @Override + public ChannelConfig config() { + return config; + } + + @Override + public LocalAddress localAddress() { + return (LocalAddress) super.localAddress(); + } + + @Override + public LocalAddress remoteAddress() { + return (LocalAddress) super.remoteAddress(); + } + + @Override + public boolean isOpen() { + return state < 2; + } + + @Override + public boolean isActive() { + return state == 1; + } + + @Override + protected boolean isCompatible(EventLoop loop) { + return loop instanceof SingleThreadEventLoop; + } + + @Override + protected SocketAddress localAddress0() { + return localAddress; + } + + @Override + protected void doRegister() throws Exception { + ((SingleThreadEventExecutor) eventLoop()).addShutdownHook(shutdownHook); + } + + @Override + protected void doBind(SocketAddress localAddress) throws Exception { + this.localAddress = LocalChannelRegistry.register(this, this.localAddress, localAddress); + state = 1; + } + + @Override + protected void doClose() throws Exception { + if (state <= 1) { + // Update all internal state before the closeFuture is notified. + if (localAddress != null) { + LocalChannelRegistry.unregister(localAddress); + localAddress = null; + } + state = 2; + } + } + + @Override + protected void doDeregister() throws Exception { + ((SingleThreadEventExecutor) eventLoop()).removeShutdownHook(shutdownHook); + } + + @Override + protected void doBeginRead() throws Exception { + if (acceptInProgress) { + return; + } + + Queue inboundBuffer = this.inboundBuffer; + if (inboundBuffer.isEmpty()) { + acceptInProgress = true; + return; + } + + ChannelPipeline pipeline = pipeline(); + for (;;) { + Object m = inboundBuffer.poll(); + if (m == null) { + break; + } + pipeline.fireChannelRead(m); + } + pipeline.fireChannelReadComplete(); + } + + LocalChannel serve(final LocalChannel peer) { + final LocalChannel child = new LocalChannel(this, peer); + if (eventLoop().inEventLoop()) { + serve0(child); + } else { + eventLoop().execute(new Runnable() { + @Override + public void run() { + serve0(child); + } + }); + } + return child; + } + + private void serve0(final LocalChannel child) { + inboundBuffer.add(child); + if (acceptInProgress) { + acceptInProgress = false; + ChannelPipeline pipeline = pipeline(); + for (;;) { + Object m = inboundBuffer.poll(); + if (m == null) { + break; + } + pipeline.fireChannelRead(m); + } + pipeline.fireChannelReadComplete(); + } + } +} diff --git a/common/src/main/java/common/net/channel/nio/AbstractNioByteChannel.java b/common/src/main/java/common/net/channel/nio/AbstractNioByteChannel.java new file mode 100644 index 0000000..ac4cc89 --- /dev/null +++ b/common/src/main/java/common/net/channel/nio/AbstractNioByteChannel.java @@ -0,0 +1,347 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.nio; + +import java.io.IOException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; + +import common.net.buffer.ByteBuf; +import common.net.buffer.ByteBufAllocator; +import common.net.channel.Channel; +import common.net.channel.ChannelConfig; +import common.net.channel.ChannelOption; +import common.net.channel.ChannelOutboundBuffer; +import common.net.channel.ChannelPipeline; +import common.net.channel.RecvByteBufAllocator; +import common.net.channel.socket.ChannelInputShutdownEvent; +import common.net.util.internal.StringUtil; + +/** + * {@link AbstractNioChannel} base class for {@link Channel}s that operate on bytes. + */ +public abstract class AbstractNioByteChannel extends AbstractNioChannel { + + private static final String EXPECTED_TYPES = + " (expected: " + StringUtil.simpleClassName(ByteBuf.class) + ')'; // ", " + +// StringUtil.simpleClassName(FileRegion.class) + ')'; + + private Runnable flushTask; + + /** + * Create a new instance + * + * @param parent the parent {@link Channel} by which this instance was created. May be {@code null} + * @param ch the underlying {@link SelectableChannel} on which it operates + */ + protected AbstractNioByteChannel(Channel parent, SelectableChannel ch) { + super(parent, ch, SelectionKey.OP_READ); + } + + @Override + protected AbstractNioUnsafe newUnsafe() { + return new NioByteUnsafe(); + } + + private final class NioByteUnsafe extends AbstractNioUnsafe { + private RecvByteBufAllocator.Handle allocHandle; + + private void closeOnRead(ChannelPipeline pipeline) { + SelectionKey key = selectionKey(); + setInputShutdown(); + if (isOpen()) { + if (Boolean.TRUE.equals(config().getOption(ChannelOption.ALLOW_HALF_CLOSURE))) { + key.interestOps(key.interestOps() & ~readInterestOp); + pipeline.fireUserEventTriggered(ChannelInputShutdownEvent.INSTANCE); + } else { + close(voidPromise()); + } + } + } + + private void handleReadException(ChannelPipeline pipeline, + ByteBuf byteBuf, Throwable cause, boolean close) { + if (byteBuf != null) { + if (byteBuf.isReadable()) { + setReadPending(false); + pipeline.fireChannelRead(byteBuf); + } else { + byteBuf.release(); + } + } + pipeline.fireChannelReadComplete(); + pipeline.fireExceptionCaught(cause); + if (close || cause instanceof IOException) { + closeOnRead(pipeline); + } + } + + @Override + public void read() { + final ChannelConfig config = config(); + if (!config.isAutoRead() && !isReadPending()) { + // ChannelConfig.setAutoRead(false) was called in the meantime + removeReadOp(); + return; + } + + final ChannelPipeline pipeline = pipeline(); + final ByteBufAllocator allocator = config.getAllocator(); + final int maxMessagesPerRead = config.getMaxMessagesPerRead(); + RecvByteBufAllocator.Handle allocHandle = this.allocHandle; + if (allocHandle == null) { + this.allocHandle = allocHandle = config.getRecvByteBufAllocator().newHandle(); + } + + ByteBuf byteBuf = null; + int messages = 0; + boolean close = false; + try { + int totalReadAmount = 0; + boolean readPendingReset = false; + do { + byteBuf = allocHandle.allocate(allocator); + int writable = byteBuf.writableBytes(); + int localReadAmount = doReadBytes(byteBuf); + if (localReadAmount <= 0) { + // not was read release the buffer + byteBuf.release(); + close = localReadAmount < 0; + break; + } + if (!readPendingReset) { + readPendingReset = true; + setReadPending(false); + } + pipeline.fireChannelRead(byteBuf); + byteBuf = null; + + if (totalReadAmount >= Integer.MAX_VALUE - localReadAmount) { + // Avoid overflow. + totalReadAmount = Integer.MAX_VALUE; + break; + } + + totalReadAmount += localReadAmount; + + // stop reading + if (!config.isAutoRead()) { + break; + } + + if (localReadAmount < writable) { + // Read less than what the buffer can hold, + // which might mean we drained the recv buffer completely. + break; + } + } while (++ messages < maxMessagesPerRead); + + pipeline.fireChannelReadComplete(); + allocHandle.record(totalReadAmount); + + if (close) { + closeOnRead(pipeline); + close = false; + } + } catch (Throwable t) { + handleReadException(pipeline, byteBuf, t, close); + } finally { + // Check if there is a readPending which was not processed yet. + // This could be for two reasons: + // * The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method + // * The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method + // + // See https://github.com/netty/netty/issues/2254 + if (!config.isAutoRead() && !isReadPending()) { + removeReadOp(); + } + } + } + } + + @Override + protected void doWrite(ChannelOutboundBuffer in) throws Exception { + int writeSpinCount = -1; + + for (;;) { + Object msg = in.current(); + if (msg == null) { + // Wrote all messages. + clearOpWrite(); + break; + } + + if (msg instanceof ByteBuf) { + ByteBuf buf = (ByteBuf) msg; + int readableBytes = buf.readableBytes(); + if (readableBytes == 0) { + in.remove(); + continue; + } + + boolean setOpWrite = false; + boolean done = false; + long flushedAmount = 0; + if (writeSpinCount == -1) { + writeSpinCount = config().getWriteSpinCount(); + } + for (int i = writeSpinCount - 1; i >= 0; i --) { + int localFlushedAmount = doWriteBytes(buf); + if (localFlushedAmount == 0) { + setOpWrite = true; + break; + } + + flushedAmount += localFlushedAmount; + if (!buf.isReadable()) { + done = true; + break; + } + } + + in.progress(flushedAmount); + + if (done) { + in.remove(); + } else { + incompleteWrite(setOpWrite); + break; + } + } +// else if (msg instanceof FileRegion) { +// FileRegion region = (FileRegion) msg; +// boolean setOpWrite = false; +// boolean done = false; +// long flushedAmount = 0; +// if (writeSpinCount == -1) { +// writeSpinCount = config().getWriteSpinCount(); +// } +// for (int i = writeSpinCount - 1; i >= 0; i --) { +// long localFlushedAmount = doWriteFileRegion(region); +// if (localFlushedAmount == 0) { +// setOpWrite = true; +// break; +// } +// +// flushedAmount += localFlushedAmount; +// if (region.transfered() >= region.count()) { +// done = true; +// break; +// } +// } +// +// in.progress(flushedAmount); +// +// if (done) { +// in.remove(); +// } else { +// incompleteWrite(setOpWrite); +// break; +// } +// } + else { + // Should not reach here. + throw new Error(); + } + } + } + + @Override + protected final Object filterOutboundMessage(Object msg) { + if (msg instanceof ByteBuf) { + ByteBuf buf = (ByteBuf) msg; + if (buf.isDirect()) { + return msg; + } + + return newDirectBuffer(buf); + } + +// if (msg instanceof FileRegion) { +// return msg; +// } + + throw new UnsupportedOperationException( + "unsupported message type: " + StringUtil.simpleClassName(msg) + EXPECTED_TYPES); + } + + protected final void incompleteWrite(boolean setOpWrite) { + // Did not write completely. + if (setOpWrite) { + setOpWrite(); + } else { + // Schedule flush again later so other tasks can be picked up in the meantime + Runnable flushTask = this.flushTask; + if (flushTask == null) { + flushTask = this.flushTask = new Runnable() { + @Override + public void run() { + flush(); + } + }; + } + eventLoop().execute(flushTask); + } + } + + /** + * Write a {@link FileRegion} + * + * @param region the {@link FileRegion} from which the bytes should be written + * @return amount the amount of written bytes + */ +// protected abstract long doWriteFileRegion(FileRegion region) throws Exception; + + /** + * Read bytes into the given {@link ByteBuf} and return the amount. + */ + protected abstract int doReadBytes(ByteBuf buf) throws Exception; + + /** + * Write bytes form the given {@link ByteBuf} to the underlying {@link java.nio.channels.Channel}. + * @param buf the {@link ByteBuf} from which the bytes should be written + * @return amount the amount of written bytes + */ + protected abstract int doWriteBytes(ByteBuf buf) throws Exception; + + protected final void setOpWrite() { + final SelectionKey key = selectionKey(); + // Check first if the key is still valid as it may be canceled as part of the deregistration + // from the EventLoop + // See https://github.com/netty/netty/issues/2104 + if (!key.isValid()) { + return; + } + final int interestOps = key.interestOps(); + if ((interestOps & SelectionKey.OP_WRITE) == 0) { + key.interestOps(interestOps | SelectionKey.OP_WRITE); + } + } + + protected final void clearOpWrite() { + final SelectionKey key = selectionKey(); + // Check first if the key is still valid as it may be canceled as part of the deregistration + // from the EventLoop + // See https://github.com/netty/netty/issues/2104 + if (!key.isValid()) { + return; + } + final int interestOps = key.interestOps(); + if ((interestOps & SelectionKey.OP_WRITE) != 0) { + key.interestOps(interestOps & ~SelectionKey.OP_WRITE); + } + } +} diff --git a/common/src/main/java/common/net/channel/nio/AbstractNioChannel.java b/common/src/main/java/common/net/channel/nio/AbstractNioChannel.java new file mode 100644 index 0000000..214f1de --- /dev/null +++ b/common/src/main/java/common/net/channel/nio/AbstractNioChannel.java @@ -0,0 +1,460 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.nio; + +import java.io.IOException; +import java.net.ConnectException; +import java.net.SocketAddress; +import java.nio.channels.CancelledKeyException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import common.net.buffer.ByteBuf; +import common.net.buffer.ByteBufAllocator; +import common.net.buffer.ByteBufUtil; +import common.net.buffer.Unpooled; +import common.net.channel.AbstractChannel; +import common.net.channel.Channel; +import common.net.channel.ChannelException; +import common.net.channel.ChannelFuture; +import common.net.channel.ChannelFutureListener; +import common.net.channel.ChannelPromise; +import common.net.channel.ConnectTimeoutException; +import common.net.channel.EventLoop; +import common.net.util.ReferenceCountUtil; +import common.net.util.ReferenceCounted; +import common.net.util.internal.OneTimeTask; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * Abstract base class for {@link Channel} implementations which use a Selector based approach. + */ +public abstract class AbstractNioChannel extends AbstractChannel { + + private static final InternalLogger logger = + InternalLoggerFactory.getInstance(AbstractNioChannel.class); + + private final SelectableChannel ch; + protected final int readInterestOp; + volatile SelectionKey selectionKey; + private volatile boolean inputShutdown; + private volatile boolean readPending; + + /** + * The future of the current connection attempt. If not null, subsequent + * connection attempts will fail. + */ + private ChannelPromise connectPromise; + private ScheduledFuture connectTimeoutFuture; + private SocketAddress requestedRemoteAddress; + + /** + * Create a new instance + * + * @param parent the parent {@link Channel} by which this instance was created. May be {@code null} + * @param ch the underlying {@link SelectableChannel} on which it operates + * @param readInterestOp the ops to set to receive data from the {@link SelectableChannel} + */ + protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) { + super(parent); + this.ch = ch; + this.readInterestOp = readInterestOp; + try { + ch.configureBlocking(false); + } catch (IOException e) { + try { + ch.close(); + } catch (IOException e2) { + if (logger.isWarnEnabled()) { + logger.warn( + "Failed to close a partially initialized socket.", e2); + } + } + + throw new ChannelException("Failed to enter non-blocking mode.", e); + } + } + + @Override + public boolean isOpen() { + return ch.isOpen(); + } + + @Override + public NioUnsafe unsafe() { + return (NioUnsafe) super.unsafe(); + } + + protected SelectableChannel javaChannel() { + return ch; + } + + @Override + public NioEventLoop eventLoop() { + return (NioEventLoop) super.eventLoop(); + } + + /** + * Return the current {@link SelectionKey} + */ + protected SelectionKey selectionKey() { + assert selectionKey != null; + return selectionKey; + } + + protected boolean isReadPending() { + return readPending; + } + + protected void setReadPending(boolean readPending) { + this.readPending = readPending; + } + + /** + * Return {@code true} if the input of this {@link Channel} is shutdown + */ + protected boolean isInputShutdown() { + return inputShutdown; + } + + /** + * Shutdown the input of this {@link Channel}. + */ + void setInputShutdown() { + inputShutdown = true; + } + + /** + * Special {@link Unsafe} sub-type which allows to access the underlying {@link SelectableChannel} + */ + public interface NioUnsafe extends Unsafe { + /** + * Return underlying {@link SelectableChannel} + */ + SelectableChannel ch(); + + /** + * Finish connect + */ + void finishConnect(); + + /** + * Read from underlying {@link SelectableChannel} + */ + void read(); + + void forceFlush(); + } + + protected abstract class AbstractNioUnsafe extends AbstractUnsafe implements NioUnsafe { + + protected final void removeReadOp() { + SelectionKey key = selectionKey(); + // Check first if the key is still valid as it may be canceled as part of the deregistration + // from the EventLoop + // See https://github.com/netty/netty/issues/2104 + if (!key.isValid()) { + return; + } + int interestOps = key.interestOps(); + if ((interestOps & readInterestOp) != 0) { + // only remove readInterestOp if needed + key.interestOps(interestOps & ~readInterestOp); + } + } + + @Override + public final SelectableChannel ch() { + return javaChannel(); + } + + @Override + public final void connect( + final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelPromise promise) { + if (!promise.setUncancellable() || !ensureOpen(promise)) { + return; + } + + try { + if (connectPromise != null) { + throw new IllegalStateException("connection attempt already made"); + } + + boolean wasActive = isActive(); + if (doConnect(remoteAddress, localAddress)) { + fulfillConnectPromise(promise, wasActive); + } else { + connectPromise = promise; + requestedRemoteAddress = remoteAddress; + + // Schedule connect timeout. + int connectTimeoutMillis = config().getConnectTimeoutMillis(); + if (connectTimeoutMillis > 0) { + connectTimeoutFuture = eventLoop().schedule(new OneTimeTask() { + @Override + public void run() { + ChannelPromise connectPromise = AbstractNioChannel.this.connectPromise; + ConnectTimeoutException cause = + new ConnectTimeoutException("connection timed out: " + remoteAddress); + if (connectPromise != null && connectPromise.tryFailure(cause)) { + close(voidPromise()); + } + } + }, connectTimeoutMillis, TimeUnit.MILLISECONDS); + } + + promise.addListener(new ChannelFutureListener() { + @Override + public void operationComplete(ChannelFuture future) throws Exception { + if (future.isCancelled()) { + if (connectTimeoutFuture != null) { + connectTimeoutFuture.cancel(false); + } + connectPromise = null; + close(voidPromise()); + } + } + }); + } + } catch (Throwable t) { + if (t instanceof ConnectException) { + Throwable newT = new ConnectException(t.getMessage() + ": " + remoteAddress); + newT.setStackTrace(t.getStackTrace()); + t = newT; + } + promise.tryFailure(t); + closeIfClosed(); + } + } + + private void fulfillConnectPromise(ChannelPromise promise, boolean wasActive) { + if (promise == null) { + // Closed via cancellation and the promise has been notified already. + return; + } + + // trySuccess() will return false if a user cancelled the connection attempt. + boolean promiseSet = promise.trySuccess(); + + // Regardless if the connection attempt was cancelled, channelActive() event should be triggered, + // because what happened is what happened. + if (!wasActive && isActive()) { + pipeline().fireChannelActive(); + } + + // If a user cancelled the connection attempt, close the channel, which is followed by channelInactive(). + if (!promiseSet) { + close(voidPromise()); + } + } + + private void fulfillConnectPromise(ChannelPromise promise, Throwable cause) { + if (promise == null) { + // Closed via cancellation and the promise has been notified already. + return; + } + + // Use tryFailure() instead of setFailure() to avoid the race against cancel(). + promise.tryFailure(cause); + closeIfClosed(); + } + + @Override + public final void finishConnect() { + // Note this method is invoked by the event loop only if the connection attempt was + // neither cancelled nor timed out. + + assert eventLoop().inEventLoop(); + + try { + boolean wasActive = isActive(); + doFinishConnect(); + fulfillConnectPromise(connectPromise, wasActive); + } catch (Throwable t) { + if (t instanceof ConnectException) { + Throwable newT = new ConnectException(t.getMessage() + ": " + requestedRemoteAddress); + newT.setStackTrace(t.getStackTrace()); + t = newT; + } + + fulfillConnectPromise(connectPromise, t); + } finally { + // Check for null as the connectTimeoutFuture is only created if a connectTimeoutMillis > 0 is used + // See https://github.com/netty/netty/issues/1770 + if (connectTimeoutFuture != null) { + connectTimeoutFuture.cancel(false); + } + connectPromise = null; + } + } + + @Override + protected final void flush0() { + // Flush immediately only when there's no pending flush. + // If there's a pending flush operation, event loop will call forceFlush() later, + // and thus there's no need to call it now. + if (isFlushPending()) { + return; + } + super.flush0(); + } + + @Override + public final void forceFlush() { + // directly call super.flush0() to force a flush now + super.flush0(); + } + + private boolean isFlushPending() { + SelectionKey selectionKey = selectionKey(); + return selectionKey.isValid() && (selectionKey.interestOps() & SelectionKey.OP_WRITE) != 0; + } + } + + @Override + protected boolean isCompatible(EventLoop loop) { + return loop instanceof NioEventLoop; + } + + @Override + protected void doRegister() throws Exception { + boolean selected = false; + for (;;) { + try { + selectionKey = javaChannel().register(eventLoop().selector, 0, this); + return; + } catch (CancelledKeyException e) { + if (!selected) { + // Force the Selector to select now as the "canceled" SelectionKey may still be + // cached and not removed because no Select.select(..) operation was called yet. + eventLoop().selectNow(); + selected = true; + } else { + // We forced a select operation on the selector before but the SelectionKey is still cached + // for whatever reason. JDK bug ? + throw e; + } + } + } + } + + @Override + protected void doDeregister() throws Exception { + eventLoop().cancel(selectionKey()); + } + + @Override + protected void doBeginRead() throws Exception { + // Channel.read() or ChannelHandlerContext.read() was called + if (inputShutdown) { + return; + } + + final SelectionKey selectionKey = this.selectionKey; + if (!selectionKey.isValid()) { + return; + } + + readPending = true; + + final int interestOps = selectionKey.interestOps(); + if ((interestOps & readInterestOp) == 0) { + selectionKey.interestOps(interestOps | readInterestOp); + } + } + + /** + * Connect to the remote peer + */ + protected abstract boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception; + + /** + * Finish the connect + */ + protected abstract void doFinishConnect() throws Exception; + + /** + * Returns an off-heap copy of the specified {@link ByteBuf}, and releases the original one. + * Note that this method does not create an off-heap copy if the allocation / deallocation cost is too high, + * but just returns the original {@link ByteBuf}.. + */ + protected final ByteBuf newDirectBuffer(ByteBuf buf) { + final int readableBytes = buf.readableBytes(); + if (readableBytes == 0) { + ReferenceCountUtil.safeRelease(buf); + return Unpooled.EMPTY_BUFFER; + } + + final ByteBufAllocator alloc = alloc(); + if (alloc.isDirectBufferPooled()) { + ByteBuf directBuf = alloc.directBuffer(readableBytes); + directBuf.writeBytes(buf, buf.readerIndex(), readableBytes); + ReferenceCountUtil.safeRelease(buf); + return directBuf; + } + + final ByteBuf directBuf = ByteBufUtil.threadLocalDirectBuffer(); + if (directBuf != null) { + directBuf.writeBytes(buf, buf.readerIndex(), readableBytes); + ReferenceCountUtil.safeRelease(buf); + return directBuf; + } + + // Allocating and deallocating an unpooled direct buffer is very expensive; give up. + return buf; + } + + /** + * Returns an off-heap copy of the specified {@link ByteBuf}, and releases the specified holder. + * The caller must ensure that the holder releases the original {@link ByteBuf} when the holder is released by + * this method. Note that this method does not create an off-heap copy if the allocation / deallocation cost is + * too high, but just returns the original {@link ByteBuf}.. + */ + protected final ByteBuf newDirectBuffer(ReferenceCounted holder, ByteBuf buf) { + final int readableBytes = buf.readableBytes(); + if (readableBytes == 0) { + ReferenceCountUtil.safeRelease(holder); + return Unpooled.EMPTY_BUFFER; + } + + final ByteBufAllocator alloc = alloc(); + if (alloc.isDirectBufferPooled()) { + ByteBuf directBuf = alloc.directBuffer(readableBytes); + directBuf.writeBytes(buf, buf.readerIndex(), readableBytes); + ReferenceCountUtil.safeRelease(holder); + return directBuf; + } + + final ByteBuf directBuf = ByteBufUtil.threadLocalDirectBuffer(); + if (directBuf != null) { + directBuf.writeBytes(buf, buf.readerIndex(), readableBytes); + ReferenceCountUtil.safeRelease(holder); + return directBuf; + } + + // Allocating and deallocating an unpooled direct buffer is very expensive; give up. + if (holder != buf) { + // Ensure to call holder.release() to give the holder a chance to release other resources than its content. + buf.retain(); + ReferenceCountUtil.safeRelease(holder); + } + + return buf; + } +} diff --git a/common/src/main/java/common/net/channel/nio/AbstractNioMessageChannel.java b/common/src/main/java/common/net/channel/nio/AbstractNioMessageChannel.java new file mode 100644 index 0000000..3153d17 --- /dev/null +++ b/common/src/main/java/common/net/channel/nio/AbstractNioMessageChannel.java @@ -0,0 +1,187 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.nio; + +import java.io.IOException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.util.ArrayList; +import java.util.List; + +import common.net.channel.Channel; +import common.net.channel.ChannelConfig; +import common.net.channel.ChannelOutboundBuffer; +import common.net.channel.ChannelPipeline; +import common.net.channel.ServerChannel; + +/** + * {@link AbstractNioChannel} base class for {@link Channel}s that operate on messages. + */ +public abstract class AbstractNioMessageChannel extends AbstractNioChannel { + + /** + * @see {@link AbstractNioChannel#AbstractNioChannel(Channel, SelectableChannel, int)} + */ + protected AbstractNioMessageChannel(Channel parent, SelectableChannel ch, int readInterestOp) { + super(parent, ch, readInterestOp); + } + + @Override + protected AbstractNioUnsafe newUnsafe() { + return new NioMessageUnsafe(); + } + + private final class NioMessageUnsafe extends AbstractNioUnsafe { + + private final List readBuf = new ArrayList(); + + @Override + public void read() { + assert eventLoop().inEventLoop(); + final ChannelConfig config = config(); + if (!config.isAutoRead() && !isReadPending()) { + // ChannelConfig.setAutoRead(false) was called in the meantime + removeReadOp(); + return; + } + + final int maxMessagesPerRead = config.getMaxMessagesPerRead(); + final ChannelPipeline pipeline = pipeline(); + boolean closed = false; + Throwable exception = null; + try { + try { + for (;;) { + int localRead = doReadMessages(readBuf); + if (localRead == 0) { + break; + } + if (localRead < 0) { + closed = true; + break; + } + + // stop reading and remove op + if (!config.isAutoRead()) { + break; + } + + if (readBuf.size() >= maxMessagesPerRead) { + break; + } + } + } catch (Throwable t) { + exception = t; + } + setReadPending(false); + int size = readBuf.size(); + for (int i = 0; i < size; i ++) { + pipeline.fireChannelRead(readBuf.get(i)); + } + + readBuf.clear(); + pipeline.fireChannelReadComplete(); + + if (exception != null) { + if (exception instanceof IOException) { + // ServerChannel should not be closed even on IOException because it can often continue + // accepting incoming connections. (e.g. too many open files) + closed = !(AbstractNioMessageChannel.this instanceof ServerChannel); + } + + pipeline.fireExceptionCaught(exception); + } + + if (closed) { + if (isOpen()) { + close(voidPromise()); + } + } + } finally { + // Check if there is a readPending which was not processed yet. + // This could be for two reasons: + // * The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method + // * The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method + // + // See https://github.com/netty/netty/issues/2254 + if (!config.isAutoRead() && !isReadPending()) { + removeReadOp(); + } + } + } + } + + @Override + protected void doWrite(ChannelOutboundBuffer in) throws Exception { + final SelectionKey key = selectionKey(); + final int interestOps = key.interestOps(); + + for (;;) { + Object msg = in.current(); + if (msg == null) { + // Wrote all messages. + if ((interestOps & SelectionKey.OP_WRITE) != 0) { + key.interestOps(interestOps & ~SelectionKey.OP_WRITE); + } + break; + } + try { + boolean done = false; + for (int i = config().getWriteSpinCount() - 1; i >= 0; i--) { + if (doWriteMessage(msg, in)) { + done = true; + break; + } + } + + if (done) { + in.remove(); + } else { + // Did not write all messages. + if ((interestOps & SelectionKey.OP_WRITE) == 0) { + key.interestOps(interestOps | SelectionKey.OP_WRITE); + } + break; + } + } catch (IOException e) { + if (continueOnWriteError()) { + in.remove(e); + } else { + throw e; + } + } + } + } + + /** + * Returns {@code true} if we should continue the write loop on a write error. + */ + protected boolean continueOnWriteError() { + return false; + } + + /** + * Read messages into the given array and return the amount which was read. + */ + protected abstract int doReadMessages(List buf) throws Exception; + + /** + * Write a message to the underlying {@link java.nio.channels.Channel}. + * + * @return {@code true} if and only if the message has been written + */ + protected abstract boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception; +} diff --git a/common/src/main/java/common/net/channel/nio/NioEventLoop.java b/common/src/main/java/common/net/channel/nio/NioEventLoop.java new file mode 100644 index 0000000..dcb46d0 --- /dev/null +++ b/common/src/main/java/common/net/channel/nio/NioEventLoop.java @@ -0,0 +1,691 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.nio; + + +import java.io.IOException; +import java.lang.reflect.Field; +import java.nio.channels.CancelledKeyException; +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; +import java.nio.channels.Selector; +import java.nio.channels.spi.SelectorProvider; +import java.util.ArrayList; +import java.util.Collection; +import java.util.ConcurrentModificationException; +import java.util.Iterator; +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import common.net.channel.ChannelException; +import common.net.channel.EventLoopException; +import common.net.channel.SingleThreadEventLoop; +import common.net.channel.nio.AbstractNioChannel.NioUnsafe; +import common.net.util.internal.MpscLinkedQueue; +import common.net.util.internal.SystemPropertyUtil; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * {@link SingleThreadEventLoop} implementation which register the {@link Channel}'s to a + * {@link Selector} and so does the multi-plexing of these in the event loop. + * + */ +public final class NioEventLoop extends SingleThreadEventLoop { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(NioEventLoop.class); + + private static final int CLEANUP_INTERVAL = 256; // XXX Hard-coded value, but won't need customization. + + private static final boolean DISABLE_KEYSET_OPTIMIZATION = + SystemPropertyUtil.getBoolean("game.net.noKeySetOptimization", false); + + private static final int MIN_PREMATURE_SELECTOR_RETURNS = 3; + private static final int SELECTOR_AUTO_REBUILD_THRESHOLD; + + // Workaround for JDK NIO bug. + // + // See: + // - http://bugs.sun.com/view_bug.do?bug_id=6427854 + // - https://github.com/netty/netty/issues/203 + static { + String key = "sun.nio.ch.bugLevel"; + try { + String buglevel = SystemPropertyUtil.get(key); + if (buglevel == null) { + System.setProperty(key, ""); + } + } catch (SecurityException e) { + if (logger.isDebugEnabled()) { + logger.debug("Unable to get/set System Property: {}", key, e); + } + } + + int selectorAutoRebuildThreshold = SystemPropertyUtil.getInt("game.net.selectorAutoRebuildThreshold", 512); + if (selectorAutoRebuildThreshold < MIN_PREMATURE_SELECTOR_RETURNS) { + selectorAutoRebuildThreshold = 0; + } + + SELECTOR_AUTO_REBUILD_THRESHOLD = selectorAutoRebuildThreshold; + + if (logger.isDebugEnabled()) { + logger.debug("-Dgame.net.noKeySetOptimization: {}", DISABLE_KEYSET_OPTIMIZATION); + logger.debug("-Dgame.net.selectorAutoRebuildThreshold: {}", SELECTOR_AUTO_REBUILD_THRESHOLD); + } + } + + /** + * The NIO {@link Selector}. + */ + Selector selector; + private SelectedSelectionKeySet selectedKeys; + + private final SelectorProvider provider; + + /** + * Boolean that controls determines if a blocked Selector.select should + * break out of its selection process. In our case we use a timeout for + * the select method and the select method will block for that time unless + * waken up. + */ + private final AtomicBoolean wakenUp = new AtomicBoolean(); + + private volatile int ioRatio = 50; + private int cancelledKeys; + private boolean needsToSelectAgain; + + NioEventLoop(NioEventLoopGroup parent, ThreadFactory threadFactory, SelectorProvider selectorProvider) { + super(parent, threadFactory, false); + if (selectorProvider == null) { + throw new NullPointerException("selectorProvider"); + } + provider = selectorProvider; + selector = openSelector(); + } + + private Selector openSelector() { + final Selector selector; + try { + selector = provider.openSelector(); + } catch (IOException e) { + throw new ChannelException("failed to open a new selector", e); + } + + if (DISABLE_KEYSET_OPTIMIZATION) { + return selector; + } + + try { + SelectedSelectionKeySet selectedKeySet = new SelectedSelectionKeySet(); + + Class selectorImplClass = + Class.forName("sun.nio.ch.SelectorImpl", false, ClassLoader.getSystemClassLoader()); + + // Ensure the current selector implementation is what we can instrument. + if (!selectorImplClass.isAssignableFrom(selector.getClass())) { + return selector; + } + + Field selectedKeysField = selectorImplClass.getDeclaredField("selectedKeys"); + Field publicSelectedKeysField = selectorImplClass.getDeclaredField("publicSelectedKeys"); + + selectedKeysField.setAccessible(true); + publicSelectedKeysField.setAccessible(true); + + selectedKeysField.set(selector, selectedKeySet); + publicSelectedKeysField.set(selector, selectedKeySet); + + selectedKeys = selectedKeySet; + logger.trace("Instrumented an optimized java.util.Set into: {}", selector); + } catch (Throwable t) { + selectedKeys = null; + logger.trace("Failed to instrument an optimized java.util.Set into: {}", selector, t); + } + + return selector; + } + + @Override + protected Queue newTaskQueue() { + // This event loop never calls takeTask() + return new MpscLinkedQueue(); + } + + /** + * Registers an arbitrary {@link SelectableChannel}, not necessarily created by Netty, to the {@link Selector} + * of this event loop. Once the specified {@link SelectableChannel} is registered, the specified {@code task} will + * be executed by this event loop when the {@link SelectableChannel} is ready. + */ + public void register(final SelectableChannel ch, final int interestOps, final NioTask task) { + if (ch == null) { + throw new NullPointerException("ch"); + } + if (interestOps == 0) { + throw new IllegalArgumentException("interestOps must be non-zero."); + } + if ((interestOps & ~ch.validOps()) != 0) { + throw new IllegalArgumentException( + "invalid interestOps: " + interestOps + "(validOps: " + ch.validOps() + ')'); + } + if (task == null) { + throw new NullPointerException("task"); + } + + if (isShutdown()) { + throw new IllegalStateException("event loop shut down"); + } + + try { + ch.register(selector, interestOps, task); + } catch (Exception e) { + throw new EventLoopException("failed to register a channel", e); + } + } + + /** + * Returns the percentage of the desired amount of time spent for I/O in the event loop. + */ + public int getIoRatio() { + return ioRatio; + } + + /** + * Sets the percentage of the desired amount of time spent for I/O in the event loop. The default value is + * {@code 50}, which means the event loop will try to spend the same amount of time for I/O as for non-I/O tasks. + */ + public void setIoRatio(int ioRatio) { + if (ioRatio <= 0 || ioRatio > 100) { + throw new IllegalArgumentException("ioRatio: " + ioRatio + " (expected: 0 < ioRatio <= 100)"); + } + this.ioRatio = ioRatio; + } + + /** + * Replaces the current {@link Selector} of this event loop with newly created {@link Selector}s to work + * around the infamous epoll 100% CPU bug. + */ + public void rebuildSelector() { + if (!inEventLoop()) { + execute(new Runnable() { + @Override + public void run() { + rebuildSelector(); + } + }); + return; + } + + final Selector oldSelector = selector; + final Selector newSelector; + + if (oldSelector == null) { + return; + } + + try { + newSelector = openSelector(); + } catch (Exception e) { + logger.warn("Failed to create a new Selector.", e); + return; + } + + // Register all channels to the new Selector. + int nChannels = 0; + for (;;) { + try { + for (SelectionKey key: oldSelector.keys()) { + Object a = key.attachment(); + try { + if (!key.isValid() || key.channel().keyFor(newSelector) != null) { + continue; + } + + int interestOps = key.interestOps(); + key.cancel(); + SelectionKey newKey = key.channel().register(newSelector, interestOps, a); + if (a instanceof AbstractNioChannel) { + // Update SelectionKey + ((AbstractNioChannel) a).selectionKey = newKey; + } + nChannels ++; + } catch (Exception e) { + logger.warn("Failed to re-register a Channel to the new Selector.", e); + if (a instanceof AbstractNioChannel) { + AbstractNioChannel ch = (AbstractNioChannel) a; + ch.unsafe().close(ch.unsafe().voidPromise()); + } else { + + NioTask task = (NioTask) a; + invokeChannelUnregistered(task, key, e); + } + } + } + } catch (ConcurrentModificationException e) { + // Probably due to concurrent modification of the key set. + continue; + } + + break; + } + + selector = newSelector; + + try { + // time to close the old selector as everything else is registered to the new one + oldSelector.close(); + } catch (Throwable t) { + if (logger.isWarnEnabled()) { + logger.warn("Failed to close the old Selector.", t); + } + } + + logger.info("Migrated " + nChannels + " channel(s) to the new Selector."); + } + + @Override + protected void run() { + for (;;) { + boolean oldWakenUp = wakenUp.getAndSet(false); + try { + if (hasTasks()) { + selectNow(); + } else { + select(oldWakenUp); + + // 'wakenUp.compareAndSet(false, true)' is always evaluated + // before calling 'selector.wakeup()' to reduce the wake-up + // overhead. (Selector.wakeup() is an expensive operation.) + // + // However, there is a race condition in this approach. + // The race condition is triggered when 'wakenUp' is set to + // true too early. + // + // 'wakenUp' is set to true too early if: + // 1) Selector is waken up between 'wakenUp.set(false)' and + // 'selector.select(...)'. (BAD) + // 2) Selector is waken up between 'selector.select(...)' and + // 'if (wakenUp.get()) { ... }'. (OK) + // + // In the first case, 'wakenUp' is set to true and the + // following 'selector.select(...)' will wake up immediately. + // Until 'wakenUp' is set to false again in the next round, + // 'wakenUp.compareAndSet(false, true)' will fail, and therefore + // any attempt to wake up the Selector will fail, too, causing + // the following 'selector.select(...)' call to block + // unnecessarily. + // + // To fix this problem, we wake up the selector again if wakenUp + // is true immediately after selector.select(...). + // It is inefficient in that it wakes up the selector for both + // the first case (BAD - wake-up required) and the second case + // (OK - no wake-up required). + + if (wakenUp.get()) { + selector.wakeup(); + } + } + + cancelledKeys = 0; + needsToSelectAgain = false; + final int ioRatio = this.ioRatio; + if (ioRatio == 100) { + processSelectedKeys(); + runAllTasks(); + } else { + final long ioStartTime = System.nanoTime(); + + processSelectedKeys(); + + final long ioTime = System.nanoTime() - ioStartTime; + runAllTasks(ioTime * (100 - ioRatio) / ioRatio); + } + + if (isShuttingDown()) { + closeAll(); + if (confirmShutdown()) { + break; + } + } + } catch (Throwable t) { + logger.warn("Unexpected exception in the selector loop.", t); + + // Prevent possible consecutive immediate failures that lead to + // excessive CPU consumption. + try { + Thread.sleep(1000); + } catch (InterruptedException e) { + // Ignore. + } + } + } + } + + private void processSelectedKeys() { + if (selectedKeys != null) { + processSelectedKeysOptimized(selectedKeys.flip()); + } else { + processSelectedKeysPlain(selector.selectedKeys()); + } + } + + @Override + protected void cleanup() { + try { + selector.close(); + } catch (IOException e) { + logger.warn("Failed to close a selector.", e); + } + } + + void cancel(SelectionKey key) { + key.cancel(); + cancelledKeys ++; + if (cancelledKeys >= CLEANUP_INTERVAL) { + cancelledKeys = 0; + needsToSelectAgain = true; + } + } + + @Override + protected Runnable pollTask() { + Runnable task = super.pollTask(); + if (needsToSelectAgain) { + selectAgain(); + } + return task; + } + + private void processSelectedKeysPlain(Set selectedKeys) { + // check if the set is empty and if so just return to not create garbage by + // creating a new Iterator every time even if there is nothing to process. + // See https://github.com/netty/netty/issues/597 + if (selectedKeys.isEmpty()) { + return; + } + + Iterator i = selectedKeys.iterator(); + for (;;) { + final SelectionKey k = i.next(); + final Object a = k.attachment(); + i.remove(); + + if (a instanceof AbstractNioChannel) { + processSelectedKey(k, (AbstractNioChannel) a); + } else { + + NioTask task = (NioTask) a; + processSelectedKey(k, task); + } + + if (!i.hasNext()) { + break; + } + + if (needsToSelectAgain) { + selectAgain(); + selectedKeys = selector.selectedKeys(); + + // Create the iterator again to avoid ConcurrentModificationException + if (selectedKeys.isEmpty()) { + break; + } else { + i = selectedKeys.iterator(); + } + } + } + } + + private void processSelectedKeysOptimized(SelectionKey[] selectedKeys) { + for (int i = 0;; i ++) { + final SelectionKey k = selectedKeys[i]; + if (k == null) { + break; + } + // null out entry in the array to allow to have it GC'ed once the Channel close + // See https://github.com/netty/netty/issues/2363 + selectedKeys[i] = null; + + final Object a = k.attachment(); + + if (a instanceof AbstractNioChannel) { + processSelectedKey(k, (AbstractNioChannel) a); + } else { + + NioTask task = (NioTask) a; + processSelectedKey(k, task); + } + + if (needsToSelectAgain) { + // null out entries in the array to allow to have it GC'ed once the Channel close + // See https://github.com/netty/netty/issues/2363 + for (;;) { + if (selectedKeys[i] == null) { + break; + } + selectedKeys[i] = null; + i++; + } + + selectAgain(); + // Need to flip the optimized selectedKeys to get the right reference to the array + // and reset the index to -1 which will then set to 0 on the for loop + // to start over again. + // + // See https://github.com/netty/netty/issues/1523 + selectedKeys = this.selectedKeys.flip(); + i = -1; + } + } + } + + private static void processSelectedKey(SelectionKey k, AbstractNioChannel ch) { + final NioUnsafe unsafe = ch.unsafe(); + if (!k.isValid()) { + // close the channel if the key is not valid anymore + unsafe.close(unsafe.voidPromise()); + return; + } + + try { + int readyOps = k.readyOps(); + // Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead + // to a spin loop + if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) { + unsafe.read(); + if (!ch.isOpen()) { + // Connection already closed - no need to handle write. + return; + } + } + if ((readyOps & SelectionKey.OP_WRITE) != 0) { + // Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write + ch.unsafe().forceFlush(); + } + if ((readyOps & SelectionKey.OP_CONNECT) != 0) { + // remove OP_CONNECT as otherwise Selector.select(..) will always return without blocking + // See https://github.com/netty/netty/issues/924 + int ops = k.interestOps(); + ops &= ~SelectionKey.OP_CONNECT; + k.interestOps(ops); + + unsafe.finishConnect(); + } + } catch (CancelledKeyException ignored) { + unsafe.close(unsafe.voidPromise()); + } + } + + private static void processSelectedKey(SelectionKey k, NioTask task) { + int state = 0; + try { + task.channelReady(k.channel(), k); + state = 1; + } catch (Exception e) { + k.cancel(); + invokeChannelUnregistered(task, k, e); + state = 2; + } finally { + switch (state) { + case 0: + k.cancel(); + invokeChannelUnregistered(task, k, null); + break; + case 1: + if (!k.isValid()) { // Cancelled by channelReady() + invokeChannelUnregistered(task, k, null); + } + break; + } + } + } + + private void closeAll() { + selectAgain(); + Set keys = selector.keys(); + Collection channels = new ArrayList(keys.size()); + for (SelectionKey k: keys) { + Object a = k.attachment(); + if (a instanceof AbstractNioChannel) { + channels.add((AbstractNioChannel) a); + } else { + k.cancel(); + + NioTask task = (NioTask) a; + invokeChannelUnregistered(task, k, null); + } + } + + for (AbstractNioChannel ch: channels) { + ch.unsafe().close(ch.unsafe().voidPromise()); + } + } + + private static void invokeChannelUnregistered(NioTask task, SelectionKey k, Throwable cause) { + try { + task.channelUnregistered(k.channel(), cause); + } catch (Exception e) { + logger.warn("Unexpected exception while running NioTask.channelUnregistered()", e); + } + } + + @Override + protected void wakeup(boolean inEventLoop) { + if (!inEventLoop && wakenUp.compareAndSet(false, true)) { + selector.wakeup(); + } + } + + void selectNow() throws IOException { + try { + selector.selectNow(); + } finally { + // restore wakup state if needed + if (wakenUp.get()) { + selector.wakeup(); + } + } + } + + private void select(boolean oldWakenUp) throws IOException { + Selector selector = this.selector; + try { + int selectCnt = 0; + long currentTimeNanos = System.nanoTime(); + long selectDeadLineNanos = currentTimeNanos + delayNanos(currentTimeNanos); + for (;;) { + long timeoutMillis = (selectDeadLineNanos - currentTimeNanos + 500000L) / 1000000L; + if (timeoutMillis <= 0) { + if (selectCnt == 0) { + selector.selectNow(); + selectCnt = 1; + } + break; + } + + int selectedKeys = selector.select(timeoutMillis); + selectCnt ++; + + if (selectedKeys != 0 || oldWakenUp || wakenUp.get() || hasTasks() || hasScheduledTasks()) { + // - Selected something, + // - waken up by user, or + // - the task queue has a pending task. + // - a scheduled task is ready for processing + break; + } + if (Thread.interrupted()) { + // Thread was interrupted so reset selected keys and break so we not run into a busy loop. + // As this is most likely a bug in the handler of the user or it's client library we will + // also log it. + // + // See https://github.com/netty/netty/issues/2426 + if (logger.isDebugEnabled()) { + logger.debug("Selector.select() returned prematurely because " + + "Thread.currentThread().interrupt() was called. Use " + + "NioEventLoop.shutdownGracefully() to shutdown the NioEventLoop."); + } + selectCnt = 1; + break; + } + + long time = System.nanoTime(); + if (time - TimeUnit.MILLISECONDS.toNanos(timeoutMillis) >= currentTimeNanos) { + // timeoutMillis elapsed without anything selected. + selectCnt = 1; + } else if (SELECTOR_AUTO_REBUILD_THRESHOLD > 0 && + selectCnt >= SELECTOR_AUTO_REBUILD_THRESHOLD) { + // The selector returned prematurely many times in a row. + // Rebuild the selector to work around the problem. + logger.warn( + "Selector.select() returned prematurely {} times in a row; rebuilding selector.", + selectCnt); + + rebuildSelector(); + selector = this.selector; + + // Select again to populate selectedKeys. + selector.selectNow(); + selectCnt = 1; + break; + } + + currentTimeNanos = time; + } + + if (selectCnt > MIN_PREMATURE_SELECTOR_RETURNS) { + if (logger.isDebugEnabled()) { + logger.debug("Selector.select() returned prematurely {} times in a row.", selectCnt - 1); + } + } + } catch (CancelledKeyException e) { + if (logger.isDebugEnabled()) { + logger.debug(CancelledKeyException.class.getSimpleName() + " raised by a Selector - JDK bug?", e); + } + // Harmless exception - log anyway + } + } + + private void selectAgain() { + needsToSelectAgain = false; + try { + selector.selectNow(); + } catch (Throwable t) { + logger.warn("Failed to update SelectionKeys.", t); + } + } +} diff --git a/common/src/main/java/common/net/channel/nio/NioEventLoopGroup.java b/common/src/main/java/common/net/channel/nio/NioEventLoopGroup.java new file mode 100644 index 0000000..926efc8 --- /dev/null +++ b/common/src/main/java/common/net/channel/nio/NioEventLoopGroup.java @@ -0,0 +1,87 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.nio; + +import java.nio.channels.spi.SelectorProvider; +import java.util.concurrent.ThreadFactory; + +import common.net.channel.MultithreadEventLoopGroup; +import common.net.util.concurrent.EventExecutor; + +/** + * {@link MultithreadEventLoopGroup} implementations which is used for NIO {@link Selector} based {@link Channel}s. + */ +public class NioEventLoopGroup extends MultithreadEventLoopGroup { + + /** + * Create a new instance using the default number of threads, the default {@link ThreadFactory} and + * the {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}. + */ + public NioEventLoopGroup() { + this(0); + } + + /** + * Create a new instance using the specified number of threads, {@link ThreadFactory} and the + * {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}. + */ + public NioEventLoopGroup(int nThreads) { + this(nThreads, null); + } + + /** + * Create a new instance using the specified number of threads, the given {@link ThreadFactory} and the + * {@link SelectorProvider} which is returned by {@link SelectorProvider#provider()}. + */ + public NioEventLoopGroup(int nThreads, ThreadFactory threadFactory) { + this(nThreads, threadFactory, SelectorProvider.provider()); + } + + /** + * Create a new instance using the specified number of threads, the given {@link ThreadFactory} and the given + * {@link SelectorProvider}. + */ + public NioEventLoopGroup( + int nThreads, ThreadFactory threadFactory, final SelectorProvider selectorProvider) { + super(nThreads, threadFactory, selectorProvider); + } + + /** + * Sets the percentage of the desired amount of time spent for I/O in the child event loops. The default value is + * {@code 50}, which means the event loop will try to spend the same amount of time for I/O as for non-I/O tasks. + */ + public void setIoRatio(int ioRatio) { + for (EventExecutor e: children()) { + ((NioEventLoop) e).setIoRatio(ioRatio); + } + } + + /** + * Replaces the current {@link Selector}s of the child event loops with newly created {@link Selector}s to work + * around the infamous epoll 100% CPU bug. + */ + public void rebuildSelectors() { + for (EventExecutor e: children()) { + ((NioEventLoop) e).rebuildSelector(); + } + } + + @Override + protected EventExecutor newChild( + ThreadFactory threadFactory, Object... args) throws Exception { + return new NioEventLoop(this, threadFactory, (SelectorProvider) args[0]); + } +} diff --git a/common/src/main/java/common/net/channel/nio/NioTask.java b/common/src/main/java/common/net/channel/nio/NioTask.java new file mode 100644 index 0000000..43dea6b --- /dev/null +++ b/common/src/main/java/common/net/channel/nio/NioTask.java @@ -0,0 +1,40 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.nio; + +import java.nio.channels.SelectableChannel; +import java.nio.channels.SelectionKey; + +/** + * An arbitrary task that can be executed by {@link NioEventLoop} when a {@link SelectableChannel} becomes ready. + * + * @see NioEventLoop#register(SelectableChannel, int, NioTask) + */ +public interface NioTask { + /** + * Invoked when the {@link SelectableChannel} has been selected by the {@link Selector}. + */ + void channelReady(C ch, SelectionKey key) throws Exception; + + /** + * Invoked when the {@link SelectionKey} of the specified {@link SelectableChannel} has been cancelled and thus + * this {@link NioTask} will not be notified anymore. + * + * @param cause the cause of the unregistration. {@code null} if a user called {@link SelectionKey#cancel()} or + * the event loop has been shut down. + */ + void channelUnregistered(C ch, Throwable cause) throws Exception; +} diff --git a/common/src/main/java/common/net/channel/nio/SelectedSelectionKeySet.java b/common/src/main/java/common/net/channel/nio/SelectedSelectionKeySet.java new file mode 100644 index 0000000..8d7cfd8 --- /dev/null +++ b/common/src/main/java/common/net/channel/nio/SelectedSelectionKeySet.java @@ -0,0 +1,110 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.channel.nio; + +import java.nio.channels.SelectionKey; +import java.util.AbstractSet; +import java.util.Iterator; + +final class SelectedSelectionKeySet extends AbstractSet { + + private SelectionKey[] keysA; + private int keysASize; + private SelectionKey[] keysB; + private int keysBSize; + private boolean isA = true; + + SelectedSelectionKeySet() { + keysA = new SelectionKey[1024]; + keysB = keysA.clone(); + } + + @Override + public boolean add(SelectionKey o) { + if (o == null) { + return false; + } + + if (isA) { + int size = keysASize; + keysA[size ++] = o; + keysASize = size; + if (size == keysA.length) { + doubleCapacityA(); + } + } else { + int size = keysBSize; + keysB[size ++] = o; + keysBSize = size; + if (size == keysB.length) { + doubleCapacityB(); + } + } + + return true; + } + + private void doubleCapacityA() { + SelectionKey[] newKeysA = new SelectionKey[keysA.length << 1]; + System.arraycopy(keysA, 0, newKeysA, 0, keysASize); + keysA = newKeysA; + } + + private void doubleCapacityB() { + SelectionKey[] newKeysB = new SelectionKey[keysB.length << 1]; + System.arraycopy(keysB, 0, newKeysB, 0, keysBSize); + keysB = newKeysB; + } + + SelectionKey[] flip() { + if (isA) { + isA = false; + keysA[keysASize] = null; + keysBSize = 0; + return keysA; + } else { + isA = true; + keysB[keysBSize] = null; + keysASize = 0; + return keysB; + } + } + + @Override + public int size() { + if (isA) { + return keysASize; + } else { + return keysBSize; + } + } + + @Override + public boolean remove(Object o) { + return false; + } + + @Override + public boolean contains(Object o) { + return false; + } + + @Override + public Iterator iterator() { + throw new UnsupportedOperationException(); + } +} diff --git a/common/src/main/java/common/net/channel/socket/ChannelInputShutdownEvent.java b/common/src/main/java/common/net/channel/socket/ChannelInputShutdownEvent.java new file mode 100644 index 0000000..3886008 --- /dev/null +++ b/common/src/main/java/common/net/channel/socket/ChannelInputShutdownEvent.java @@ -0,0 +1,33 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.socket; + +/** + * Special event which will be fired and passed to the + * {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)} methods once the input of + * a {@link SocketChannel} was shutdown and the {@link SocketChannelConfig#isAllowHalfClosure()} method returns + * {@code true}. + */ +public final class ChannelInputShutdownEvent { + + /** + * Instance to use + */ + + public static final ChannelInputShutdownEvent INSTANCE = new ChannelInputShutdownEvent(); + + private ChannelInputShutdownEvent() { } +} diff --git a/common/src/main/java/common/net/channel/socket/DefaultServerSocketChannelConfig.java b/common/src/main/java/common/net/channel/socket/DefaultServerSocketChannelConfig.java new file mode 100644 index 0000000..52db912 --- /dev/null +++ b/common/src/main/java/common/net/channel/socket/DefaultServerSocketChannelConfig.java @@ -0,0 +1,203 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.socket; + +import static common.net.channel.ChannelOption.SO_BACKLOG; +import static common.net.channel.ChannelOption.SO_RCVBUF; +import static common.net.channel.ChannelOption.SO_REUSEADDR; + +import java.net.ServerSocket; +import java.net.SocketException; +import java.util.Map; + +import common.net.buffer.ByteBufAllocator; +import common.net.channel.ChannelException; +import common.net.channel.ChannelOption; +import common.net.channel.DefaultChannelConfig; +import common.net.channel.MessageSizeEstimator; +import common.net.channel.RecvByteBufAllocator; +import common.net.util.NetUtil; + +/** + * The default {@link ServerSocketChannelConfig} implementation. + */ +public class DefaultServerSocketChannelConfig extends DefaultChannelConfig + implements ServerSocketChannelConfig { + + protected final ServerSocket javaSocket; + private volatile int backlog = NetUtil.SOMAXCONN; + + /** + * Creates a new instance. + */ + public DefaultServerSocketChannelConfig(ServerSocketChannel channel, ServerSocket javaSocket) { + super(channel); + if (javaSocket == null) { + throw new NullPointerException("javaSocket"); + } + this.javaSocket = javaSocket; + } + + @Override + public Map, Object> getOptions() { + return getOptions(super.getOptions(), SO_RCVBUF, SO_REUSEADDR, SO_BACKLOG); + } + + + @Override + public T getOption(ChannelOption option) { + if (option == SO_RCVBUF) { + return (T) Integer.valueOf(getReceiveBufferSize()); + } + if (option == SO_REUSEADDR) { + return (T) Boolean.valueOf(isReuseAddress()); + } + if (option == SO_BACKLOG) { + return (T) Integer.valueOf(getBacklog()); + } + + return super.getOption(option); + } + + @Override + public boolean setOption(ChannelOption option, T value) { + validate(option, value); + + if (option == SO_RCVBUF) { + setReceiveBufferSize((Integer) value); + } else if (option == SO_REUSEADDR) { + setReuseAddress((Boolean) value); + } else if (option == SO_BACKLOG) { + setBacklog((Integer) value); + } else { + return super.setOption(option, value); + } + + return true; + } + + @Override + public boolean isReuseAddress() { + try { + return javaSocket.getReuseAddress(); + } catch (SocketException e) { + throw new ChannelException(e); + } + } + + @Override + public ServerSocketChannelConfig setReuseAddress(boolean reuseAddress) { + try { + javaSocket.setReuseAddress(reuseAddress); + } catch (SocketException e) { + throw new ChannelException(e); + } + return this; + } + + @Override + public int getReceiveBufferSize() { + try { + return javaSocket.getReceiveBufferSize(); + } catch (SocketException e) { + throw new ChannelException(e); + } + } + + @Override + public ServerSocketChannelConfig setReceiveBufferSize(int receiveBufferSize) { + try { + javaSocket.setReceiveBufferSize(receiveBufferSize); + } catch (SocketException e) { + throw new ChannelException(e); + } + return this; + } + + @Override + public ServerSocketChannelConfig setPerformancePreferences(int connectionTime, int latency, int bandwidth) { + javaSocket.setPerformancePreferences(connectionTime, latency, bandwidth); + return this; + } + + @Override + public int getBacklog() { + return backlog; + } + + @Override + public ServerSocketChannelConfig setBacklog(int backlog) { + if (backlog < 0) { + throw new IllegalArgumentException("backlog: " + backlog); + } + this.backlog = backlog; + return this; + } + + @Override + public ServerSocketChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) { + super.setConnectTimeoutMillis(connectTimeoutMillis); + return this; + } + + @Override + public ServerSocketChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) { + super.setMaxMessagesPerRead(maxMessagesPerRead); + return this; + } + + @Override + public ServerSocketChannelConfig setWriteSpinCount(int writeSpinCount) { + super.setWriteSpinCount(writeSpinCount); + return this; + } + + @Override + public ServerSocketChannelConfig setAllocator(ByteBufAllocator allocator) { + super.setAllocator(allocator); + return this; + } + + @Override + public ServerSocketChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) { + super.setRecvByteBufAllocator(allocator); + return this; + } + + @Override + public ServerSocketChannelConfig setAutoRead(boolean autoRead) { + super.setAutoRead(autoRead); + return this; + } + + @Override + public ServerSocketChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark) { + super.setWriteBufferHighWaterMark(writeBufferHighWaterMark); + return this; + } + + @Override + public ServerSocketChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark) { + super.setWriteBufferLowWaterMark(writeBufferLowWaterMark); + return this; + } + + @Override + public ServerSocketChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) { + super.setMessageSizeEstimator(estimator); + return this; + } +} diff --git a/common/src/main/java/common/net/channel/socket/DefaultSocketChannelConfig.java b/common/src/main/java/common/net/channel/socket/DefaultSocketChannelConfig.java new file mode 100644 index 0000000..32bb532 --- /dev/null +++ b/common/src/main/java/common/net/channel/socket/DefaultSocketChannelConfig.java @@ -0,0 +1,339 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.socket; + +import static common.net.channel.ChannelOption.ALLOW_HALF_CLOSURE; +import static common.net.channel.ChannelOption.IP_TOS; +import static common.net.channel.ChannelOption.SO_KEEPALIVE; +import static common.net.channel.ChannelOption.SO_LINGER; +import static common.net.channel.ChannelOption.SO_RCVBUF; +import static common.net.channel.ChannelOption.SO_REUSEADDR; +import static common.net.channel.ChannelOption.SO_SNDBUF; +import static common.net.channel.ChannelOption.TCP_NODELAY; + +import java.net.Socket; +import java.net.SocketException; +import java.util.Map; + +import common.net.buffer.ByteBufAllocator; +import common.net.channel.ChannelException; +import common.net.channel.ChannelOption; +import common.net.channel.DefaultChannelConfig; +import common.net.channel.MessageSizeEstimator; +import common.net.channel.RecvByteBufAllocator; + +/** + * The default {@link SocketChannelConfig} implementation. + */ +public class DefaultSocketChannelConfig extends DefaultChannelConfig + implements SocketChannelConfig { + + protected final Socket javaSocket; + private volatile boolean allowHalfClosure; + + /** + * Creates a new instance. + */ + public DefaultSocketChannelConfig(SocketChannel channel, Socket javaSocket) { + super(channel); + if (javaSocket == null) { + throw new NullPointerException("javaSocket"); + } + this.javaSocket = javaSocket; + + // Enable TCP_NODELAY by default. + try { + setTcpNoDelay(true); + } catch (Exception e) { + // Ignore. + } + } + + @Override + public Map, Object> getOptions() { + return getOptions( + super.getOptions(), + SO_RCVBUF, SO_SNDBUF, TCP_NODELAY, SO_KEEPALIVE, SO_REUSEADDR, SO_LINGER, IP_TOS, + ALLOW_HALF_CLOSURE); + } + + + @Override + public T getOption(ChannelOption option) { + if (option == SO_RCVBUF) { + return (T) Integer.valueOf(getReceiveBufferSize()); + } + if (option == SO_SNDBUF) { + return (T) Integer.valueOf(getSendBufferSize()); + } + if (option == TCP_NODELAY) { + return (T) Boolean.valueOf(isTcpNoDelay()); + } + if (option == SO_KEEPALIVE) { + return (T) Boolean.valueOf(isKeepAlive()); + } + if (option == SO_REUSEADDR) { + return (T) Boolean.valueOf(isReuseAddress()); + } + if (option == SO_LINGER) { + return (T) Integer.valueOf(getSoLinger()); + } + if (option == IP_TOS) { + return (T) Integer.valueOf(getTrafficClass()); + } + if (option == ALLOW_HALF_CLOSURE) { + return (T) Boolean.valueOf(isAllowHalfClosure()); + } + + return super.getOption(option); + } + + @Override + public boolean setOption(ChannelOption option, T value) { + validate(option, value); + + if (option == SO_RCVBUF) { + setReceiveBufferSize((Integer) value); + } else if (option == SO_SNDBUF) { + setSendBufferSize((Integer) value); + } else if (option == TCP_NODELAY) { + setTcpNoDelay((Boolean) value); + } else if (option == SO_KEEPALIVE) { + setKeepAlive((Boolean) value); + } else if (option == SO_REUSEADDR) { + setReuseAddress((Boolean) value); + } else if (option == SO_LINGER) { + setSoLinger((Integer) value); + } else if (option == IP_TOS) { + setTrafficClass((Integer) value); + } else if (option == ALLOW_HALF_CLOSURE) { + setAllowHalfClosure((Boolean) value); + } else { + return super.setOption(option, value); + } + + return true; + } + + @Override + public int getReceiveBufferSize() { + try { + return javaSocket.getReceiveBufferSize(); + } catch (SocketException e) { + throw new ChannelException(e); + } + } + + @Override + public int getSendBufferSize() { + try { + return javaSocket.getSendBufferSize(); + } catch (SocketException e) { + throw new ChannelException(e); + } + } + + @Override + public int getSoLinger() { + try { + return javaSocket.getSoLinger(); + } catch (SocketException e) { + throw new ChannelException(e); + } + } + + @Override + public int getTrafficClass() { + try { + return javaSocket.getTrafficClass(); + } catch (SocketException e) { + throw new ChannelException(e); + } + } + + @Override + public boolean isKeepAlive() { + try { + return javaSocket.getKeepAlive(); + } catch (SocketException e) { + throw new ChannelException(e); + } + } + + @Override + public boolean isReuseAddress() { + try { + return javaSocket.getReuseAddress(); + } catch (SocketException e) { + throw new ChannelException(e); + } + } + + @Override + public boolean isTcpNoDelay() { + try { + return javaSocket.getTcpNoDelay(); + } catch (SocketException e) { + throw new ChannelException(e); + } + } + + @Override + public SocketChannelConfig setKeepAlive(boolean keepAlive) { + try { + javaSocket.setKeepAlive(keepAlive); + } catch (SocketException e) { + throw new ChannelException(e); + } + return this; + } + + @Override + public SocketChannelConfig setPerformancePreferences( + int connectionTime, int latency, int bandwidth) { + javaSocket.setPerformancePreferences(connectionTime, latency, bandwidth); + return this; + } + + @Override + public SocketChannelConfig setReceiveBufferSize(int receiveBufferSize) { + try { + javaSocket.setReceiveBufferSize(receiveBufferSize); + } catch (SocketException e) { + throw new ChannelException(e); + } + return this; + } + + @Override + public SocketChannelConfig setReuseAddress(boolean reuseAddress) { + try { + javaSocket.setReuseAddress(reuseAddress); + } catch (SocketException e) { + throw new ChannelException(e); + } + return this; + } + + @Override + public SocketChannelConfig setSendBufferSize(int sendBufferSize) { + try { + javaSocket.setSendBufferSize(sendBufferSize); + } catch (SocketException e) { + throw new ChannelException(e); + } + return this; + } + + @Override + public SocketChannelConfig setSoLinger(int soLinger) { + try { + if (soLinger < 0) { + javaSocket.setSoLinger(false, 0); + } else { + javaSocket.setSoLinger(true, soLinger); + } + } catch (SocketException e) { + throw new ChannelException(e); + } + return this; + } + + @Override + public SocketChannelConfig setTcpNoDelay(boolean tcpNoDelay) { + try { + javaSocket.setTcpNoDelay(tcpNoDelay); + } catch (SocketException e) { + throw new ChannelException(e); + } + return this; + } + + @Override + public SocketChannelConfig setTrafficClass(int trafficClass) { + try { + javaSocket.setTrafficClass(trafficClass); + } catch (SocketException e) { + throw new ChannelException(e); + } + return this; + } + + @Override + public boolean isAllowHalfClosure() { + return allowHalfClosure; + } + + @Override + public SocketChannelConfig setAllowHalfClosure(boolean allowHalfClosure) { + this.allowHalfClosure = allowHalfClosure; + return this; + } + + @Override + public SocketChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis) { + super.setConnectTimeoutMillis(connectTimeoutMillis); + return this; + } + + @Override + public SocketChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead) { + super.setMaxMessagesPerRead(maxMessagesPerRead); + return this; + } + + @Override + public SocketChannelConfig setWriteSpinCount(int writeSpinCount) { + super.setWriteSpinCount(writeSpinCount); + return this; + } + + @Override + public SocketChannelConfig setAllocator(ByteBufAllocator allocator) { + super.setAllocator(allocator); + return this; + } + + @Override + public SocketChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator) { + super.setRecvByteBufAllocator(allocator); + return this; + } + + @Override + public SocketChannelConfig setAutoRead(boolean autoRead) { + super.setAutoRead(autoRead); + return this; + } + + @Override + public SocketChannelConfig setWriteBufferHighWaterMark(int writeBufferHighWaterMark) { + super.setWriteBufferHighWaterMark(writeBufferHighWaterMark); + return this; + } + + @Override + public SocketChannelConfig setWriteBufferLowWaterMark(int writeBufferLowWaterMark) { + super.setWriteBufferLowWaterMark(writeBufferLowWaterMark); + return this; + } + + @Override + public SocketChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator) { + super.setMessageSizeEstimator(estimator); + return this; + } +} diff --git a/common/src/main/java/common/net/channel/socket/ServerSocketChannel.java b/common/src/main/java/common/net/channel/socket/ServerSocketChannel.java new file mode 100644 index 0000000..8808778 --- /dev/null +++ b/common/src/main/java/common/net/channel/socket/ServerSocketChannel.java @@ -0,0 +1,32 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.socket; + +import java.net.InetSocketAddress; + +import common.net.channel.ServerChannel; + +/** + * A TCP/IP {@link ServerChannel} which accepts incoming TCP/IP connections. + */ +public interface ServerSocketChannel extends ServerChannel { + @Override + ServerSocketChannelConfig config(); + @Override + InetSocketAddress localAddress(); + @Override + InetSocketAddress remoteAddress(); +} diff --git a/common/src/main/java/common/net/channel/socket/ServerSocketChannelConfig.java b/common/src/main/java/common/net/channel/socket/ServerSocketChannelConfig.java new file mode 100644 index 0000000..56138d6 --- /dev/null +++ b/common/src/main/java/common/net/channel/socket/ServerSocketChannelConfig.java @@ -0,0 +1,104 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.socket; + +import common.net.buffer.ByteBufAllocator; +import common.net.channel.ChannelConfig; +import common.net.channel.MessageSizeEstimator; +import common.net.channel.RecvByteBufAllocator; + +/** + * A {@link ChannelConfig} for a {@link ServerSocketChannel}. + * + *

Available options

+ * + * In addition to the options provided by {@link ChannelConfig}, + * {@link ServerSocketChannelConfig} allows the following options in the + * option map: + * + * + * + * + * + * + * + * + * + * + * + *
NameAssociated setter method
{@code "backlog"}{@link #setBacklog(int)}
{@code "reuseAddress"}{@link #setReuseAddress(boolean)}
{@code "receiveBufferSize"}{@link #setReceiveBufferSize(int)}
+ */ +public interface ServerSocketChannelConfig extends ChannelConfig { + + /** + * Gets the backlog value to specify when the channel binds to a local + * address. + */ + int getBacklog(); + + /** + * Sets the backlog value to specify when the channel binds to a local + * address. + */ + ServerSocketChannelConfig setBacklog(int backlog); + + /** + * Gets the {@link StandardSocketOptions#SO_REUSEADDR} option. + */ + boolean isReuseAddress(); + + /** + * Sets the {@link StandardSocketOptions#SO_REUSEADDR} option. + */ + ServerSocketChannelConfig setReuseAddress(boolean reuseAddress); + + /** + * Gets the {@link StandardSocketOptions#SO_RCVBUF} option. + */ + int getReceiveBufferSize(); + + /** + * Gets the {@link StandardSocketOptions#SO_SNDBUF} option. + */ + ServerSocketChannelConfig setReceiveBufferSize(int receiveBufferSize); + + /** + * Sets the performance preferences as specified in + * {@link ServerSocket#setPerformancePreferences(int, int, int)}. + */ + ServerSocketChannelConfig setPerformancePreferences(int connectionTime, int latency, int bandwidth); + + @Override + ServerSocketChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis); + + @Override + ServerSocketChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead); + + @Override + ServerSocketChannelConfig setWriteSpinCount(int writeSpinCount); + + @Override + ServerSocketChannelConfig setAllocator(ByteBufAllocator allocator); + + @Override + ServerSocketChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator); + + @Override + ServerSocketChannelConfig setAutoRead(boolean autoRead); + + @Override + ServerSocketChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator); +} diff --git a/common/src/main/java/common/net/channel/socket/SocketChannel.java b/common/src/main/java/common/net/channel/socket/SocketChannel.java new file mode 100644 index 0000000..f2b3006 --- /dev/null +++ b/common/src/main/java/common/net/channel/socket/SocketChannel.java @@ -0,0 +1,61 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.socket; + +import java.net.InetSocketAddress; + +import common.net.channel.Channel; +import common.net.channel.ChannelFuture; +import common.net.channel.ChannelPromise; + +/** + * A TCP/IP socket {@link Channel}. + */ +public interface SocketChannel extends Channel { + @Override + ServerSocketChannel parent(); + + @Override + SocketChannelConfig config(); + @Override + InetSocketAddress localAddress(); + @Override + InetSocketAddress remoteAddress(); + + /** + * Returns {@code true} if and only if the remote peer shut down its output so that no more + * data is received from this channel. Note that the semantic of this method is different from + * that of {@link Socket#shutdownInput()} and {@link Socket#isInputShutdown()}. + */ + boolean isInputShutdown(); + + /** + * @see Socket#isOutputShutdown() + */ + boolean isOutputShutdown(); + + /** + * @see Socket#shutdownOutput() + */ + ChannelFuture shutdownOutput(); + + /** + * @see Socket#shutdownOutput() + * + * Will notify the given {@link ChannelPromise} + */ + ChannelFuture shutdownOutput(ChannelPromise future); +} diff --git a/common/src/main/java/common/net/channel/socket/SocketChannelConfig.java b/common/src/main/java/common/net/channel/socket/SocketChannelConfig.java new file mode 100644 index 0000000..395bb63 --- /dev/null +++ b/common/src/main/java/common/net/channel/socket/SocketChannelConfig.java @@ -0,0 +1,174 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.socket; + +import common.net.buffer.ByteBufAllocator; +import common.net.channel.ChannelConfig; +import common.net.channel.MessageSizeEstimator; +import common.net.channel.RecvByteBufAllocator; + +/** + * A {@link ChannelConfig} for a {@link SocketChannel}. + * + *

Available options

+ * + * In addition to the options provided by {@link ChannelConfig}, + * {@link SocketChannelConfig} allows the following options in the option map: + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
NameAssociated setter method
{@link ChannelOption#SO_KEEPALIVE}{@link #setKeepAlive(boolean)}
{@link ChannelOption#SO_REUSEADDR}{@link #setReuseAddress(boolean)}
{@link ChannelOption#SO_LINGER}{@link #setSoLinger(int)}
{@link ChannelOption#TCP_NODELAY}{@link #setTcpNoDelay(boolean)}
{@link ChannelOption#SO_RCVBUF}{@link #setReceiveBufferSize(int)}
{@link ChannelOption#SO_SNDBUF}{@link #setSendBufferSize(int)}
{@link ChannelOption#IP_TOS}{@link #setTrafficClass(int)}
{@link ChannelOption#ALLOW_HALF_CLOSURE}{@link #setAllowHalfClosure(boolean)}
+ */ +public interface SocketChannelConfig extends ChannelConfig { + + /** + * Gets the {@link StandardSocketOptions#TCP_NODELAY} option. Please note that the default value of this option + * is {@code true} unlike the operating system default ({@code false}). However, for some buggy platforms, such as + * Android, that shows erratic behavior with Nagle's algorithm disabled, the default value remains to be + * {@code false}. + */ + boolean isTcpNoDelay(); + + /** + * Sets the {@link StandardSocketOptions#TCP_NODELAY} option. Please note that the default value of this option + * is {@code true} unlike the operating system default ({@code false}). However, for some buggy platforms, such as + * Android, that shows erratic behavior with Nagle's algorithm disabled, the default value remains to be + * {@code false}. + */ + SocketChannelConfig setTcpNoDelay(boolean tcpNoDelay); + + /** + * Gets the {@link StandardSocketOptions#SO_LINGER} option. + */ + int getSoLinger(); + + /** + * Sets the {@link StandardSocketOptions#SO_LINGER} option. + */ + SocketChannelConfig setSoLinger(int soLinger); + + /** + * Gets the {@link StandardSocketOptions#SO_SNDBUF} option. + */ + int getSendBufferSize(); + + /** + * Sets the {@link StandardSocketOptions#SO_SNDBUF} option. + */ + SocketChannelConfig setSendBufferSize(int sendBufferSize); + + /** + * Gets the {@link StandardSocketOptions#SO_RCVBUF} option. + */ + int getReceiveBufferSize(); + + /** + * Sets the {@link StandardSocketOptions#SO_RCVBUF} option. + */ + SocketChannelConfig setReceiveBufferSize(int receiveBufferSize); + + /** + * Gets the {@link StandardSocketOptions#SO_KEEPALIVE} option. + */ + boolean isKeepAlive(); + + /** + * Sets the {@link StandardSocketOptions#SO_KEEPALIVE} option. + */ + SocketChannelConfig setKeepAlive(boolean keepAlive); + + /** + * Gets the {@link StandardSocketOptions#IP_TOS} option. + */ + int getTrafficClass(); + + /** + * Sets the {@link StandardSocketOptions#IP_TOS} option. + */ + SocketChannelConfig setTrafficClass(int trafficClass); + + /** + * Gets the {@link StandardSocketOptions#SO_REUSEADDR} option. + */ + boolean isReuseAddress(); + + /** + * Sets the {@link StandardSocketOptions#SO_REUSEADDR} option. + */ + SocketChannelConfig setReuseAddress(boolean reuseAddress); + + /** + * Sets the performance preferences as specified in + * {@link Socket#setPerformancePreferences(int, int, int)}. + */ + SocketChannelConfig setPerformancePreferences(int connectionTime, int latency, int bandwidth); + + /** + * Returns {@code true} if and only if the channel should not close itself when its remote + * peer shuts down output to make the connection half-closed. If {@code false}, the connection + * is closed automatically when the remote peer shuts down output. + */ + boolean isAllowHalfClosure(); + + /** + * Sets whether the channel should not close itself when its remote peer shuts down output to + * make the connection half-closed. If {@code true} the connection is not closed when the + * remote peer shuts down output. Instead, + * {@link ChannelInboundHandler#userEventTriggered(ChannelHandlerContext, Object)} + * is invoked with a {@link ChannelInputShutdownEvent} object. If {@code false}, the connection + * is closed automatically. + */ + SocketChannelConfig setAllowHalfClosure(boolean allowHalfClosure); + + @Override + SocketChannelConfig setConnectTimeoutMillis(int connectTimeoutMillis); + + @Override + SocketChannelConfig setMaxMessagesPerRead(int maxMessagesPerRead); + + @Override + SocketChannelConfig setWriteSpinCount(int writeSpinCount); + + @Override + SocketChannelConfig setAllocator(ByteBufAllocator allocator); + + @Override + SocketChannelConfig setRecvByteBufAllocator(RecvByteBufAllocator allocator); + + @Override + SocketChannelConfig setAutoRead(boolean autoRead); + + @Override + SocketChannelConfig setMessageSizeEstimator(MessageSizeEstimator estimator); +} diff --git a/common/src/main/java/common/net/channel/socket/nio/NioServerSocketChannel.java b/common/src/main/java/common/net/channel/socket/nio/NioServerSocketChannel.java new file mode 100644 index 0000000..b006e1f --- /dev/null +++ b/common/src/main/java/common/net/channel/socket/nio/NioServerSocketChannel.java @@ -0,0 +1,197 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.socket.nio; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.ServerSocket; +import java.net.SocketAddress; +import java.nio.channels.SelectionKey; +import java.nio.channels.ServerSocketChannel; +import java.nio.channels.SocketChannel; +import java.nio.channels.spi.SelectorProvider; +import java.util.List; + +import common.net.channel.ChannelException; +import common.net.channel.ChannelMetadata; +import common.net.channel.ChannelOutboundBuffer; +import common.net.channel.nio.AbstractNioMessageChannel; +import common.net.channel.socket.DefaultServerSocketChannelConfig; +import common.net.channel.socket.ServerSocketChannelConfig; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * A {@link game.net.channel.socket.ServerSocketChannel} implementation which uses + * NIO selector based implementation to accept new connections. + */ +public class NioServerSocketChannel extends AbstractNioMessageChannel + implements common.net.channel.socket.ServerSocketChannel { + + private static final ChannelMetadata METADATA = new ChannelMetadata(false); + private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider(); + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(NioServerSocketChannel.class); + + private static ServerSocketChannel newSocket(SelectorProvider provider) { + try { + /** + * Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in + * {@link SelectorProvider#provider()} which is called by each ServerSocketChannel.open() otherwise. + * + * See #2308. + */ + return provider.openServerSocketChannel(); + } catch (IOException e) { + throw new ChannelException( + "Failed to open a server socket.", e); + } + } + + private final ServerSocketChannelConfig config; + + /** + * Create a new instance + */ + public NioServerSocketChannel() { + this(newSocket(DEFAULT_SELECTOR_PROVIDER)); + } + + /** + * Create a new instance using the given {@link SelectorProvider}. + */ + public NioServerSocketChannel(SelectorProvider provider) { + this(newSocket(provider)); + } + + /** + * Create a new instance using the given {@link ServerSocketChannel}. + */ + public NioServerSocketChannel(ServerSocketChannel channel) { + super(null, channel, SelectionKey.OP_ACCEPT); + config = new NioServerSocketChannelConfig(this, javaChannel().socket()); + } + + @Override + public InetSocketAddress localAddress() { + return (InetSocketAddress) super.localAddress(); + } + + @Override + public ChannelMetadata metadata() { + return METADATA; + } + + @Override + public ServerSocketChannelConfig config() { + return config; + } + + @Override + public boolean isActive() { + return javaChannel().socket().isBound(); + } + + @Override + public InetSocketAddress remoteAddress() { + return null; + } + + @Override + protected ServerSocketChannel javaChannel() { + return (ServerSocketChannel) super.javaChannel(); + } + + @Override + protected SocketAddress localAddress0() { + return javaChannel().socket().getLocalSocketAddress(); + } + + @Override + protected void doBind(SocketAddress localAddress) throws Exception { + javaChannel().socket().bind(localAddress, config.getBacklog()); + } + + @Override + protected void doClose() throws Exception { + javaChannel().close(); + } + + @Override + protected int doReadMessages(List buf) throws Exception { + SocketChannel ch = javaChannel().accept(); + + try { + if (ch != null) { + buf.add(new NioSocketChannel(this, ch)); + return 1; + } + } catch (Throwable t) { + logger.warn("Failed to create a new channel from an accepted socket.", t); + + try { + ch.close(); + } catch (Throwable t2) { + logger.warn("Failed to close a socket.", t2); + } + } + + return 0; + } + + // Unnecessary stuff + @Override + protected boolean doConnect( + SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { + throw new UnsupportedOperationException(); + } + + @Override + protected void doFinishConnect() throws Exception { + throw new UnsupportedOperationException(); + } + + @Override + protected SocketAddress remoteAddress0() { + return null; + } + + @Override + protected void doDisconnect() throws Exception { + throw new UnsupportedOperationException(); + } + + @Override + protected boolean doWriteMessage(Object msg, ChannelOutboundBuffer in) throws Exception { + throw new UnsupportedOperationException(); + } + + @Override + protected final Object filterOutboundMessage(Object msg) throws Exception { + throw new UnsupportedOperationException(); + } + + private final class NioServerSocketChannelConfig extends DefaultServerSocketChannelConfig { + private NioServerSocketChannelConfig(NioServerSocketChannel channel, ServerSocket javaSocket) { + super(channel, javaSocket); + } + + @Override + protected void autoReadCleared() { + setReadPending(false); + } + } +} diff --git a/common/src/main/java/common/net/channel/socket/nio/NioSocketChannel.java b/common/src/main/java/common/net/channel/socket/nio/NioSocketChannel.java new file mode 100644 index 0000000..1ce8c3b --- /dev/null +++ b/common/src/main/java/common/net/channel/socket/nio/NioSocketChannel.java @@ -0,0 +1,320 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.channel.socket.nio; + +import java.io.IOException; +import java.net.InetSocketAddress; +import java.net.Socket; +import java.net.SocketAddress; +import java.nio.ByteBuffer; +import java.nio.channels.SelectionKey; +import java.nio.channels.SocketChannel; +import java.nio.channels.spi.SelectorProvider; + +import common.net.buffer.ByteBuf; +import common.net.channel.Channel; +import common.net.channel.ChannelException; +import common.net.channel.ChannelFuture; +import common.net.channel.ChannelMetadata; +import common.net.channel.ChannelOutboundBuffer; +import common.net.channel.ChannelPromise; +import common.net.channel.EventLoop; +import common.net.channel.nio.AbstractNioByteChannel; +import common.net.channel.socket.DefaultSocketChannelConfig; +import common.net.channel.socket.ServerSocketChannel; +import common.net.channel.socket.SocketChannelConfig; +import common.net.util.internal.OneTimeTask; + +/** + * {@link game.net.channel.socket.SocketChannel} which uses NIO selector based implementation. + */ +public class NioSocketChannel extends AbstractNioByteChannel implements common.net.channel.socket.SocketChannel { + + private static final ChannelMetadata METADATA = new ChannelMetadata(false); + private static final SelectorProvider DEFAULT_SELECTOR_PROVIDER = SelectorProvider.provider(); + + private static SocketChannel newSocket(SelectorProvider provider) { + try { + /** + * Use the {@link SelectorProvider} to open {@link SocketChannel} and so remove condition in + * {@link SelectorProvider#provider()} which is called by each SocketChannel.open() otherwise. + * + * See #2308. + */ + return provider.openSocketChannel(); + } catch (IOException e) { + throw new ChannelException("Failed to open a socket.", e); + } + } + + private final SocketChannelConfig config; + + /** + * Create a new instance + */ + public NioSocketChannel() { + this(newSocket(DEFAULT_SELECTOR_PROVIDER)); + } + + /** + * Create a new instance using the given {@link SelectorProvider}. + */ + public NioSocketChannel(SelectorProvider provider) { + this(newSocket(provider)); + } + + /** + * Create a new instance using the given {@link SocketChannel}. + */ + public NioSocketChannel(SocketChannel socket) { + this(null, socket); + } + + /** + * Create a new instance + * + * @param parent the {@link Channel} which created this instance or {@code null} if it was created by the user + * @param socket the {@link SocketChannel} which will be used + */ + public NioSocketChannel(Channel parent, SocketChannel socket) { + super(parent, socket); + config = new NioSocketChannelConfig(this, socket.socket()); + } + + @Override + public ServerSocketChannel parent() { + return (ServerSocketChannel) super.parent(); + } + + @Override + public ChannelMetadata metadata() { + return METADATA; + } + + @Override + public SocketChannelConfig config() { + return config; + } + + @Override + protected SocketChannel javaChannel() { + return (SocketChannel) super.javaChannel(); + } + + @Override + public boolean isActive() { + SocketChannel ch = javaChannel(); + return ch.isOpen() && ch.isConnected(); + } + + @Override + public boolean isInputShutdown() { + return super.isInputShutdown(); + } + + @Override + public InetSocketAddress localAddress() { + return (InetSocketAddress) super.localAddress(); + } + + @Override + public InetSocketAddress remoteAddress() { + return (InetSocketAddress) super.remoteAddress(); + } + + @Override + public boolean isOutputShutdown() { + return javaChannel().socket().isOutputShutdown() || !isActive(); + } + + @Override + public ChannelFuture shutdownOutput() { + return shutdownOutput(newPromise()); + } + + @Override + public ChannelFuture shutdownOutput(final ChannelPromise promise) { + EventLoop loop = eventLoop(); + if (loop.inEventLoop()) { + try { + javaChannel().socket().shutdownOutput(); + promise.setSuccess(); + } catch (Throwable t) { + promise.setFailure(t); + } + } else { + loop.execute(new OneTimeTask() { + @Override + public void run() { + shutdownOutput(promise); + } + }); + } + return promise; + } + + @Override + protected SocketAddress localAddress0() { + return javaChannel().socket().getLocalSocketAddress(); + } + + @Override + protected SocketAddress remoteAddress0() { + return javaChannel().socket().getRemoteSocketAddress(); + } + + @Override + protected void doBind(SocketAddress localAddress) throws Exception { + javaChannel().socket().bind(localAddress); + } + + @Override + protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception { + if (localAddress != null) { + javaChannel().socket().bind(localAddress); + } + + boolean success = false; + try { + boolean connected = javaChannel().connect(remoteAddress); + if (!connected) { + selectionKey().interestOps(SelectionKey.OP_CONNECT); + } + success = true; + return connected; + } finally { + if (!success) { + doClose(); + } + } + } + + @Override + protected void doFinishConnect() throws Exception { + if (!javaChannel().finishConnect()) { + throw new Error(); + } + } + + @Override + protected void doDisconnect() throws Exception { + doClose(); + } + + @Override + protected void doClose() throws Exception { + javaChannel().close(); + } + + @Override + protected int doReadBytes(ByteBuf byteBuf) throws Exception { + return byteBuf.writeBytes(javaChannel(), byteBuf.writableBytes()); + } + + @Override + protected int doWriteBytes(ByteBuf buf) throws Exception { + final int expectedWrittenBytes = buf.readableBytes(); + return buf.readBytes(javaChannel(), expectedWrittenBytes); + } + +// @Override +// protected long doWriteFileRegion(FileRegion region) throws Exception { +// final long position = region.transfered(); +// return region.transferTo(javaChannel(), position); +// } + + @Override + protected void doWrite(ChannelOutboundBuffer in) throws Exception { + for (;;) { + int size = in.size(); + if (size == 0) { + // All written so clear OP_WRITE + clearOpWrite(); + break; + } + long writtenBytes = 0; + boolean done = false; + boolean setOpWrite = false; + + // Ensure the pending writes are made of ByteBufs only. + ByteBuffer[] nioBuffers = in.nioBuffers(); + int nioBufferCnt = in.nioBufferCount(); + long expectedWrittenBytes = in.nioBufferSize(); + SocketChannel ch = javaChannel(); + + // Always us nioBuffers() to workaround data-corruption. + // See https://github.com/netty/netty/issues/2761 + switch (nioBufferCnt) { + case 0: + // We have something else beside ByteBuffers to write so fallback to normal writes. + super.doWrite(in); + return; + case 1: + // Only one ByteBuf so use non-gathering write + ByteBuffer nioBuffer = nioBuffers[0]; + for (int i = config().getWriteSpinCount() - 1; i >= 0; i --) { + final int localWrittenBytes = ch.write(nioBuffer); + if (localWrittenBytes == 0) { + setOpWrite = true; + break; + } + expectedWrittenBytes -= localWrittenBytes; + writtenBytes += localWrittenBytes; + if (expectedWrittenBytes == 0) { + done = true; + break; + } + } + break; + default: + for (int i = config().getWriteSpinCount() - 1; i >= 0; i --) { + final long localWrittenBytes = ch.write(nioBuffers, 0, nioBufferCnt); + if (localWrittenBytes == 0) { + setOpWrite = true; + break; + } + expectedWrittenBytes -= localWrittenBytes; + writtenBytes += localWrittenBytes; + if (expectedWrittenBytes == 0) { + done = true; + break; + } + } + break; + } + + // Release the fully written buffers, and update the indexes of the partially written buffer. + in.removeBytes(writtenBytes); + + if (!done) { + // Did not write all buffers completely. + incompleteWrite(setOpWrite); + break; + } + } + } + + private final class NioSocketChannelConfig extends DefaultSocketChannelConfig { + private NioSocketChannelConfig(NioSocketChannel channel, Socket javaSocket) { + super(channel, javaSocket); + } + + @Override + protected void autoReadCleared() { + setReadPending(false); + } + } +} diff --git a/common/src/main/java/common/net/handler/codec/ByteToMessageDecoder.java b/common/src/main/java/common/net/handler/codec/ByteToMessageDecoder.java new file mode 100644 index 0000000..9957e17 --- /dev/null +++ b/common/src/main/java/common/net/handler/codec/ByteToMessageDecoder.java @@ -0,0 +1,306 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.handler.codec; + +import java.util.List; + +import common.net.buffer.ByteBuf; +import common.net.buffer.Unpooled; +import common.net.channel.ChannelHandlerContext; +import common.net.channel.ChannelInboundHandlerAdapter; +import common.net.util.internal.RecyclableArrayList; +import common.net.util.internal.StringUtil; + +/** + * {@link ChannelInboundHandlerAdapter} which decodes bytes in a stream-like fashion from one {@link ByteBuf} to an + * other Message type. + * + * For example here is an implementation which reads all readable bytes from + * the input {@link ByteBuf} and create a new {@link ByteBuf}. + * + *
+ *     public class SquareDecoder extends {@link ByteToMessageDecoder} {
+ *         {@code @Override}
+ *         public void decode({@link ChannelHandlerContext} ctx, {@link ByteBuf} in, List<Object> out)
+ *                 throws {@link Exception} {
+ *             out.add(in.readBytes(in.readableBytes()));
+ *         }
+ *     }
+ * 
+ * + * Be aware that sub-classes of {@link ByteToMessageDecoder} MUST NOT + * annotated with {@link @Sharable}. + */ +public abstract class ByteToMessageDecoder extends ChannelInboundHandlerAdapter { + + ByteBuf cumulation; + private boolean singleDecode; + private boolean decodeWasNull; + private boolean first; + + protected ByteToMessageDecoder() { + if (isSharable()) { + throw new IllegalStateException("@Sharable annotation is not allowed"); + } + } + + /** + * If set then only one message is decoded on each {@link #channelRead(ChannelHandlerContext, Object)} + * call. This may be useful if you need to do some protocol upgrade and want to make sure nothing is mixed up. + * + * Default is {@code false} as this has performance impacts. + */ + public void setSingleDecode(boolean singleDecode) { + this.singleDecode = singleDecode; + } + + /** + * If {@code true} then only one message is decoded on each + * {@link #channelRead(ChannelHandlerContext, Object)} call. + * + * Default is {@code false} as this has performance impacts. + */ + public boolean isSingleDecode() { + return singleDecode; + } + + /** + * Returns the actual number of readable bytes in the internal cumulative + * buffer of this decoder. You usually do not need to rely on this value + * to write a decoder. Use it only when you must use it at your own risk. + * This method is a shortcut to {@link #internalBuffer() internalBuffer().readableBytes()}. + */ + protected int actualReadableBytes() { + return internalBuffer().readableBytes(); + } + + /** + * Returns the internal cumulative buffer of this decoder. You usually + * do not need to access the internal buffer directly to write a decoder. + * Use it only when you must use it at your own risk. + */ + protected ByteBuf internalBuffer() { + if (cumulation != null) { + return cumulation; + } else { + return Unpooled.EMPTY_BUFFER; + } + } + + @Override + public final void handlerRemoved(ChannelHandlerContext ctx) throws Exception { + ByteBuf buf = internalBuffer(); + int readable = buf.readableBytes(); + if (buf.isReadable()) { + ByteBuf bytes = buf.readBytes(readable); + buf.release(); + ctx.fireChannelRead(bytes); + } else { + buf.release(); + } + cumulation = null; + ctx.fireChannelReadComplete(); + handlerRemoved0(ctx); + } + + /** + * Gets called after the {@link ByteToMessageDecoder} was removed from the actual context and it doesn't handle + * events anymore. + */ + protected void handlerRemoved0(ChannelHandlerContext ctx) throws Exception { } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + if (msg instanceof ByteBuf) { + RecyclableArrayList out = RecyclableArrayList.newInstance(); + try { + ByteBuf data = (ByteBuf) msg; + first = cumulation == null; + if (first) { + cumulation = data; + } else { + if (cumulation.writerIndex() > cumulation.maxCapacity() - data.readableBytes() + || cumulation.refCnt() > 1) { + // Expand cumulation (by replace it) when either there is not more room in the buffer + // or if the refCnt is greater then 1 which may happen when the user use slice().retain() or + // duplicate().retain(). + // + // See: + // - https://github.com/netty/netty/issues/2327 + // - https://github.com/netty/netty/issues/1764 + expandCumulation(ctx, data.readableBytes()); + } + cumulation.writeBytes(data); + data.release(); + } + callDecode(ctx, cumulation, out); + } catch (DecoderException e) { + throw e; + } catch (Throwable t) { + throw new DecoderException(t); + } finally { + if (cumulation != null && !cumulation.isReadable()) { + cumulation.release(); + cumulation = null; + } + int size = out.size(); + decodeWasNull = size == 0; + + for (int i = 0; i < size; i ++) { + ctx.fireChannelRead(out.get(i)); + } + out.recycle(); + } + } else { + ctx.fireChannelRead(msg); + } + } + + private void expandCumulation(ChannelHandlerContext ctx, int readable) { + ByteBuf oldCumulation = cumulation; + cumulation = ctx.alloc().buffer(oldCumulation.readableBytes() + readable); + cumulation.writeBytes(oldCumulation); + oldCumulation.release(); + } + + @Override + public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { + if (cumulation != null && !first && cumulation.refCnt() == 1) { + // discard some bytes if possible to make more room in the + // buffer but only if the refCnt == 1 as otherwise the user may have + // used slice().retain() or duplicate().retain(). + // + // See: + // - https://github.com/netty/netty/issues/2327 + // - https://github.com/netty/netty/issues/1764 + cumulation.discardSomeReadBytes(); + } + if (decodeWasNull) { + decodeWasNull = false; + if (!ctx.channel().config().isAutoRead()) { + ctx.read(); + } + } + ctx.fireChannelReadComplete(); + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + RecyclableArrayList out = RecyclableArrayList.newInstance(); + try { + if (cumulation != null) { + callDecode(ctx, cumulation, out); + decodeLast(ctx, cumulation, out); + } else { + decodeLast(ctx, Unpooled.EMPTY_BUFFER, out); + } + } catch (DecoderException e) { + throw e; + } catch (Exception e) { + throw new DecoderException(e); + } finally { + try { + if (cumulation != null) { + cumulation.release(); + cumulation = null; + } + int size = out.size(); + for (int i = 0; i < size; i++) { + ctx.fireChannelRead(out.get(i)); + } + if (size > 0) { + // Something was read, call fireChannelReadComplete() + ctx.fireChannelReadComplete(); + } + ctx.fireChannelInactive(); + } finally { + // recycle in all cases + out.recycle(); + } + } + } + + /** + * Called once data should be decoded from the given {@link ByteBuf}. This method will call + * {@link #decode(ChannelHandlerContext, ByteBuf, List)} as long as decoding should take place. + * + * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to + * @param in the {@link ByteBuf} from which to read data + * @param out the {@link List} to which decoded messages should be added + */ + protected void callDecode(ChannelHandlerContext ctx, ByteBuf in, List out) { + try { + while (in.isReadable()) { + int outSize = out.size(); + int oldInputLength = in.readableBytes(); + decode(ctx, in, out); + + // Check if this handler was removed before continuing the loop. + // If it was removed, it is not safe to continue to operate on the buffer. + // + // See https://github.com/netty/netty/issues/1664 + if (ctx.isRemoved()) { + break; + } + + if (outSize == out.size()) { + if (oldInputLength == in.readableBytes()) { + break; + } else { + continue; + } + } + + if (oldInputLength == in.readableBytes()) { + throw new DecoderException( + StringUtil.simpleClassName(getClass()) + + ".decode() did not read anything but decoded a message."); + } + + if (isSingleDecode()) { + break; + } + } + } catch (DecoderException e) { + throw e; + } catch (Throwable cause) { + throw new DecoderException(cause); + } + } + + /** + * Decode the from one {@link ByteBuf} to an other. This method will be called till either the input + * {@link ByteBuf} has nothing to read when return from this method or till nothing was read from the input + * {@link ByteBuf}. + * + * @param ctx the {@link ChannelHandlerContext} which this {@link ByteToMessageDecoder} belongs to + * @param in the {@link ByteBuf} from which to read data + * @param out the {@link List} to which decoded messages should be added + * @throws Exception is thrown if an error accour + */ + protected abstract void decode(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception; + + /** + * Is called one last time when the {@link ChannelHandlerContext} goes in-active. Which means the + * {@link #channelInactive(ChannelHandlerContext)} was triggered. + * + * By default this will just call {@link #decode(ChannelHandlerContext, ByteBuf, List)} but sub-classes may + * override this for some special cleanup operation. + */ + protected void decodeLast(ChannelHandlerContext ctx, ByteBuf in, List out) throws Exception { + decode(ctx, in, out); + } +} diff --git a/common/src/main/java/common/net/handler/codec/CodecException.java b/common/src/main/java/common/net/handler/codec/CodecException.java new file mode 100644 index 0000000..e024083 --- /dev/null +++ b/common/src/main/java/common/net/handler/codec/CodecException.java @@ -0,0 +1,51 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.handler.codec; + +/** + * An {@link Exception} which is thrown by a codec. + */ +public class CodecException extends RuntimeException { + + private static final long serialVersionUID = -1464830400709348473L; + + /** + * Creates a new instance. + */ + public CodecException() { + } + + /** + * Creates a new instance. + */ + public CodecException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Creates a new instance. + */ + public CodecException(String message) { + super(message); + } + + /** + * Creates a new instance. + */ + public CodecException(Throwable cause) { + super(cause); + } +} diff --git a/common/src/main/java/common/net/handler/codec/CorruptedFrameException.java b/common/src/main/java/common/net/handler/codec/CorruptedFrameException.java new file mode 100644 index 0000000..d62f750 --- /dev/null +++ b/common/src/main/java/common/net/handler/codec/CorruptedFrameException.java @@ -0,0 +1,52 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.handler.codec; + +/** + * An {@link DecoderException} which is thrown when the received frame data could not be decoded by + * an inbound handler. + */ +public class CorruptedFrameException extends DecoderException { + + private static final long serialVersionUID = 3918052232492988408L; + + /** + * Creates a new instance. + */ + public CorruptedFrameException() { + } + + /** + * Creates a new instance. + */ + public CorruptedFrameException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Creates a new instance. + */ + public CorruptedFrameException(String message) { + super(message); + } + + /** + * Creates a new instance. + */ + public CorruptedFrameException(Throwable cause) { + super(cause); + } +} diff --git a/common/src/main/java/common/net/handler/codec/DecoderException.java b/common/src/main/java/common/net/handler/codec/DecoderException.java new file mode 100644 index 0000000..35f2beb --- /dev/null +++ b/common/src/main/java/common/net/handler/codec/DecoderException.java @@ -0,0 +1,51 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.handler.codec; + +/** + * An {@link CodecException} which is thrown by a dencoder. + */ +public class DecoderException extends CodecException { + + private static final long serialVersionUID = 6926716840699621852L; + + /** + * Creates a new instance. + */ + public DecoderException() { + } + + /** + * Creates a new instance. + */ + public DecoderException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Creates a new instance. + */ + public DecoderException(String message) { + super(message); + } + + /** + * Creates a new instance. + */ + public DecoderException(Throwable cause) { + super(cause); + } +} diff --git a/common/src/main/java/common/net/handler/codec/EncoderException.java b/common/src/main/java/common/net/handler/codec/EncoderException.java new file mode 100644 index 0000000..549455d --- /dev/null +++ b/common/src/main/java/common/net/handler/codec/EncoderException.java @@ -0,0 +1,51 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.handler.codec; + +/** + * An {@link CodecException} which is thrown by an encoder. + */ +public class EncoderException extends CodecException { + + private static final long serialVersionUID = -5086121160476476774L; + + /** + * Creates a new instance. + */ + public EncoderException() { + } + + /** + * Creates a new instance. + */ + public EncoderException(String message, Throwable cause) { + super(message, cause); + } + + /** + * Creates a new instance. + */ + public EncoderException(String message) { + super(message); + } + + /** + * Creates a new instance. + */ + public EncoderException(Throwable cause) { + super(cause); + } +} diff --git a/common/src/main/java/common/net/handler/codec/MessageToByteEncoder.java b/common/src/main/java/common/net/handler/codec/MessageToByteEncoder.java new file mode 100644 index 0000000..9cb059d --- /dev/null +++ b/common/src/main/java/common/net/handler/codec/MessageToByteEncoder.java @@ -0,0 +1,154 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.handler.codec; + +import common.net.buffer.ByteBuf; +import common.net.buffer.Unpooled; +import common.net.channel.ChannelHandlerContext; +import common.net.channel.ChannelOutboundHandlerAdapter; +import common.net.channel.ChannelPromise; +import common.net.util.ReferenceCountUtil; +import common.net.util.internal.TypeParameterMatcher; + + +/** + * {@link ChannelOutboundHandlerAdapter} which encodes message in a stream-like fashion from one message to an + * {@link ByteBuf}. + * + * + * Example implementation which encodes {@link Integer}s to a {@link ByteBuf}. + * + *
+ *     public class IntegerEncoder extends {@link MessageToByteEncoder}<{@link Integer}> {
+ *         {@code @Override}
+ *         public void encode({@link ChannelHandlerContext} ctx, {@link Integer} msg, {@link ByteBuf} out)
+ *                 throws {@link Exception} {
+ *             out.writeInt(msg);
+ *         }
+ *     }
+ * 
+ */ +public abstract class MessageToByteEncoder extends ChannelOutboundHandlerAdapter { + + private final TypeParameterMatcher matcher; + private final boolean preferDirect; + + /** + * @see {@link #MessageToByteEncoder(boolean)} with {@code true} as boolean parameter. + */ + protected MessageToByteEncoder() { + this(true); + } + + /** + * @see {@link #MessageToByteEncoder(Class, boolean)} with {@code true} as boolean value. + */ + protected MessageToByteEncoder(Class outboundMessageType) { + this(outboundMessageType, true); + } + + /** + * Create a new instance which will try to detect the types to match out of the type parameter of the class. + * + * @param preferDirect {@code true} if a direct {@link ByteBuf} should be tried to be used as target for + * the encoded messages. If {@code false} is used it will allocate a heap + * {@link ByteBuf}, which is backed by an byte array. + */ + protected MessageToByteEncoder(boolean preferDirect) { + matcher = TypeParameterMatcher.find(this, MessageToByteEncoder.class, "I"); + this.preferDirect = preferDirect; + } + + /** + * Create a new instance + * + * @param outboundMessageType The tpye of messages to match + * @param preferDirect {@code true} if a direct {@link ByteBuf} should be tried to be used as target for + * the encoded messages. If {@code false} is used it will allocate a heap + * {@link ByteBuf}, which is backed by an byte array. + */ + protected MessageToByteEncoder(Class outboundMessageType, boolean preferDirect) { + matcher = TypeParameterMatcher.get(outboundMessageType); + this.preferDirect = preferDirect; + } + + /** + * Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next + * {@link ChannelOutboundHandler} in the {@link ChannelPipeline}. + */ + public boolean acceptOutboundMessage(Object msg) throws Exception { + return matcher.match(msg); + } + + @Override + public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception { + ByteBuf buf = null; + try { + if (acceptOutboundMessage(msg)) { + + I cast = (I) msg; + buf = allocateBuffer(ctx, cast, preferDirect); + try { + encode(ctx, cast, buf); + } finally { + ReferenceCountUtil.release(cast); + } + + if (buf.isReadable()) { + ctx.write(buf, promise); + } else { + buf.release(); + ctx.write(Unpooled.EMPTY_BUFFER, promise); + } + buf = null; + } else { + ctx.write(msg, promise); + } + } catch (EncoderException e) { + throw e; + } catch (Throwable e) { + throw new EncoderException(e); + } finally { + if (buf != null) { + buf.release(); + } + } + } + + /** + * Allocate a {@link ByteBuf} which will be used as argument of {@link #encode(ChannelHandlerContext, I, ByteBuf)}. + * Sub-classes may override this method to returna {@link ByteBuf} with a perfect matching {@code initialCapacity}. + */ + protected ByteBuf allocateBuffer(ChannelHandlerContext ctx, I msg, + boolean preferDirect) throws Exception { + if (preferDirect) { + return ctx.alloc().ioBuffer(); + } else { + return ctx.alloc().heapBuffer(); + } + } + + /** + * Encode a message into a {@link ByteBuf}. This method will be called for each written message that can be handled + * by this encoder. + * + * @param ctx the {@link ChannelHandlerContext} which this {@link MessageToByteEncoder} belongs to + * @param msg the message to encode + * @param out the {@link ByteBuf} into which the encoded message will be written + * @throws Exception is thrown if an error accour + */ + protected abstract void encode(ChannelHandlerContext ctx, I msg, ByteBuf out) throws Exception; +} diff --git a/common/src/main/java/common/net/handler/codec/MessageToMessageDecoder.java b/common/src/main/java/common/net/handler/codec/MessageToMessageDecoder.java new file mode 100644 index 0000000..6b6c2eb --- /dev/null +++ b/common/src/main/java/common/net/handler/codec/MessageToMessageDecoder.java @@ -0,0 +1,115 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.handler.codec; + +import java.util.List; + +import common.net.channel.ChannelHandlerContext; +import common.net.channel.ChannelInboundHandlerAdapter; +import common.net.util.ReferenceCountUtil; +import common.net.util.internal.RecyclableArrayList; +import common.net.util.internal.TypeParameterMatcher; + +/** + * {@link ChannelInboundHandlerAdapter} which decodes from one message to an other message. + * + * + * For example here is an implementation which decodes a {@link String} to an {@link Integer} which represent + * the length of the {@link String}. + * + *
+ *     public class StringToIntegerDecoder extends
+ *             {@link MessageToMessageDecoder}<{@link String}> {
+ *
+ *         {@code @Override}
+ *         public void decode({@link ChannelHandlerContext} ctx, {@link String} message,
+ *                            List<Object> out) throws {@link Exception} {
+ *             out.add(message.length());
+ *         }
+ *     }
+ * 
+ * + * Be aware that you need to call {@link ReferenceCounted#retain()} on messages that are just passed through if they + * are of type {@link ReferenceCounted}. This is needed as the {@link MessageToMessageDecoder} will call + * {@link ReferenceCounted#release()} on decoded messages. + * + */ +public abstract class MessageToMessageDecoder extends ChannelInboundHandlerAdapter { + + private final TypeParameterMatcher matcher; + + /** + * Create a new instance which will try to detect the types to match out of the type parameter of the class. + */ + protected MessageToMessageDecoder() { + matcher = TypeParameterMatcher.find(this, MessageToMessageDecoder.class, "I"); + } + + /** + * Create a new instance + * + * @param inboundMessageType The type of messages to match and so decode + */ + protected MessageToMessageDecoder(Class inboundMessageType) { + matcher = TypeParameterMatcher.get(inboundMessageType); + } + + /** + * Returns {@code true} if the given message should be handled. If {@code false} it will be passed to the next + * {@link ChannelInboundHandler} in the {@link ChannelPipeline}. + */ + public boolean acceptInboundMessage(Object msg) throws Exception { + return matcher.match(msg); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + RecyclableArrayList out = RecyclableArrayList.newInstance(); + try { + if (acceptInboundMessage(msg)) { + I cast = (I) msg; + try { + decode(ctx, cast, out); + } finally { + ReferenceCountUtil.release(cast); + } + } else { + out.add(msg); + } + } catch (DecoderException e) { + throw e; + } catch (Exception e) { + throw new DecoderException(e); + } finally { + int size = out.size(); + for (int i = 0; i < size; i ++) { + ctx.fireChannelRead(out.get(i)); + } + out.recycle(); + } + } + + /** + * Decode from one message to an other. This method will be called for each written message that can be handled + * by this encoder. + * + * @param ctx the {@link ChannelHandlerContext} which this {@link MessageToMessageDecoder} belongs to + * @param msg the message to decode to an other one + * @param out the {@link List} to which decoded messages should be added + * @throws Exception is thrown if an error accour + */ + protected abstract void decode(ChannelHandlerContext ctx, I msg, List out) throws Exception; +} diff --git a/common/src/main/java/common/net/handler/timeout/ReadTimeoutException.java b/common/src/main/java/common/net/handler/timeout/ReadTimeoutException.java new file mode 100644 index 0000000..3216773 --- /dev/null +++ b/common/src/main/java/common/net/handler/timeout/ReadTimeoutException.java @@ -0,0 +1,29 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.handler.timeout; + +/** + * A {@link TimeoutException} raised by {@link ReadTimeoutHandler} when no data + * was read within a certain period of time. + */ +public final class ReadTimeoutException extends TimeoutException { + + private static final long serialVersionUID = 169287984113283421L; + + public static final ReadTimeoutException INSTANCE = new ReadTimeoutException(); + + private ReadTimeoutException() { } +} diff --git a/common/src/main/java/common/net/handler/timeout/ReadTimeoutHandler.java b/common/src/main/java/common/net/handler/timeout/ReadTimeoutHandler.java new file mode 100644 index 0000000..d21019c --- /dev/null +++ b/common/src/main/java/common/net/handler/timeout/ReadTimeoutHandler.java @@ -0,0 +1,218 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.handler.timeout; + +import java.util.concurrent.ScheduledFuture; +import java.util.concurrent.TimeUnit; + +import common.net.channel.ChannelHandlerContext; +import common.net.channel.ChannelInboundHandlerAdapter; + +/** + * Raises a {@link ReadTimeoutException} when no data was read within a certain + * period of time. + * + *
+ * // The connection is closed when there is no inbound traffic
+ * // for 30 seconds.
+ *
+ * public class MyChannelInitializer extends {@link ChannelInitializer}<{@link Channel}> {
+ *     public void initChannel({@link Channel} channel) {
+ *         channel.pipeline().addLast("readTimeoutHandler", new {@link ReadTimeoutHandler}(30);
+ *         channel.pipeline().addLast("myHandler", new MyHandler());
+ *     }
+ * }
+ *
+ * // Handler should handle the {@link ReadTimeoutException}.
+ * public class MyHandler extends {@link ChannelDuplexHandler} {
+ *     {@code @Override}
+ *     public void exceptionCaught({@link ChannelHandlerContext} ctx, {@link Throwable} cause)
+ *             throws {@link Exception} {
+ *         if (cause instanceof {@link ReadTimeoutException}) {
+ *             // do something
+ *         } else {
+ *             super.exceptionCaught(ctx, cause);
+ *         }
+ *     }
+ * }
+ *
+ * {@link ServerBootstrap} bootstrap = ...;
+ * ...
+ * bootstrap.childHandler(new MyChannelInitializer());
+ * ...
+ * 
+ * @see WriteTimeoutHandler + * @see IdleStateHandler + */ +public class ReadTimeoutHandler extends ChannelInboundHandlerAdapter { + private static final long MIN_TIMEOUT_NANOS = TimeUnit.MILLISECONDS.toNanos(1); + + private final long timeoutNanos; + + private volatile ScheduledFuture timeout; + private volatile long lastReadTime; + + private volatile int state; // 0 - none, 1 - Initialized, 2 - Destroyed; + + private boolean closed; + + /** + * Creates a new instance. + * + * @param timeoutSeconds + * read timeout in seconds + */ + public ReadTimeoutHandler(int timeoutSeconds) { + this(timeoutSeconds, TimeUnit.SECONDS); + } + + /** + * Creates a new instance. + * + * @param timeout + * read timeout + * @param unit + * the {@link TimeUnit} of {@code timeout} + */ + public ReadTimeoutHandler(long timeout, TimeUnit unit) { + if (unit == null) { + throw new NullPointerException("unit"); + } + + if (timeout <= 0) { + timeoutNanos = 0; + } else { + timeoutNanos = Math.max(unit.toNanos(timeout), MIN_TIMEOUT_NANOS); + } + } + + @Override + public void handlerAdded(ChannelHandlerContext ctx) throws Exception { + if (ctx.channel().isActive() && ctx.channel().isRegistered()) { + // channelActvie() event has been fired already, which means this.channelActive() will + // not be invoked. We have to initialize here instead. + initialize(ctx); + } else { + // channelActive() event has not been fired yet. this.channelActive() will be invoked + // and initialization will occur there. + } + } + + @Override + public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { + destroy(); + } + + @Override + public void channelRegistered(ChannelHandlerContext ctx) throws Exception { + // Initialize early if channel is active already. + if (ctx.channel().isActive()) { + initialize(ctx); + } + super.channelRegistered(ctx); + } + + @Override + public void channelActive(ChannelHandlerContext ctx) throws Exception { + // This method will be invoked only if this handler was added + // before channelActive() event is fired. If a user adds this handler + // after the channelActive() event, initialize() will be called by beforeAdd(). + initialize(ctx); + super.channelActive(ctx); + } + + @Override + public void channelInactive(ChannelHandlerContext ctx) throws Exception { + destroy(); + super.channelInactive(ctx); + } + + @Override + public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception { + lastReadTime = System.nanoTime(); + ctx.fireChannelRead(msg); + } + + private void initialize(ChannelHandlerContext ctx) { + // Avoid the case where destroy() is called before scheduling timeouts. + // See: https://github.com/netty/netty/issues/143 + switch (state) { + case 1: + case 2: + return; + } + + state = 1; + + lastReadTime = System.nanoTime(); + if (timeoutNanos > 0) { + timeout = ctx.executor().schedule( + new ReadTimeoutTask(ctx), + timeoutNanos, TimeUnit.NANOSECONDS); + } + } + + private void destroy() { + state = 2; + + if (timeout != null) { + timeout.cancel(false); + timeout = null; + } + } + + /** + * Is called when a read timeout was detected. + */ + protected void readTimedOut(ChannelHandlerContext ctx) throws Exception { + if (!closed) { + ctx.fireExceptionCaught(ReadTimeoutException.INSTANCE); + ctx.close(); + closed = true; + } + } + + private final class ReadTimeoutTask implements Runnable { + + private final ChannelHandlerContext ctx; + + ReadTimeoutTask(ChannelHandlerContext ctx) { + this.ctx = ctx; + } + + @Override + public void run() { + if (!ctx.channel().isOpen()) { + return; + } + + long currentTime = System.nanoTime(); + long nextDelay = timeoutNanos - (currentTime - lastReadTime); + if (nextDelay <= 0) { + // Read timed out - set a new timeout and notify the callback. + timeout = ctx.executor().schedule(this, timeoutNanos, TimeUnit.NANOSECONDS); + try { + readTimedOut(ctx); + } catch (Throwable t) { + ctx.fireExceptionCaught(t); + } + } else { + // Read occurred before the timeout - set a new timeout with shorter delay. + timeout = ctx.executor().schedule(this, nextDelay, TimeUnit.NANOSECONDS); + } + } + } +} diff --git a/common/src/main/java/common/net/handler/timeout/TimeoutException.java b/common/src/main/java/common/net/handler/timeout/TimeoutException.java new file mode 100644 index 0000000..491f161 --- /dev/null +++ b/common/src/main/java/common/net/handler/timeout/TimeoutException.java @@ -0,0 +1,34 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.handler.timeout; + +import common.net.channel.ChannelException; + +/** + * A {@link TimeoutException} when no data was either read or written within a + * certain period of time. + */ +public class TimeoutException extends ChannelException { + + private static final long serialVersionUID = 4673641882869672533L; + + TimeoutException() { } + + @Override + public Throwable fillInStackTrace() { + return this; + } +} diff --git a/common/src/main/java/common/net/util/Attribute.java b/common/src/main/java/common/net/util/Attribute.java new file mode 100644 index 0000000..56075ee --- /dev/null +++ b/common/src/main/java/common/net/util/Attribute.java @@ -0,0 +1,67 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util; + +/** + * An attribute which allows to store a value reference. It may be updated atomically and so is thread-safe. + * + * @param the type of the value it holds. + */ +public interface Attribute { + + /** + * Returns the key of this attribute. + */ + AttributeKey key(); + + /** + * Returns the current value, which may be {@code null} + */ + T get(); + + /** + * Sets the value + */ + void set(T value); + + /** + * Atomically sets to the given value and returns the old value which may be {@code null} if non was set before. + */ + T getAndSet(T value); + + /** + * Atomically sets to the given value if this {@link Attribute} does not contain a value at the moment. + * If it was not possible to set the value as it contains a value it will just return the current value. + */ + T setIfAbsent(T value); + + /** + * Removes this attribute from the {@link AttributeMap} and returns the old value.. Subsequent {@link #get()} + * calls will return @{code null}. + */ + T getAndRemove(); + + /** + * Atomically sets the value to the given updated value if the current value == the expected value. + * If it the set was successful it returns {@code true} otherwise {@code false}. + */ + boolean compareAndSet(T oldValue, T newValue); + + /** + * Removes this attribute from the {@link AttributeMap}. Subsequent {@link #get()} calls will return @{code null}. + */ + void remove(); +} diff --git a/common/src/main/java/common/net/util/AttributeKey.java b/common/src/main/java/common/net/util/AttributeKey.java new file mode 100644 index 0000000..30f87f0 --- /dev/null +++ b/common/src/main/java/common/net/util/AttributeKey.java @@ -0,0 +1,44 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util; + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * Key which can be used to access {@link Attribute} out of the {@link AttributeMap}. Be aware that it is not be + * possible to have multiple keys with the same name. + * + * + * @param the type of the {@link Attribute} which can be accessed via this {@link AttributeKey}. + */ + // 'T' is used only at compile time +public final class AttributeKey extends UniqueName { + + private static final ConcurrentMap names = new ConcurrentHashMap(); + + /** + * Creates a new {@link AttributeKey} with the specified {@code name}. + */ + + public static AttributeKey valueOf(String name) { + return new AttributeKey(name); + } + + private AttributeKey(String name) { + super(names, name); + } +} diff --git a/common/src/main/java/common/net/util/AttributeMap.java b/common/src/main/java/common/net/util/AttributeMap.java new file mode 100644 index 0000000..2a1e85a --- /dev/null +++ b/common/src/main/java/common/net/util/AttributeMap.java @@ -0,0 +1,29 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util; + +/** + * Holds {@link Attribute}s which can be accessed via {@link AttributeKey}. + * + * Implementations must be Thread-safe. + */ +public interface AttributeMap { + /** + * Get the {@link Attribute} for the given {@link AttributeKey}. This method will never return null, but may return + * an {@link Attribute} which does not have a value set yet. + */ + Attribute attr(AttributeKey key); +} diff --git a/common/src/main/java/common/net/util/CharsetUtil.java b/common/src/main/java/common/net/util/CharsetUtil.java new file mode 100644 index 0000000..5e69ad3 --- /dev/null +++ b/common/src/main/java/common/net/util/CharsetUtil.java @@ -0,0 +1,117 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util; + +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CodingErrorAction; +import java.util.Map; + +import common.net.util.internal.InternalThreadLocalMap; + +/** + * A utility class that provides various common operations and constants + * related with {@link Charset} and its relevant classes. + */ +public final class CharsetUtil { + + /** + * 16-bit UTF (UCS Transformation Format) whose byte order is identified by + * an optional byte-order mark + */ + public static final Charset UTF_16 = Charset.forName("UTF-16"); + + /** + * 16-bit UTF (UCS Transformation Format) whose byte order is big-endian + */ + public static final Charset UTF_16BE = Charset.forName("UTF-16BE"); + + /** + * 16-bit UTF (UCS Transformation Format) whose byte order is little-endian + */ + public static final Charset UTF_16LE = Charset.forName("UTF-16LE"); + + /** + * 8-bit UTF (UCS Transformation Format) + */ + public static final Charset UTF_8 = Charset.forName("UTF-8"); + + /** + * ISO Latin Alphabet No. 1, as known as ISO-LATIN-1 + */ + public static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); + + /** + * 7-bit ASCII, as known as ISO646-US or the Basic Latin block of the + * Unicode character set + */ + public static final Charset US_ASCII = Charset.forName("US-ASCII"); + + /** + * Returns a cached thread-local {@link CharsetEncoder} for the specified + * charset. + */ + public static CharsetEncoder getEncoder(Charset charset) { + if (charset == null) { + throw new NullPointerException("charset"); + } + + Map map = InternalThreadLocalMap.get().charsetEncoderCache(); + CharsetEncoder e = map.get(charset); + if (e != null) { + e.reset(); + e.onMalformedInput(CodingErrorAction.REPLACE); + e.onUnmappableCharacter(CodingErrorAction.REPLACE); + return e; + } + + e = charset.newEncoder(); + e.onMalformedInput(CodingErrorAction.REPLACE); + e.onUnmappableCharacter(CodingErrorAction.REPLACE); + map.put(charset, e); + return e; + } + + /** + * Returns a cached thread-local {@link CharsetDecoder} for the specified + * charset. + */ + public static CharsetDecoder getDecoder(Charset charset) { + if (charset == null) { + throw new NullPointerException("charset"); + } + + Map map = InternalThreadLocalMap.get().charsetDecoderCache(); + CharsetDecoder d = map.get(charset); + if (d != null) { + d.reset(); + d.onMalformedInput(CodingErrorAction.REPLACE); + d.onUnmappableCharacter(CodingErrorAction.REPLACE); + return d; + } + + d = charset.newDecoder(); + d.onMalformedInput(CodingErrorAction.REPLACE); + d.onUnmappableCharacter(CodingErrorAction.REPLACE); + map.put(charset, d); + return d; + } + + private CharsetUtil() { + // Unused + } +} diff --git a/common/src/main/java/common/net/util/DefaultAttributeMap.java b/common/src/main/java/common/net/util/DefaultAttributeMap.java new file mode 100644 index 0000000..83c28ab --- /dev/null +++ b/common/src/main/java/common/net/util/DefaultAttributeMap.java @@ -0,0 +1,177 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util; + +import java.util.concurrent.atomic.AtomicReference; +import java.util.concurrent.atomic.AtomicReferenceArray; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; + +/** + * Default {@link AttributeMap} implementation which use simple synchronization per bucket to keep the memory overhead + * as low as possible. + */ +public class DefaultAttributeMap implements AttributeMap { + + + private static final AtomicReferenceFieldUpdater updater; + + static { + + AtomicReferenceFieldUpdater referenceFieldUpdater = + null; + if (referenceFieldUpdater == null) { + referenceFieldUpdater = AtomicReferenceFieldUpdater + .newUpdater(DefaultAttributeMap.class, AtomicReferenceArray.class, "attributes"); + } + updater = referenceFieldUpdater; + } + + private static final int BUCKET_SIZE = 4; + private static final int MASK = BUCKET_SIZE - 1; + + // Initialize lazily to reduce memory consumption; updated by AtomicReferenceFieldUpdater above. + + private volatile AtomicReferenceArray> attributes; + + + @Override + public Attribute attr(AttributeKey key) { + if (key == null) { + throw new NullPointerException("key"); + } + AtomicReferenceArray> attributes = this.attributes; + if (attributes == null) { + // Not using ConcurrentHashMap due to high memory consumption. + attributes = new AtomicReferenceArray>(BUCKET_SIZE); + + if (!updater.compareAndSet(this, null, attributes)) { + attributes = this.attributes; + } + } + + int i = index(key); + DefaultAttribute head = attributes.get(i); + if (head == null) { + // No head exists yet which means we may be able to add the attribute without synchronization and just + // use compare and set. At worst we need to fallback to synchronization + head = new DefaultAttribute(key); + if (attributes.compareAndSet(i, null, head)) { + // we were able to add it so return the head right away + return (Attribute) head; + } else { + head = attributes.get(i); + } + } + + synchronized (head) { + DefaultAttribute curr = head; + for (;;) { + if (!curr.removed && curr.key == key) { + return (Attribute) curr; + } + + DefaultAttribute next = curr.next; + if (next == null) { + DefaultAttribute attr = new DefaultAttribute(head, key); + curr.next = attr; + attr.prev = curr; + return attr; + } else { + curr = next; + } + } + } + } + + private static int index(AttributeKey key) { + return key.id() & MASK; + } + + + private static final class DefaultAttribute extends AtomicReference implements Attribute { + + private static final long serialVersionUID = -2661411462200283011L; + + // The head of the linked-list this attribute belongs to, which may be itself + private final DefaultAttribute head; + private final AttributeKey key; + + // Double-linked list to prev and next node to allow fast removal + private DefaultAttribute prev; + private DefaultAttribute next; + + // Will be set to true one the attribute is removed via getAndRemove() or remove() + private volatile boolean removed; + + DefaultAttribute(DefaultAttribute head, AttributeKey key) { + this.head = head; + this.key = key; + } + + DefaultAttribute(AttributeKey key) { + head = this; + this.key = key; + } + + @Override + public AttributeKey key() { + return key; + } + + @Override + public T setIfAbsent(T value) { + while (!compareAndSet(null, value)) { + T old = get(); + if (old != null) { + return old; + } + } + return null; + } + + @Override + public T getAndRemove() { + removed = true; + T oldValue = getAndSet(null); + remove0(); + return oldValue; + } + + @Override + public void remove() { + removed = true; + set(null); + remove0(); + } + + private void remove0() { + synchronized (head) { + // We only update the linked-list structure if prev != null because if it is null this + // DefaultAttribute acts also as head. The head must never be removed completely and just be + // marked as removed as all synchronization is done on the head itself for each bucket. + // The head itself will be GC'ed once the DefaultAttributeMap is GC'ed. So at most 5 heads will + // be removed lazy as the array size is 5. + if (prev != null) { + prev.next = next; + + if (next != null) { + next.prev = prev; + } + } + } + } + } +} diff --git a/common/src/main/java/common/net/util/IllegalReferenceCountException.java b/common/src/main/java/common/net/util/IllegalReferenceCountException.java new file mode 100644 index 0000000..eed5aa7 --- /dev/null +++ b/common/src/main/java/common/net/util/IllegalReferenceCountException.java @@ -0,0 +1,48 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util; + +/** + * An {@link IllegalStateException} which is raised when a user attempts to access a {@link ReferenceCounted} whose + * reference count has been decreased to 0 (and consequently freed). + */ +public class IllegalReferenceCountException extends IllegalStateException { + + private static final long serialVersionUID = -2507492394288153468L; + + public IllegalReferenceCountException() { } + + public IllegalReferenceCountException(int refCnt) { + this("refCnt: " + refCnt); + } + + public IllegalReferenceCountException(int refCnt, int increment) { + this("refCnt: " + refCnt + ", " + (increment > 0? "increment: " + increment : "decrement: " + -increment)); + } + + public IllegalReferenceCountException(String message) { + super(message); + } + + public IllegalReferenceCountException(String message, Throwable cause) { + super(message, cause); + } + + public IllegalReferenceCountException(Throwable cause) { + super(cause); + } +} diff --git a/common/src/main/java/common/net/util/NetUtil.java b/common/src/main/java/common/net/util/NetUtil.java new file mode 100644 index 0000000..99e420a --- /dev/null +++ b/common/src/main/java/common/net/util/NetUtil.java @@ -0,0 +1,614 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileReader; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; +import java.util.StringTokenizer; + +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; +import common.util.Util; + +/** + * A class that holds a number of network-related constants. + *

+ * This class borrowed some of its methods from a modified fork of the + * Inet6Util class which was part of Apache Harmony. + */ +public final class NetUtil { + + /** + * The {@link Inet4Address} that represents the IPv4 loopback address '127.0.0.1' + */ + public static final Inet4Address LOCALHOST4; + + /** + * The {@link Inet6Address} that represents the IPv6 loopback address '::1' + */ + public static final Inet6Address LOCALHOST6; + + /** + * The {@link InetAddress} that represents the loopback address. If IPv6 stack is available, it will refer to + * {@link #LOCALHOST6}. Otherwise, {@link #LOCALHOST4}. + */ + public static final InetAddress LOCALHOST; + + /** + * The loopback {@link NetworkInterface} of the current machine + */ + public static final NetworkInterface LOOPBACK_IF; + + /** + * The SOMAXCONN value of the current machine. If failed to get the value, 3072 is used as a + * default value. + */ + public static final int SOMAXCONN; + + /** + * The logger being used by this class + */ + private static final InternalLogger logger = InternalLoggerFactory.getInstance(NetUtil.class); + + static { + byte[] LOCALHOST4_BYTES = {127, 0, 0, 1}; + byte[] LOCALHOST6_BYTES = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1}; + + // Create IPv4 loopback address. + Inet4Address localhost4 = null; + try { + localhost4 = (Inet4Address) InetAddress.getByAddress(LOCALHOST4_BYTES); + } catch (Exception e) { + // We should not get here as long as the length of the address is correct. + Util.throwUnchecked(e); + } + LOCALHOST4 = localhost4; + + // Create IPv6 loopback address. + Inet6Address localhost6 = null; + try { + localhost6 = (Inet6Address) InetAddress.getByAddress(LOCALHOST6_BYTES); + } catch (Exception e) { + // We should not get here as long as the length of the address is correct. + Util.throwUnchecked(e); + } + LOCALHOST6 = localhost6; + + // Retrieve the list of available network interfaces. + List ifaces = new ArrayList(); + try { + for (Enumeration i = NetworkInterface.getNetworkInterfaces(); i.hasMoreElements();) { + NetworkInterface iface = i.nextElement(); + // Use the interface with proper INET addresses only. + if (iface.getInetAddresses().hasMoreElements()) { + ifaces.add(iface); + } + } + } catch (SocketException e) { + logger.warn("Failed to retrieve the list of available network interfaces", e); + } + + // Find the first loopback interface available from its INET address (127.0.0.1 or ::1) + // Note that we do not use NetworkInterface.isLoopback() in the first place because it takes long time + // on a certain environment. (e.g. Windows with -Djava.net.preferIPv4Stack=true) + NetworkInterface loopbackIface = null; + InetAddress loopbackAddr = null; + loop: for (NetworkInterface iface: ifaces) { + for (Enumeration i = iface.getInetAddresses(); i.hasMoreElements();) { + InetAddress addr = i.nextElement(); + if (addr.isLoopbackAddress()) { + // Found + loopbackIface = iface; + loopbackAddr = addr; + break loop; + } + } + } + + // If failed to find the loopback interface from its INET address, fall back to isLoopback(). + if (loopbackIface == null) { + try { + for (NetworkInterface iface: ifaces) { + if (iface.isLoopback()) { + Enumeration i = iface.getInetAddresses(); + if (i.hasMoreElements()) { + // Found the one with INET address. + loopbackIface = iface; + loopbackAddr = i.nextElement(); + break; + } + } + } + + if (loopbackIface == null) { + logger.warn("Failed to find the loopback interface"); + } + } catch (SocketException e) { + logger.warn("Failed to find the loopback interface", e); + } + } + + if (loopbackIface != null) { + // Found the loopback interface with an INET address. + logger.debug( + "Loopback interface: {} ({}, {})", + loopbackIface.getName(), loopbackIface.getDisplayName(), loopbackAddr.getHostAddress()); + } else { + // Could not find the loopback interface, but we can't leave LOCALHOST as null. + // Use LOCALHOST6 or LOCALHOST4, preferably the IPv6 one. + if (loopbackAddr == null) { + try { + if (NetworkInterface.getByInetAddress(LOCALHOST6) != null) { + logger.debug("Using hard-coded IPv6 localhost address: {}", localhost6); + loopbackAddr = localhost6; + } + } catch (Exception e) { + // Ignore + } finally { + if (loopbackAddr == null) { + logger.debug("Using hard-coded IPv4 localhost address: {}", localhost4); + loopbackAddr = localhost4; + } + } + } + } + + LOOPBACK_IF = loopbackIface; + LOCALHOST = loopbackAddr; + + // Determine the default somaxconn (server socket backlog) value of the platform. + // The known defaults: + // - Windows NT Server 4.0+: 200 + // - Linux and Mac OS X: 128 + int somaxconn = Util.WINDOWS ? 200 : 128; + File file = new File("/proc/sys/net/core/somaxconn"); + if (file.exists()) { + BufferedReader in = null; + try { + in = new BufferedReader(new FileReader(file)); + somaxconn = Integer.parseInt(in.readLine()); + if (logger.isDebugEnabled()) { + logger.debug("{}: {}", file, somaxconn); + } + } catch (Exception e) { + logger.debug("Failed to get SOMAXCONN from: {}", file, e); + } finally { + if (in != null) { + try { + in.close(); + } catch (Exception e) { + // Ignored. + } + } + } + } else { + if (logger.isDebugEnabled()) { + logger.debug("{}: {} (non-existent)", file, somaxconn); + } + } + + SOMAXCONN = somaxconn; + } + + /** + * Creates an byte[] based on an ipAddressString. No error handling is + * performed here. + */ + public static byte[] createByteArrayFromIpAddressString(String ipAddressString) { + + if (isValidIpV4Address(ipAddressString)) { + StringTokenizer tokenizer = new StringTokenizer(ipAddressString, "."); + String token; + int tempInt; + byte[] byteAddress = new byte[4]; + for (int i = 0; i < 4; i ++) { + token = tokenizer.nextToken(); + tempInt = Integer.parseInt(token); + byteAddress[i] = (byte) tempInt; + } + + return byteAddress; + } + + if (isValidIpV6Address(ipAddressString)) { + if (ipAddressString.charAt(0) == '[') { + ipAddressString = ipAddressString.substring(1, ipAddressString.length() - 1); + } + + StringTokenizer tokenizer = new StringTokenizer(ipAddressString, ":.", true); + ArrayList hexStrings = new ArrayList(); + ArrayList decStrings = new ArrayList(); + String token = ""; + String prevToken = ""; + int doubleColonIndex = -1; // If a double colon exists, we need to + // insert 0s. + + // Go through the tokens, including the seperators ':' and '.' + // When we hit a : or . the previous token will be added to either + // the hex list or decimal list. In the case where we hit a :: + // we will save the index of the hexStrings so we can add zeros + // in to fill out the string + while (tokenizer.hasMoreTokens()) { + prevToken = token; + token = tokenizer.nextToken(); + + if (":".equals(token)) { + if (":".equals(prevToken)) { + doubleColonIndex = hexStrings.size(); + } else if (!prevToken.isEmpty()) { + hexStrings.add(prevToken); + } + } else if (".".equals(token)) { + decStrings.add(prevToken); + } + } + + if (":".equals(prevToken)) { + if (":".equals(token)) { + doubleColonIndex = hexStrings.size(); + } else { + hexStrings.add(token); + } + } else if (".".equals(prevToken)) { + decStrings.add(token); + } + + // figure out how many hexStrings we should have + // also check if it is a IPv4 address + int hexStringsLength = 8; + + // If we have an IPv4 address tagged on at the end, subtract + // 4 bytes, or 2 hex words from the total + if (!decStrings.isEmpty()) { + hexStringsLength -= 2; + } + + // if we hit a double Colon add the appropriate hex strings + if (doubleColonIndex != -1) { + int numberToInsert = hexStringsLength - hexStrings.size(); + for (int i = 0; i < numberToInsert; i ++) { + hexStrings.add(doubleColonIndex, "0"); + } + } + + byte[] ipByteArray = new byte[16]; + + // Finally convert these strings to bytes... + for (int i = 0; i < hexStrings.size(); i ++) { + convertToBytes(hexStrings.get(i), ipByteArray, i * 2); + } + + // Now if there are any decimal values, we know where they go... + for (int i = 0; i < decStrings.size(); i ++) { + ipByteArray[i + 12] = (byte) (Integer.parseInt(decStrings.get(i)) & 255); + } + return ipByteArray; + } + return null; + } + + /** + * Converts a 4 character hex word into a 2 byte word equivalent + */ + private static void convertToBytes(String hexWord, byte[] ipByteArray, int byteIndex) { + + int hexWordLength = hexWord.length(); + int hexWordIndex = 0; + ipByteArray[byteIndex] = 0; + ipByteArray[byteIndex + 1] = 0; + int charValue; + + // high order 4 bits of first byte + if (hexWordLength > 3) { + charValue = getIntValue(hexWord.charAt(hexWordIndex ++)); + ipByteArray[byteIndex] |= charValue << 4; + } + + // low order 4 bits of the first byte + if (hexWordLength > 2) { + charValue = getIntValue(hexWord.charAt(hexWordIndex ++)); + ipByteArray[byteIndex] |= charValue; + } + + // high order 4 bits of second byte + if (hexWordLength > 1) { + charValue = getIntValue(hexWord.charAt(hexWordIndex ++)); + ipByteArray[byteIndex + 1] |= charValue << 4; + } + + // low order 4 bits of the first byte + charValue = getIntValue(hexWord.charAt(hexWordIndex)); + ipByteArray[byteIndex + 1] |= charValue & 15; + } + + static int getIntValue(char c) { + + switch (c) { + case '0': + return 0; + case '1': + return 1; + case '2': + return 2; + case '3': + return 3; + case '4': + return 4; + case '5': + return 5; + case '6': + return 6; + case '7': + return 7; + case '8': + return 8; + case '9': + return 9; + } + + c = Character.toLowerCase(c); + switch (c) { + case 'a': + return 10; + case 'b': + return 11; + case 'c': + return 12; + case 'd': + return 13; + case 'e': + return 14; + case 'f': + return 15; + } + return 0; + } + + public static boolean isValidIpV6Address(String ipAddress) { + int length = ipAddress.length(); + boolean doubleColon = false; + int numberOfColons = 0; + int numberOfPeriods = 0; + int numberOfPercent = 0; + StringBuilder word = new StringBuilder(); + char c = 0; + char prevChar; + int offset = 0; // offset for [] ip addresses + + if (length < 2) { + return false; + } + + for (int i = 0; i < length; i ++) { + prevChar = c; + c = ipAddress.charAt(i); + switch (c) { + + // case for an open bracket [x:x:x:...x] + case '[': + if (i != 0) { + return false; // must be first character + } + if (ipAddress.charAt(length - 1) != ']') { + return false; // must have a close ] + } + offset = 1; + if (length < 4) { + return false; + } + break; + + // case for a closed bracket at end of IP [x:x:x:...x] + case ']': + if (i != length - 1) { + return false; // must be last charcter + } + if (ipAddress.charAt(0) != '[') { + return false; // must have a open [ + } + break; + + // case for the last 32-bits represented as IPv4 x:x:x:x:x:x:d.d.d.d + case '.': + numberOfPeriods ++; + if (numberOfPeriods > 3) { + return false; + } + if (!isValidIp4Word(word.toString())) { + return false; + } + if (numberOfColons != 6 && !doubleColon) { + return false; + } + // a special case ::1:2:3:4:5:d.d.d.d allows 7 colons with an + // IPv4 ending, otherwise 7 :'s is bad + if (numberOfColons == 7 && ipAddress.charAt(offset) != ':' && + ipAddress.charAt(1 + offset) != ':') { + return false; + } + word.delete(0, word.length()); + break; + + case ':': + // FIX "IP6 mechanism syntax #ip6-bad1" + // An IPV6 address cannot start with a single ":". + // Either it can starti with "::" or with a number. + if (i == offset && (ipAddress.length() <= i || ipAddress.charAt(i + 1) != ':')) { + return false; + } + // END FIX "IP6 mechanism syntax #ip6-bad1" + numberOfColons ++; + if (numberOfColons > 7) { + return false; + } + if (numberOfPeriods > 0) { + return false; + } + if (prevChar == ':') { + if (doubleColon) { + return false; + } + doubleColon = true; + } + word.delete(0, word.length()); + break; + case '%': + if (numberOfColons == 0) { + return false; + } + numberOfPercent ++; + + // validate that the stuff after the % is valid + if (i + 1 >= length) { + // in this case the percent is there but no number is + // available + return false; + } + try { + if (Integer.parseInt(ipAddress.substring(i + 1)) < 0) { + return false; + } + } catch (NumberFormatException e) { + // right now we just support an integer after the % so if + // this is not + // what is there then return + return false; + } + break; + + default: + if (numberOfPercent == 0) { + if (word != null && word.length() > 3) { + return false; + } + if (!isValidHexChar(c)) { + return false; + } + } + word.append(c); + } + } + + // Check if we have an IPv4 ending + if (numberOfPeriods > 0) { + // There is a test case with 7 colons and valid ipv4 this should resolve it + if (numberOfPeriods != 3 || !(isValidIp4Word(word.toString()) && numberOfColons < 7)) { + return false; + } + } else { + // If we're at then end and we haven't had 7 colons then there is a + // problem unless we encountered a doubleColon + if (numberOfColons != 7 && !doubleColon) { + return false; + } + + // If we have an empty word at the end, it means we ended in either + // a : or a . + // If we did not end in :: then this is invalid + if (numberOfPercent == 0) { + if (word.length() == 0 && ipAddress.charAt(length - 1 - offset) == ':' && + ipAddress.charAt(length - 2 - offset) != ':') { + return false; + } + } + } + + return true; + } + + public static boolean isValidIp4Word(String word) { + char c; + if (word.length() < 1 || word.length() > 3) { + return false; + } + for (int i = 0; i < word.length(); i ++) { + c = word.charAt(i); + if (!(c >= '0' && c <= '9')) { + return false; + } + } + return Integer.parseInt(word) <= 255; + } + + static boolean isValidHexChar(char c) { + return c >= '0' && c <= '9' || c >= 'A' && c <= 'F' || c >= 'a' && c <= 'f'; + } + + /** + * Takes a string and parses it to see if it is a valid IPV4 address. + * + * @return true, if the string represents an IPV4 address in dotted + * notation, false otherwise + */ + public static boolean isValidIpV4Address(String value) { + + int periods = 0; + int i; + int length = value.length(); + + if (length > 15) { + return false; + } + char c; + StringBuilder word = new StringBuilder(); + for (i = 0; i < length; i ++) { + c = value.charAt(i); + if (c == '.') { + periods ++; + if (periods > 3) { + return false; + } + if (word.length() == 0) { + return false; + } + if (Integer.parseInt(word.toString()) > 255) { + return false; + } + word.delete(0, word.length()); + } else if (!Character.isDigit(c)) { + return false; + } else { + if (word.length() > 2) { + return false; + } + word.append(c); + } + } + + if (word.length() == 0 || Integer.parseInt(word.toString()) > 255) { + return false; + } + + return periods == 3; + } + + /** + * A constructor to stop this class being constructed. + */ + private NetUtil() { + // Unused + } +} diff --git a/common/src/main/java/common/net/util/Recycler.java b/common/src/main/java/common/net/util/Recycler.java new file mode 100644 index 0000000..9fb120d --- /dev/null +++ b/common/src/main/java/common/net/util/Recycler.java @@ -0,0 +1,353 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util; + +import java.lang.ref.WeakReference; +import java.util.Arrays; +import java.util.Map; +import java.util.WeakHashMap; +import java.util.concurrent.atomic.AtomicInteger; + +import common.net.util.concurrent.FastThreadLocal; +import common.net.util.internal.SystemPropertyUtil; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * Light-weight object pool based on a thread-local stack. + * + * @param the type of the pooled object + */ +public abstract class Recycler { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(Recycler.class); + + private static final AtomicInteger ID_GENERATOR = new AtomicInteger(Integer.MIN_VALUE); + private static final int OWN_THREAD_ID = ID_GENERATOR.getAndIncrement(); + private static final int DEFAULT_MAX_CAPACITY; + private static final int INITIAL_CAPACITY; + + static { + // In the future, we might have different maxCapacity for different object types. + // e.g. game.net.recycler.maxCapacity.writeTask + // game.net.recycler.maxCapacity.outboundBuffer + int maxCapacity = SystemPropertyUtil.getInt("game.net.recycler.maxCapacity.default", 0); + if (maxCapacity <= 0) { + // TODO: Some arbitrary large number - should adjust as we get more production experience. + maxCapacity = 262144; + } + + DEFAULT_MAX_CAPACITY = maxCapacity; + if (logger.isDebugEnabled()) { + logger.debug("-Dgame.net.recycler.maxCapacity.default: {}", DEFAULT_MAX_CAPACITY); + } + + INITIAL_CAPACITY = Math.min(DEFAULT_MAX_CAPACITY, 256); + } + + private final int maxCapacity; + private final FastThreadLocal> threadLocal = new FastThreadLocal>() { + @Override + protected Stack initialValue() { + return new Stack(Recycler.this, Thread.currentThread(), maxCapacity); + } + }; + + protected Recycler() { + this(DEFAULT_MAX_CAPACITY); + } + + protected Recycler(int maxCapacity) { + this.maxCapacity = Math.max(0, maxCapacity); + } + + + public final T get() { + Stack stack = threadLocal.get(); + DefaultHandle handle = stack.pop(); + if (handle == null) { + handle = stack.newHandle(); + handle.value = newObject(handle); + } + return (T) handle.value; + } + + public final boolean recycle(T o, Handle handle) { + DefaultHandle h = (DefaultHandle) handle; + if (h.stack.parent != this) { + return false; + } + if (o != h.value) { + throw new IllegalArgumentException("o does not belong to handle"); + } + h.recycle(); + return true; + } + + protected abstract T newObject(Handle handle); + + public interface Handle { } + + static final class DefaultHandle implements Handle { + private int lastRecycledId; + private int recycleId; + + private Stack stack; + private Object value; + + DefaultHandle(Stack stack) { + this.stack = stack; + } + + public void recycle() { + Thread thread = Thread.currentThread(); + if (thread == stack.thread) { + stack.push(this); + return; + } + // we don't want to have a ref to the queue as the value in our weak map + // so we null it out; to ensure there are no races with restoring it later + // we impose a memory ordering here (no-op on x86) + Map, WeakOrderQueue> delayedRecycled = DELAYED_RECYCLED.get(); + WeakOrderQueue queue = delayedRecycled.get(stack); + if (queue == null) { + delayedRecycled.put(stack, queue = new WeakOrderQueue(stack, thread)); + } + queue.add(this); + } + } + + private static final FastThreadLocal, WeakOrderQueue>> DELAYED_RECYCLED = + new FastThreadLocal, WeakOrderQueue>>() { + @Override + protected Map, WeakOrderQueue> initialValue() { + return new WeakHashMap, WeakOrderQueue>(); + } + }; + + // a queue that makes only moderate guarantees about visibility: items are seen in the correct order, + // but we aren't absolutely guaranteed to ever see anything at all, thereby keeping the queue cheap to maintain + private static final class WeakOrderQueue { + private static final int LINK_CAPACITY = 16; + + // Let Link extend AtomicInteger for intrinsics. The Link itself will be used as writerIndex. + + private static final class Link extends AtomicInteger { + private final DefaultHandle[] elements = new DefaultHandle[LINK_CAPACITY]; + + private int readIndex; + private Link next; + } + + // chain of data items + private Link head, tail; + // pointer to another queue of delayed items for the same stack + private WeakOrderQueue next; + private final WeakReference owner; + private final int id = ID_GENERATOR.getAndIncrement(); + + WeakOrderQueue(Stack stack, Thread thread) { + head = tail = new Link(); + owner = new WeakReference(thread); + synchronized (stack) { + next = stack.head; + stack.head = this; + } + } + + void add(DefaultHandle handle) { + handle.lastRecycledId = id; + + Link tail = this.tail; + int writeIndex; + if ((writeIndex = tail.get()) == LINK_CAPACITY) { + this.tail = tail = tail.next = new Link(); + writeIndex = tail.get(); + } + tail.elements[writeIndex] = handle; + handle.stack = null; + // we lazy set to ensure that setting stack to null appears before we unnull it in the owning thread; + // this also means we guarantee visibility of an element in the queue if we see the index updated + tail.lazySet(writeIndex + 1); + } + + boolean hasFinalData() { + return tail.readIndex != tail.get(); + } + + // transfer as many items as we can from this queue to the stack, returning true if any were transferred + + boolean transfer(Stack to) { + + Link head = this.head; + if (head == null) { + return false; + } + + if (head.readIndex == LINK_CAPACITY) { + if (head.next == null) { + return false; + } + this.head = head = head.next; + } + + int start = head.readIndex; + int end = head.get(); + if (start == end) { + return false; + } + + int count = end - start; + if (to.size + count > to.elements.length) { + to.elements = Arrays.copyOf(to.elements, (to.size + count) * 2); + } + + DefaultHandle[] src = head.elements; + DefaultHandle[] trg = to.elements; + int size = to.size; + while (start < end) { + DefaultHandle element = src[start]; + if (element.recycleId == 0) { + element.recycleId = element.lastRecycledId; + } else if (element.recycleId != element.lastRecycledId) { + throw new IllegalStateException("recycled already"); + } + element.stack = to; + trg[size++] = element; + src[start++] = null; + } + to.size = size; + + if (end == LINK_CAPACITY && head.next != null) { + this.head = head.next; + } + + head.readIndex = end; + return true; + } + } + + static final class Stack { + + // we keep a queue of per-thread queues, which is appended to once only, each time a new thread other + // than the stack owner recycles: when we run out of items in our stack we iterate this collection + // to scavenge those that can be reused. this permits us to incur minimal thread synchronisation whilst + // still recycling all items. + final Recycler parent; + final Thread thread; + private DefaultHandle[] elements; + private final int maxCapacity; + private int size; + + private volatile WeakOrderQueue head; + private WeakOrderQueue cursor, prev; + + Stack(Recycler parent, Thread thread, int maxCapacity) { + this.parent = parent; + this.thread = thread; + this.maxCapacity = maxCapacity; + elements = new DefaultHandle[INITIAL_CAPACITY]; + } + + DefaultHandle pop() { + int size = this.size; + if (size == 0) { + if (!scavenge()) { + return null; + } + size = this.size; + } + size --; + DefaultHandle ret = elements[size]; + if (ret.lastRecycledId != ret.recycleId) { + throw new IllegalStateException("recycled multiple times"); + } + ret.recycleId = 0; + ret.lastRecycledId = 0; + this.size = size; + return ret; + } + + boolean scavenge() { + // continue an existing scavenge, if any + if (scavengeSome()) { + return true; + } + + // reset our scavenge cursor + prev = null; + cursor = head; + return false; + } + + boolean scavengeSome() { + boolean success = false; + WeakOrderQueue cursor = this.cursor, prev = this.prev; + while (cursor != null) { + if (cursor.transfer(this)) { + success = true; + break; + } + WeakOrderQueue next = cursor.next; + if (cursor.owner.get() == null) { + // if the thread associated with the queue is gone, unlink it, after + // performing a volatile read to confirm there is no data left to collect + // we never unlink the first queue, as we don't want to synchronize on updating the head + if (cursor.hasFinalData()) { + for (;;) { + if (!cursor.transfer(this)) { + break; + } + } + } + if (prev != null) { + prev.next = next; + } + } else { + prev = cursor; + } + cursor = next; + } + this.prev = prev; + this.cursor = cursor; + return success; + } + + void push(DefaultHandle item) { + if ((item.recycleId | item.lastRecycledId) != 0) { + throw new IllegalStateException("recycled already"); + } + item.recycleId = item.lastRecycledId = OWN_THREAD_ID; + + int size = this.size; + if (size == elements.length) { + if (size == maxCapacity) { + // Hit the maximum capacity - drop the possibly youngest object. + return; + } + elements = Arrays.copyOf(elements, size << 1); + } + + elements[size] = item; + this.size = size + 1; + } + + DefaultHandle newHandle() { + return new DefaultHandle(this); + } + } +} diff --git a/common/src/main/java/common/net/util/ReferenceCountUtil.java b/common/src/main/java/common/net/util/ReferenceCountUtil.java new file mode 100644 index 0000000..7c55c48 --- /dev/null +++ b/common/src/main/java/common/net/util/ReferenceCountUtil.java @@ -0,0 +1,161 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util; + +import common.net.util.internal.StringUtil; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * Collection of method to handle objects that may implement {@link ReferenceCounted}. + */ +public final class ReferenceCountUtil { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(ReferenceCountUtil.class); + + /** + * Try to call {@link ReferenceCounted#retain()} if the specified message implements {@link ReferenceCounted}. + * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. + */ + + public static T retain(T msg) { + if (msg instanceof ReferenceCounted) { + return (T) ((ReferenceCounted) msg).retain(); + } + return msg; + } + + /** + * Try to call {@link ReferenceCounted#retain()} if the specified message implements {@link ReferenceCounted}. + * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. + */ + + public static T retain(T msg, int increment) { + if (msg instanceof ReferenceCounted) { + return (T) ((ReferenceCounted) msg).retain(increment); + } + return msg; + } + + /** + * Try to call {@link ReferenceCounted#release()} if the specified message implements {@link ReferenceCounted}. + * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. + */ + public static boolean release(Object msg) { + if (msg instanceof ReferenceCounted) { + return ((ReferenceCounted) msg).release(); + } + return false; + } + + /** + * Try to call {@link ReferenceCounted#release(int)} if the specified message implements {@link ReferenceCounted}. + * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. + */ + public static boolean release(Object msg, int decrement) { + if (msg instanceof ReferenceCounted) { + return ((ReferenceCounted) msg).release(decrement); + } + return false; + } + + /** + * Try to call {@link ReferenceCounted#release()} if the specified message implements {@link ReferenceCounted}. + * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. + * Unlike {@link #release(Object)} this method catches an exception raised by {@link ReferenceCounted#release()} + * and logs it, rather than rethrowing it to the caller. It is usually recommended to use {@link #release(Object)} + * instead, unless you absolutely need to swallow an exception. + */ + public static void safeRelease(Object msg) { + try { + release(msg); + } catch (Throwable t) { + logger.warn("Failed to release a message: {}", msg, t); + } + } + + /** + * Try to call {@link ReferenceCounted#release(int)} if the specified message implements {@link ReferenceCounted}. + * If the specified message doesn't implement {@link ReferenceCounted}, this method does nothing. + * Unlike {@link #release(Object)} this method catches an exception raised by {@link ReferenceCounted#release(int)} + * and logs it, rather than rethrowing it to the caller. It is usually recommended to use + * {@link #release(Object, int)} instead, unless you absolutely need to swallow an exception. + */ + public static void safeRelease(Object msg, int decrement) { + try { + release(msg, decrement); + } catch (Throwable t) { + if (logger.isWarnEnabled()) { + logger.warn("Failed to release a message: {} (decrement: {})", msg, decrement, t); + } + } + } + + /** + * Schedules the specified object to be released when the caller thread terminates. Note that this operation is + * intended to simplify reference counting of ephemeral objects during unit tests. Do not use it beyond the + * intended use case. + */ + public static T releaseLater(T msg) { + return releaseLater(msg, 1); + } + + /** + * Schedules the specified object to be released when the caller thread terminates. Note that this operation is + * intended to simplify reference counting of ephemeral objects during unit tests. Do not use it beyond the + * intended use case. + */ + public static T releaseLater(T msg, int decrement) { + if (msg instanceof ReferenceCounted) { + ThreadDeathWatcher.watch(Thread.currentThread(), new ReleasingTask((ReferenceCounted) msg, decrement)); + } + return msg; + } + + /** + * Releases the objects when the thread that called {@link #releaseLater(Object)} has been terminated. + */ + private static final class ReleasingTask implements Runnable { + + private final ReferenceCounted obj; + private final int decrement; + + ReleasingTask(ReferenceCounted obj, int decrement) { + this.obj = obj; + this.decrement = decrement; + } + + @Override + public void run() { + try { + if (!obj.release(decrement)) { + logger.warn("Non-zero refCnt: {}", this); + } else { + logger.debug("Released: {}", this); + } + } catch (Exception ex) { + logger.warn("Failed to release an object: {}", obj, ex); + } + } + + @Override + public String toString() { + return StringUtil.simpleClassName(obj) + ".release(" + decrement + ") refCnt: " + obj.refCnt(); + } + } + + private ReferenceCountUtil() { } +} diff --git a/common/src/main/java/common/net/util/ReferenceCounted.java b/common/src/main/java/common/net/util/ReferenceCounted.java new file mode 100644 index 0000000..33d6097 --- /dev/null +++ b/common/src/main/java/common/net/util/ReferenceCounted.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util; + +/** + * A reference-counted object that requires explicit deallocation. + *

+ * When a new {@link ReferenceCounted} is instantiated, it starts with the reference count of {@code 1}. + * {@link #retain()} increases the reference count, and {@link #release()} decreases the reference count. + * If the reference count is decreased to {@code 0}, the object will be deallocated explicitly, and accessing + * the deallocated object will usually result in an access violation. + *

+ *

+ * If an object that implements {@link ReferenceCounted} is a container of other objects that implement + * {@link ReferenceCounted}, the contained objects will also be released via {@link #release()} when the container's + * reference count becomes 0. + *

+ */ +public interface ReferenceCounted { + /** + * Returns the reference count of this object. If {@code 0}, it means this object has been deallocated. + */ + int refCnt(); + + /** + * Increases the reference count by {@code 1}. + */ + ReferenceCounted retain(); + + /** + * Increases the reference count by the specified {@code increment}. + */ + ReferenceCounted retain(int increment); + + /** + * Decreases the reference count by {@code 1} and deallocates this object if the reference count reaches at + * {@code 0}. + * + * @return {@code true} if and only if the reference count became {@code 0} and this object has been deallocated + */ + boolean release(); + + /** + * Decreases the reference count by the specified {@code decrement} and deallocates this object if the reference + * count reaches at {@code 0}. + * + * @return {@code true} if and only if the reference count became {@code 0} and this object has been deallocated + */ + boolean release(int decrement); +} diff --git a/common/src/main/java/common/net/util/ResourceLeak.java b/common/src/main/java/common/net/util/ResourceLeak.java new file mode 100644 index 0000000..00064a7 --- /dev/null +++ b/common/src/main/java/common/net/util/ResourceLeak.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util; + +public interface ResourceLeak { + /** + * Records the caller's current stack trace so that the {@link ResourceLeakDetector} can tell where the leaked + * resource was accessed lastly. + */ + void record(); + + /** + * Close the leak so that {@link ResourceLeakDetector} does not warn about leaked resources. + * + * @return {@code true} if called first time, {@code false} if called already + */ + boolean close(); +} diff --git a/common/src/main/java/common/net/util/ResourceLeakDetector.java b/common/src/main/java/common/net/util/ResourceLeakDetector.java new file mode 100644 index 0000000..0159efd --- /dev/null +++ b/common/src/main/java/common/net/util/ResourceLeakDetector.java @@ -0,0 +1,380 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util; + +import static common.net.util.internal.StringUtil.NEWLINE; +import static common.net.util.internal.StringUtil.simpleClassName; + +import java.lang.ref.PhantomReference; +import java.lang.ref.ReferenceQueue; +import java.util.ArrayDeque; +import java.util.Deque; +import java.util.EnumSet; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicBoolean; + +import common.net.util.internal.SystemPropertyUtil; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +public final class ResourceLeakDetector { + + private static final String PROP_LEVEL = "game.net.leakDetectionLevel"; + private static final Level DEFAULT_LEVEL = Level.SIMPLE; + + /** + * Represents the level of resource leak detection. + */ + public enum Level { + /** + * Disables resource leak detection. + */ + DISABLED, + /** + * Enables simplistic sampling resource leak detection which reports there is a leak or not, + * at the cost of small overhead (default). + */ + SIMPLE, + /** + * Enables advanced sampling resource leak detection which reports where the leaked object was accessed + * recently at the cost of high overhead. + */ + ADVANCED, + /** + * Enables paranoid resource leak detection which reports where the leaked object was accessed recently, + * at the cost of the highest possible overhead (for testing purposes only). + */ + PARANOID + } + + private static Level level; + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(ResourceLeakDetector.class); + + static { + final boolean disabled; + if (SystemPropertyUtil.get("game.net.noResourceLeakDetection") != null) { + disabled = SystemPropertyUtil.getBoolean("game.net.noResourceLeakDetection", false); + logger.debug("-Dgame.net.noResourceLeakDetection: {}", disabled); + logger.warn( + "-Dgame.net.noResourceLeakDetection is deprecated. Use '-D{}={}' instead.", + PROP_LEVEL, DEFAULT_LEVEL.name().toLowerCase()); + } else { + disabled = false; + } + + Level defaultLevel = disabled? Level.DISABLED : DEFAULT_LEVEL; + String levelStr = SystemPropertyUtil.get(PROP_LEVEL, defaultLevel.name()).trim().toUpperCase(); + Level level = DEFAULT_LEVEL; + for (Level l: EnumSet.allOf(Level.class)) { + if (levelStr.equals(l.name()) || levelStr.equals(String.valueOf(l.ordinal()))) { + level = l; + } + } + + ResourceLeakDetector.level = level; + if (logger.isDebugEnabled()) { + logger.debug("-D{}: {}", PROP_LEVEL, level.name().toLowerCase()); + } + } + + private static final int DEFAULT_SAMPLING_INTERVAL = 113; + + /** + * Returns {@code true} if resource leak detection is enabled. + */ + public static boolean isEnabled() { + return getLevel().ordinal() > Level.DISABLED.ordinal(); + } + + /** + * Sets the resource leak detection level. + */ + public static void setLevel(Level level) { + if (level == null) { + throw new NullPointerException("level"); + } + ResourceLeakDetector.level = level; + } + + /** + * Returns the current resource leak detection level. + */ + public static Level getLevel() { + return level; + } + + /** the linked list of active resources */ + private final DefaultResourceLeak head = new DefaultResourceLeak(null); + private final DefaultResourceLeak tail = new DefaultResourceLeak(null); + + private final ReferenceQueue refQueue = new ReferenceQueue(); + private final ConcurrentMap reportedLeaks = new ConcurrentHashMap(); + + private final String resourceType; + private final int samplingInterval; + private final long maxActive; + private long active; + private final AtomicBoolean loggedTooManyActive = new AtomicBoolean(); + + private long leakCheckCnt; + + public ResourceLeakDetector(Class resourceType) { + this(simpleClassName(resourceType)); + } + + public ResourceLeakDetector(String resourceType) { + this(resourceType, DEFAULT_SAMPLING_INTERVAL, Long.MAX_VALUE); + } + + public ResourceLeakDetector(Class resourceType, int samplingInterval, long maxActive) { + this(simpleClassName(resourceType), samplingInterval, maxActive); + } + + public ResourceLeakDetector(String resourceType, int samplingInterval, long maxActive) { + if (resourceType == null) { + throw new NullPointerException("resourceType"); + } + if (samplingInterval <= 0) { + throw new IllegalArgumentException("samplingInterval: " + samplingInterval + " (expected: 1+)"); + } + if (maxActive <= 0) { + throw new IllegalArgumentException("maxActive: " + maxActive + " (expected: 1+)"); + } + + this.resourceType = resourceType; + this.samplingInterval = samplingInterval; + this.maxActive = maxActive; + + head.next = tail; + tail.prev = head; + } + + /** + * Creates a new {@link ResourceLeak} which is expected to be closed via {@link ResourceLeak#close()} when the + * related resource is deallocated. + * + * @return the {@link ResourceLeak} or {@code null} + */ + public ResourceLeak open(T obj) { + Level level = ResourceLeakDetector.level; + if (level == Level.DISABLED) { + return null; + } + + if (level.ordinal() < Level.PARANOID.ordinal()) { + if (leakCheckCnt ++ % samplingInterval == 0) { + reportLeak(level); + return new DefaultResourceLeak(obj); + } else { + return null; + } + } else { + reportLeak(level); + return new DefaultResourceLeak(obj); + } + } + + private void reportLeak(Level level) { + if (!logger.isErrorEnabled()) { + for (;;) { + + DefaultResourceLeak ref = (DefaultResourceLeak) refQueue.poll(); + if (ref == null) { + break; + } + ref.close(); + } + return; + } + + // Report too many instances. + int samplingInterval = level == Level.PARANOID? 1 : this.samplingInterval; + if (active * samplingInterval > maxActive && loggedTooManyActive.compareAndSet(false, true)) { + logger.error("LEAK: You are creating too many " + resourceType + " instances. " + + resourceType + " is a shared resource that must be reused across the JVM," + + "so that only a few instances are created."); + } + + // Detect and report previous leaks. + for (;;) { + + DefaultResourceLeak ref = (DefaultResourceLeak) refQueue.poll(); + if (ref == null) { + break; + } + + ref.clear(); + + if (!ref.close()) { + continue; + } + + String records = ref.toString(); + if (reportedLeaks.putIfAbsent(records, Boolean.TRUE) == null) { + if (records.isEmpty()) { + logger.error("LEAK: {}.release() was not called before it's garbage-collected. " + + "Enable advanced leak reporting to find out where the leak occurred. " + + "To enable advanced leak reporting, " + + "specify the JVM option '-D{}={}' or call {}.setLevel()", + resourceType, PROP_LEVEL, Level.ADVANCED.name().toLowerCase(), simpleClassName(this)); + } else { + logger.error( + "LEAK: {}.release() was not called before it's garbage-collected.{}", + resourceType, records); + } + } + } + } + + private final class DefaultResourceLeak extends PhantomReference implements ResourceLeak { + + private static final int MAX_RECORDS = 4; + + private final String creationRecord; + private final Deque lastRecords = new ArrayDeque(); + private final AtomicBoolean freed; + private DefaultResourceLeak prev; + private DefaultResourceLeak next; + + DefaultResourceLeak(Object referent) { + super(referent, referent != null? refQueue : null); + + if (referent != null) { + Level level = getLevel(); + if (level.ordinal() >= Level.ADVANCED.ordinal()) { + creationRecord = newRecord(3); + } else { + creationRecord = null; + } + + // TODO: Use CAS to update the list. + synchronized (head) { + prev = head; + next = head.next; + head.next.prev = this; + head.next = this; + active ++; + } + freed = new AtomicBoolean(); + } else { + creationRecord = null; + freed = new AtomicBoolean(true); + } + } + + @Override + public void record() { + if (creationRecord != null) { + String value = newRecord(2); + + synchronized (lastRecords) { + int size = lastRecords.size(); + if (size == 0 || !lastRecords.getLast().equals(value)) { + lastRecords.add(value); + } + if (size > MAX_RECORDS) { + lastRecords.removeFirst(); + } + } + } + } + + @Override + public boolean close() { + if (freed.compareAndSet(false, true)) { + synchronized (head) { + active --; + prev.next = next; + next.prev = prev; + prev = null; + next = null; + } + return true; + } + return false; + } + + public String toString() { + if (creationRecord == null) { + return ""; + } + + Object[] array; + synchronized (lastRecords) { + array = lastRecords.toArray(); + } + + StringBuilder buf = new StringBuilder(16384); + buf.append(NEWLINE); + buf.append("Recent access records: "); + buf.append(array.length); + buf.append(NEWLINE); + + if (array.length > 0) { + for (int i = array.length - 1; i >= 0; i --) { + buf.append('#'); + buf.append(i + 1); + buf.append(':'); + buf.append(NEWLINE); + buf.append(array[i]); + } + } + + buf.append("Created at:"); + buf.append(NEWLINE); + buf.append(creationRecord); + buf.setLength(buf.length() - NEWLINE.length()); + + return buf.toString(); + } + } + + private static final String[] STACK_TRACE_ELEMENT_EXCLUSIONS = { + "game.net.buffer.AbstractByteBufAllocator.toLeakAwareBuffer(", + }; + + static String newRecord(int recordsToSkip) { + StringBuilder buf = new StringBuilder(4096); + StackTraceElement[] array = new Throwable().getStackTrace(); + for (StackTraceElement e: array) { + if (recordsToSkip > 0) { + recordsToSkip --; + } else { + String estr = e.toString(); + + // Strip the noisy stack trace elements. + boolean excluded = false; + for (String exclusion: STACK_TRACE_ELEMENT_EXCLUSIONS) { + if (estr.startsWith(exclusion)) { + excluded = true; + break; + } + } + + if (!excluded) { + buf.append('\t'); + buf.append(estr); + buf.append(NEWLINE); + } + } + } + + return buf.toString(); + } +} diff --git a/common/src/main/java/common/net/util/Signal.java b/common/src/main/java/common/net/util/Signal.java new file mode 100644 index 0000000..b0f041d --- /dev/null +++ b/common/src/main/java/common/net/util/Signal.java @@ -0,0 +1,72 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util; + + +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.ConcurrentMap; + +/** + * A special {@link Error} which is used to signal some state or request by throwing it. + * {@link Signal} has an empty stack trace and has no cause to save the instantiation overhead. + */ +public final class Signal extends Error { + + private static final long serialVersionUID = -221145131122459977L; + + private static final ConcurrentMap map = new ConcurrentHashMap(); + + + private final UniqueName uname; + + /** + * Creates a new {@link Signal} with the specified {@code name}. + */ + + public static Signal valueOf(String name) { + return new Signal(name); + } + + private Signal(String name) { + super(name); + uname = new UniqueName(map, name); + } + + /** + * Check if the given {@link Signal} is the same as this instance. If not an {@link IllegalStateException} will + * be thrown. + */ + public void expect(Signal signal) { + if (this != signal) { + throw new IllegalStateException("unexpected signal: " + signal); + } + } + + @Override + public Throwable initCause(Throwable cause) { + return this; + } + + @Override + public Throwable fillInStackTrace() { + return this; + } + + @Override + public String toString() { + return uname.name(); + } +} diff --git a/common/src/main/java/common/net/util/ThreadDeathWatcher.java b/common/src/main/java/common/net/util/ThreadDeathWatcher.java new file mode 100644 index 0000000..1020596 --- /dev/null +++ b/common/src/main/java/common/net/util/ThreadDeathWatcher.java @@ -0,0 +1,241 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util; + +import java.util.ArrayList; +import java.util.List; +import java.util.Queue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import common.net.util.concurrent.DefaultThreadFactory; +import common.net.util.internal.MpscLinkedQueue; +import common.net.util.internal.MpscLinkedQueueNode; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * Checks if a thread is alive periodically and runs a task when a thread dies. + *

+ * This thread starts a daemon thread to check the state of the threads being watched and to invoke their + * associated {@link Runnable}s. When there is no thread to watch (i.e. all threads are dead), the daemon thread + * will terminate itself, and a new daemon thread will be started again when a new watch is added. + *

+ */ +public final class ThreadDeathWatcher { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(ThreadDeathWatcher.class); + private static final ThreadFactory threadFactory = + new DefaultThreadFactory(ThreadDeathWatcher.class, true, Thread.MIN_PRIORITY); + + private static final Queue pendingEntries = new MpscLinkedQueue(); + private static final Watcher watcher = new Watcher(); + private static final AtomicBoolean started = new AtomicBoolean(); + private static volatile Thread watcherThread; + + /** + * Schedules the specified {@code task} to run when the specified {@code thread} dies. + * + * @param thread the {@link Thread} to watch + * @param task the {@link Runnable} to run when the {@code thread} dies + * + * @throws IllegalArgumentException if the specified {@code thread} is not alive + */ + public static void watch(Thread thread, Runnable task) { + if (thread == null) { + throw new NullPointerException("thread"); + } + if (task == null) { + throw new NullPointerException("task"); + } + if (!thread.isAlive()) { + throw new IllegalArgumentException("thread must be alive."); + } + + schedule(thread, task, true); + } + + /** + * Cancels the task scheduled via {@link #watch(Thread, Runnable)}. + */ + public static void unwatch(Thread thread, Runnable task) { + if (thread == null) { + throw new NullPointerException("thread"); + } + if (task == null) { + throw new NullPointerException("task"); + } + + schedule(thread, task, false); + } + + private static void schedule(Thread thread, Runnable task, boolean isWatch) { + pendingEntries.add(new Entry(thread, task, isWatch)); + + if (started.compareAndSet(false, true)) { + Thread watcherThread = threadFactory.newThread(watcher); + watcherThread.start(); + ThreadDeathWatcher.watcherThread = watcherThread; + } + } + + /** + * Waits until the thread of this watcher has no threads to watch and terminates itself. + * Because a new watcher thread will be started again on {@link #watch(Thread, Runnable)}, + * this operation is only useful when you want to ensure that the watcher thread is terminated + * after your application is shut down and there's no chance of calling + * {@link #watch(Thread, Runnable)} afterwards. + * + * @return {@code true} if and only if the watcher thread has been terminated + */ + public static boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { + if (unit == null) { + throw new NullPointerException("unit"); + } + + Thread watcherThread = ThreadDeathWatcher.watcherThread; + if (watcherThread != null) { + watcherThread.join(unit.toMillis(timeout)); + return !watcherThread.isAlive(); + } else { + return true; + } + } + + private ThreadDeathWatcher() { } + + private static final class Watcher implements Runnable { + + private final List watchees = new ArrayList(); + + @Override + public void run() { + for (;;) { + fetchWatchees(); + notifyWatchees(); + + // Try once again just in case notifyWatchees() triggered watch() or unwatch(). + fetchWatchees(); + notifyWatchees(); + + try { + Thread.sleep(1000); + } catch (InterruptedException ignore) { + // Ignore the interrupt; do not terminate until all tasks are run. + } + + if (watchees.isEmpty() && pendingEntries.isEmpty()) { + + // Mark the current worker thread as stopped. + // The following CAS must always success and must be uncontended, + // because only one watcher thread should be running at the same time. + boolean stopped = started.compareAndSet(true, false); + assert stopped; + + // Check if there are pending entries added by watch() while we do CAS above. + if (pendingEntries.isEmpty()) { + // A) watch() was not invoked and thus there's nothing to handle + // -> safe to terminate because there's nothing left to do + // B) a new watcher thread started and handled them all + // -> safe to terminate the new watcher thread will take care the rest + break; + } + + // There are pending entries again, added by watch() + if (!started.compareAndSet(false, true)) { + // watch() started a new watcher thread and set 'started' to true. + // -> terminate this thread so that the new watcher reads from pendingEntries exclusively. + break; + } + + // watch() added an entry, but this worker was faster to set 'started' to true. + // i.e. a new watcher thread was not started + // -> keep this thread alive to handle the newly added entries. + } + } + } + + private void fetchWatchees() { + for (;;) { + Entry e = pendingEntries.poll(); + if (e == null) { + break; + } + + if (e.isWatch) { + watchees.add(e); + } else { + watchees.remove(e); + } + } + } + + private void notifyWatchees() { + List watchees = this.watchees; + for (int i = 0; i < watchees.size();) { + Entry e = watchees.get(i); + if (!e.thread.isAlive()) { + watchees.remove(i); + try { + e.task.run(); + } catch (Throwable t) { + logger.warn("Thread death watcher task raised an exception:", t); + } + } else { + i ++; + } + } + } + } + + private static final class Entry extends MpscLinkedQueueNode { + final Thread thread; + final Runnable task; + final boolean isWatch; + + Entry(Thread thread, Runnable task, boolean isWatch) { + this.thread = thread; + this.task = task; + this.isWatch = isWatch; + } + + @Override + public Entry value() { + return this; + } + + @Override + public int hashCode() { + return thread.hashCode() ^ task.hashCode(); + } + + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (!(obj instanceof Entry)) { + return false; + } + + Entry that = (Entry) obj; + return thread == that.thread && task == that.task; + } + } +} diff --git a/common/src/main/java/common/net/util/UniqueName.java b/common/src/main/java/common/net/util/UniqueName.java new file mode 100644 index 0000000..0a20a99 --- /dev/null +++ b/common/src/main/java/common/net/util/UniqueName.java @@ -0,0 +1,99 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util; + +import java.util.concurrent.ConcurrentMap; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Defines a name that must be unique in the map that is provided during construction. + */ +public class UniqueName implements Comparable { + + private static final AtomicInteger nextId = new AtomicInteger(); + + private final int id; + private final String name; + + /** + * Constructs a new {@link UniqueName} + * + * @param map the map of names to compare with + * @param name the name of this {@link UniqueName} + */ + public UniqueName(ConcurrentMap map, String name) { + if (map == null) { + throw new NullPointerException("map"); + } + if (name == null) { + throw new NullPointerException("name"); + } + + if (map.putIfAbsent(name, Boolean.TRUE) != null) { + throw new IllegalArgumentException(String.format("'%s' is already in use", name)); + } + + id = nextId.incrementAndGet(); + this.name = name; + } + + /** + * Returns this {@link UniqueName}'s name + * + * @return the name + */ + public final String name() { + return name; + } + + /** + * Returns this {@link UniqueName}'s ID + * + * @return the id + */ + public final int id() { + return id; + } + + @Override + public final int hashCode() { + return super.hashCode(); + } + + @Override + public final boolean equals(Object o) { + return super.equals(o); + } + + @Override + public int compareTo(UniqueName other) { + if (this == other) { + return 0; + } + + int returnCode = name.compareTo(other.name); + if (returnCode != 0) { + return returnCode; + } + + return ((Integer) id).compareTo(other.id); + } + + @Override + public String toString() { + return name(); + } +} diff --git a/common/src/main/java/common/net/util/concurrent/AbstractEventExecutor.java b/common/src/main/java/common/net/util/concurrent/AbstractEventExecutor.java new file mode 100644 index 0000000..1392ed6 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/AbstractEventExecutor.java @@ -0,0 +1,157 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.NoSuchElementException; +import java.util.concurrent.AbstractExecutorService; +import java.util.concurrent.Callable; +import java.util.concurrent.RunnableFuture; +import java.util.concurrent.TimeUnit; + +/** + * Abstract base class for {@link EventExecutor} implementations. + */ +public abstract class AbstractEventExecutor extends AbstractExecutorService implements EventExecutor { + + @Override + public EventExecutor next() { + return this; + } + + @Override + public boolean inEventLoop() { + return inEventLoop(Thread.currentThread()); + } + + @Override + public Iterator iterator() { + return new EventExecutorIterator(); + } + + @Override + public Future shutdownGracefully() { + return shutdownGracefully(2, 15, TimeUnit.SECONDS); + } + + /** + * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. + */ + @Override + @Deprecated + public abstract void shutdown(); + + /** + * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. + */ + @Override + @Deprecated + public List shutdownNow() { + shutdown(); + return Collections.emptyList(); + } + + @Override + public Promise newPromise() { + return new DefaultPromise(this); + } + + @Override + public ProgressivePromise newProgressivePromise() { + return new DefaultProgressivePromise(this); + } + + @Override + public Future newSucceededFuture(V result) { + return new SucceededFuture(this, result); + } + + @Override + public Future newFailedFuture(Throwable cause) { + return new FailedFuture(this, cause); + } + + @Override + public Future submit(Runnable task) { + return (Future) super.submit(task); + } + + @Override + public Future submit(Runnable task, T result) { + return (Future) super.submit(task, result); + } + + @Override + public Future submit(Callable task) { + return (Future) super.submit(task); + } + + @Override + protected final RunnableFuture newTaskFor(Runnable runnable, T value) { + return new PromiseTask(this, runnable, value); + } + + @Override + protected final RunnableFuture newTaskFor(Callable callable) { + return new PromiseTask(this, callable); + } + + @Override + public ScheduledFuture schedule(Runnable command, long delay, + TimeUnit unit) { + throw new UnsupportedOperationException(); + } + + @Override + public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { + throw new UnsupportedOperationException(); + } + + @Override + public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { + throw new UnsupportedOperationException(); + } + + @Override + public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { + throw new UnsupportedOperationException(); + } + + private final class EventExecutorIterator implements Iterator { + private boolean nextCalled; + + @Override + public boolean hasNext() { + return !nextCalled; + } + + @Override + public EventExecutor next() { + if (!hasNext()) { + throw new NoSuchElementException(); + } + nextCalled = true; + return AbstractEventExecutor.this; + } + + @Override + public void remove() { + throw new UnsupportedOperationException("read-only"); + } + } +} diff --git a/common/src/main/java/common/net/util/concurrent/AbstractEventExecutorGroup.java b/common/src/main/java/common/net/util/concurrent/AbstractEventExecutorGroup.java new file mode 100644 index 0000000..8c1b768 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/AbstractEventExecutorGroup.java @@ -0,0 +1,116 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + + +/** + * Abstract base class for {@link EventExecutorGroup} implementations. + */ +public abstract class AbstractEventExecutorGroup implements EventExecutorGroup { + + @Override + public Future submit(Runnable task) { + return next().submit(task); + } + + @Override + public Future submit(Runnable task, T result) { + return next().submit(task, result); + } + + @Override + public Future submit(Callable task) { + return next().submit(task); + } + + @Override + public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { + return next().schedule(command, delay, unit); + } + + @Override + public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { + return next().schedule(callable, delay, unit); + } + + @Override + public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { + return next().scheduleAtFixedRate(command, initialDelay, period, unit); + } + + @Override + public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { + return next().scheduleWithFixedDelay(command, initialDelay, delay, unit); + } + + @Override + public Future shutdownGracefully() { + return shutdownGracefully(2, 15, TimeUnit.SECONDS); + } + + /** + * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. + */ + @Override + @Deprecated + public abstract void shutdown(); + + /** + * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. + */ + @Override + @Deprecated + public List shutdownNow() { + shutdown(); + return Collections.emptyList(); + } + + @Override + public List> invokeAll(Collection> tasks) + throws InterruptedException { + return next().invokeAll(tasks); + } + + @Override + public List> invokeAll( + Collection> tasks, long timeout, TimeUnit unit) throws InterruptedException { + return next().invokeAll(tasks, timeout, unit); + } + + @Override + public T invokeAny(Collection> tasks) throws InterruptedException, ExecutionException { + return next().invokeAny(tasks); + } + + @Override + public T invokeAny(Collection> tasks, long timeout, TimeUnit unit) + throws InterruptedException, ExecutionException, TimeoutException { + return next().invokeAny(tasks, timeout, unit); + } + + @Override + public void execute(Runnable command) { + next().execute(command); + } +} diff --git a/common/src/main/java/common/net/util/concurrent/AbstractFuture.java b/common/src/main/java/common/net/util/concurrent/AbstractFuture.java new file mode 100644 index 0000000..e288643 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/AbstractFuture.java @@ -0,0 +1,51 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; + +/** + * Abstract {@link Future} implementation which does not allow for cancellation. + * + * @param + */ +public abstract class AbstractFuture implements Future { + + @Override + public V get() throws InterruptedException, ExecutionException { + await(); + + Throwable cause = cause(); + if (cause == null) { + return getNow(); + } + throw new ExecutionException(cause); + } + + @Override + public V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { + if (await(timeout, unit)) { + Throwable cause = cause(); + if (cause == null) { + return getNow(); + } + throw new ExecutionException(cause); + } + throw new TimeoutException(); + } +} diff --git a/common/src/main/java/common/net/util/concurrent/BlockingOperationException.java b/common/src/main/java/common/net/util/concurrent/BlockingOperationException.java new file mode 100644 index 0000000..725b524 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/BlockingOperationException.java @@ -0,0 +1,41 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +/** + * An {@link IllegalStateException} which is raised when a user performed a blocking operation + * when the user is in an event loop thread. If a blocking operation is performed in an event loop + * thread, the blocking operation will most likely enter a dead lock state, hence throwing this + * exception. + */ +public class BlockingOperationException extends IllegalStateException { + + private static final long serialVersionUID = 2462223247762460301L; + + public BlockingOperationException() { } + + public BlockingOperationException(String s) { + super(s); + } + + public BlockingOperationException(Throwable cause) { + super(cause); + } + + public BlockingOperationException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/common/src/main/java/common/net/util/concurrent/CompleteFuture.java b/common/src/main/java/common/net/util/concurrent/CompleteFuture.java new file mode 100644 index 0000000..2761a6e --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/CompleteFuture.java @@ -0,0 +1,147 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.concurrent; + +import java.util.concurrent.TimeUnit; + +/** + * A skeletal {@link Future} implementation which represents a {@link Future} which has been completed already. + */ +public abstract class CompleteFuture extends AbstractFuture { + + private final EventExecutor executor; + + /** + * Creates a new instance. + * + * @param executor the {@link EventExecutor} associated with this future + */ + protected CompleteFuture(EventExecutor executor) { + this.executor = executor; + } + + /** + * Return the {@link EventExecutor} which is used by this {@link CompleteFuture}. + */ + protected EventExecutor executor() { + return executor; + } + + @Override + public Future addListener(GenericFutureListener> listener) { + if (listener == null) { + throw new NullPointerException("listener"); + } + DefaultPromise.notifyListener(executor(), this, listener); + return this; + } + + @Override + public Future addListeners(GenericFutureListener>... listeners) { + if (listeners == null) { + throw new NullPointerException("listeners"); + } + for (GenericFutureListener> l: listeners) { + if (l == null) { + break; + } + DefaultPromise.notifyListener(executor(), this, l); + } + return this; + } + + @Override + public Future removeListener(GenericFutureListener> listener) { + // NOOP + return this; + } + + @Override + public Future removeListeners(GenericFutureListener>... listeners) { + // NOOP + return this; + } + + @Override + public Future await() throws InterruptedException { + if (Thread.interrupted()) { + throw new InterruptedException(); + } + return this; + } + + @Override + public boolean await(long timeout, TimeUnit unit) throws InterruptedException { + if (Thread.interrupted()) { + throw new InterruptedException(); + } + return true; + } + + @Override + public Future sync() throws InterruptedException { + return this; + } + + @Override + public Future syncUninterruptibly() { + return this; + } + + @Override + public boolean await(long timeoutMillis) throws InterruptedException { + if (Thread.interrupted()) { + throw new InterruptedException(); + } + return true; + } + + @Override + public Future awaitUninterruptibly() { + return this; + } + + @Override + public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { + return true; + } + + @Override + public boolean awaitUninterruptibly(long timeoutMillis) { + return true; + } + + @Override + public boolean isDone() { + return true; + } + + @Override + public boolean isCancellable() { + return false; + } + + @Override + public boolean isCancelled() { + return false; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + return false; + } +} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultEventExecutor.java b/common/src/main/java/common/net/util/concurrent/DefaultEventExecutor.java new file mode 100644 index 0000000..7f7c611 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/DefaultEventExecutor.java @@ -0,0 +1,45 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.concurrent.ThreadFactory; + +/** + * Default {@link SingleThreadEventExecutor} implementation which just execute all submitted task in a + * serial fashion + * + */ +final class DefaultEventExecutor extends SingleThreadEventExecutor { + + DefaultEventExecutor(DefaultEventExecutorGroup parent, ThreadFactory threadFactory) { + super(parent, threadFactory, true); + } + + @Override + protected void run() { + for (;;) { + Runnable task = takeTask(); + if (task != null) { + task.run(); + updateLastExecutionTime(); + } + + if (confirmShutdown()) { + break; + } + } + } +} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultEventExecutorGroup.java b/common/src/main/java/common/net/util/concurrent/DefaultEventExecutorGroup.java new file mode 100644 index 0000000..10c165a --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/DefaultEventExecutorGroup.java @@ -0,0 +1,48 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.concurrent.ThreadFactory; + +/** + * Default implementation of {@link MultithreadEventExecutorGroup} which will use {@link DefaultEventExecutor} instances + * to handle the tasks. + */ +public class DefaultEventExecutorGroup extends MultithreadEventExecutorGroup { + + /** + * @see {@link #DefaultEventExecutorGroup(int, ThreadFactory)} + */ + public DefaultEventExecutorGroup(int nThreads) { + this(nThreads, null); + } + + /** + * Create a new instance. + * + * @param nThreads the number of threads that will be used by this instance. + * @param threadFactory the ThreadFactory to use, or {@code null} if the default should be used. + */ + public DefaultEventExecutorGroup(int nThreads, ThreadFactory threadFactory) { + super(nThreads, threadFactory); + } + + @Override + protected EventExecutor newChild( + ThreadFactory threadFactory, Object... args) throws Exception { + return new DefaultEventExecutor(this, threadFactory); + } +} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultFutureListeners.java b/common/src/main/java/common/net/util/concurrent/DefaultFutureListeners.java new file mode 100644 index 0000000..37a830e --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/DefaultFutureListeners.java @@ -0,0 +1,86 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.Arrays; + +final class DefaultFutureListeners { + + private GenericFutureListener>[] listeners; + private int size; + private int progressiveSize; // the number of progressive listeners + + + DefaultFutureListeners( + GenericFutureListener> first, GenericFutureListener> second) { + listeners = new GenericFutureListener[2]; + listeners[0] = first; + listeners[1] = second; + size = 2; + if (first instanceof GenericProgressiveFutureListener) { + progressiveSize ++; + } + if (second instanceof GenericProgressiveFutureListener) { + progressiveSize ++; + } + } + + public void add(GenericFutureListener> l) { + GenericFutureListener>[] listeners = this.listeners; + final int size = this.size; + if (size == listeners.length) { + this.listeners = listeners = Arrays.copyOf(listeners, size << 1); + } + listeners[size] = l; + this.size = size + 1; + + if (l instanceof GenericProgressiveFutureListener) { + progressiveSize ++; + } + } + + public void remove(GenericFutureListener> l) { + final GenericFutureListener>[] listeners = this.listeners; + int size = this.size; + for (int i = 0; i < size; i ++) { + if (listeners[i] == l) { + int listenersToMove = size - i - 1; + if (listenersToMove > 0) { + System.arraycopy(listeners, i + 1, listeners, i, listenersToMove); + } + listeners[-- size] = null; + this.size = size; + + if (l instanceof GenericProgressiveFutureListener) { + progressiveSize --; + } + return; + } + } + } + + public GenericFutureListener>[] listeners() { + return listeners; + } + + public int size() { + return size; + } + + public int progressiveSize() { + return progressiveSize; + } +} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultProgressivePromise.java b/common/src/main/java/common/net/util/concurrent/DefaultProgressivePromise.java new file mode 100644 index 0000000..57d908a --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/DefaultProgressivePromise.java @@ -0,0 +1,130 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.concurrent; + +public class DefaultProgressivePromise extends DefaultPromise implements ProgressivePromise { + + /** + * Creates a new instance. + * + * It is preferable to use {@link EventExecutor#newProgressivePromise()} to create a new progressive promise + * + * @param executor + * the {@link EventExecutor} which is used to notify the promise when it progresses or it is complete + */ + public DefaultProgressivePromise(EventExecutor executor) { + super(executor); + } + + protected DefaultProgressivePromise() { /* only for subclasses */ } + + @Override + public ProgressivePromise setProgress(long progress, long total) { + if (total < 0) { + // total unknown + total = -1; // normalize + if (progress < 0) { + throw new IllegalArgumentException("progress: " + progress + " (expected: >= 0)"); + } + } else if (progress < 0 || progress > total) { + throw new IllegalArgumentException( + "progress: " + progress + " (expected: 0 <= progress <= total (" + total + "))"); + } + + if (isDone()) { + throw new IllegalStateException("complete already"); + } + + notifyProgressiveListeners(progress, total); + return this; + } + + @Override + public boolean tryProgress(long progress, long total) { + if (total < 0) { + total = -1; + if (progress < 0 || isDone()) { + return false; + } + } else if (progress < 0 || progress > total || isDone()) { + return false; + } + + notifyProgressiveListeners(progress, total); + return true; + } + + @Override + public ProgressivePromise addListener(GenericFutureListener> listener) { + super.addListener(listener); + return this; + } + + @Override + public ProgressivePromise addListeners(GenericFutureListener>... listeners) { + super.addListeners(listeners); + return this; + } + + @Override + public ProgressivePromise removeListener(GenericFutureListener> listener) { + super.removeListener(listener); + return this; + } + + @Override + public ProgressivePromise removeListeners(GenericFutureListener>... listeners) { + super.removeListeners(listeners); + return this; + } + + @Override + public ProgressivePromise sync() throws InterruptedException { + super.sync(); + return this; + } + + @Override + public ProgressivePromise syncUninterruptibly() { + super.syncUninterruptibly(); + return this; + } + + @Override + public ProgressivePromise await() throws InterruptedException { + super.await(); + return this; + } + + @Override + public ProgressivePromise awaitUninterruptibly() { + super.awaitUninterruptibly(); + return this; + } + + @Override + public ProgressivePromise setSuccess(V result) { + super.setSuccess(result); + return this; + } + + @Override + public ProgressivePromise setFailure(Throwable cause) { + super.setFailure(cause); + return this; + } +} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultPromise.java b/common/src/main/java/common/net/util/concurrent/DefaultPromise.java new file mode 100644 index 0000000..f7cad80 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/DefaultPromise.java @@ -0,0 +1,876 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import static java.util.concurrent.TimeUnit.MILLISECONDS; + +import java.util.ArrayDeque; +import java.util.concurrent.CancellationException; +import java.util.concurrent.TimeUnit; + +import common.net.util.Signal; +import common.net.util.internal.EmptyArrays; +import common.net.util.internal.InternalThreadLocalMap; +import common.net.util.internal.StringUtil; +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; +import common.util.Util; + +public class DefaultPromise extends AbstractFuture implements Promise { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultPromise.class); + private static final InternalLogger rejectedExecutionLogger = + InternalLoggerFactory.getInstance(DefaultPromise.class.getName() + ".rejectedExecution"); + + private static final int MAX_LISTENER_STACK_DEPTH = 8; + private static final Signal SUCCESS = Signal.valueOf(DefaultPromise.class.getName() + ".SUCCESS"); + private static final Signal UNCANCELLABLE = Signal.valueOf(DefaultPromise.class.getName() + ".UNCANCELLABLE"); + private static final CauseHolder CANCELLATION_CAUSE_HOLDER = new CauseHolder(new CancellationException()); + + static { + CANCELLATION_CAUSE_HOLDER.cause.setStackTrace(EmptyArrays.EMPTY_STACK_TRACE); + } + + private final EventExecutor executor; + + private volatile Object result; + + /** + * One or more listeners. Can be a {@link GenericFutureListener} or a {@link DefaultFutureListeners}. + * If {@code null}, it means either 1) no listeners were added yet or 2) all listeners were notified. + */ + private Object listeners; + + /** + * The list of the listeners that were added after the promise is done. Initially {@code null} and lazily + * instantiated when the late listener is scheduled to be notified later. Also used as a cached {@link Runnable} + * that performs the notification of the listeners it contains. + */ + private LateListeners lateListeners; + + private short waiters; + + /** + * Creates a new instance. + * + * It is preferable to use {@link EventExecutor#newPromise()} to create a new promise + * + * @param executor + * the {@link EventExecutor} which is used to notify the promise once it is complete + */ + public DefaultPromise(EventExecutor executor) { + if (executor == null) { + throw new NullPointerException("executor"); + } + this.executor = executor; + } + + protected DefaultPromise() { + // only for subclasses + executor = null; + } + + protected EventExecutor executor() { + return executor; + } + + @Override + public boolean isCancelled() { + return isCancelled0(result); + } + + private static boolean isCancelled0(Object result) { + return result instanceof CauseHolder && ((CauseHolder) result).cause instanceof CancellationException; + } + + @Override + public boolean isCancellable() { + return result == null; + } + + @Override + public boolean isDone() { + return isDone0(result); + } + + private static boolean isDone0(Object result) { + return result != null && result != UNCANCELLABLE; + } + + @Override + public boolean isSuccess() { + Object result = this.result; + if (result == null || result == UNCANCELLABLE) { + return false; + } + return !(result instanceof CauseHolder); + } + + @Override + public Throwable cause() { + Object result = this.result; + if (result instanceof CauseHolder) { + return ((CauseHolder) result).cause; + } + return null; + } + + @Override + public Promise addListener(GenericFutureListener> listener) { + if (listener == null) { + throw new NullPointerException("listener"); + } + + if (isDone()) { + notifyLateListener(listener); + return this; + } + + synchronized (this) { + if (!isDone()) { + if (listeners == null) { + listeners = listener; + } else { + if (listeners instanceof DefaultFutureListeners) { + ((DefaultFutureListeners) listeners).add(listener); + } else { + final GenericFutureListener> firstListener = + (GenericFutureListener>) listeners; + listeners = new DefaultFutureListeners(firstListener, listener); + } + } + return this; + } + } + + notifyLateListener(listener); + return this; + } + + @Override + public Promise addListeners(GenericFutureListener>... listeners) { + if (listeners == null) { + throw new NullPointerException("listeners"); + } + + for (GenericFutureListener> l: listeners) { + if (l == null) { + break; + } + addListener(l); + } + return this; + } + + @Override + public Promise removeListener(GenericFutureListener> listener) { + if (listener == null) { + throw new NullPointerException("listener"); + } + + if (isDone()) { + return this; + } + + synchronized (this) { + if (!isDone()) { + if (listeners instanceof DefaultFutureListeners) { + ((DefaultFutureListeners) listeners).remove(listener); + } else if (listeners == listener) { + listeners = null; + } + } + } + + return this; + } + + @Override + public Promise removeListeners(GenericFutureListener>... listeners) { + if (listeners == null) { + throw new NullPointerException("listeners"); + } + + for (GenericFutureListener> l: listeners) { + if (l == null) { + break; + } + removeListener(l); + } + return this; + } + + @Override + public Promise sync() throws InterruptedException { + await(); + rethrowIfFailed(); + return this; + } + + @Override + public Promise syncUninterruptibly() { + awaitUninterruptibly(); + rethrowIfFailed(); + return this; + } + + private void rethrowIfFailed() { + Throwable cause = cause(); + if (cause == null) { + return; + } + + Util.throwUnchecked(cause); + } + + @Override + public Promise await() throws InterruptedException { + if (isDone()) { + return this; + } + + if (Thread.interrupted()) { + throw new InterruptedException(toString()); + } + + synchronized (this) { + while (!isDone()) { + checkDeadLock(); + incWaiters(); + try { + wait(); + } finally { + decWaiters(); + } + } + } + return this; + } + + @Override + public boolean await(long timeout, TimeUnit unit) + throws InterruptedException { + return await0(unit.toNanos(timeout), true); + } + + @Override + public boolean await(long timeoutMillis) throws InterruptedException { + return await0(MILLISECONDS.toNanos(timeoutMillis), true); + } + + @Override + public Promise awaitUninterruptibly() { + if (isDone()) { + return this; + } + + boolean interrupted = false; + synchronized (this) { + while (!isDone()) { + checkDeadLock(); + incWaiters(); + try { + wait(); + } catch (InterruptedException e) { + // Interrupted while waiting. + interrupted = true; + } finally { + decWaiters(); + } + } + } + + if (interrupted) { + Thread.currentThread().interrupt(); + } + + return this; + } + + @Override + public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { + try { + return await0(unit.toNanos(timeout), false); + } catch (InterruptedException e) { + // Should not be raised at all. + throw new InternalError(); + } + } + + @Override + public boolean awaitUninterruptibly(long timeoutMillis) { + try { + return await0(MILLISECONDS.toNanos(timeoutMillis), false); + } catch (InterruptedException e) { + // Should not be raised at all. + throw new InternalError(); + } + } + + private boolean await0(long timeoutNanos, boolean interruptable) throws InterruptedException { + if (isDone()) { + return true; + } + + if (timeoutNanos <= 0) { + return isDone(); + } + + if (interruptable && Thread.interrupted()) { + throw new InterruptedException(toString()); + } + + long startTime = System.nanoTime(); + long waitTime = timeoutNanos; + boolean interrupted = false; + + try { + synchronized (this) { + if (isDone()) { + return true; + } + + if (waitTime <= 0) { + return isDone(); + } + + checkDeadLock(); + incWaiters(); + try { + for (;;) { + try { + wait(waitTime / 1000000, (int) (waitTime % 1000000)); + } catch (InterruptedException e) { + if (interruptable) { + throw e; + } else { + interrupted = true; + } + } + + if (isDone()) { + return true; + } else { + waitTime = timeoutNanos - (System.nanoTime() - startTime); + if (waitTime <= 0) { + return isDone(); + } + } + } + } finally { + decWaiters(); + } + } + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + } + + /** + * Do deadlock checks + */ + protected void checkDeadLock() { + EventExecutor e = executor(); + if (e != null && e.inEventLoop()) { + throw new BlockingOperationException(toString()); + } + } + + @Override + public Promise setSuccess(V result) { + if (setSuccess0(result)) { + notifyListeners(); + return this; + } + throw new IllegalStateException("complete already: " + this); + } + + @Override + public boolean trySuccess(V result) { + if (setSuccess0(result)) { + notifyListeners(); + return true; + } + return false; + } + + @Override + public Promise setFailure(Throwable cause) { + if (setFailure0(cause)) { + notifyListeners(); + return this; + } + throw new IllegalStateException("complete already: " + this, cause); + } + + @Override + public boolean tryFailure(Throwable cause) { + if (setFailure0(cause)) { + notifyListeners(); + return true; + } + return false; + } + + @Override + public boolean cancel(boolean mayInterruptIfRunning) { + Object result = this.result; + if (isDone0(result) || result == UNCANCELLABLE) { + return false; + } + + synchronized (this) { + // Allow only once. + result = this.result; + if (isDone0(result) || result == UNCANCELLABLE) { + return false; + } + + this.result = CANCELLATION_CAUSE_HOLDER; + if (hasWaiters()) { + notifyAll(); + } + } + + notifyListeners(); + return true; + } + + @Override + public boolean setUncancellable() { + Object result = this.result; + if (isDone0(result)) { + return !isCancelled0(result); + } + + synchronized (this) { + // Allow only once. + result = this.result; + if (isDone0(result)) { + return !isCancelled0(result); + } + + this.result = UNCANCELLABLE; + } + return true; + } + + private boolean setFailure0(Throwable cause) { + if (cause == null) { + throw new NullPointerException("cause"); + } + + if (isDone()) { + return false; + } + + synchronized (this) { + // Allow only once. + if (isDone()) { + return false; + } + + result = new CauseHolder(cause); + if (hasWaiters()) { + notifyAll(); + } + } + return true; + } + + private boolean setSuccess0(V result) { + if (isDone()) { + return false; + } + + synchronized (this) { + // Allow only once. + if (isDone()) { + return false; + } + if (result == null) { + this.result = SUCCESS; + } else { + this.result = result; + } + if (hasWaiters()) { + notifyAll(); + } + } + return true; + } + + @Override + + public V getNow() { + Object result = this.result; + if (result instanceof CauseHolder || result == SUCCESS) { + return null; + } + return (V) result; + } + + private boolean hasWaiters() { + return waiters > 0; + } + + private void incWaiters() { + if (waiters == Short.MAX_VALUE) { + throw new IllegalStateException("too many waiters: " + this); + } + waiters ++; + } + + private void decWaiters() { + waiters --; + } + + private void notifyListeners() { + // This method doesn't need synchronization because: + // 1) This method is always called after synchronized (this) block. + // Hence any listener list modification happens-before this method. + // 2) This method is called only when 'done' is true. Once 'done' + // becomes true, the listener list is never modified - see add/removeListener() + + Object listeners = this.listeners; + if (listeners == null) { + return; + } + + EventExecutor executor = executor(); + if (executor.inEventLoop()) { + final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get(); + final int stackDepth = threadLocals.futureListenerStackDepth(); + if (stackDepth < MAX_LISTENER_STACK_DEPTH) { + threadLocals.setFutureListenerStackDepth(stackDepth + 1); + try { + if (listeners instanceof DefaultFutureListeners) { + notifyListeners0(this, (DefaultFutureListeners) listeners); + } else { + final GenericFutureListener> l = + (GenericFutureListener>) listeners; + notifyListener0(this, l); + } + } finally { + this.listeners = null; + threadLocals.setFutureListenerStackDepth(stackDepth); + } + return; + } + } + + if (listeners instanceof DefaultFutureListeners) { + final DefaultFutureListeners dfl = (DefaultFutureListeners) listeners; + execute(executor, new Runnable() { + @Override + public void run() { + notifyListeners0(DefaultPromise.this, dfl); + DefaultPromise.this.listeners = null; + } + }); + } else { + final GenericFutureListener> l = + (GenericFutureListener>) listeners; + execute(executor, new Runnable() { + @Override + public void run() { + notifyListener0(DefaultPromise.this, l); + DefaultPromise.this.listeners = null; + } + }); + } + } + + private static void notifyListeners0(Future future, DefaultFutureListeners listeners) { + final GenericFutureListener[] a = listeners.listeners(); + final int size = listeners.size(); + for (int i = 0; i < size; i ++) { + notifyListener0(future, a[i]); + } + } + + /** + * Notifies the specified listener which were added after this promise is already done. + * This method ensures that the specified listener is not notified until {@link #listeners} becomes {@code null} + * to avoid the case where the late listeners are notified even before the early listeners are notified. + */ + private void notifyLateListener(final GenericFutureListener l) { + final EventExecutor executor = executor(); + if (executor.inEventLoop()) { + if (listeners == null && lateListeners == null) { + final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get(); + final int stackDepth = threadLocals.futureListenerStackDepth(); + if (stackDepth < MAX_LISTENER_STACK_DEPTH) { + threadLocals.setFutureListenerStackDepth(stackDepth + 1); + try { + notifyListener0(this, l); + } finally { + threadLocals.setFutureListenerStackDepth(stackDepth); + } + return; + } + } else { + LateListeners lateListeners = this.lateListeners; + if (lateListeners == null) { + this.lateListeners = lateListeners = new LateListeners(); + } + lateListeners.add(l); + execute(executor, lateListeners); + return; + } + } + + // Add the late listener to lateListeners in the executor thread for thread safety. + // We could just make LateListeners extend ConcurrentLinkedQueue, but it's an overkill considering + // that most asynchronous applications won't execute this code path. + execute(executor, new LateListenerNotifier(l)); + } + + protected static void notifyListener( + final EventExecutor eventExecutor, final Future future, final GenericFutureListener l) { + + if (eventExecutor.inEventLoop()) { + final InternalThreadLocalMap threadLocals = InternalThreadLocalMap.get(); + final int stackDepth = threadLocals.futureListenerStackDepth(); + if (stackDepth < MAX_LISTENER_STACK_DEPTH) { + threadLocals.setFutureListenerStackDepth(stackDepth + 1); + try { + notifyListener0(future, l); + } finally { + threadLocals.setFutureListenerStackDepth(stackDepth); + } + return; + } + } + + execute(eventExecutor, new Runnable() { + @Override + public void run() { + notifyListener0(future, l); + } + }); + } + + private static void execute(EventExecutor executor, Runnable task) { + try { + executor.execute(task); + } catch (Throwable t) { + rejectedExecutionLogger.error("Failed to submit a listener notification task. Event loop shut down?", t); + } + } + + + static void notifyListener0(Future future, GenericFutureListener l) { + try { + l.operationComplete(future); + } catch (Throwable t) { + if (logger.isWarnEnabled()) { + logger.warn("An exception was thrown by " + l.getClass().getName() + ".operationComplete()", t); + } + } + } + + /** + * Returns a {@link GenericProgressiveFutureListener}, an array of {@link GenericProgressiveFutureListener}, or + * {@code null}. + */ + private synchronized Object progressiveListeners() { + Object listeners = this.listeners; + if (listeners == null) { + // No listeners added + return null; + } + + if (listeners instanceof DefaultFutureListeners) { + // Copy DefaultFutureListeners into an array of listeners. + DefaultFutureListeners dfl = (DefaultFutureListeners) listeners; + int progressiveSize = dfl.progressiveSize(); + switch (progressiveSize) { + case 0: + return null; + case 1: + for (GenericFutureListener l: dfl.listeners()) { + if (l instanceof GenericProgressiveFutureListener) { + return l; + } + } + return null; + } + + GenericFutureListener[] array = dfl.listeners(); + GenericProgressiveFutureListener[] copy = new GenericProgressiveFutureListener[progressiveSize]; + for (int i = 0, j = 0; j < progressiveSize; i ++) { + GenericFutureListener l = array[i]; + if (l instanceof GenericProgressiveFutureListener) { + copy[j ++] = (GenericProgressiveFutureListener) l; + } + } + + return copy; + } else if (listeners instanceof GenericProgressiveFutureListener) { + return listeners; + } else { + // Only one listener was added and it's not a progressive listener. + return null; + } + } + + + void notifyProgressiveListeners(final long progress, final long total) { + final Object listeners = progressiveListeners(); + if (listeners == null) { + return; + } + + final ProgressiveFuture self = (ProgressiveFuture) this; + + EventExecutor executor = executor(); + if (executor.inEventLoop()) { + if (listeners instanceof GenericProgressiveFutureListener[]) { + notifyProgressiveListeners0( + self, (GenericProgressiveFutureListener[]) listeners, progress, total); + } else { + notifyProgressiveListener0( + self, (GenericProgressiveFutureListener>) listeners, progress, total); + } + } else { + if (listeners instanceof GenericProgressiveFutureListener[]) { + final GenericProgressiveFutureListener[] array = + (GenericProgressiveFutureListener[]) listeners; + execute(executor, new Runnable() { + @Override + public void run() { + notifyProgressiveListeners0(self, array, progress, total); + } + }); + } else { + final GenericProgressiveFutureListener> l = + (GenericProgressiveFutureListener>) listeners; + execute(executor, new Runnable() { + @Override + public void run() { + notifyProgressiveListener0(self, l, progress, total); + } + }); + } + } + } + + private static void notifyProgressiveListeners0( + ProgressiveFuture future, GenericProgressiveFutureListener[] listeners, long progress, long total) { + for (GenericProgressiveFutureListener l: listeners) { + if (l == null) { + break; + } + notifyProgressiveListener0(future, l, progress, total); + } + } + + + private static void notifyProgressiveListener0( + ProgressiveFuture future, GenericProgressiveFutureListener l, long progress, long total) { + try { + l.operationProgressed(future, progress, total); + } catch (Throwable t) { + if (logger.isWarnEnabled()) { + logger.warn("An exception was thrown by " + l.getClass().getName() + ".operationProgressed()", t); + } + } + } + + private static final class CauseHolder { + final Throwable cause; + CauseHolder(Throwable cause) { + this.cause = cause; + } + } + + @Override + public String toString() { + return toStringBuilder().toString(); + } + + protected StringBuilder toStringBuilder() { + StringBuilder buf = new StringBuilder(64); + buf.append(StringUtil.simpleClassName(this)); + buf.append('@'); + buf.append(Integer.toHexString(hashCode())); + + Object result = this.result; + if (result == SUCCESS) { + buf.append("(success)"); + } else if (result == UNCANCELLABLE) { + buf.append("(uncancellable)"); + } else if (result instanceof CauseHolder) { + buf.append("(failure("); + buf.append(((CauseHolder) result).cause); + buf.append(')'); + } else { + buf.append("(incomplete)"); + } + return buf; + } + + private final class LateListeners extends ArrayDeque> implements Runnable { + + private static final long serialVersionUID = -687137418080392244L; + + LateListeners() { + super(2); + } + + @Override + public void run() { + if (listeners == null) { + for (;;) { + GenericFutureListener l = poll(); + if (l == null) { + break; + } + notifyListener0(DefaultPromise.this, l); + } + } else { + // Reschedule until the initial notification is done to avoid the race condition + // where the notification is made in an incorrect order. + execute(executor(), this); + } + } + } + + private final class LateListenerNotifier implements Runnable { + private GenericFutureListener l; + + LateListenerNotifier(GenericFutureListener l) { + this.l = l; + } + + @Override + public void run() { + LateListeners lateListeners = DefaultPromise.this.lateListeners; + if (l != null) { + if (lateListeners == null) { + DefaultPromise.this.lateListeners = lateListeners = new LateListeners(); + } + lateListeners.add(l); + l = null; + } + + lateListeners.run(); + } + } +} diff --git a/common/src/main/java/common/net/util/concurrent/DefaultThreadFactory.java b/common/src/main/java/common/net/util/concurrent/DefaultThreadFactory.java new file mode 100644 index 0000000..8dc939d --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/DefaultThreadFactory.java @@ -0,0 +1,143 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.concurrent; + +import java.util.Locale; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + +import common.net.util.internal.StringUtil; + +/** + * A {@link ThreadFactory} implementation with a simple naming rule. + */ +public class DefaultThreadFactory implements ThreadFactory { + + private static final AtomicInteger poolId = new AtomicInteger(); + + private final AtomicInteger nextId = new AtomicInteger(); + private final String prefix; + private final boolean daemon; + private final int priority; + + public DefaultThreadFactory(Class poolType) { + this(poolType, false, Thread.NORM_PRIORITY); + } + + public DefaultThreadFactory(String poolName) { + this(poolName, false, Thread.NORM_PRIORITY); + } + + public DefaultThreadFactory(Class poolType, boolean daemon) { + this(poolType, daemon, Thread.NORM_PRIORITY); + } + + public DefaultThreadFactory(String poolName, boolean daemon) { + this(poolName, daemon, Thread.NORM_PRIORITY); + } + + public DefaultThreadFactory(Class poolType, int priority) { + this(poolType, false, priority); + } + + public DefaultThreadFactory(String poolName, int priority) { + this(poolName, false, priority); + } + + public DefaultThreadFactory(Class poolType, boolean daemon, int priority) { + this(toPoolName(poolType), daemon, priority); + } + + private static String toPoolName(Class poolType) { + if (poolType == null) { + throw new NullPointerException("poolType"); + } + + String poolName = StringUtil.simpleClassName(poolType); + switch (poolName.length()) { + case 0: + return "unknown"; + case 1: + return poolName.toLowerCase(Locale.US); + default: + if (Character.isUpperCase(poolName.charAt(0)) && Character.isLowerCase(poolName.charAt(1))) { + return Character.toLowerCase(poolName.charAt(0)) + poolName.substring(1); + } else { + return poolName; + } + } + } + + public DefaultThreadFactory(String poolName, boolean daemon, int priority) { + if (poolName == null) { + throw new NullPointerException("poolName"); + } + if (priority < Thread.MIN_PRIORITY || priority > Thread.MAX_PRIORITY) { + throw new IllegalArgumentException( + "priority: " + priority + " (expected: Thread.MIN_PRIORITY <= priority <= Thread.MAX_PRIORITY)"); + } + + prefix = poolName + '-' + poolId.incrementAndGet() + '-'; + this.daemon = daemon; + this.priority = priority; + } + + @Override + public Thread newThread(Runnable r) { + Thread t = newThread(new DefaultRunnableDecorator(r), prefix + nextId.incrementAndGet()); + try { + if (t.isDaemon()) { + if (!daemon) { + t.setDaemon(false); + } + } else { + if (daemon) { + t.setDaemon(true); + } + } + + if (t.getPriority() != priority) { + t.setPriority(priority); + } + } catch (Exception ignored) { + // Doesn't matter even if failed to set. + } + return t; + } + + protected Thread newThread(Runnable r, String name) { + return new FastThreadLocalThread(r, name); + } + + private static final class DefaultRunnableDecorator implements Runnable { + + private final Runnable r; + + DefaultRunnableDecorator(Runnable r) { + this.r = r; + } + + @Override + public void run() { + try { + r.run(); + } finally { + FastThreadLocal.removeAll(); + } + } + } +} diff --git a/common/src/main/java/common/net/util/concurrent/EventExecutor.java b/common/src/main/java/common/net/util/concurrent/EventExecutor.java new file mode 100644 index 0000000..e145548 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/EventExecutor.java @@ -0,0 +1,72 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +/** + * The {@link EventExecutor} is a special {@link EventExecutorGroup} which comes + * with some handy methods to see if a {@link Thread} is executed in a event loop. + * Beside this it also extends the {@link EventExecutorGroup} to allow a generic way to + * access methods. + * + */ +public interface EventExecutor extends EventExecutorGroup { + + /** + * Returns a reference to itself. + */ + @Override + EventExecutor next(); + + /** + * Return the {@link EventExecutorGroup} which is the parent of this {@link EventExecutor}, + */ + EventExecutorGroup parent(); + + /** + * Calls {@link #inEventLoop(Thread)} with {@link Thread#currentThread()} as argument + */ + boolean inEventLoop(); + + /** + * Return {@code true} if the given {@link Thread} is executed in the event loop, + * {@code false} otherwise. + */ + boolean inEventLoop(Thread thread); + + /** + * Return a new {@link Promise}. + */ + Promise newPromise(); + + /** + * Create a new {@link ProgressivePromise}. + */ + ProgressivePromise newProgressivePromise(); + + /** + * Create a new {@link Future} which is marked as successes already. So {@link Future#isSuccess()} + * will return {@code true}. All {@link FutureListener} added to it will be notified directly. Also + * every call of blocking methods will just return without blocking. + */ + Future newSucceededFuture(V result); + + /** + * Create a new {@link Future} which is marked as fakued already. So {@link Future#isSuccess()} + * will return {@code false}. All {@link FutureListener} added to it will be notified directly. Also + * every call of blocking methods will just return without blocking. + */ + Future newFailedFuture(Throwable cause); +} diff --git a/common/src/main/java/common/net/util/concurrent/EventExecutorGroup.java b/common/src/main/java/common/net/util/concurrent/EventExecutorGroup.java new file mode 100644 index 0000000..16da3f8 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/EventExecutorGroup.java @@ -0,0 +1,112 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.Iterator; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ScheduledExecutorService; +import java.util.concurrent.TimeUnit; + +/** + * The {@link EventExecutorGroup} is responsible to provide {@link EventExecutor}'s to use via its + * {@link #next()} method. Beside this it also is responsible to handle their live-cycle and allows + * to shut them down in a global fashion. + * + */ +public interface EventExecutorGroup extends ScheduledExecutorService, Iterable { + + /** + * Returns {@code true} if and only if this executor was started to be + * {@linkplain #shutdownGracefully() shut down gracefuclly} or was {@linkplain #isShutdown() shut down}. + */ + boolean isShuttingDown(); + + /** + * Shortcut method for {@link #shutdownGracefully(long, long, TimeUnit)} with sensible default values. + * + * @return the {@link #terminationFuture()} + */ + Future shutdownGracefully(); + + /** + * Signals this executor that the caller wants the executor to be shut down. Once this method is called, + * {@link #isShuttingDown()} starts to return {@code true}, and the executor prepares to shut itself down. + * Unlike {@link #shutdown()}, graceful shutdown ensures that no tasks are submitted for 'the quiet period' + * (usually a couple seconds) before it shuts itself down. If a task is submitted during the quiet period, + * it is guaranteed to be accepted and the quiet period will start over. + * + * @param quietPeriod the quiet period as described in the documentation + * @param timeout the maximum amount of time to wait until the executor is {@linkplain #shutdown()} + * regardless if a task was submitted during the quiet period + * @param unit the unit of {@code quietPeriod} and {@code timeout} + * + * @return the {@link #terminationFuture()} + */ + Future shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit); + + /** + * Returns the {@link Future} which is notified when this executor has been terminated. + */ + Future terminationFuture(); + + /** + * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. + */ + @Override + @Deprecated + void shutdown(); + + /** + * @deprecated {@link #shutdownGracefully(long, long, TimeUnit)} or {@link #shutdownGracefully()} instead. + */ + @Override + @Deprecated + List shutdownNow(); + + /** + * Returns one of the {@link EventExecutor}s that belong to this group. + */ + EventExecutor next(); + + /** + * Returns a read-only {@link Iterator} over all {@link EventExecutor}, which are handled by this + * {@link EventExecutorGroup} at the time of invoke this method. + */ + @Override + Iterator iterator(); + + @Override + Future submit(Runnable task); + + @Override + Future submit(Runnable task, T result); + + @Override + Future submit(Callable task); + + @Override + ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit); + + @Override + ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit); + + @Override + ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit); + + @Override + ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit); +} diff --git a/common/src/main/java/common/net/util/concurrent/FailedFuture.java b/common/src/main/java/common/net/util/concurrent/FailedFuture.java new file mode 100644 index 0000000..f0c6ce7 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/FailedFuture.java @@ -0,0 +1,69 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import common.util.Util; + +/** + * The {@link CompleteFuture} which is failed already. It is + * recommended to use {@link EventExecutor#newFailedFuture(Throwable)} + * instead of calling the constructor of this future. + */ +public final class FailedFuture extends CompleteFuture { + + private final Throwable cause; + + /** + * Creates a new instance. + * + * @param executor the {@link EventExecutor} associated with this future + * @param cause the cause of failure + */ + public FailedFuture(EventExecutor executor, Throwable cause) { + super(executor); + if (cause == null) { + throw new NullPointerException("cause"); + } + this.cause = cause; + } + + @Override + public Throwable cause() { + return cause; + } + + @Override + public boolean isSuccess() { + return false; + } + + @Override + public Future sync() { + Util.throwUnchecked(cause); + return this; + } + + @Override + public Future syncUninterruptibly() { + Util.throwUnchecked(cause); + return this; + } + + @Override + public V getNow() { + return null; + } +} diff --git a/common/src/main/java/common/net/util/concurrent/FastThreadLocal.java b/common/src/main/java/common/net/util/concurrent/FastThreadLocal.java new file mode 100644 index 0000000..a435abf --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/FastThreadLocal.java @@ -0,0 +1,244 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.Set; + +import common.net.util.internal.InternalThreadLocalMap; +import common.util.Util; + +/** + * A special variant of {@link ThreadLocal} that yields higher access performan when accessed from a + * {@link FastThreadLocalThread}. + *

+ * Internally, a {@link FastThreadLocal} uses a constant index in an array, instead of using hash code and hash table, + * to look for a variable. Although seemingly very subtle, it yields slight performance advantage over using a hash + * table, and it is useful when accessed frequently. + *

+ * To take advantage of this thread-local variable, your thread must be a {@link FastThreadLocalThread} or its subtype. + * By default, all threads created by {@link DefaultThreadFactory} are {@link FastThreadLocalThread} due to this reason. + *

+ * Note that the fast path is only possible on threads that extend {@link FastThreadLocalThread}, because it requires + * a special field to store the necessary state. An access by any other kind of thread falls back to a regular + * {@link ThreadLocal}. + *

+ * + * @param the type of the thread-local variable + * @see ThreadLocal + */ +public class FastThreadLocal { + + private static final int variablesToRemoveIndex = InternalThreadLocalMap.nextVariableIndex(); + + /** + * Removes all {@link FastThreadLocal} variables bound to the current thread. This operation is useful when you + * are in a container environment, and you don't want to leave the thread local variables in the threads you do not + * manage. + */ + public static void removeAll() { + InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); + if (threadLocalMap == null) { + return; + } + + try { + Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex); + if (v != null && v != InternalThreadLocalMap.UNSET) { + + Set> variablesToRemove = (Set>) v; + FastThreadLocal[] variablesToRemoveArray = + variablesToRemove.toArray(new FastThreadLocal[variablesToRemove.size()]); + for (FastThreadLocal tlv: variablesToRemoveArray) { + tlv.remove(threadLocalMap); + } + } + } finally { + InternalThreadLocalMap.remove(); + } + } + + /** + * Returns the number of thread local variables bound to the current thread. + */ + public static int size() { + InternalThreadLocalMap threadLocalMap = InternalThreadLocalMap.getIfSet(); + if (threadLocalMap == null) { + return 0; + } else { + return threadLocalMap.size(); + } + } + + /** + * Destroys the data structure that keeps all {@link FastThreadLocal} variables accessed from + * non-{@link FastThreadLocalThread}s. This operation is useful when you are in a container environment, and you + * do not want to leave the thread local variables in the threads you do not manage. Call this method when your + * application is being unloaded from the container. + */ + public static void destroy() { + InternalThreadLocalMap.destroy(); + } + + + private static void addToVariablesToRemove(InternalThreadLocalMap threadLocalMap, FastThreadLocal variable) { + Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex); + Set> variablesToRemove; + if (v == InternalThreadLocalMap.UNSET || v == null) { + variablesToRemove = Collections.newSetFromMap(new IdentityHashMap, Boolean>()); + threadLocalMap.setIndexedVariable(variablesToRemoveIndex, variablesToRemove); + } else { + variablesToRemove = (Set>) v; + } + + variablesToRemove.add(variable); + } + + private static void removeFromVariablesToRemove( + InternalThreadLocalMap threadLocalMap, FastThreadLocal variable) { + + Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex); + + if (v == InternalThreadLocalMap.UNSET || v == null) { + return; + } + + + Set> variablesToRemove = (Set>) v; + variablesToRemove.remove(variable); + } + + private final int index; + + public FastThreadLocal() { + index = InternalThreadLocalMap.nextVariableIndex(); + } + + /** + * Returns the current value for the current thread + */ + public final V get() { + return get(InternalThreadLocalMap.get()); + } + + /** + * Returns the current value for the specified thread local map. + * The specified thread local map must be for the current thread. + */ + + public final V get(InternalThreadLocalMap threadLocalMap) { + Object v = threadLocalMap.indexedVariable(index); + if (v != InternalThreadLocalMap.UNSET) { + return (V) v; + } + + return initialize(threadLocalMap); + } + + private V initialize(InternalThreadLocalMap threadLocalMap) { + V v = null; + try { + v = initialValue(); + } catch (Exception e) { + Util.throwUnchecked(e); + } + + threadLocalMap.setIndexedVariable(index, v); + addToVariablesToRemove(threadLocalMap, this); + return v; + } + + /** + * Set the value for the current thread. + */ + public final void set(V value) { + if (value != InternalThreadLocalMap.UNSET) { + set(InternalThreadLocalMap.get(), value); + } else { + remove(); + } + } + + /** + * Set the value for the specified thread local map. The specified thread local map must be for the current thread. + */ + public final void set(InternalThreadLocalMap threadLocalMap, V value) { + if (value != InternalThreadLocalMap.UNSET) { + if (threadLocalMap.setIndexedVariable(index, value)) { + addToVariablesToRemove(threadLocalMap, this); + } + } else { + remove(threadLocalMap); + } + } + + /** + * Returns {@code true} if and only if this thread-local variable is set. + */ + public final boolean isSet() { + return isSet(InternalThreadLocalMap.getIfSet()); + } + + /** + * Returns {@code true} if and only if this thread-local variable is set. + * The specified thread local map must be for the current thread. + */ + public final boolean isSet(InternalThreadLocalMap threadLocalMap) { + return threadLocalMap != null && threadLocalMap.isIndexedVariableSet(index); + } + /** + * Sets the value to uninitialized; a proceeding call to get() will trigger a call to initialValue(). + */ + public final void remove() { + remove(InternalThreadLocalMap.getIfSet()); + } + + /** + * Sets the value to uninitialized for the specified thread local map; + * a proceeding call to get() will trigger a call to initialValue(). + * The specified thread local map must be for the current thread. + */ + + public final void remove(InternalThreadLocalMap threadLocalMap) { + if (threadLocalMap == null) { + return; + } + + Object v = threadLocalMap.removeIndexedVariable(index); + removeFromVariablesToRemove(threadLocalMap, this); + + if (v != InternalThreadLocalMap.UNSET) { + try { + onRemoval((V) v); + } catch (Exception e) { + Util.throwUnchecked(e); + } + } + } + + /** + * Returns the initial value for this thread-local variable. + */ + protected V initialValue() throws Exception { + return null; + } + + /** + * Invoked when this thread local variable is removed by {@link #remove()}. + */ + protected void onRemoval( V value) throws Exception { } +} diff --git a/common/src/main/java/common/net/util/concurrent/FastThreadLocalThread.java b/common/src/main/java/common/net/util/concurrent/FastThreadLocalThread.java new file mode 100644 index 0000000..e81083f --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/FastThreadLocalThread.java @@ -0,0 +1,72 @@ +/* +* Copyright 2014 The Netty Project +* +* The Netty Project licenses this file to you under the Apache License, +* version 2.0 (the "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at: +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +* License for the specific language governing permissions and limitations +* under the License. +*/ +package common.net.util.concurrent; + +import common.net.util.internal.InternalThreadLocalMap; + +/** + * A special {@link Thread} that provides fast access to {@link FastThreadLocal} variables. + */ +public class FastThreadLocalThread extends Thread { + + private InternalThreadLocalMap threadLocalMap; + + public FastThreadLocalThread() { } + + public FastThreadLocalThread(Runnable target) { + super(target); + } + + public FastThreadLocalThread(ThreadGroup group, Runnable target) { + super(group, target); + } + + public FastThreadLocalThread(String name) { + super(name); + } + + public FastThreadLocalThread(ThreadGroup group, String name) { + super(group, name); + } + + public FastThreadLocalThread(Runnable target, String name) { + super(target, name); + } + + public FastThreadLocalThread(ThreadGroup group, Runnable target, String name) { + super(group, target, name); + } + + public FastThreadLocalThread(ThreadGroup group, Runnable target, String name, long stackSize) { + super(group, target, name, stackSize); + } + + /** + * Returns the internal data structure that keeps the thread-local variables bound to this thread. + * Note that this method is for internal use only, and thus is subject to change at any time. + */ + public final InternalThreadLocalMap threadLocalMap() { + return threadLocalMap; + } + + /** + * Sets the internal data structure that keeps the thread-local variables bound to this thread. + * Note that this method is for internal use only, and thus is subject to change at any time. + */ + public final void setThreadLocalMap(InternalThreadLocalMap threadLocalMap) { + this.threadLocalMap = threadLocalMap; + } +} diff --git a/common/src/main/java/common/net/util/concurrent/Future.java b/common/src/main/java/common/net/util/concurrent/Future.java new file mode 100644 index 0000000..37748cd --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/Future.java @@ -0,0 +1,168 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.concurrent.TimeUnit; + + +/** + * The result of an asynchronous operation. + */ + +public interface Future extends java.util.concurrent.Future { + + /** + * Returns {@code true} if and only if the I/O operation was completed + * successfully. + */ + boolean isSuccess(); + + /** + * returns {@code true} if and only if the operation can be cancelled via {@link #cancel(boolean)}. + */ + boolean isCancellable(); + + /** + * Returns the cause of the failed I/O operation if the I/O operation has + * failed. + * + * @return the cause of the failure. + * {@code null} if succeeded or this future is not + * completed yet. + */ + Throwable cause(); + + /** + * Adds the specified listener to this future. The + * specified listener is notified when this future is + * {@linkplain #isDone() done}. If this future is already + * completed, the specified listener is notified immediately. + */ + Future addListener(GenericFutureListener> listener); + + /** + * Adds the specified listeners to this future. The + * specified listeners are notified when this future is + * {@linkplain #isDone() done}. If this future is already + * completed, the specified listeners are notified immediately. + */ + Future addListeners(GenericFutureListener>... listeners); + + /** + * Removes the specified listener from this future. + * The specified listener is no longer notified when this + * future is {@linkplain #isDone() done}. If the specified + * listener is not associated with this future, this method + * does nothing and returns silently. + */ + Future removeListener(GenericFutureListener> listener); + + /** + * Removes the specified listeners from this future. + * The specified listeners are no longer notified when this + * future is {@linkplain #isDone() done}. If the specified + * listeners are not associated with this future, this method + * does nothing and returns silently. + */ + Future removeListeners(GenericFutureListener>... listeners); + + /** + * Waits for this future until it is done, and rethrows the cause of the failure if this future + * failed. + */ + Future sync() throws InterruptedException; + + /** + * Waits for this future until it is done, and rethrows the cause of the failure if this future + * failed. + */ + Future syncUninterruptibly(); + + /** + * Waits for this future to be completed. + * + * @throws InterruptedException + * if the current thread was interrupted + */ + Future await() throws InterruptedException; + + /** + * Waits for this future to be completed without + * interruption. This method catches an {@link InterruptedException} and + * discards it silently. + */ + Future awaitUninterruptibly(); + + /** + * Waits for this future to be completed within the + * specified time limit. + * + * @return {@code true} if and only if the future was completed within + * the specified time limit + * + * @throws InterruptedException + * if the current thread was interrupted + */ + boolean await(long timeout, TimeUnit unit) throws InterruptedException; + + /** + * Waits for this future to be completed within the + * specified time limit. + * + * @return {@code true} if and only if the future was completed within + * the specified time limit + * + * @throws InterruptedException + * if the current thread was interrupted + */ + boolean await(long timeoutMillis) throws InterruptedException; + + /** + * Waits for this future to be completed within the + * specified time limit without interruption. This method catches an + * {@link InterruptedException} and discards it silently. + * + * @return {@code true} if and only if the future was completed within + * the specified time limit + */ + boolean awaitUninterruptibly(long timeout, TimeUnit unit); + + /** + * Waits for this future to be completed within the + * specified time limit without interruption. This method catches an + * {@link InterruptedException} and discards it silently. + * + * @return {@code true} if and only if the future was completed within + * the specified time limit + */ + boolean awaitUninterruptibly(long timeoutMillis); + + /** + * Return the result without blocking. If the future is not done yet this will return {@code null}. + * + * As it is possible that a {@code null} value is used to mark the future as successful you also need to check + * if the future is really done with {@link #isDone()} and not relay on the returned {@code null} value. + */ + V getNow(); + + /** + * {@inheritDoc} + * + * If the cancellation was successful it will fail the future with an {@link CancellationException}. + */ + @Override + boolean cancel(boolean mayInterruptIfRunning); +} diff --git a/common/src/main/java/common/net/util/concurrent/FutureListener.java b/common/src/main/java/common/net/util/concurrent/FutureListener.java new file mode 100644 index 0000000..8d5a690 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/FutureListener.java @@ -0,0 +1,28 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.concurrent; + +/** + * A subtype of {@link GenericFutureListener} that hides type parameter for convenience. + *
+ * Future f = new DefaultPromise(..);
+ * f.addListener(new FutureListener() {
+ *     public void operationComplete(Future f) { .. }
+ * });
+ * 
+ */ +public interface FutureListener extends GenericFutureListener> { } diff --git a/common/src/main/java/common/net/util/concurrent/GenericFutureListener.java b/common/src/main/java/common/net/util/concurrent/GenericFutureListener.java new file mode 100644 index 0000000..a5d46cc --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/GenericFutureListener.java @@ -0,0 +1,32 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.EventListener; + +/** + * Listens to the result of a {@link Future}. The result of the asynchronous operation is notified once this listener + * is added by calling {@link Future#addListener(GenericFutureListener)}. + */ +public interface GenericFutureListener> extends EventListener { + + /** + * Invoked when the operation associated with the {@link Future} has been completed. + * + * @param future the source {@link Future} which called this callback + */ + void operationComplete(F future) throws Exception; +} diff --git a/common/src/main/java/common/net/util/concurrent/GenericProgressiveFutureListener.java b/common/src/main/java/common/net/util/concurrent/GenericProgressiveFutureListener.java new file mode 100644 index 0000000..8da4cbb --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/GenericProgressiveFutureListener.java @@ -0,0 +1,28 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.concurrent; + +public interface GenericProgressiveFutureListener> extends GenericFutureListener { + /** + * Invoked when the operation has progressed. + * + * @param progress the progress of the operation so far (cumulative) + * @param total the number that signifies the end of the operation when {@code progress} reaches at it. + * {@code -1} if the end of operation is unknown. + */ + void operationProgressed(F future, long progress, long total) throws Exception; +} diff --git a/common/src/main/java/common/net/util/concurrent/GlobalEventExecutor.java b/common/src/main/java/common/net/util/concurrent/GlobalEventExecutor.java new file mode 100644 index 0000000..103143b --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/GlobalEventExecutor.java @@ -0,0 +1,391 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.Iterator; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicBoolean; + +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * Single-thread singleton {@link EventExecutor}. It starts the thread automatically and stops it when there is no + * task pending in the task queue for 1 second. Please note it is not scalable to schedule large number of tasks to + * this executor; use a dedicated executor. + */ +public final class GlobalEventExecutor extends AbstractEventExecutor { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(GlobalEventExecutor.class); + + private static final long SCHEDULE_PURGE_INTERVAL = TimeUnit.SECONDS.toNanos(1); + + public static final GlobalEventExecutor INSTANCE = new GlobalEventExecutor(); + + final BlockingQueue taskQueue = new LinkedBlockingQueue(); + final Queue> delayedTaskQueue = new PriorityQueue>(); + final ScheduledFutureTask purgeTask = new ScheduledFutureTask( + this, delayedTaskQueue, Executors.callable(new PurgeTask(), null), + ScheduledFutureTask.deadlineNanos(SCHEDULE_PURGE_INTERVAL), -SCHEDULE_PURGE_INTERVAL); + + private final ThreadFactory threadFactory = new DefaultThreadFactory(getClass()); + private final TaskRunner taskRunner = new TaskRunner(); + private final AtomicBoolean started = new AtomicBoolean(); + volatile Thread thread; + + private final Future terminationFuture = new FailedFuture(this, new UnsupportedOperationException()); + + private GlobalEventExecutor() { + delayedTaskQueue.add(purgeTask); + } + + @Override + public EventExecutorGroup parent() { + return null; + } + + /** + * Take the next {@link Runnable} from the task queue and so will block if no task is currently present. + * + * @return {@code null} if the executor thread has been interrupted or waken up. + */ + Runnable takeTask() { + BlockingQueue taskQueue = this.taskQueue; + for (;;) { + ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); + if (delayedTask == null) { + Runnable task = null; + try { + task = taskQueue.take(); + } catch (InterruptedException e) { + // Ignore + } + return task; + } else { + long delayNanos = delayedTask.delayNanos(); + Runnable task; + if (delayNanos > 0) { + try { + task = taskQueue.poll(delayNanos, TimeUnit.NANOSECONDS); + } catch (InterruptedException e) { + return null; + } + } else { + task = taskQueue.poll(); + } + + if (task == null) { + fetchFromDelayedQueue(); + task = taskQueue.poll(); + } + + if (task != null) { + return task; + } + } + } + } + + private void fetchFromDelayedQueue() { + long nanoTime = 0L; + for (;;) { + ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); + if (delayedTask == null) { + break; + } + + if (nanoTime == 0L) { + nanoTime = ScheduledFutureTask.nanoTime(); + } + + if (delayedTask.deadlineNanos() <= nanoTime) { + delayedTaskQueue.remove(); + taskQueue.add(delayedTask); + } else { + break; + } + } + } + + /** + * Return the number of tasks that are pending for processing. + * + * Be aware that this operation may be expensive as it depends on the internal implementation of the + * SingleThreadEventExecutor. So use it was care! + */ + public int pendingTasks() { + return taskQueue.size(); + } + + /** + * Add a task to the task queue, or throws a {@link RejectedExecutionException} if this instance was shutdown + * before. + */ + private void addTask(Runnable task) { + if (task == null) { + throw new NullPointerException("task"); + } + taskQueue.add(task); + } + + @Override + public boolean inEventLoop(Thread thread) { + return thread == this.thread; + } + + @Override + public Future shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { + return terminationFuture(); + } + + @Override + public Future terminationFuture() { + return terminationFuture; + } + + @Override + @Deprecated + public void shutdown() { + throw new UnsupportedOperationException(); + } + + @Override + public boolean isShuttingDown() { + return false; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return false; + } + + /** + * Waits until the worker thread of this executor has no tasks left in its task queue and terminates itself. + * Because a new worker thread will be started again when a new task is submitted, this operation is only useful + * when you want to ensure that the worker thread is terminated after your application is shut + * down and there's no chance of submitting a new task afterwards. + * + * @return {@code true} if and only if the worker thread has been terminated + */ + public boolean awaitInactivity(long timeout, TimeUnit unit) throws InterruptedException { + if (unit == null) { + throw new NullPointerException("unit"); + } + + final Thread thread = this.thread; + if (thread == null) { + throw new IllegalStateException("thread was not started"); + } + thread.join(unit.toMillis(timeout)); + return !thread.isAlive(); + } + + @Override + public void execute(Runnable task) { + if (task == null) { + throw new NullPointerException("task"); + } + + addTask(task); + if (!inEventLoop()) { + startThread(); + } + } + + // ScheduledExecutorService implementation + + @Override + public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { + if (command == null) { + throw new NullPointerException("command"); + } + if (unit == null) { + throw new NullPointerException("unit"); + } + if (delay < 0) { + throw new IllegalArgumentException( + String.format("delay: %d (expected: >= 0)", delay)); + } + return schedule(new ScheduledFutureTask( + this, delayedTaskQueue, command, null, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay)))); + } + + @Override + public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { + if (callable == null) { + throw new NullPointerException("callable"); + } + if (unit == null) { + throw new NullPointerException("unit"); + } + if (delay < 0) { + throw new IllegalArgumentException( + String.format("delay: %d (expected: >= 0)", delay)); + } + return schedule(new ScheduledFutureTask( + this, delayedTaskQueue, callable, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay)))); + } + + @Override + public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { + if (command == null) { + throw new NullPointerException("command"); + } + if (unit == null) { + throw new NullPointerException("unit"); + } + if (initialDelay < 0) { + throw new IllegalArgumentException( + String.format("initialDelay: %d (expected: >= 0)", initialDelay)); + } + if (period <= 0) { + throw new IllegalArgumentException( + String.format("period: %d (expected: > 0)", period)); + } + + return schedule(new ScheduledFutureTask( + this, delayedTaskQueue, Executors.callable(command, null), + ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), unit.toNanos(period))); + } + + @Override + public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { + if (command == null) { + throw new NullPointerException("command"); + } + if (unit == null) { + throw new NullPointerException("unit"); + } + if (initialDelay < 0) { + throw new IllegalArgumentException( + String.format("initialDelay: %d (expected: >= 0)", initialDelay)); + } + if (delay <= 0) { + throw new IllegalArgumentException( + String.format("delay: %d (expected: > 0)", delay)); + } + + return schedule(new ScheduledFutureTask( + this, delayedTaskQueue, Executors.callable(command, null), + ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), -unit.toNanos(delay))); + } + + private ScheduledFuture schedule(final ScheduledFutureTask task) { + if (task == null) { + throw new NullPointerException("task"); + } + + if (inEventLoop()) { + delayedTaskQueue.add(task); + } else { + execute(new Runnable() { + @Override + public void run() { + delayedTaskQueue.add(task); + } + }); + } + + return task; + } + + private void startThread() { + if (started.compareAndSet(false, true)) { + Thread t = threadFactory.newThread(taskRunner); + t.start(); + thread = t; + } + } + + final class TaskRunner implements Runnable { + @Override + public void run() { + for (;;) { + Runnable task = takeTask(); + if (task != null) { + try { + task.run(); + } catch (Throwable t) { + logger.warn("Unexpected exception from the global event executor: ", t); + } + + if (task != purgeTask) { + continue; + } + } + + // Terminate if there is no task in the queue (except the purge task). + if (taskQueue.isEmpty() && delayedTaskQueue.size() == 1) { + // Mark the current thread as stopped. + // The following CAS must always success and must be uncontended, + // because only one thread should be running at the same time. + boolean stopped = started.compareAndSet(true, false); + assert stopped; + + // Check if there are pending entries added by execute() or schedule*() while we do CAS above. + if (taskQueue.isEmpty() && delayedTaskQueue.size() == 1) { + // A) No new task was added and thus there's nothing to handle + // -> safe to terminate because there's nothing left to do + // B) A new thread started and handled all the new tasks. + // -> safe to terminate the new thread will take care the rest + break; + } + + // There are pending tasks added again. + if (!started.compareAndSet(false, true)) { + // startThread() started a new thread and set 'started' to true. + // -> terminate this thread so that the new thread reads from taskQueue exclusively. + break; + } + + // New tasks were added, but this worker was faster to set 'started' to true. + // i.e. a new worker thread was not started by startThread(). + // -> keep this thread alive to handle the newly added entries. + } + } + } + } + + private final class PurgeTask implements Runnable { + @Override + public void run() { + Iterator> i = delayedTaskQueue.iterator(); + while (i.hasNext()) { + ScheduledFutureTask task = i.next(); + if (task.isCancelled()) { + i.remove(); + } + } + } + } +} diff --git a/common/src/main/java/common/net/util/concurrent/ImmediateEventExecutor.java b/common/src/main/java/common/net/util/concurrent/ImmediateEventExecutor.java new file mode 100644 index 0000000..6b8fddb --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/ImmediateEventExecutor.java @@ -0,0 +1,121 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.concurrent.TimeUnit; + +/** + * {@link AbstractEventExecutor} which execute tasks in the callers thread. + */ +public final class ImmediateEventExecutor extends AbstractEventExecutor { + public static final ImmediateEventExecutor INSTANCE = new ImmediateEventExecutor(); + + private final Future terminationFuture = new FailedFuture( + GlobalEventExecutor.INSTANCE, new UnsupportedOperationException()); + + private ImmediateEventExecutor() { + // use static instance + } + + @Override + public EventExecutorGroup parent() { + return null; + } + + @Override + public boolean inEventLoop() { + return true; + } + + @Override + public boolean inEventLoop(Thread thread) { + return true; + } + + @Override + public Future shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { + return terminationFuture(); + } + + @Override + public Future terminationFuture() { + return terminationFuture; + } + + @Override + @Deprecated + public void shutdown() { } + + @Override + public boolean isShuttingDown() { + return false; + } + + @Override + public boolean isShutdown() { + return false; + } + + @Override + public boolean isTerminated() { + return false; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) { + return false; + } + + @Override + public void execute(Runnable command) { + if (command == null) { + throw new NullPointerException("command"); + } + command.run(); + } + + @Override + public Promise newPromise() { + return new ImmediatePromise(this); + } + + @Override + public ProgressivePromise newProgressivePromise() { + return new ImmediateProgressivePromise(this); + } + + static class ImmediatePromise extends DefaultPromise { + ImmediatePromise(EventExecutor executor) { + super(executor); + } + + @Override + protected void checkDeadLock() { + // No check + } + } + + static class ImmediateProgressivePromise extends DefaultProgressivePromise { + ImmediateProgressivePromise(EventExecutor executor) { + super(executor); + } + + @Override + protected void checkDeadLock() { + // No check + } + } +} diff --git a/common/src/main/java/common/net/util/concurrent/ImmediateExecutor.java b/common/src/main/java/common/net/util/concurrent/ImmediateExecutor.java new file mode 100644 index 0000000..6660c6d --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/ImmediateExecutor.java @@ -0,0 +1,37 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.concurrent.Executor; + +/** + * {@link Executor} which execute tasks in the callers thread. + */ +public final class ImmediateExecutor implements Executor { + public static final ImmediateExecutor INSTANCE = new ImmediateExecutor(); + + private ImmediateExecutor() { + // use static instance + } + + @Override + public void execute(Runnable command) { + if (command == null) { + throw new NullPointerException("command"); + } + command.run(); + } +} diff --git a/common/src/main/java/common/net/util/concurrent/MultithreadEventExecutorGroup.java b/common/src/main/java/common/net/util/concurrent/MultithreadEventExecutorGroup.java new file mode 100644 index 0000000..39a72c3 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/MultithreadEventExecutorGroup.java @@ -0,0 +1,233 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.Set; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Abstract base class for {@link EventExecutorGroup} implementations that handles their tasks with multiple threads at + * the same time. + */ +public abstract class MultithreadEventExecutorGroup extends AbstractEventExecutorGroup { + + private final EventExecutor[] children; + private final AtomicInteger childIndex = new AtomicInteger(); + private final AtomicInteger terminatedChildren = new AtomicInteger(); + private final Promise terminationFuture = new DefaultPromise(GlobalEventExecutor.INSTANCE); + private final EventExecutorChooser chooser; + + /** + * Create a new instance. + * + * @param nThreads the number of threads that will be used by this instance. + * @param threadFactory the ThreadFactory to use, or {@code null} if the default should be used. + * @param args arguments which will passed to each {@link #newChild(ThreadFactory, Object...)} call + */ + protected MultithreadEventExecutorGroup(int nThreads, ThreadFactory threadFactory, Object... args) { + if (nThreads <= 0) { + throw new IllegalArgumentException(String.format("nThreads: %d (expected: > 0)", nThreads)); + } + + if (threadFactory == null) { + threadFactory = newDefaultThreadFactory(); + } + + children = new SingleThreadEventExecutor[nThreads]; + if (isPowerOfTwo(children.length)) { + chooser = new PowerOfTwoEventExecutorChooser(); + } else { + chooser = new GenericEventExecutorChooser(); + } + + for (int i = 0; i < nThreads; i ++) { + boolean success = false; + try { + children[i] = newChild(threadFactory, args); + success = true; + } catch (Exception e) { + // TODO: Think about if this is a good exception type + throw new IllegalStateException("failed to create a child event loop", e); + } finally { + if (!success) { + for (int j = 0; j < i; j ++) { + children[j].shutdownGracefully(); + } + + for (int j = 0; j < i; j ++) { + EventExecutor e = children[j]; + try { + while (!e.isTerminated()) { + e.awaitTermination(Integer.MAX_VALUE, TimeUnit.SECONDS); + } + } catch (InterruptedException interrupted) { + Thread.currentThread().interrupt(); + break; + } + } + } + } + } + + final FutureListener terminationListener = new FutureListener() { + @Override + public void operationComplete(Future future) throws Exception { + if (terminatedChildren.incrementAndGet() == children.length) { + terminationFuture.setSuccess(null); + } + } + }; + + for (EventExecutor e: children) { + e.terminationFuture().addListener(terminationListener); + } + } + + protected ThreadFactory newDefaultThreadFactory() { + return new DefaultThreadFactory(getClass()); + } + + @Override + public EventExecutor next() { + return chooser.next(); + } + + @Override + public Iterator iterator() { + return children().iterator(); + } + + /** + * Return the number of {@link EventExecutor} this implementation uses. This number is the maps + * 1:1 to the threads it use. + */ + public final int executorCount() { + return children.length; + } + + /** + * Return a safe-copy of all of the children of this group. + */ + protected Set children() { + Set children = Collections.newSetFromMap(new LinkedHashMap()); + Collections.addAll(children, this.children); + return children; + } + + /** + * Create a new EventExecutor which will later then accessible via the {@link #next()} method. This method will be + * called for each thread that will serve this {@link MultithreadEventExecutorGroup}. + * + */ + protected abstract EventExecutor newChild( + ThreadFactory threadFactory, Object... args) throws Exception; + + @Override + public Future shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { + for (EventExecutor l: children) { + l.shutdownGracefully(quietPeriod, timeout, unit); + } + return terminationFuture(); + } + + @Override + public Future terminationFuture() { + return terminationFuture; + } + + @Override + @Deprecated + public void shutdown() { + for (EventExecutor l: children) { + l.shutdown(); + } + } + + @Override + public boolean isShuttingDown() { + for (EventExecutor l: children) { + if (!l.isShuttingDown()) { + return false; + } + } + return true; + } + + @Override + public boolean isShutdown() { + for (EventExecutor l: children) { + if (!l.isShutdown()) { + return false; + } + } + return true; + } + + @Override + public boolean isTerminated() { + for (EventExecutor l: children) { + if (!l.isTerminated()) { + return false; + } + } + return true; + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) + throws InterruptedException { + long deadline = System.nanoTime() + unit.toNanos(timeout); + loop: for (EventExecutor l: children) { + for (;;) { + long timeLeft = deadline - System.nanoTime(); + if (timeLeft <= 0) { + break loop; + } + if (l.awaitTermination(timeLeft, TimeUnit.NANOSECONDS)) { + break; + } + } + } + return isTerminated(); + } + + private static boolean isPowerOfTwo(int val) { + return (val & -val) == val; + } + + private interface EventExecutorChooser { + EventExecutor next(); + } + + private final class PowerOfTwoEventExecutorChooser implements EventExecutorChooser { + @Override + public EventExecutor next() { + return children[childIndex.getAndIncrement() & children.length - 1]; + } + } + + private final class GenericEventExecutorChooser implements EventExecutorChooser { + @Override + public EventExecutor next() { + return children[Math.abs(childIndex.getAndIncrement() % children.length)]; + } + } +} diff --git a/common/src/main/java/common/net/util/concurrent/ProgressiveFuture.java b/common/src/main/java/common/net/util/concurrent/ProgressiveFuture.java new file mode 100644 index 0000000..71c7134 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/ProgressiveFuture.java @@ -0,0 +1,47 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.concurrent; + +/** + * A {@link Future} which is used to indicate the progress of an operation. + */ +public interface ProgressiveFuture extends Future { + + @Override + ProgressiveFuture addListener(GenericFutureListener> listener); + + @Override + ProgressiveFuture addListeners(GenericFutureListener>... listeners); + + @Override + ProgressiveFuture removeListener(GenericFutureListener> listener); + + @Override + ProgressiveFuture removeListeners(GenericFutureListener>... listeners); + + @Override + ProgressiveFuture sync() throws InterruptedException; + + @Override + ProgressiveFuture syncUninterruptibly(); + + @Override + ProgressiveFuture await() throws InterruptedException; + + @Override + ProgressiveFuture awaitUninterruptibly(); +} diff --git a/common/src/main/java/common/net/util/concurrent/ProgressivePromise.java b/common/src/main/java/common/net/util/concurrent/ProgressivePromise.java new file mode 100644 index 0000000..e6a2e35 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/ProgressivePromise.java @@ -0,0 +1,65 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +/** + * Special {@link ProgressiveFuture} which is writable. + */ +public interface ProgressivePromise extends Promise, ProgressiveFuture { + + /** + * Sets the current progress of the operation and notifies the listeners that implement + * {@link GenericProgressiveFutureListener}. + */ + ProgressivePromise setProgress(long progress, long total); + + /** + * Tries to set the current progress of the operation and notifies the listeners that implement + * {@link GenericProgressiveFutureListener}. If the operation is already complete or the progress is out of range, + * this method does nothing but returning {@code false}. + */ + boolean tryProgress(long progress, long total); + + @Override + ProgressivePromise setSuccess(V result); + + @Override + ProgressivePromise setFailure(Throwable cause); + + @Override + ProgressivePromise addListener(GenericFutureListener> listener); + + @Override + ProgressivePromise addListeners(GenericFutureListener>... listeners); + + @Override + ProgressivePromise removeListener(GenericFutureListener> listener); + + @Override + ProgressivePromise removeListeners(GenericFutureListener>... listeners); + + @Override + ProgressivePromise await() throws InterruptedException; + + @Override + ProgressivePromise awaitUninterruptibly(); + + @Override + ProgressivePromise sync() throws InterruptedException; + + @Override + ProgressivePromise syncUninterruptibly(); +} diff --git a/common/src/main/java/common/net/util/concurrent/Promise.java b/common/src/main/java/common/net/util/concurrent/Promise.java new file mode 100644 index 0000000..252d895 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/Promise.java @@ -0,0 +1,90 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +/** + * Special {@link Future} which is writable. + */ +public interface Promise extends Future { + + /** + * Marks this future as a success and notifies all + * listeners. + * + * If it is success or failed already it will throw an {@link IllegalStateException}. + */ + Promise setSuccess(V result); + + /** + * Marks this future as a success and notifies all + * listeners. + * + * @return {@code true} if and only if successfully marked this future as + * a success. Otherwise {@code false} because this future is + * already marked as either a success or a failure. + */ + boolean trySuccess(V result); + + /** + * Marks this future as a failure and notifies all + * listeners. + * + * If it is success or failed already it will throw an {@link IllegalStateException}. + */ + Promise setFailure(Throwable cause); + + /** + * Marks this future as a failure and notifies all + * listeners. + * + * @return {@code true} if and only if successfully marked this future as + * a failure. Otherwise {@code false} because this future is + * already marked as either a success or a failure. + */ + boolean tryFailure(Throwable cause); + + /** + * Make this future impossible to cancel. + * + * @return {@code true} if and only if successfully marked this future as uncancellable or it is already done + * without being cancelled. {@code false} if this future has been cancelled already. + */ + boolean setUncancellable(); + + @Override + Promise addListener(GenericFutureListener> listener); + + @Override + Promise addListeners(GenericFutureListener>... listeners); + + @Override + Promise removeListener(GenericFutureListener> listener); + + @Override + Promise removeListeners(GenericFutureListener>... listeners); + + @Override + Promise await() throws InterruptedException; + + @Override + Promise awaitUninterruptibly(); + + @Override + Promise sync() throws InterruptedException; + + @Override + Promise syncUninterruptibly(); +} diff --git a/common/src/main/java/common/net/util/concurrent/PromiseTask.java b/common/src/main/java/common/net/util/concurrent/PromiseTask.java new file mode 100644 index 0000000..8a897ad --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/PromiseTask.java @@ -0,0 +1,137 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.concurrent.Callable; +import java.util.concurrent.RunnableFuture; + +class PromiseTask extends DefaultPromise implements RunnableFuture { + + static Callable toCallable(Runnable runnable, T result) { + return new RunnableAdapter(runnable, result); + } + + private static final class RunnableAdapter implements Callable { + final Runnable task; + final T result; + + RunnableAdapter(Runnable task, T result) { + this.task = task; + this.result = result; + } + + @Override + public T call() { + task.run(); + return result; + } + + @Override + public String toString() { + return "Callable(task: " + task + ", result: " + result + ')'; + } + } + + protected final Callable task; + + PromiseTask(EventExecutor executor, Runnable runnable, V result) { + this(executor, toCallable(runnable, result)); + } + + PromiseTask(EventExecutor executor, Callable callable) { + super(executor); + task = callable; + } + + @Override + public final int hashCode() { + return System.identityHashCode(this); + } + + @Override + public final boolean equals(Object obj) { + return this == obj; + } + + @Override + public void run() { + try { + if (setUncancellableInternal()) { + V result = task.call(); + setSuccessInternal(result); + } + } catch (Throwable e) { + setFailureInternal(e); + } + } + + @Override + public final Promise setFailure(Throwable cause) { + throw new IllegalStateException(); + } + + protected final Promise setFailureInternal(Throwable cause) { + super.setFailure(cause); + return this; + } + + @Override + public final boolean tryFailure(Throwable cause) { + return false; + } + + protected final boolean tryFailureInternal(Throwable cause) { + return super.tryFailure(cause); + } + + @Override + public final Promise setSuccess(V result) { + throw new IllegalStateException(); + } + + protected final Promise setSuccessInternal(V result) { + super.setSuccess(result); + return this; + } + + @Override + public final boolean trySuccess(V result) { + return false; + } + + protected final boolean trySuccessInternal(V result) { + return super.trySuccess(result); + } + + @Override + public final boolean setUncancellable() { + throw new IllegalStateException(); + } + + protected final boolean setUncancellableInternal() { + return super.setUncancellable(); + } + + @Override + protected StringBuilder toStringBuilder() { + StringBuilder buf = super.toStringBuilder(); + buf.setCharAt(buf.length() - 1, ','); + buf.append(" task: "); + buf.append(task); + buf.append(')'); + return buf; + } +} diff --git a/common/src/main/java/common/net/util/concurrent/ScheduledFuture.java b/common/src/main/java/common/net/util/concurrent/ScheduledFuture.java new file mode 100644 index 0000000..3498b13 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/ScheduledFuture.java @@ -0,0 +1,23 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +/** + * The result of an scheduled asynchronous operation. + */ + +public interface ScheduledFuture extends Future, java.util.concurrent.ScheduledFuture { +} diff --git a/common/src/main/java/common/net/util/concurrent/ScheduledFutureTask.java b/common/src/main/java/common/net/util/concurrent/ScheduledFutureTask.java new file mode 100644 index 0000000..83f64b3 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/ScheduledFutureTask.java @@ -0,0 +1,161 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.concurrent; + +import java.util.Queue; +import java.util.concurrent.Callable; +import java.util.concurrent.Delayed; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; + + +final class ScheduledFutureTask extends PromiseTask implements ScheduledFuture { + private static final AtomicLong nextTaskId = new AtomicLong(); + private static final long START_TIME = System.nanoTime(); + + static long nanoTime() { + return System.nanoTime() - START_TIME; + } + + static long deadlineNanos(long delay) { + return nanoTime() + delay; + } + + private final long id = nextTaskId.getAndIncrement(); + private final Queue> delayedTaskQueue; + private long deadlineNanos; + /* 0 - no repeat, >0 - repeat at fixed rate, <0 - repeat with fixed delay */ + private final long periodNanos; + + ScheduledFutureTask( + EventExecutor executor, Queue> delayedTaskQueue, + Runnable runnable, V result, long nanoTime) { + + this(executor, delayedTaskQueue, toCallable(runnable, result), nanoTime); + } + + ScheduledFutureTask( + EventExecutor executor, Queue> delayedTaskQueue, + Callable callable, long nanoTime, long period) { + + super(executor, callable); + if (period == 0) { + throw new IllegalArgumentException("period: 0 (expected: != 0)"); + } + this.delayedTaskQueue = delayedTaskQueue; + deadlineNanos = nanoTime; + periodNanos = period; + } + + ScheduledFutureTask( + EventExecutor executor, Queue> delayedTaskQueue, + Callable callable, long nanoTime) { + + super(executor, callable); + this.delayedTaskQueue = delayedTaskQueue; + deadlineNanos = nanoTime; + periodNanos = 0; + } + + @Override + protected EventExecutor executor() { + return super.executor(); + } + + public long deadlineNanos() { + return deadlineNanos; + } + + public long delayNanos() { + return Math.max(0, deadlineNanos() - nanoTime()); + } + + public long delayNanos(long currentTimeNanos) { + return Math.max(0, deadlineNanos() - (currentTimeNanos - START_TIME)); + } + + @Override + public long getDelay(TimeUnit unit) { + return unit.convert(delayNanos(), TimeUnit.NANOSECONDS); + } + + @Override + public int compareTo(Delayed o) { + if (this == o) { + return 0; + } + + ScheduledFutureTask that = (ScheduledFutureTask) o; + long d = deadlineNanos() - that.deadlineNanos(); + if (d < 0) { + return -1; + } else if (d > 0) { + return 1; + } else if (id < that.id) { + return -1; + } else if (id == that.id) { + throw new Error(); + } else { + return 1; + } + } + + @Override + public void run() { + assert executor().inEventLoop(); + try { + if (periodNanos == 0) { + if (setUncancellableInternal()) { + V result = task.call(); + setSuccessInternal(result); + } + } else { + // check if is done as it may was cancelled + if (!isCancelled()) { + task.call(); + if (!executor().isShutdown()) { + long p = periodNanos; + if (p > 0) { + deadlineNanos += p; + } else { + deadlineNanos = nanoTime() - p; + } + if (!isCancelled()) { + delayedTaskQueue.add(this); + } + } + } + } + } catch (Throwable cause) { + setFailureInternal(cause); + } + } + + @Override + protected StringBuilder toStringBuilder() { + StringBuilder buf = super.toStringBuilder(); + buf.setCharAt(buf.length() - 1, ','); + buf.append(" id: "); + buf.append(id); + buf.append(", deadline: "); + buf.append(deadlineNanos); + buf.append(", period: "); + buf.append(periodNanos); + buf.append(')'); + return buf; + } +} diff --git a/common/src/main/java/common/net/util/concurrent/SingleThreadEventExecutor.java b/common/src/main/java/common/net/util/concurrent/SingleThreadEventExecutor.java new file mode 100644 index 0000000..044f794 --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/SingleThreadEventExecutor.java @@ -0,0 +1,869 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.PriorityQueue; +import java.util.Queue; +import java.util.Set; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.Callable; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.RejectedExecutionException; +import java.util.concurrent.Semaphore; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; + +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * Abstract base class for {@link EventExecutor}'s that execute all its submitted tasks in a single thread. + * + */ +public abstract class SingleThreadEventExecutor extends AbstractEventExecutor { + + private static final InternalLogger logger = + InternalLoggerFactory.getInstance(SingleThreadEventExecutor.class); + + private static final int ST_NOT_STARTED = 1; + private static final int ST_STARTED = 2; + private static final int ST_SHUTTING_DOWN = 3; + private static final int ST_SHUTDOWN = 4; + private static final int ST_TERMINATED = 5; + + private static final Runnable WAKEUP_TASK = new Runnable() { + @Override + public void run() { + // Do nothing. + } + }; + + private static final AtomicIntegerFieldUpdater STATE_UPDATER; + + static { + AtomicIntegerFieldUpdater updater = + null; + if (updater == null) { + updater = AtomicIntegerFieldUpdater.newUpdater(SingleThreadEventExecutor.class, "state"); + } + STATE_UPDATER = updater; + } + + private final EventExecutorGroup parent; + private final Queue taskQueue; + final Queue> delayedTaskQueue = new PriorityQueue>(); + + private final Thread thread; + private final Semaphore threadLock = new Semaphore(0); + private final Set shutdownHooks = new LinkedHashSet(); + private final boolean addTaskWakesUp; + + private long lastExecutionTime; + + + private volatile int state = ST_NOT_STARTED; + + private volatile long gracefulShutdownQuietPeriod; + private volatile long gracefulShutdownTimeout; + private long gracefulShutdownStartTime; + + private final Promise terminationFuture = new DefaultPromise(GlobalEventExecutor.INSTANCE); + + /** + * Create a new instance + * + * @param parent the {@link EventExecutorGroup} which is the parent of this instance and belongs to it + * @param threadFactory the {@link ThreadFactory} which will be used for the used {@link Thread} + * @param addTaskWakesUp {@code true} if and only if invocation of {@link #addTask(Runnable)} will wake up the + * executor thread + */ + protected SingleThreadEventExecutor( + EventExecutorGroup parent, ThreadFactory threadFactory, boolean addTaskWakesUp) { + + if (threadFactory == null) { + throw new NullPointerException("threadFactory"); + } + + this.parent = parent; + this.addTaskWakesUp = addTaskWakesUp; + + thread = threadFactory.newThread(new Runnable() { + @Override + public void run() { + boolean success = false; + updateLastExecutionTime(); + try { + SingleThreadEventExecutor.this.run(); + success = true; + } catch (Throwable t) { + logger.warn("Unexpected exception from an event executor: ", t); + } finally { + for (;;) { + int oldState = STATE_UPDATER.get(SingleThreadEventExecutor.this); + if (oldState >= ST_SHUTTING_DOWN || STATE_UPDATER.compareAndSet( + SingleThreadEventExecutor.this, oldState, ST_SHUTTING_DOWN)) { + break; + } + } + // Check if confirmShutdown() was called at the end of the loop. + if (success && gracefulShutdownStartTime == 0) { + logger.error( + "Buggy " + EventExecutor.class.getSimpleName() + " implementation; " + + SingleThreadEventExecutor.class.getSimpleName() + ".confirmShutdown() must be called " + + "before run() implementation terminates."); + } + + try { + // Run all remaining tasks and shutdown hooks. + for (;;) { + if (confirmShutdown()) { + break; + } + } + } finally { + try { + cleanup(); + } finally { + STATE_UPDATER.set(SingleThreadEventExecutor.this, ST_TERMINATED); + threadLock.release(); + if (!taskQueue.isEmpty()) { + logger.warn( + "An event executor terminated with " + + "non-empty task queue (" + taskQueue.size() + ')'); + } + + terminationFuture.setSuccess(null); + } + } + } + } + }); + + taskQueue = newTaskQueue(); + } + + /** + * Create a new {@link Queue} which will holds the tasks to execute. This default implementation will return a + * {@link LinkedBlockingQueue} but if your sub-class of {@link SingleThreadEventExecutor} will not do any blocking + * calls on the this {@link Queue} it may make sense to {@code @Override} this and return some more performant + * implementation that does not support blocking operations at all. + */ + protected Queue newTaskQueue() { + return new LinkedBlockingQueue(); + } + + @Override + public EventExecutorGroup parent() { + return parent; + } + + /** + * Interrupt the current running {@link Thread}. + */ + protected void interruptThread() { + thread.interrupt(); + } + + /** + * @see {@link Queue#poll()} + */ + protected Runnable pollTask() { + assert inEventLoop(); + for (;;) { + Runnable task = taskQueue.poll(); + if (task == WAKEUP_TASK) { + continue; + } + return task; + } + } + + /** + * Take the next {@link Runnable} from the task queue and so will block if no task is currently present. + *

+ * Be aware that this method will throw an {@link UnsupportedOperationException} if the task queue, which was + * created via {@link #newTaskQueue()}, does not implement {@link BlockingQueue}. + *

+ * + * @return {@code null} if the executor thread has been interrupted or waken up. + */ + protected Runnable takeTask() { + assert inEventLoop(); + if (!(taskQueue instanceof BlockingQueue)) { + throw new UnsupportedOperationException(); + } + + BlockingQueue taskQueue = (BlockingQueue) this.taskQueue; + for (;;) { + ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); + if (delayedTask == null) { + Runnable task = null; + try { + task = taskQueue.take(); + if (task == WAKEUP_TASK) { + task = null; + } + } catch (InterruptedException e) { + // Ignore + } + return task; + } else { + long delayNanos = delayedTask.delayNanos(); + Runnable task = null; + if (delayNanos > 0) { + try { + task = taskQueue.poll(delayNanos, TimeUnit.NANOSECONDS); + } catch (InterruptedException e) { + return null; + } + } + if (task == null) { + // We need to fetch the delayed tasks now as otherwise there may be a chance that + // delayed tasks are never executed if there is always one task in the taskQueue. + // This is for example true for the read task of OIO Transport + // See https://github.com/netty/netty/issues/1614 + fetchFromDelayedQueue(); + task = taskQueue.poll(); + } + + if (task != null) { + return task; + } + } + } + } + + private void fetchFromDelayedQueue() { + long nanoTime = 0L; + for (;;) { + ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); + if (delayedTask == null) { + break; + } + + if (nanoTime == 0L) { + nanoTime = ScheduledFutureTask.nanoTime(); + } + + if (delayedTask.deadlineNanos() <= nanoTime) { + delayedTaskQueue.remove(); + taskQueue.add(delayedTask); + } else { + break; + } + } + } + + /** + * @see {@link Queue#peek()} + */ + protected Runnable peekTask() { + assert inEventLoop(); + return taskQueue.peek(); + } + + /** + * @see {@link Queue#isEmpty()} + */ + protected boolean hasTasks() { + assert inEventLoop(); + return !taskQueue.isEmpty(); + } + + /** + * Returns {@code true} if a scheduled task is ready for processing by {@link #runAllTasks()} or + * {@link #runAllTasks(long)}. + */ + protected boolean hasScheduledTasks() { + assert inEventLoop(); + ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); + return delayedTask != null && delayedTask.deadlineNanos() <= ScheduledFutureTask.nanoTime(); + } + + /** + * Return the number of tasks that are pending for processing. + * + * Be aware that this operation may be expensive as it depends on the internal implementation of the + * SingleThreadEventExecutor. So use it was care! + */ + public final int pendingTasks() { + return taskQueue.size(); + } + + /** + * Add a task to the task queue, or throws a {@link RejectedExecutionException} if this instance was shutdown + * before. + */ + protected void addTask(Runnable task) { + if (task == null) { + throw new NullPointerException("task"); + } + if (isShutdown()) { + reject(); + } + taskQueue.add(task); + } + + /** + * @see {@link Queue#remove(Object)} + */ + protected boolean removeTask(Runnable task) { + if (task == null) { + throw new NullPointerException("task"); + } + return taskQueue.remove(task); + } + + /** + * Poll all tasks from the task queue and run them via {@link Runnable#run()} method. + * + * @return {@code true} if and only if at least one task was run + */ + protected boolean runAllTasks() { + fetchFromDelayedQueue(); + Runnable task = pollTask(); + if (task == null) { + return false; + } + + for (;;) { + try { + task.run(); + } catch (Throwable t) { + logger.warn("A task raised an exception.", t); + } + + task = pollTask(); + if (task == null) { + lastExecutionTime = ScheduledFutureTask.nanoTime(); + return true; + } + } + } + + /** + * Poll all tasks from the task queue and run them via {@link Runnable#run()} method. This method stops running + * the tasks in the task queue and returns if it ran longer than {@code timeoutNanos}. + */ + protected boolean runAllTasks(long timeoutNanos) { + fetchFromDelayedQueue(); + Runnable task = pollTask(); + if (task == null) { + return false; + } + + final long deadline = ScheduledFutureTask.nanoTime() + timeoutNanos; + long runTasks = 0; + long lastExecutionTime; + for (;;) { + try { + task.run(); + } catch (Throwable t) { + logger.warn("A task raised an exception.", t); + } + + runTasks ++; + + // Check timeout every 64 tasks because nanoTime() is relatively expensive. + // XXX: Hard-coded value - will make it configurable if it is really a problem. + if ((runTasks & 0x3F) == 0) { + lastExecutionTime = ScheduledFutureTask.nanoTime(); + if (lastExecutionTime >= deadline) { + break; + } + } + + task = pollTask(); + if (task == null) { + lastExecutionTime = ScheduledFutureTask.nanoTime(); + break; + } + } + + this.lastExecutionTime = lastExecutionTime; + return true; + } + + /** + * Returns the amount of time left until the scheduled task with the closest dead line is executed. + */ + protected long delayNanos(long currentTimeNanos) { + ScheduledFutureTask delayedTask = delayedTaskQueue.peek(); + if (delayedTask == null) { + return SCHEDULE_PURGE_INTERVAL; + } + + return delayedTask.delayNanos(currentTimeNanos); + } + + /** + * Updates the internal timestamp that tells when a submitted task was executed most recently. + * {@link #runAllTasks()} and {@link #runAllTasks(long)} updates this timestamp automatically, and thus there's + * usually no need to call this method. However, if you take the tasks manually using {@link #takeTask()} or + * {@link #pollTask()}, you have to call this method at the end of task execution loop for accurate quiet period + * checks. + */ + protected void updateLastExecutionTime() { + lastExecutionTime = ScheduledFutureTask.nanoTime(); + } + + /** + * + */ + protected abstract void run(); + + /** + * Do nothing, sub-classes may override + */ + protected void cleanup() { + // NOOP + } + + protected void wakeup(boolean inEventLoop) { + if (!inEventLoop || STATE_UPDATER.get(this) == ST_SHUTTING_DOWN) { + taskQueue.add(WAKEUP_TASK); + } + } + + @Override + public boolean inEventLoop(Thread thread) { + return thread == this.thread; + } + + /** + * Add a {@link Runnable} which will be executed on shutdown of this instance + */ + public void addShutdownHook(final Runnable task) { + if (inEventLoop()) { + shutdownHooks.add(task); + } else { + execute(new Runnable() { + @Override + public void run() { + shutdownHooks.add(task); + } + }); + } + } + + /** + * Remove a previous added {@link Runnable} as a shutdown hook + */ + public void removeShutdownHook(final Runnable task) { + if (inEventLoop()) { + shutdownHooks.remove(task); + } else { + execute(new Runnable() { + @Override + public void run() { + shutdownHooks.remove(task); + } + }); + } + } + + private boolean runShutdownHooks() { + boolean ran = false; + // Note shutdown hooks can add / remove shutdown hooks. + while (!shutdownHooks.isEmpty()) { + List copy = new ArrayList(shutdownHooks); + shutdownHooks.clear(); + for (Runnable task: copy) { + try { + task.run(); + } catch (Throwable t) { + logger.warn("Shutdown hook raised an exception.", t); + } finally { + ran = true; + } + } + } + + if (ran) { + lastExecutionTime = ScheduledFutureTask.nanoTime(); + } + + return ran; + } + + @Override + public Future shutdownGracefully(long quietPeriod, long timeout, TimeUnit unit) { + if (quietPeriod < 0) { + throw new IllegalArgumentException("quietPeriod: " + quietPeriod + " (expected >= 0)"); + } + if (timeout < quietPeriod) { + throw new IllegalArgumentException( + "timeout: " + timeout + " (expected >= quietPeriod (" + quietPeriod + "))"); + } + if (unit == null) { + throw new NullPointerException("unit"); + } + + if (isShuttingDown()) { + return terminationFuture(); + } + + boolean inEventLoop = inEventLoop(); + boolean wakeup; + int oldState; + for (;;) { + if (isShuttingDown()) { + return terminationFuture(); + } + int newState; + wakeup = true; + oldState = STATE_UPDATER.get(this); + if (inEventLoop) { + newState = ST_SHUTTING_DOWN; + } else { + switch (oldState) { + case ST_NOT_STARTED: + case ST_STARTED: + newState = ST_SHUTTING_DOWN; + break; + default: + newState = oldState; + wakeup = false; + } + } + if (STATE_UPDATER.compareAndSet(this, oldState, newState)) { + break; + } + } + gracefulShutdownQuietPeriod = unit.toNanos(quietPeriod); + gracefulShutdownTimeout = unit.toNanos(timeout); + + if (oldState == ST_NOT_STARTED) { + thread.start(); + } + + if (wakeup) { + wakeup(inEventLoop); + } + + return terminationFuture(); + } + + @Override + public Future terminationFuture() { + return terminationFuture; + } + + @Override + @Deprecated + public void shutdown() { + if (isShutdown()) { + return; + } + + boolean inEventLoop = inEventLoop(); + boolean wakeup; + int oldState; + for (;;) { + if (isShuttingDown()) { + return; + } + int newState; + wakeup = true; + oldState = STATE_UPDATER.get(this); + if (inEventLoop) { + newState = ST_SHUTDOWN; + } else { + switch (oldState) { + case ST_NOT_STARTED: + case ST_STARTED: + case ST_SHUTTING_DOWN: + newState = ST_SHUTDOWN; + break; + default: + newState = oldState; + wakeup = false; + } + } + if (STATE_UPDATER.compareAndSet(this, oldState, newState)) { + break; + } + } + + if (oldState == ST_NOT_STARTED) { + thread.start(); + } + + if (wakeup) { + wakeup(inEventLoop); + } + } + + @Override + public boolean isShuttingDown() { + return STATE_UPDATER.get(this) >= ST_SHUTTING_DOWN; + } + + @Override + public boolean isShutdown() { + return STATE_UPDATER.get(this) >= ST_SHUTDOWN; + } + + @Override + public boolean isTerminated() { + return STATE_UPDATER.get(this) == ST_TERMINATED; + } + + /** + * Confirm that the shutdown if the instance should be done now! + */ + protected boolean confirmShutdown() { + if (!isShuttingDown()) { + return false; + } + + if (!inEventLoop()) { + throw new IllegalStateException("must be invoked from an event loop"); + } + + cancelDelayedTasks(); + + if (gracefulShutdownStartTime == 0) { + gracefulShutdownStartTime = ScheduledFutureTask.nanoTime(); + } + + if (runAllTasks() || runShutdownHooks()) { + if (isShutdown()) { + // Executor shut down - no new tasks anymore. + return true; + } + + // There were tasks in the queue. Wait a little bit more until no tasks are queued for the quiet period. + wakeup(true); + return false; + } + + final long nanoTime = ScheduledFutureTask.nanoTime(); + + if (isShutdown() || nanoTime - gracefulShutdownStartTime > gracefulShutdownTimeout) { + return true; + } + + if (nanoTime - lastExecutionTime <= gracefulShutdownQuietPeriod) { + // Check if any tasks were added to the queue every 100ms. + // TODO: Change the behavior of takeTask() so that it returns on timeout. + wakeup(true); + try { + Thread.sleep(100); + } catch (InterruptedException e) { + // Ignore + } + + return false; + } + + // No tasks were added for last quiet period - hopefully safe to shut down. + // (Hopefully because we really cannot make a guarantee that there will be no execute() calls by a user.) + return true; + } + + private void cancelDelayedTasks() { + if (delayedTaskQueue.isEmpty()) { + return; + } + + final ScheduledFutureTask[] delayedTasks = + delayedTaskQueue.toArray(new ScheduledFutureTask[delayedTaskQueue.size()]); + + for (ScheduledFutureTask task: delayedTasks) { + task.cancel(false); + } + + delayedTaskQueue.clear(); + } + + @Override + public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { + if (unit == null) { + throw new NullPointerException("unit"); + } + + if (inEventLoop()) { + throw new IllegalStateException("cannot await termination of the current thread"); + } + + if (threadLock.tryAcquire(timeout, unit)) { + threadLock.release(); + } + + return isTerminated(); + } + + @Override + public void execute(Runnable task) { + if (task == null) { + throw new NullPointerException("task"); + } + + boolean inEventLoop = inEventLoop(); + if (inEventLoop) { + addTask(task); + } else { + startThread(); + addTask(task); + if (isShutdown() && removeTask(task)) { + reject(); + } + } + + if (!addTaskWakesUp && wakesUpForTask(task)) { + wakeup(inEventLoop); + } + } + + + protected boolean wakesUpForTask(Runnable task) { + return true; + } + + protected static void reject() { + throw new RejectedExecutionException("event executor terminated"); + } + + // ScheduledExecutorService implementation + + private static final long SCHEDULE_PURGE_INTERVAL = TimeUnit.SECONDS.toNanos(1); + + @Override + public ScheduledFuture schedule(Runnable command, long delay, TimeUnit unit) { + if (command == null) { + throw new NullPointerException("command"); + } + if (unit == null) { + throw new NullPointerException("unit"); + } + if (delay < 0) { + throw new IllegalArgumentException( + String.format("delay: %d (expected: >= 0)", delay)); + } + return schedule(new ScheduledFutureTask( + this, delayedTaskQueue, command, null, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay)))); + } + + @Override + public ScheduledFuture schedule(Callable callable, long delay, TimeUnit unit) { + if (callable == null) { + throw new NullPointerException("callable"); + } + if (unit == null) { + throw new NullPointerException("unit"); + } + if (delay < 0) { + throw new IllegalArgumentException( + String.format("delay: %d (expected: >= 0)", delay)); + } + return schedule(new ScheduledFutureTask( + this, delayedTaskQueue, callable, ScheduledFutureTask.deadlineNanos(unit.toNanos(delay)))); + } + + @Override + public ScheduledFuture scheduleAtFixedRate(Runnable command, long initialDelay, long period, TimeUnit unit) { + if (command == null) { + throw new NullPointerException("command"); + } + if (unit == null) { + throw new NullPointerException("unit"); + } + if (initialDelay < 0) { + throw new IllegalArgumentException( + String.format("initialDelay: %d (expected: >= 0)", initialDelay)); + } + if (period <= 0) { + throw new IllegalArgumentException( + String.format("period: %d (expected: > 0)", period)); + } + + return schedule(new ScheduledFutureTask( + this, delayedTaskQueue, Executors.callable(command, null), + ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), unit.toNanos(period))); + } + + @Override + public ScheduledFuture scheduleWithFixedDelay(Runnable command, long initialDelay, long delay, TimeUnit unit) { + if (command == null) { + throw new NullPointerException("command"); + } + if (unit == null) { + throw new NullPointerException("unit"); + } + if (initialDelay < 0) { + throw new IllegalArgumentException( + String.format("initialDelay: %d (expected: >= 0)", initialDelay)); + } + if (delay <= 0) { + throw new IllegalArgumentException( + String.format("delay: %d (expected: > 0)", delay)); + } + + return schedule(new ScheduledFutureTask( + this, delayedTaskQueue, Executors.callable(command, null), + ScheduledFutureTask.deadlineNanos(unit.toNanos(initialDelay)), -unit.toNanos(delay))); + } + + private ScheduledFuture schedule(final ScheduledFutureTask task) { + if (task == null) { + throw new NullPointerException("task"); + } + + if (inEventLoop()) { + delayedTaskQueue.add(task); + } else { + execute(new Runnable() { + @Override + public void run() { + delayedTaskQueue.add(task); + } + }); + } + + return task; + } + + private void startThread() { + if (STATE_UPDATER.get(this) == ST_NOT_STARTED) { + if (STATE_UPDATER.compareAndSet(this, ST_NOT_STARTED, ST_STARTED)) { + delayedTaskQueue.add(new ScheduledFutureTask( + this, delayedTaskQueue, Executors.callable(new PurgeTask(), null), + ScheduledFutureTask.deadlineNanos(SCHEDULE_PURGE_INTERVAL), -SCHEDULE_PURGE_INTERVAL)); + thread.start(); + } + } + } + + private final class PurgeTask implements Runnable { + @Override + public void run() { + Iterator> i = delayedTaskQueue.iterator(); + while (i.hasNext()) { + ScheduledFutureTask task = i.next(); + if (task.isCancelled()) { + i.remove(); + } + } + } + } +} diff --git a/common/src/main/java/common/net/util/concurrent/SucceededFuture.java b/common/src/main/java/common/net/util/concurrent/SucceededFuture.java new file mode 100644 index 0000000..ddcd86f --- /dev/null +++ b/common/src/main/java/common/net/util/concurrent/SucceededFuture.java @@ -0,0 +1,50 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.concurrent; + +/** + * The {@link CompleteFuture} which is succeeded already. It is + * recommended to use {@link EventExecutor#newSucceededFuture(Object)} instead of + * calling the constructor of this future. + */ +public final class SucceededFuture extends CompleteFuture { + private final V result; + + /** + * Creates a new instance. + * + * @param executor the {@link EventExecutor} associated with this future + */ + public SucceededFuture(EventExecutor executor, V result) { + super(executor); + this.result = result; + } + + @Override + public Throwable cause() { + return null; + } + + @Override + public boolean isSuccess() { + return true; + } + + @Override + public V getNow() { + return result; + } +} diff --git a/common/src/main/java/common/net/util/internal/EmptyArrays.java b/common/src/main/java/common/net/util/internal/EmptyArrays.java new file mode 100644 index 0000000..e5fac07 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/EmptyArrays.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +import java.nio.ByteBuffer; +import java.security.cert.X509Certificate; + +public final class EmptyArrays { + + public static final byte[] EMPTY_BYTES = new byte[0]; + public static final boolean[] EMPTY_BOOLEANS = new boolean[0]; + public static final double[] EMPTY_DOUBLES = new double[0]; + public static final float[] EMPTY_FLOATS = new float[0]; + public static final int[] EMPTY_INTS = new int[0]; + public static final short[] EMPTY_SHORTS = new short[0]; + public static final long[] EMPTY_LONGS = new long[0]; + public static final Object[] EMPTY_OBJECTS = new Object[0]; + public static final Class[] EMPTY_CLASSES = new Class[0]; + public static final String[] EMPTY_STRINGS = new String[0]; + public static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0]; + public static final ByteBuffer[] EMPTY_BYTE_BUFFERS = new ByteBuffer[0]; + public static final X509Certificate[] EMPTY_X509_CERTIFICATES = new X509Certificate[0]; + + private EmptyArrays() { } +} diff --git a/common/src/main/java/common/net/util/internal/IntegerHolder.java b/common/src/main/java/common/net/util/internal/IntegerHolder.java new file mode 100644 index 0000000..992a27c --- /dev/null +++ b/common/src/main/java/common/net/util/internal/IntegerHolder.java @@ -0,0 +1,21 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +public final class IntegerHolder { + public int value; +} diff --git a/common/src/main/java/common/net/util/internal/InternalThreadLocalMap.java b/common/src/main/java/common/net/util/internal/InternalThreadLocalMap.java new file mode 100644 index 0000000..85565f0 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/InternalThreadLocalMap.java @@ -0,0 +1,309 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.util.Arrays; +import java.util.IdentityHashMap; +import java.util.Map; +import java.util.WeakHashMap; + +import common.net.util.concurrent.FastThreadLocalThread; + +/** + * The internal data structure that stores the thread-local variables for Netty and all {@link FastThreadLocal}s. + * Note that this class is for internal use only and is subject to change at any time. Use {@link FastThreadLocal} + * unless you know what you are doing. + */ +public final class InternalThreadLocalMap extends UnpaddedInternalThreadLocalMap { + + public static final Object UNSET = new Object(); + + public static InternalThreadLocalMap getIfSet() { + Thread thread = Thread.currentThread(); + InternalThreadLocalMap threadLocalMap; + if (thread instanceof FastThreadLocalThread) { + threadLocalMap = ((FastThreadLocalThread) thread).threadLocalMap(); + } else { + ThreadLocal slowThreadLocalMap = UnpaddedInternalThreadLocalMap.slowThreadLocalMap; + if (slowThreadLocalMap == null) { + threadLocalMap = null; + } else { + threadLocalMap = slowThreadLocalMap.get(); + } + } + return threadLocalMap; + } + + public static InternalThreadLocalMap get() { + Thread thread = Thread.currentThread(); + if (thread instanceof FastThreadLocalThread) { + return fastGet((FastThreadLocalThread) thread); + } else { + return slowGet(); + } + } + + private static InternalThreadLocalMap fastGet(FastThreadLocalThread thread) { + InternalThreadLocalMap threadLocalMap = thread.threadLocalMap(); + if (threadLocalMap == null) { + thread.setThreadLocalMap(threadLocalMap = new InternalThreadLocalMap()); + } + return threadLocalMap; + } + + private static InternalThreadLocalMap slowGet() { + ThreadLocal slowThreadLocalMap = UnpaddedInternalThreadLocalMap.slowThreadLocalMap; + if (slowThreadLocalMap == null) { + UnpaddedInternalThreadLocalMap.slowThreadLocalMap = + slowThreadLocalMap = new ThreadLocal(); + } + + InternalThreadLocalMap ret = slowThreadLocalMap.get(); + if (ret == null) { + ret = new InternalThreadLocalMap(); + slowThreadLocalMap.set(ret); + } + return ret; + } + + public static void remove() { + Thread thread = Thread.currentThread(); + if (thread instanceof FastThreadLocalThread) { + ((FastThreadLocalThread) thread).setThreadLocalMap(null); + } else { + ThreadLocal slowThreadLocalMap = UnpaddedInternalThreadLocalMap.slowThreadLocalMap; + if (slowThreadLocalMap != null) { + slowThreadLocalMap.remove(); + } + } + } + + public static void destroy() { + slowThreadLocalMap = null; + } + + public static int nextVariableIndex() { + int index = nextIndex.getAndIncrement(); + if (index < 0) { + nextIndex.decrementAndGet(); + throw new IllegalStateException("too many thread-local indexed variables"); + } + return index; + } + + public static int lastVariableIndex() { + return nextIndex.get() - 1; + } + + // Cache line padding (must be public) + // With CompressedOops enabled, an instance of this class should occupy at least 128 bytes. + public long rp1, rp2, rp3, rp4, rp5, rp6, rp7, rp8, rp9; + + private InternalThreadLocalMap() { + super(newIndexedVariableTable()); + } + + private static Object[] newIndexedVariableTable() { + Object[] array = new Object[32]; + Arrays.fill(array, UNSET); + return array; + } + + public int size() { + int count = 0; + + if (futureListenerStackDepth != 0) { + count ++; + } + if (localChannelReaderStackDepth != 0) { + count ++; + } + if (handlerSharableCache != null) { + count ++; + } + if (counterHashCode != null) { + count ++; + } + if (random != null) { + count ++; + } + if (typeParameterMatcherGetCache != null) { + count ++; + } + if (typeParameterMatcherFindCache != null) { + count ++; + } + if (stringBuilder != null) { + count ++; + } + if (charsetEncoderCache != null) { + count ++; + } + if (charsetDecoderCache != null) { + count ++; + } + + for (Object o: indexedVariables) { + if (o != UNSET) { + count ++; + } + } + + // We should subtract 1 from the count because the first element in 'indexedVariables' is reserved + // by 'FastThreadLocal' to keep the list of 'FastThreadLocal's to remove on 'FastThreadLocal.removeAll()'. + return count - 1; + } + + public StringBuilder stringBuilder() { + StringBuilder builder = stringBuilder; + if (builder == null) { + stringBuilder = builder = new StringBuilder(512); + } else { + builder.setLength(0); + } + return builder; + } + + public Map charsetEncoderCache() { + Map cache = charsetEncoderCache; + if (cache == null) { + charsetEncoderCache = cache = new IdentityHashMap(); + } + return cache; + } + + public Map charsetDecoderCache() { + Map cache = charsetDecoderCache; + if (cache == null) { + charsetDecoderCache = cache = new IdentityHashMap(); + } + return cache; + } + + public int futureListenerStackDepth() { + return futureListenerStackDepth; + } + + public void setFutureListenerStackDepth(int futureListenerStackDepth) { + this.futureListenerStackDepth = futureListenerStackDepth; + } + + public ThreadLocalRandom random() { + ThreadLocalRandom r = random; + if (r == null) { + random = r = new ThreadLocalRandom(); + } + return r; + } + + public Map, TypeParameterMatcher> typeParameterMatcherGetCache() { + Map, TypeParameterMatcher> cache = typeParameterMatcherGetCache; + if (cache == null) { + typeParameterMatcherGetCache = cache = new IdentityHashMap, TypeParameterMatcher>(); + } + return cache; + } + + public Map, Map> typeParameterMatcherFindCache() { + Map, Map> cache = typeParameterMatcherFindCache; + if (cache == null) { + typeParameterMatcherFindCache = cache = new IdentityHashMap, Map>(); + } + return cache; + } + + public IntegerHolder counterHashCode() { + return counterHashCode; + } + + public void setCounterHashCode(IntegerHolder counterHashCode) { + this.counterHashCode = counterHashCode; + } + + public Map, Boolean> handlerSharableCache() { + Map, Boolean> cache = handlerSharableCache; + if (cache == null) { + // Start with small capacity to keep memory overhead as low as possible. + handlerSharableCache = cache = new WeakHashMap, Boolean>(4); + } + return cache; + } + + public int localChannelReaderStackDepth() { + return localChannelReaderStackDepth; + } + + public void setLocalChannelReaderStackDepth(int localChannelReaderStackDepth) { + this.localChannelReaderStackDepth = localChannelReaderStackDepth; + } + + public Object indexedVariable(int index) { + Object[] lookup = indexedVariables; + return index < lookup.length? lookup[index] : UNSET; + } + + /** + * @return {@code true} if and only if a new thread-local variable has been created + */ + public boolean setIndexedVariable(int index, Object value) { + Object[] lookup = indexedVariables; + if (index < lookup.length) { + Object oldValue = lookup[index]; + lookup[index] = value; + return oldValue == UNSET; + } else { + expandIndexedVariableTableAndSet(index, value); + return true; + } + } + + private void expandIndexedVariableTableAndSet(int index, Object value) { + Object[] oldArray = indexedVariables; + final int oldCapacity = oldArray.length; + int newCapacity = index; + newCapacity |= newCapacity >>> 1; + newCapacity |= newCapacity >>> 2; + newCapacity |= newCapacity >>> 4; + newCapacity |= newCapacity >>> 8; + newCapacity |= newCapacity >>> 16; + newCapacity ++; + + Object[] newArray = Arrays.copyOf(oldArray, newCapacity); + Arrays.fill(newArray, oldCapacity, newArray.length, UNSET); + newArray[index] = value; + indexedVariables = newArray; + } + + public Object removeIndexedVariable(int index) { + Object[] lookup = indexedVariables; + if (index < lookup.length) { + Object v = lookup[index]; + lookup[index] = UNSET; + return v; + } else { + return UNSET; + } + } + + public boolean isIndexedVariableSet(int index) { + Object[] lookup = indexedVariables; + return index < lookup.length && lookup[index] != UNSET; + } +} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueue.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueue.java new file mode 100644 index 0000000..0e6f378 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/MpscLinkedQueue.java @@ -0,0 +1,397 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/** + * Copyright (C) 2009-2013 Typesafe Inc. + */ +package common.net.util.internal; + +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.lang.reflect.Array; +import java.util.Arrays; +import java.util.Collection; +import java.util.Iterator; +import java.util.NoSuchElementException; +import java.util.Queue; + +/** + * A lock-free concurrent single-consumer multi-producer {@link Queue}. + * It allows multiple producer threads to perform the following operations simultaneously: + *
    + *
  • {@link #offer(Object)}, {@link #add(Object)}, and {@link #addAll(Collection)}
  • + *
  • All other read-only operations: + *
      + *
    • {@link #contains(Object)} and {@link #containsAll(Collection)}
    • + *
    • {@link #element()}, {@link #peek()}
    • + *
    • {@link #size()} and {@link #isEmpty()}
    • + *
    • {@link #iterator()} (except {@link Iterator#remove()}
    • + *
    • {@link #toArray()} and {@link #toArray(Object[])}
    • + *
    + *
  • + *
+ * .. while only one consumer thread is allowed to perform the following operations exclusively: + *
    + *
  • {@link #poll()} and {@link #remove()}
  • + *
  • {@link #remove(Object)}, {@link #removeAll(Collection)}, and {@link #retainAll(Collection)}
  • + *
  • {@link #clear()}
  • {@link #} + *
+ * + * The behavior of this implementation is undefined if you perform the operations for a consumer thread only + * from multiple threads. + * + * The initial implementation is based on: + * + * and adopted padded head node changes from: + * + * data structure modified to avoid false sharing between head and tail Ref as per implementation of MpscLinkedQueue + * on JCTools project. + */ +public final class MpscLinkedQueue extends MpscLinkedQueueTailRef implements Queue { + + private static final long serialVersionUID = -1878402552271506449L; + + long p00, p01, p02, p03, p04, p05, p06, p07; + long p30, p31, p32, p33, p34, p35, p36, p37; + + // offer() occurs at the tail of the linked list. + // poll() occurs at the head of the linked list. + // + // Resulting layout is: + // + // head --next--> 1st element --next--> 2nd element --next--> ... tail (last element) + // + // where the head is a dummy node whose value is null. + // + // offer() appends a new node next to the tail using AtomicReference.getAndSet() + // poll() removes head from the linked list and promotes the 1st element to the head, + // setting its value to null if possible. + // + // Also note that this class extends AtomicReference for the "tail" slot (which is the one that is appended to) + // since Unsafe does not expose XCHG operation intrinsically. + public MpscLinkedQueue() { + MpscLinkedQueueNode tombstone = new DefaultNode(null); + setHeadRef(tombstone); + setTailRef(tombstone); + } + + /** + * Returns the node right next to the head, which contains the first element of this queue. + */ + private MpscLinkedQueueNode peekNode() { + for (;;) { + final MpscLinkedQueueNode head = headRef(); + final MpscLinkedQueueNode next = head.next(); + if (next != null) { + return next; + } + if (head == tailRef()) { + return null; + } + + // If we are here, it means: + // * offer() is adding the first element, and + // * it's between replaceTail(newTail) and oldTail.setNext(newTail). + // (i.e. next == oldTail and oldTail.next == null and head == oldTail != newTail) + } + } + + @Override + + public boolean offer(E value) { + if (value == null) { + throw new NullPointerException("value"); + } + + final MpscLinkedQueueNode newTail; + if (value instanceof MpscLinkedQueueNode) { + newTail = (MpscLinkedQueueNode) value; + newTail.setNext(null); + } else { + newTail = new DefaultNode(value); + } + + MpscLinkedQueueNode oldTail = getAndSetTailRef(newTail); + oldTail.setNext(newTail); + return true; + } + + @Override + public E poll() { + final MpscLinkedQueueNode next = peekNode(); + if (next == null) { + return null; + } + + // next becomes a new head. + MpscLinkedQueueNode oldHead = headRef(); + // Similar to 'headRef.node = next', but slightly faster (storestore vs loadstore) + // See: http://robsjava.blogspot.com/2013/06/a-faster-volatile.html + // See: http://psy-lob-saw.blogspot.com/2012/12/atomiclazyset-is-performance-win-for.html + lazySetHeadRef(next); + + // Break the linkage between the old head and the new head. + oldHead.unlink(); + + return next.clearMaybe(); + } + + @Override + public E peek() { + final MpscLinkedQueueNode next = peekNode(); + if (next == null) { + return null; + } + return next.value(); + } + + @Override + public int size() { + int count = 0; + MpscLinkedQueueNode n = peekNode(); + for (;;) { + if (n == null) { + break; + } + count ++; + n = n.next(); + } + return count; + } + + @Override + public boolean isEmpty() { + return peekNode() == null; + } + + @Override + public boolean contains(Object o) { + MpscLinkedQueueNode n = peekNode(); + for (;;) { + if (n == null) { + break; + } + if (n.value() == o) { + return true; + } + n = n.next(); + } + return false; + } + + @Override + public Iterator iterator() { + return new Iterator() { + private MpscLinkedQueueNode node = peekNode(); + + @Override + public boolean hasNext() { + return node != null; + } + + @Override + public E next() { + MpscLinkedQueueNode node = this.node; + if (node == null) { + throw new NoSuchElementException(); + } + E value = node.value(); + this.node = node.next(); + return value; + } + + @Override + public void remove() { + throw new UnsupportedOperationException(); + } + }; + } + + @Override + public boolean add(E e) { + if (offer(e)) { + return true; + } + throw new IllegalStateException("queue full"); + } + + @Override + public E remove() { + E e = poll(); + if (e != null) { + return e; + } + throw new NoSuchElementException(); + } + + @Override + public E element() { + E e = peek(); + if (e != null) { + return e; + } + throw new NoSuchElementException(); + } + + @Override + public Object[] toArray() { + final Object[] array = new Object[size()]; + final Iterator it = iterator(); + for (int i = 0; i < array.length; i ++) { + if (it.hasNext()) { + array[i] = it.next(); + } else { + return Arrays.copyOf(array, i); + } + } + return array; + } + + @Override + + public T[] toArray(T[] a) { + final int size = size(); + final T[] array; + if (a.length >= size) { + array = a; + } else { + array = (T[]) Array.newInstance(a.getClass().getComponentType(), size); + } + + final Iterator it = iterator(); + for (int i = 0; i < array.length; i++) { + if (it.hasNext()) { + array[i] = (T) it.next(); + } else { + if (a == array) { + array[i] = null; + return array; + } + + if (a.length < i) { + return Arrays.copyOf(array, i); + } + + System.arraycopy(array, 0, a, 0, i); + if (a.length > i) { + a[i] = null; + } + return a; + } + } + return array; + } + + @Override + public boolean remove(Object o) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean containsAll(Collection c) { + for (Object e: c) { + if (!contains(e)) { + return false; + } + } + return true; + } + + @Override + public boolean addAll(Collection c) { + if (c == null) { + throw new NullPointerException("c"); + } + if (c == this) { + throw new IllegalArgumentException("c == this"); + } + + boolean modified = false; + for (E e: c) { + add(e); + modified = true; + } + return modified; + } + + @Override + public boolean removeAll(Collection c) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean retainAll(Collection c) { + throw new UnsupportedOperationException(); + } + + @Override + public void clear() { + while (poll() != null) { + continue; + } + } + + private void writeObject(ObjectOutputStream out) throws IOException { + out.defaultWriteObject(); + for (E e: this) { + out.writeObject(e); + } + out.writeObject(null); + } + + private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { + in.defaultReadObject(); + + final MpscLinkedQueueNode tombstone = new DefaultNode(null); + setHeadRef(tombstone); + setTailRef(tombstone); + + for (;;) { + + E e = (E) in.readObject(); + if (e == null) { + break; + } + add(e); + } + } + + private static final class DefaultNode extends MpscLinkedQueueNode { + + private T value; + + DefaultNode(T value) { + this.value = value; + } + + @Override + public T value() { + return value; + } + + @Override + protected T clearMaybe() { + T value = this.value; + this.value = null; + return value; + } + } +} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueueHeadRef.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueueHeadRef.java new file mode 100644 index 0000000..fc70e65 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/MpscLinkedQueueHeadRef.java @@ -0,0 +1,54 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +import java.io.Serializable; +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; + + +abstract class MpscLinkedQueueHeadRef extends MpscLinkedQueuePad0 implements Serializable { + + private static final long serialVersionUID = 8467054865577874285L; + + + private static final AtomicReferenceFieldUpdater UPDATER; + + static { + + AtomicReferenceFieldUpdater updater; + updater = null; + if (updater == null) { + updater = AtomicReferenceFieldUpdater.newUpdater( + MpscLinkedQueueHeadRef.class, MpscLinkedQueueNode.class, "headRef"); + } + UPDATER = updater; + } + + private transient volatile MpscLinkedQueueNode headRef; + + protected final MpscLinkedQueueNode headRef() { + return headRef; + } + + protected final void setHeadRef(MpscLinkedQueueNode headRef) { + this.headRef = headRef; + } + + protected final void lazySetHeadRef(MpscLinkedQueueNode headRef) { + UPDATER.lazySet(this, headRef); + } +} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueueNode.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueueNode.java new file mode 100644 index 0000000..b44975f --- /dev/null +++ b/common/src/main/java/common/net/util/internal/MpscLinkedQueueNode.java @@ -0,0 +1,65 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; + +public abstract class MpscLinkedQueueNode { + + + private static final AtomicReferenceFieldUpdater nextUpdater; + + static { + + AtomicReferenceFieldUpdater u; + + u = null; + if (u == null) { + u = AtomicReferenceFieldUpdater.newUpdater(MpscLinkedQueueNode.class, MpscLinkedQueueNode.class, "next"); + } + nextUpdater = u; + } + + + private volatile MpscLinkedQueueNode next; + + final MpscLinkedQueueNode next() { + return next; + } + + final void setNext(final MpscLinkedQueueNode newNext) { + // Similar to 'next = newNext', but slightly faster (storestore vs loadstore) + // See: http://robsjava.blogspot.com/2013/06/a-faster-volatile.html + nextUpdater.lazySet(this, newNext); + } + + public abstract T value(); + + /** + * Sets the element this node contains to {@code null} so that the node can be used as a tombstone. + */ + protected T clearMaybe() { + return value(); + } + + /** + * Unlink to allow GC'ed + */ + void unlink() { + setNext(null); + } +} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad0.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad0.java new file mode 100644 index 0000000..0fe9e45 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad0.java @@ -0,0 +1,22 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +abstract class MpscLinkedQueuePad0 { + long p00, p01, p02, p03, p04, p05, p06, p07; + long p30, p31, p32, p33, p34, p35, p36, p37; +} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad1.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad1.java new file mode 100644 index 0000000..6cfd53f --- /dev/null +++ b/common/src/main/java/common/net/util/internal/MpscLinkedQueuePad1.java @@ -0,0 +1,25 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +abstract class MpscLinkedQueuePad1 extends MpscLinkedQueueHeadRef { + + private static final long serialVersionUID = 2886694927079691637L; + + long p00, p01, p02, p03, p04, p05, p06, p07; + long p30, p31, p32, p33, p34, p35, p36, p37; +} diff --git a/common/src/main/java/common/net/util/internal/MpscLinkedQueueTailRef.java b/common/src/main/java/common/net/util/internal/MpscLinkedQueueTailRef.java new file mode 100644 index 0000000..55f9537 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/MpscLinkedQueueTailRef.java @@ -0,0 +1,54 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; + +abstract class MpscLinkedQueueTailRef extends MpscLinkedQueuePad1 { + + private static final long serialVersionUID = 8717072462993327429L; + + + private static final AtomicReferenceFieldUpdater UPDATER; + + static { + + AtomicReferenceFieldUpdater updater; + updater = null; + if (updater == null) { + updater = AtomicReferenceFieldUpdater.newUpdater( + MpscLinkedQueueTailRef.class, MpscLinkedQueueNode.class, "tailRef"); + } + UPDATER = updater; + } + + private transient volatile MpscLinkedQueueNode tailRef; + + protected final MpscLinkedQueueNode tailRef() { + return tailRef; + } + + protected final void setTailRef(MpscLinkedQueueNode tailRef) { + this.tailRef = tailRef; + } + + + protected final MpscLinkedQueueNode getAndSetTailRef(MpscLinkedQueueNode tailRef) { + // LOCK XCHG in JDK8, a CAS loop in JDK 7/6 + return (MpscLinkedQueueNode) UPDATER.getAndSet(this, tailRef); + } +} diff --git a/common/src/main/java/common/net/util/internal/NoOpTypeParameterMatcher.java b/common/src/main/java/common/net/util/internal/NoOpTypeParameterMatcher.java new file mode 100644 index 0000000..fe4d34f --- /dev/null +++ b/common/src/main/java/common/net/util/internal/NoOpTypeParameterMatcher.java @@ -0,0 +1,24 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +public final class NoOpTypeParameterMatcher extends TypeParameterMatcher { + @Override + public boolean match(Object msg) { + return true; + } +} diff --git a/common/src/main/java/common/net/util/internal/OneTimeTask.java b/common/src/main/java/common/net/util/internal/OneTimeTask.java new file mode 100644 index 0000000..7fdb8ae --- /dev/null +++ b/common/src/main/java/common/net/util/internal/OneTimeTask.java @@ -0,0 +1,30 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.internal; + +/** + * {@link Runnable} which represent a one time task which may allow the {@link EventExecutor} to reduce the amount of + * produced garbage when queue it for execution. + * + * It is important this will not be reused. After submitted it is not allowed to get submitted again! + */ +public abstract class OneTimeTask extends MpscLinkedQueueNode implements Runnable { + + @Override + public Runnable value() { + return this; + } +} diff --git a/common/src/main/java/common/net/util/internal/RecyclableArrayList.java b/common/src/main/java/common/net/util/internal/RecyclableArrayList.java new file mode 100644 index 0000000..739a077 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/RecyclableArrayList.java @@ -0,0 +1,132 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.RandomAccess; + +import common.net.util.Recycler; +import common.net.util.Recycler.Handle; + +/** + * A simple list which is reyclable. This implementation does not allow {@code null} elements to be added. + */ +public final class RecyclableArrayList extends ArrayList { + + private static final long serialVersionUID = -8605125654176467947L; + + private static final int DEFAULT_INITIAL_CAPACITY = 8; + + private static final Recycler RECYCLER = new Recycler() { + @Override + protected RecyclableArrayList newObject(Handle handle) { + return new RecyclableArrayList(handle); + } + }; + + /** + * Create a new empty {@link RecyclableArrayList} instance + */ + public static RecyclableArrayList newInstance() { + return newInstance(DEFAULT_INITIAL_CAPACITY); + } + + /** + * Create a new empty {@link RecyclableArrayList} instance with the given capacity. + */ + public static RecyclableArrayList newInstance(int minCapacity) { + RecyclableArrayList ret = RECYCLER.get(); + ret.ensureCapacity(minCapacity); + return ret; + } + + private final Handle handle; + + private RecyclableArrayList(Handle handle) { + this(handle, DEFAULT_INITIAL_CAPACITY); + } + + private RecyclableArrayList(Handle handle, int initialCapacity) { + super(initialCapacity); + this.handle = handle; + } + + @Override + public boolean addAll(Collection c) { + checkNullElements(c); + return super.addAll(c); + } + + @Override + public boolean addAll(int index, Collection c) { + checkNullElements(c); + return super.addAll(index, c); + } + + private static void checkNullElements(Collection c) { + if (c instanceof RandomAccess && c instanceof List) { + // produce less garbage + List list = (List) c; + int size = list.size(); + for (int i = 0; i < size; i++) { + if (list.get(i) == null) { + throw new IllegalArgumentException("c contains null values"); + } + } + } else { + for (Object element: c) { + if (element == null) { + throw new IllegalArgumentException("c contains null values"); + } + } + } + } + + @Override + public boolean add(Object element) { + if (element == null) { + throw new NullPointerException("element"); + } + return super.add(element); + } + + @Override + public void add(int index, Object element) { + if (element == null) { + throw new NullPointerException("element"); + } + super.add(index, element); + } + + @Override + public Object set(int index, Object element) { + if (element == null) { + throw new NullPointerException("element"); + } + return super.set(index, element); + } + + /** + * Clear and recycle this instance. + */ + public boolean recycle() { + clear(); + return RECYCLER.recycle(this, handle); + } +} diff --git a/common/src/main/java/common/net/util/internal/RecyclableMpscLinkedQueueNode.java b/common/src/main/java/common/net/util/internal/RecyclableMpscLinkedQueueNode.java new file mode 100644 index 0000000..a037070 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/RecyclableMpscLinkedQueueNode.java @@ -0,0 +1,45 @@ +/* +* Copyright 2014 The Netty Project +* +* The Netty Project licenses this file to you under the Apache License, +* version 2.0 (the "License"); you may not use this file except in compliance +* with the License. You may obtain a copy of the License at: +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT +* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the +* License for the specific language governing permissions and limitations +* under the License. +*/ + +package common.net.util.internal; + +import common.net.util.Recycler; + +/** + * {@link MpscLinkedQueueNode} that will automatically call {@link #recycle(Recycler.Handle)} when the node was + * unlinked. + */ +public abstract class RecyclableMpscLinkedQueueNode extends MpscLinkedQueueNode { + private final Recycler.Handle handle; + + protected RecyclableMpscLinkedQueueNode(Recycler.Handle handle) { + if (handle == null) { + throw new NullPointerException("handle"); + } + this.handle = handle; + } + + @Override + final void unlink() { + super.unlink(); + recycle(handle); + } + + /** + * Called once unliked and so ready to recycled. + */ + protected abstract void recycle(Recycler.Handle handle); +} diff --git a/common/src/main/java/common/net/util/internal/StringUtil.java b/common/src/main/java/common/net/util/internal/StringUtil.java new file mode 100644 index 0000000..1716baa --- /dev/null +++ b/common/src/main/java/common/net/util/internal/StringUtil.java @@ -0,0 +1,276 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.internal; + +import java.io.IOException; +import java.util.ArrayList; +import java.util.Formatter; +import java.util.List; + +import common.util.Util; + +/** + * String utility class. + */ +public final class StringUtil { + + public static final String NEWLINE; + + private static final String[] BYTE2HEX_PAD = new String[256]; + private static final String[] BYTE2HEX_NOPAD = new String[256]; + private static final String EMPTY_STRING = ""; + + static { + // Determine the newline character of the current platform. + String newLine; + Formatter formatter = null; + + try { + formatter = new Formatter(); + newLine = formatter.format("%n").toString(); + } catch (Exception e) { + // Should not reach here, but just in case. + newLine = "\n"; + } + finally { + if(formatter != null) { + try { + formatter.close(); + } + catch(Throwable e) { + } + } + } + + NEWLINE = newLine; + + // Generate the lookup table that converts a byte into a 2-digit hexadecimal integer. + int i; + for (i = 0; i < 10; i ++) { + StringBuilder buf = new StringBuilder(2); + buf.append('0'); + buf.append(i); + BYTE2HEX_PAD[i] = buf.toString(); + BYTE2HEX_NOPAD[i] = String.valueOf(i); + } + for (; i < 16; i ++) { + StringBuilder buf = new StringBuilder(2); + char c = (char) ('a' + i - 10); + buf.append('0'); + buf.append(c); + BYTE2HEX_PAD[i] = buf.toString(); + BYTE2HEX_NOPAD[i] = String.valueOf(c); + } + for (; i < BYTE2HEX_PAD.length; i ++) { + StringBuilder buf = new StringBuilder(2); + buf.append(Integer.toHexString(i)); + String str = buf.toString(); + BYTE2HEX_PAD[i] = str; + BYTE2HEX_NOPAD[i] = str; + } + } + + /** + * Splits the specified {@link String} with the specified delimiter. This operation is a simplified and optimized + * version of {@link String#split(String)}. + */ + public static String[] split(String value, char delim) { + final int end = value.length(); + final List res = new ArrayList(); + + int start = 0; + for (int i = 0; i < end; i ++) { + if (value.charAt(i) == delim) { + if (start == i) { + res.add(EMPTY_STRING); + } else { + res.add(value.substring(start, i)); + } + start = i + 1; + } + } + + if (start == 0) { // If no delimiter was found in the value + res.add(value); + } else { + if (start != end) { + // Add the last element if it's not empty. + res.add(value.substring(start, end)); + } else { + // Truncate trailing empty elements. + for (int i = res.size() - 1; i >= 0; i --) { + if (res.get(i).isEmpty()) { + res.remove(i); + } else { + break; + } + } + } + } + + return res.toArray(new String[res.size()]); + } + + /** + * Converts the specified byte value into a 2-digit hexadecimal integer. + */ + public static String byteToHexStringPadded(int value) { + return BYTE2HEX_PAD[value & 0xff]; + } + + /** + * Converts the specified byte value into a 2-digit hexadecimal integer and appends it to the specified buffer. + */ + public static T byteToHexStringPadded(T buf, int value) { + try { + buf.append(byteToHexStringPadded(value)); + } catch (IOException e) { + Util.throwUnchecked(e); + } + return buf; + } + + /** + * Converts the specified byte array into a hexadecimal value. + */ + public static String toHexStringPadded(byte[] src) { + return toHexStringPadded(src, 0, src.length); + } + + /** + * Converts the specified byte array into a hexadecimal value. + */ + public static String toHexStringPadded(byte[] src, int offset, int length) { + return toHexStringPadded(new StringBuilder(length << 1), src, offset, length).toString(); + } + + /** + * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer. + */ + public static T toHexStringPadded(T dst, byte[] src) { + return toHexStringPadded(dst, src, 0, src.length); + } + + /** + * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer. + */ + public static T toHexStringPadded(T dst, byte[] src, int offset, int length) { + final int end = offset + length; + for (int i = offset; i < end; i ++) { + byteToHexStringPadded(dst, src[i]); + } + return dst; + } + + /** + * Converts the specified byte value into a hexadecimal integer. + */ + public static String byteToHexString(int value) { + return BYTE2HEX_NOPAD[value & 0xff]; + } + + /** + * Converts the specified byte value into a hexadecimal integer and appends it to the specified buffer. + */ + public static T byteToHexString(T buf, int value) { + try { + buf.append(byteToHexString(value)); + } catch (IOException e) { + Util.throwUnchecked(e); + } + return buf; + } + + /** + * Converts the specified byte array into a hexadecimal value. + */ + public static String toHexString(byte[] src) { + return toHexString(src, 0, src.length); + } + + /** + * Converts the specified byte array into a hexadecimal value. + */ + public static String toHexString(byte[] src, int offset, int length) { + return toHexString(new StringBuilder(length << 1), src, offset, length).toString(); + } + + /** + * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer. + */ + public static T toHexString(T dst, byte[] src) { + return toHexString(dst, src, 0, src.length); + } + + /** + * Converts the specified byte array into a hexadecimal value and appends it to the specified buffer. + */ + public static T toHexString(T dst, byte[] src, int offset, int length) { + assert length >= 0; + if (length == 0) { + return dst; + } + + final int end = offset + length; + final int endMinusOne = end - 1; + int i; + + // Skip preceding zeroes. + for (i = offset; i < endMinusOne; i ++) { + if (src[i] != 0) { + break; + } + } + + byteToHexString(dst, src[i ++]); + int remaining = end - i; + toHexStringPadded(dst, src, i, remaining); + + return dst; + } + + /** + * The shortcut to {@link #simpleClassName(Class) simpleClassName(o.getClass())}. + */ + public static String simpleClassName(Object o) { + if (o == null) { + return "null_object"; + } else { + return simpleClassName(o.getClass()); + } + } + + /** + * Generates a simplified name from a {@link Class}. Similar to {@link Class#getSimpleName()}, but it works fine + * with anonymous classes. + */ + public static String simpleClassName(Class clazz) { + if (clazz == null) { + return "null_class"; + } + + Package pkg = clazz.getPackage(); + if (pkg != null) { + return clazz.getName().substring(pkg.getName().length() + 1); + } else { + return clazz.getName(); + } + } + + private StringUtil() { + // Unused. + } +} diff --git a/common/src/main/java/common/net/util/internal/SystemPropertyUtil.java b/common/src/main/java/common/net/util/internal/SystemPropertyUtil.java new file mode 100644 index 0000000..1788bdb --- /dev/null +++ b/common/src/main/java/common/net/util/internal/SystemPropertyUtil.java @@ -0,0 +1,212 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.internal; + +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.regex.Pattern; + +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * A collection of utility methods to retrieve and parse the values of the Java system properties. + */ +public final class SystemPropertyUtil { + + private static boolean initializedLogger; + private static final InternalLogger logger; + private static boolean loggedException; + + static { + initializedLogger = false; + logger = InternalLoggerFactory.getInstance(SystemPropertyUtil.class); + initializedLogger = true; + } + + /** + * Returns {@code true} if and only if the system property with the specified {@code key} + * exists. + */ + public static boolean contains(String key) { + return get(key) != null; + } + + /** + * Returns the value of the Java system property with the specified + * {@code key}, while falling back to {@code null} if the property access fails. + * + * @return the property value or {@code null} + */ + public static String get(String key) { + return get(key, null); + } + + /** + * Returns the value of the Java system property with the specified + * {@code key}, while falling back to the specified default value if + * the property access fails. + * + * @return the property value. + * {@code def} if there's no such property or if an access to the + * specified property is not allowed. + */ + public static String get(final String key, String def) { + if (key == null) { + throw new NullPointerException("key"); + } + if (key.isEmpty()) { + throw new IllegalArgumentException("key must not be empty."); + } + + String value = null; + try { + value = System.getProperty(key); + } catch (Exception e) { + if (!loggedException) { + log("Unable to retrieve a system property '" + key + "'; default values will be used.", e); + loggedException = true; + } + } + + if (value == null) { + return def; + } + + return value; + } + + /** + * Returns the value of the Java system property with the specified + * {@code key}, while falling back to the specified default value if + * the property access fails. + * + * @return the property value. + * {@code def} if there's no such property or if an access to the + * specified property is not allowed. + */ + public static boolean getBoolean(String key, boolean def) { + String value = get(key); + if (value == null) { + return def; + } + + value = value.trim().toLowerCase(); + if (value.isEmpty()) { + return true; + } + + if ("true".equals(value) || "yes".equals(value) || "1".equals(value)) { + return true; + } + + if ("false".equals(value) || "no".equals(value) || "0".equals(value)) { + return false; + } + + log( + "Unable to parse the boolean system property '" + key + "':" + value + " - " + + "using the default value: " + def); + + return def; + } + + private static final Pattern INTEGER_PATTERN = Pattern.compile("-?[0-9]+"); + + /** + * Returns the value of the Java system property with the specified + * {@code key}, while falling back to the specified default value if + * the property access fails. + * + * @return the property value. + * {@code def} if there's no such property or if an access to the + * specified property is not allowed. + */ + public static int getInt(String key, int def) { + String value = get(key); + if (value == null) { + return def; + } + + value = value.trim().toLowerCase(); + if (INTEGER_PATTERN.matcher(value).matches()) { + try { + return Integer.parseInt(value); + } catch (Exception e) { + // Ignore + } + } + + log( + "Unable to parse the integer system property '" + key + "':" + value + " - " + + "using the default value: " + def); + + return def; + } + + /** + * Returns the value of the Java system property with the specified + * {@code key}, while falling back to the specified default value if + * the property access fails. + * + * @return the property value. + * {@code def} if there's no such property or if an access to the + * specified property is not allowed. + */ + public static long getLong(String key, long def) { + String value = get(key); + if (value == null) { + return def; + } + + value = value.trim().toLowerCase(); + if (INTEGER_PATTERN.matcher(value).matches()) { + try { + return Long.parseLong(value); + } catch (Exception e) { + // Ignore + } + } + + log( + "Unable to parse the long integer system property '" + key + "':" + value + " - " + + "using the default value: " + def); + + return def; + } + + private static void log(String msg) { + if (initializedLogger) { + logger.warn(msg); + } else { + // Use JDK logging if logger was not initialized yet. + Logger.getLogger(SystemPropertyUtil.class.getName()).log(Level.WARNING, msg); + } + } + + private static void log(String msg, Exception e) { + if (initializedLogger) { + logger.warn(msg, e); + } else { + // Use JDK logging if logger was not initialized yet. + Logger.getLogger(SystemPropertyUtil.class.getName()).log(Level.WARNING, msg, e); + } + } + + private SystemPropertyUtil() { + // Unused + } +} diff --git a/common/src/main/java/common/net/util/internal/ThreadLocalRandom.java b/common/src/main/java/common/net/util/internal/ThreadLocalRandom.java new file mode 100644 index 0000000..0ad7360 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/ThreadLocalRandom.java @@ -0,0 +1,336 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +/* + * Written by Doug Lea with assistance from members of JCP JSR-166 + * Expert Group and released to the public domain, as explained at + * http://creativecommons.org/publicdomain/zero/1.0/ + */ + +package common.net.util.internal; + +import java.lang.Thread.UncaughtExceptionHandler; +import java.security.SecureRandom; +import java.util.Random; +import java.util.concurrent.BlockingQueue; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.atomic.AtomicLong; + +import common.net.util.internal.logging.InternalLogger; +import common.net.util.internal.logging.InternalLoggerFactory; + +/** + * A random number generator isolated to the current thread. Like the + * global {@link java.util.Random} generator used by the {@link + * java.lang.Math} class, a {@code ThreadLocalRandom} is initialized + * with an internally generated seed that may not otherwise be + * modified. When applicable, use of {@code ThreadLocalRandom} rather + * than shared {@code Random} objects in concurrent programs will + * typically encounter much less overhead and contention. Use of + * {@code ThreadLocalRandom} is particularly appropriate when multiple + * tasks (for example, each a {@link game.net.util.internal.chmv8.ForkJoinTask}) use random numbers + * in parallel in thread pools. + * + *

Usages of this class should typically be of the form: + * {@code ThreadLocalRandom.current().nextX(...)} (where + * {@code X} is {@code Int}, {@code Long}, etc). + * When all usages are of this form, it is never possible to + * accidently share a {@code ThreadLocalRandom} across multiple threads. + * + *

This class also provides additional commonly used bounded random + * generation methods. + * + * //since 1.7 + * //author Doug Lea + */ + +public final class ThreadLocalRandom extends Random { + + private static final InternalLogger logger = InternalLoggerFactory.getInstance(ThreadLocalRandom.class); + + private static final AtomicLong seedUniquifier = new AtomicLong(); + + private static volatile long initialSeedUniquifier; + + public static void setInitialSeedUniquifier(long initialSeedUniquifier) { + ThreadLocalRandom.initialSeedUniquifier = initialSeedUniquifier; + } + + public static synchronized long getInitialSeedUniquifier() { + // Use the value set via the setter. + long initialSeedUniquifier = ThreadLocalRandom.initialSeedUniquifier; + if (initialSeedUniquifier == 0) { + // Use the system property value. + ThreadLocalRandom.initialSeedUniquifier = initialSeedUniquifier = + SystemPropertyUtil.getLong("game.net.initialSeedUniquifier", 0); + } + + // Otherwise, generate one. + if (initialSeedUniquifier == 0) { + // Try to generate a real random number from /dev/random. + // Get from a different thread to avoid blocking indefinitely on a machine without much entrophy. + final BlockingQueue queue = new LinkedBlockingQueue(); + Thread generatorThread = new Thread("initialSeedUniquifierGenerator") { + @Override + public void run() { + SecureRandom random = new SecureRandom(); // Get the real random seed from /dev/random + queue.add(random.generateSeed(8)); + } + }; + generatorThread.setDaemon(true); + generatorThread.start(); + generatorThread.setUncaughtExceptionHandler(new UncaughtExceptionHandler() { + @Override + public void uncaughtException(Thread t, Throwable e) { + logger.debug("An exception has been raised by {}", t.getName(), e); + } + }); + + // Get the random seed from the thread with timeout. + final long timeoutSeconds = 3; + final long deadLine = System.nanoTime() + TimeUnit.SECONDS.toNanos(timeoutSeconds); + boolean interrupted = false; + for (;;) { + long waitTime = deadLine - System.nanoTime(); + if (waitTime <= 0) { + generatorThread.interrupt(); + logger.warn( + "Failed to generate a seed from SecureRandom within {} seconds. " + + "Not enough entrophy?", timeoutSeconds + ); + break; + } + + try { + byte[] seed = queue.poll(waitTime, TimeUnit.NANOSECONDS); + if (seed != null) { + initialSeedUniquifier = + ((long) seed[0] & 0xff) << 56 | + ((long) seed[1] & 0xff) << 48 | + ((long) seed[2] & 0xff) << 40 | + ((long) seed[3] & 0xff) << 32 | + ((long) seed[4] & 0xff) << 24 | + ((long) seed[5] & 0xff) << 16 | + ((long) seed[6] & 0xff) << 8 | + (long) seed[7] & 0xff; + break; + } + } catch (InterruptedException e) { + interrupted = true; + logger.warn("Failed to generate a seed from SecureRandom due to an InterruptedException."); + break; + } + } + + // Just in case the initialSeedUniquifier is zero or some other constant + initialSeedUniquifier ^= 0x3255ecdc33bae119L; // just a meaningless random number + initialSeedUniquifier ^= Long.reverse(System.nanoTime()); + + ThreadLocalRandom.initialSeedUniquifier = initialSeedUniquifier; + + if (interrupted) { + // Restore the interrupt status because we don't know how to/don't need to handle it here. + Thread.currentThread().interrupt(); + + // Interrupt the generator thread if it's still running, + // in the hope that the SecureRandom provider raises an exception on interruption. + generatorThread.interrupt(); + } + } + + return initialSeedUniquifier; + } + + private static long newSeed() { + final long startTime = System.nanoTime(); + for (;;) { + final long current = seedUniquifier.get(); + final long actualCurrent = current != 0? current : getInitialSeedUniquifier(); + + // L'Ecuyer, "Tables of Linear Congruential Generators of Different Sizes and Good Lattice Structure", 1999 + final long next = actualCurrent * 181783497276652981L; + + if (seedUniquifier.compareAndSet(current, next)) { + if (current == 0 && logger.isDebugEnabled()) { + logger.debug(String.format( + "-Dgame.net.initialSeedUniquifier: 0x%016x (took %d ms)", + actualCurrent, TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime))); + } + return next ^ System.nanoTime(); + } + } + } + + // same constants as Random, but must be redeclared because private + private static final long multiplier = 0x5DEECE66DL; + private static final long addend = 0xBL; + private static final long mask = (1L << 48) - 1; + + /** + * The random seed. We can't use super.seed. + */ + private long rnd; + + /** + * Initialization flag to permit calls to setSeed to succeed only + * while executing the Random constructor. We can't allow others + * since it would cause setting seed in one part of a program to + * unintentionally impact other usages by the thread. + */ + boolean initialized; + + // Padding to help avoid memory contention among seed updates in + // different TLRs in the common case that they are located near + // each other. + private long pad0, pad1, pad2, pad3, pad4, pad5, pad6, pad7; + + /** + * Constructor called only by localRandom.initialValue. + */ + ThreadLocalRandom() { + super(newSeed()); + initialized = true; + } + + /** + * Returns the current thread's {@code ThreadLocalRandom}. + * + * @return the current thread's {@code ThreadLocalRandom} + */ + public static ThreadLocalRandom current() { + return InternalThreadLocalMap.get().random(); + } + + /** + * Throws {@code UnsupportedOperationException}. Setting seeds in + * this generator is not supported. + * + * @throws UnsupportedOperationException always + */ + public void setSeed(long seed) { + if (initialized) { + throw new UnsupportedOperationException(); + } + rnd = (seed ^ multiplier) & mask; + } + + protected int next(int bits) { + rnd = (rnd * multiplier + addend) & mask; + return (int) (rnd >>> (48 - bits)); + } + + /** + * Returns a pseudorandom, uniformly distributed value between the + * given least value (inclusive) and bound (exclusive). + * + * @param least the least value returned + * @param bound the upper bound (exclusive) + * @throws IllegalArgumentException if least greater than or equal + * to bound + * @return the next value + */ + public int nextInt(int least, int bound) { + if (least >= bound) { + throw new IllegalArgumentException(); + } + return nextInt(bound - least) + least; + } + + /** + * Returns a pseudorandom, uniformly distributed value + * between 0 (inclusive) and the specified value (exclusive). + * + * @param n the bound on the random number to be returned. Must be + * positive. + * @return the next value + * @throws IllegalArgumentException if n is not positive + */ + public long nextLong(long n) { + if (n <= 0) { + throw new IllegalArgumentException("n must be positive"); + } + + // Divide n by two until small enough for nextInt. On each + // iteration (at most 31 of them but usually much less), + // randomly choose both whether to include high bit in result + // (offset) and whether to continue with the lower vs upper + // half (which makes a difference only if odd). + long offset = 0; + while (n >= Integer.MAX_VALUE) { + int bits = next(2); + long half = n >>> 1; + long nextn = ((bits & 2) == 0) ? half : n - half; + if ((bits & 1) == 0) { + offset += n - nextn; + } + n = nextn; + } + return offset + nextInt((int) n); + } + + /** + * Returns a pseudorandom, uniformly distributed value between the + * given least value (inclusive) and bound (exclusive). + * + * @param least the least value returned + * @param bound the upper bound (exclusive) + * @return the next value + * @throws IllegalArgumentException if least greater than or equal + * to bound + */ + public long nextLong(long least, long bound) { + if (least >= bound) { + throw new IllegalArgumentException(); + } + return nextLong(bound - least) + least; + } + + /** + * Returns a pseudorandom, uniformly distributed {@code double} value + * between 0 (inclusive) and the specified value (exclusive). + * + * @param n the bound on the random number to be returned. Must be + * positive. + * @return the next value + * @throws IllegalArgumentException if n is not positive + */ + public double nextDouble(double n) { + if (n <= 0) { + throw new IllegalArgumentException("n must be positive"); + } + return nextDouble() * n; + } + + /** + * Returns a pseudorandom, uniformly distributed value between the + * given least value (inclusive) and bound (exclusive). + * + * @param least the least value returned + * @param bound the upper bound (exclusive) + * @return the next value + * @throws IllegalArgumentException if least greater than or equal + * to bound + */ + public double nextDouble(double least, double bound) { + if (least >= bound) { + throw new IllegalArgumentException(); + } + return nextDouble() * (bound - least) + least; + } + + private static final long serialVersionUID = -5851777807851030925L; +} diff --git a/common/src/main/java/common/net/util/internal/TypeParameterMatcher.java b/common/src/main/java/common/net/util/internal/TypeParameterMatcher.java new file mode 100644 index 0000000..76ba1b2 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/TypeParameterMatcher.java @@ -0,0 +1,177 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +import java.lang.reflect.Array; +import java.lang.reflect.GenericArrayType; +import java.lang.reflect.ParameterizedType; +import java.lang.reflect.Type; +import java.lang.reflect.TypeVariable; +import java.util.HashMap; +import java.util.Map; + +public abstract class TypeParameterMatcher { + + private static final TypeParameterMatcher NOOP = new NoOpTypeParameterMatcher(); + private static final Object TEST_OBJECT = new Object(); + + public static TypeParameterMatcher get(final Class parameterType) { + final Map, TypeParameterMatcher> getCache = + InternalThreadLocalMap.get().typeParameterMatcherGetCache(); + + TypeParameterMatcher matcher = getCache.get(parameterType); + if (matcher == null) { + if (parameterType == Object.class) { + matcher = NOOP; + } +// else if (PlatformDependent.hasJavassist()) { +// try { +// matcher = JavassistTypeParameterMatcherGenerator.generate(parameterType); +// matcher.match(TEST_OBJECT); +// } catch (IllegalAccessError e) { +// // Happens if parameterType is not public. +// matcher = null; +// } catch (Exception e) { +// // Will not usually happen, but just in case. +// matcher = null; +// } +// } + + if (matcher == null) { + matcher = new ReflectiveMatcher(parameterType); + } + + getCache.put(parameterType, matcher); + } + + return matcher; + } + + public static TypeParameterMatcher find( + final Object object, final Class parameterizedSuperclass, final String typeParamName) { + + final Map, Map> findCache = + InternalThreadLocalMap.get().typeParameterMatcherFindCache(); + final Class thisClass = object.getClass(); + + Map map = findCache.get(thisClass); + if (map == null) { + map = new HashMap(); + findCache.put(thisClass, map); + } + + TypeParameterMatcher matcher = map.get(typeParamName); + if (matcher == null) { + matcher = get(find0(object, parameterizedSuperclass, typeParamName)); + map.put(typeParamName, matcher); + } + + return matcher; + } + + private static Class find0( + final Object object, Class parameterizedSuperclass, String typeParamName) { + + final Class thisClass = object.getClass(); + Class currentClass = thisClass; + for (;;) { + if (currentClass.getSuperclass() == parameterizedSuperclass) { + int typeParamIndex = -1; + TypeVariable[] typeParams = currentClass.getSuperclass().getTypeParameters(); + for (int i = 0; i < typeParams.length; i ++) { + if (typeParamName.equals(typeParams[i].getName())) { + typeParamIndex = i; + break; + } + } + + if (typeParamIndex < 0) { + throw new IllegalStateException( + "unknown type parameter '" + typeParamName + "': " + parameterizedSuperclass); + } + + Type genericSuperType = currentClass.getGenericSuperclass(); + if (!(genericSuperType instanceof ParameterizedType)) { + return Object.class; + } + + Type[] actualTypeParams = ((ParameterizedType) genericSuperType).getActualTypeArguments(); + + Type actualTypeParam = actualTypeParams[typeParamIndex]; + if (actualTypeParam instanceof ParameterizedType) { + actualTypeParam = ((ParameterizedType) actualTypeParam).getRawType(); + } + if (actualTypeParam instanceof Class) { + return (Class) actualTypeParam; + } + if (actualTypeParam instanceof GenericArrayType) { + Type componentType = ((GenericArrayType) actualTypeParam).getGenericComponentType(); + if (componentType instanceof ParameterizedType) { + componentType = ((ParameterizedType) componentType).getRawType(); + } + if (componentType instanceof Class) { + return Array.newInstance((Class) componentType, 0).getClass(); + } + } + if (actualTypeParam instanceof TypeVariable) { + // Resolved type parameter points to another type parameter. + TypeVariable v = (TypeVariable) actualTypeParam; + currentClass = thisClass; + if (!(v.getGenericDeclaration() instanceof Class)) { + return Object.class; + } + + parameterizedSuperclass = (Class) v.getGenericDeclaration(); + typeParamName = v.getName(); + if (parameterizedSuperclass.isAssignableFrom(thisClass)) { + continue; + } else { + return Object.class; + } + } + + return fail(thisClass, typeParamName); + } + currentClass = currentClass.getSuperclass(); + if (currentClass == null) { + return fail(thisClass, typeParamName); + } + } + } + + private static Class fail(Class type, String typeParamName) { + throw new IllegalStateException( + "cannot determine the type of the type parameter '" + typeParamName + "': " + type); + } + + public abstract boolean match(Object msg); + + private static final class ReflectiveMatcher extends TypeParameterMatcher { + private final Class type; + + ReflectiveMatcher(Class type) { + this.type = type; + } + + @Override + public boolean match(Object msg) { + return type.isInstance(msg); + } + } + + protected TypeParameterMatcher() { } +} diff --git a/common/src/main/java/common/net/util/internal/UnpaddedInternalThreadLocalMap.java b/common/src/main/java/common/net/util/internal/UnpaddedInternalThreadLocalMap.java new file mode 100644 index 0000000..689202d --- /dev/null +++ b/common/src/main/java/common/net/util/internal/UnpaddedInternalThreadLocalMap.java @@ -0,0 +1,55 @@ +/* + * Copyright 2014 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ + +package common.net.util.internal; + +import java.nio.charset.Charset; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.util.Map; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * The internal data structure that stores the thread-local variables for Netty and all {@link FastThreadLocal}s. + * Note that this class is for internal use only and is subject to change at any time. Use {@link FastThreadLocal} + * unless you know what you are doing. + */ +class UnpaddedInternalThreadLocalMap { + + static ThreadLocal slowThreadLocalMap; + static final AtomicInteger nextIndex = new AtomicInteger(); + + /** Used by {@link FastThreadLocal} */ + Object[] indexedVariables; + + // Core thread-locals + int futureListenerStackDepth; + int localChannelReaderStackDepth; + Map, Boolean> handlerSharableCache; + IntegerHolder counterHashCode; + ThreadLocalRandom random; + Map, TypeParameterMatcher> typeParameterMatcherGetCache; + Map, Map> typeParameterMatcherFindCache; + + // String-related thread-locals + StringBuilder stringBuilder; + Map charsetEncoderCache; + Map charsetDecoderCache; + + UnpaddedInternalThreadLocalMap(Object[] indexedVariables) { + this.indexedVariables = indexedVariables; + } +} diff --git a/common/src/main/java/common/net/util/internal/logging/AbstractInternalLogger.java b/common/src/main/java/common/net/util/internal/logging/AbstractInternalLogger.java new file mode 100644 index 0000000..2ebbf8a --- /dev/null +++ b/common/src/main/java/common/net/util/internal/logging/AbstractInternalLogger.java @@ -0,0 +1,190 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.internal.logging; + +import java.io.ObjectStreamException; +import java.io.Serializable; + +import common.net.util.internal.StringUtil; + +/** + * A skeletal implementation of {@link InternalLogger}. This class implements + * all methods that have a {@link InternalLogLevel} parameter by default to call + * specific logger methods such as {@link #info(String)} or {@link #isInfoEnabled()}. + */ +public abstract class AbstractInternalLogger implements InternalLogger, Serializable { + + private static final long serialVersionUID = -6382972526573193470L; + + private final String name; + + /** + * Creates a new instance. + */ + protected AbstractInternalLogger(String name) { + if (name == null) { + throw new NullPointerException("name"); + } + this.name = name; + } + + @Override + public String name() { + return name; + } + + @Override + public boolean isEnabled(InternalLogLevel level) { + switch (level) { + case TRACE: + return isTraceEnabled(); + case DEBUG: + return isDebugEnabled(); + case INFO: + return isInfoEnabled(); + case WARN: + return isWarnEnabled(); + case ERROR: + return isErrorEnabled(); + default: + throw new Error(); + } + } + + @Override + public void log(InternalLogLevel level, String msg, Throwable cause) { + switch (level) { + case TRACE: + trace(msg, cause); + break; + case DEBUG: + debug(msg, cause); + break; + case INFO: + info(msg, cause); + break; + case WARN: + warn(msg, cause); + break; + case ERROR: + error(msg, cause); + break; + default: + throw new Error(); + } + } + + @Override + public void log(InternalLogLevel level, String msg) { + switch (level) { + case TRACE: + trace(msg); + break; + case DEBUG: + debug(msg); + break; + case INFO: + info(msg); + break; + case WARN: + warn(msg); + break; + case ERROR: + error(msg); + break; + default: + throw new Error(); + } + } + + @Override + public void log(InternalLogLevel level, String format, Object arg) { + switch (level) { + case TRACE: + trace(format, arg); + break; + case DEBUG: + debug(format, arg); + break; + case INFO: + info(format, arg); + break; + case WARN: + warn(format, arg); + break; + case ERROR: + error(format, arg); + break; + default: + throw new Error(); + } + } + + @Override + public void log(InternalLogLevel level, String format, Object argA, Object argB) { + switch (level) { + case TRACE: + trace(format, argA, argB); + break; + case DEBUG: + debug(format, argA, argB); + break; + case INFO: + info(format, argA, argB); + break; + case WARN: + warn(format, argA, argB); + break; + case ERROR: + error(format, argA, argB); + break; + default: + throw new Error(); + } + } + + @Override + public void log(InternalLogLevel level, String format, Object... arguments) { + switch (level) { + case TRACE: + trace(format, arguments); + break; + case DEBUG: + debug(format, arguments); + break; + case INFO: + info(format, arguments); + break; + case WARN: + warn(format, arguments); + break; + case ERROR: + error(format, arguments); + break; + default: + throw new Error(); + } + } + + protected Object readResolve() throws ObjectStreamException { + return InternalLoggerFactory.getInstance(name()); + } + + @Override + public String toString() { + return StringUtil.simpleClassName(this) + '(' + name() + ')'; + } +} diff --git a/common/src/main/java/common/net/util/internal/logging/FormattingTuple.java b/common/src/main/java/common/net/util/internal/logging/FormattingTuple.java new file mode 100644 index 0000000..c87a8e7 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/logging/FormattingTuple.java @@ -0,0 +1,88 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package common.net.util.internal.logging; + +/** + * Holds the results of formatting done by {@link MessageFormatter}. + */ +class FormattingTuple { + + static final FormattingTuple NULL = new FormattingTuple(null); + + private final String message; + private final Throwable throwable; + private final Object[] argArray; + + FormattingTuple(String message) { + this(message, null, null); + } + + FormattingTuple(String message, Object[] argArray, Throwable throwable) { + this.message = message; + this.throwable = throwable; + if (throwable == null) { + this.argArray = argArray; + } else { + this.argArray = trimmedCopy(argArray); + } + } + + static Object[] trimmedCopy(Object[] argArray) { + if (argArray == null || argArray.length == 0) { + throw new IllegalStateException("non-sensical empty or null argument array"); + } + final int trimemdLen = argArray.length - 1; + Object[] trimmed = new Object[trimemdLen]; + System.arraycopy(argArray, 0, trimmed, 0, trimemdLen); + return trimmed; + } + + public String getMessage() { + return message; + } + + public Object[] getArgArray() { + return argArray; + } + + public Throwable getThrowable() { + return throwable; + } +} diff --git a/common/src/main/java/common/net/util/internal/logging/InternalLogLevel.java b/common/src/main/java/common/net/util/internal/logging/InternalLogLevel.java new file mode 100644 index 0000000..108c2f5 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/logging/InternalLogLevel.java @@ -0,0 +1,42 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.internal.logging; + +/** + * The log level that {@link InternalLogger} can log at. + */ +public enum InternalLogLevel { + /** + * 'TRACE' log level. + */ + TRACE, + /** + * 'DEBUG' log level. + */ + DEBUG, + /** + * 'INFO' log level. + */ + INFO, + /** + * 'WARN' log level. + */ + WARN, + /** + * 'ERROR' log level. + */ + ERROR +} diff --git a/common/src/main/java/common/net/util/internal/logging/InternalLogger.java b/common/src/main/java/common/net/util/internal/logging/InternalLogger.java new file mode 100644 index 0000000..1c2b953 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/logging/InternalLogger.java @@ -0,0 +1,444 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package common.net.util.internal.logging; + +/** + * Internal-use-only logger used by Netty. DO NOT + * access this class outside of Netty. + */ +public interface InternalLogger { + + /** + * Return the name of this {@link InternalLogger} instance. + * + * @return name of this logger instance + */ + String name(); + + /** + * Is the logger instance enabled for the TRACE level? + * + * @return True if this Logger is enabled for the TRACE level, + * false otherwise. + */ + boolean isTraceEnabled(); + + /** + * Log a message at the TRACE level. + * + * @param msg the message string to be logged + */ + void trace(String msg); + + /** + * Log a message at the TRACE level according to the specified format + * and argument. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the TRACE level.

+ * + * @param format the format string + * @param arg the argument + */ + void trace(String format, Object arg); + + /** + * Log a message at the TRACE level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the TRACE level.

+ * + * @param format the format string + * @param argA the first argument + * @param argB the second argument + */ + void trace(String format, Object argA, Object argB); + + /** + * Log a message at the TRACE level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous string concatenation when the logger + * is disabled for the TRACE level. However, this variant incurs the hidden + * (and relatively small) cost of creating an {@code Object[]} before invoking the method, + * even if this logger is disabled for TRACE. The variants taking {@link #trace(String, Object) one} and + * {@link #trace(String, Object, Object) two} arguments exist solely in order to avoid this hidden cost.

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + void trace(String format, Object... arguments); + + /** + * Log an exception (throwable) at the TRACE level with an + * accompanying message. + * + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + void trace(String msg, Throwable t); + + /** + * Is the logger instance enabled for the DEBUG level? + * + * @return True if this Logger is enabled for the DEBUG level, + * false otherwise. + */ + boolean isDebugEnabled(); + + /** + * Log a message at the DEBUG level. + * + * @param msg the message string to be logged + */ + void debug(String msg); + + /** + * Log a message at the DEBUG level according to the specified format + * and argument. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the DEBUG level.

+ * + * @param format the format string + * @param arg the argument + */ + void debug(String format, Object arg); + + /** + * Log a message at the DEBUG level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the DEBUG level.

+ * + * @param format the format string + * @param argA the first argument + * @param argB the second argument + */ + void debug(String format, Object argA, Object argB); + + /** + * Log a message at the DEBUG level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous string concatenation when the logger + * is disabled for the DEBUG level. However, this variant incurs the hidden + * (and relatively small) cost of creating an {@code Object[]} before invoking the method, + * even if this logger is disabled for DEBUG. The variants taking + * {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two} + * arguments exist solely in order to avoid this hidden cost.

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + void debug(String format, Object... arguments); + + /** + * Log an exception (throwable) at the DEBUG level with an + * accompanying message. + * + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + void debug(String msg, Throwable t); + + /** + * Is the logger instance enabled for the INFO level? + * + * @return True if this Logger is enabled for the INFO level, + * false otherwise. + */ + boolean isInfoEnabled(); + + /** + * Log a message at the INFO level. + * + * @param msg the message string to be logged + */ + void info(String msg); + + /** + * Log a message at the INFO level according to the specified format + * and argument. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the INFO level.

+ * + * @param format the format string + * @param arg the argument + */ + void info(String format, Object arg); + + /** + * Log a message at the INFO level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the INFO level.

+ * + * @param format the format string + * @param argA the first argument + * @param argB the second argument + */ + void info(String format, Object argA, Object argB); + + /** + * Log a message at the INFO level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous string concatenation when the logger + * is disabled for the INFO level. However, this variant incurs the hidden + * (and relatively small) cost of creating an {@code Object[]} before invoking the method, + * even if this logger is disabled for INFO. The variants taking + * {@link #info(String, Object) one} and {@link #info(String, Object, Object) two} + * arguments exist solely in order to avoid this hidden cost.

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + void info(String format, Object... arguments); + + /** + * Log an exception (throwable) at the INFO level with an + * accompanying message. + * + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + void info(String msg, Throwable t); + + /** + * Is the logger instance enabled for the WARN level? + * + * @return True if this Logger is enabled for the WARN level, + * false otherwise. + */ + boolean isWarnEnabled(); + + /** + * Log a message at the WARN level. + * + * @param msg the message string to be logged + */ + void warn(String msg); + + /** + * Log a message at the WARN level according to the specified format + * and argument. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the WARN level.

+ * + * @param format the format string + * @param arg the argument + */ + void warn(String format, Object arg); + + /** + * Log a message at the WARN level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous string concatenation when the logger + * is disabled for the WARN level. However, this variant incurs the hidden + * (and relatively small) cost of creating an {@code Object[]} before invoking the method, + * even if this logger is disabled for WARN. The variants taking + * {@link #warn(String, Object) one} and {@link #warn(String, Object, Object) two} + * arguments exist solely in order to avoid this hidden cost.

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + void warn(String format, Object... arguments); + + /** + * Log a message at the WARN level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the WARN level.

+ * + * @param format the format string + * @param argA the first argument + * @param argB the second argument + */ + void warn(String format, Object argA, Object argB); + + /** + * Log an exception (throwable) at the WARN level with an + * accompanying message. + * + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + void warn(String msg, Throwable t); + + /** + * Is the logger instance enabled for the ERROR level? + * + * @return True if this Logger is enabled for the ERROR level, + * false otherwise. + */ + boolean isErrorEnabled(); + + /** + * Log a message at the ERROR level. + * + * @param msg the message string to be logged + */ + void error(String msg); + + /** + * Log a message at the ERROR level according to the specified format + * and argument. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the ERROR level.

+ * + * @param format the format string + * @param arg the argument + */ + void error(String format, Object arg); + + /** + * Log a message at the ERROR level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the ERROR level.

+ * + * @param format the format string + * @param argA the first argument + * @param argB the second argument + */ + void error(String format, Object argA, Object argB); + + /** + * Log a message at the ERROR level according to the specified format + * and arguments. + *

+ *

This form avoids superfluous string concatenation when the logger + * is disabled for the ERROR level. However, this variant incurs the hidden + * (and relatively small) cost of creating an {@code Object[]} before invoking the method, + * even if this logger is disabled for ERROR. The variants taking + * {@link #error(String, Object) one} and {@link #error(String, Object, Object) two} + * arguments exist solely in order to avoid this hidden cost.

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + void error(String format, Object... arguments); + + /** + * Log an exception (throwable) at the ERROR level with an + * accompanying message. + * + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + void error(String msg, Throwable t); + + /** + * Is the logger instance enabled for the specified {@code level}? + * + * @return True if this Logger is enabled for the specified {@code level}, + * false otherwise. + */ + boolean isEnabled(InternalLogLevel level); + + /** + * Log a message at the specified {@code level}. + * + * @param msg the message string to be logged + */ + void log(InternalLogLevel level, String msg); + + /** + * Log a message at the specified {@code level} according to the specified format + * and argument. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the specified {@code level}.

+ * + * @param format the format string + * @param arg the argument + */ + void log(InternalLogLevel level, String format, Object arg); + + /** + * Log a message at the specified {@code level} according to the specified format + * and arguments. + *

+ *

This form avoids superfluous object creation when the logger + * is disabled for the specified {@code level}.

+ * + * @param format the format string + * @param argA the first argument + * @param argB the second argument + */ + void log(InternalLogLevel level, String format, Object argA, Object argB); + + /** + * Log a message at the specified {@code level} according to the specified format + * and arguments. + *

+ *

This form avoids superfluous string concatenation when the logger + * is disabled for the specified {@code level}. However, this variant incurs the hidden + * (and relatively small) cost of creating an {@code Object[]} before invoking the method, + * even if this logger is disabled for the specified {@code level}. The variants taking + * {@link #log(InternalLogLevel, String, Object) one} and + * {@link #log(InternalLogLevel, String, Object, Object) two} arguments exist solely + * in order to avoid this hidden cost.

+ * + * @param format the format string + * @param arguments a list of 3 or more arguments + */ + void log(InternalLogLevel level, String format, Object... arguments); + + /** + * Log an exception (throwable) at the specified {@code level} with an + * accompanying message. + * + * @param msg the message accompanying the exception + * @param t the exception (throwable) to log + */ + void log(InternalLogLevel level, String msg, Throwable t); +} diff --git a/common/src/main/java/common/net/util/internal/logging/InternalLoggerFactory.java b/common/src/main/java/common/net/util/internal/logging/InternalLoggerFactory.java new file mode 100644 index 0000000..e6d10ff --- /dev/null +++ b/common/src/main/java/common/net/util/internal/logging/InternalLoggerFactory.java @@ -0,0 +1,91 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.internal.logging; + +/** + * Creates an {@link InternalLogger} or changes the default factory + * implementation. This factory allows you to choose what logging framework + * Netty should use. The default factory is {@link Slf4JLoggerFactory}. If SLF4J + * is not available, {@link Log4JLoggerFactory} is used. If Log4J is not available, + * {@link JdkLoggerFactory} is used. You can change it to your preferred + * logging framework before other Netty classes are loaded: + *
+ * {@link InternalLoggerFactory}.setDefaultFactory(new {@link Log4JLoggerFactory}());
+ * 
+ * Please note that the new default factory is effective only for the classes + * which were loaded after the default factory is changed. Therefore, + * {@link #setDefaultFactory(InternalLoggerFactory)} should be called as early + * as possible and shouldn't be called more than once. + */ +public abstract class InternalLoggerFactory { + private static volatile InternalLoggerFactory defaultFactory = + newDefaultFactory(InternalLoggerFactory.class.getName()); + +// + private static InternalLoggerFactory newDefaultFactory(String name) { + InternalLoggerFactory f; +// try { +// f = new Slf4JLoggerFactory(true); +// f.newInstance(name).debug("Using SLF4J as the default logging framework"); +// } catch (Throwable t1) { +// try { +// f = new Log4JLoggerFactory(); +// f.newInstance(name).debug("Using Log4J as the default logging framework"); +// } catch (Throwable t2) { + f = new JdkLoggerFactory(); + f.newInstance(name).debug("Using java.util.logging as the default logging framework"); +// } +// } + return f; + } + + /** + * Returns the default factory. The initial default factory is + * {@link JdkLoggerFactory}. + */ + public static InternalLoggerFactory getDefaultFactory() { + return defaultFactory; + } + + /** + * Changes the default factory. + */ + public static void setDefaultFactory(InternalLoggerFactory defaultFactory) { + if (defaultFactory == null) { + throw new NullPointerException("defaultFactory"); + } + InternalLoggerFactory.defaultFactory = defaultFactory; + } + + /** + * Creates a new logger instance with the name of the specified class. + */ + public static InternalLogger getInstance(Class clazz) { + return getInstance(clazz.getName()); + } + + /** + * Creates a new logger instance with the specified name. + */ + public static InternalLogger getInstance(String name) { + return getDefaultFactory().newInstance(name); + } + + /** + * Creates a new logger instance with the specified name. + */ + protected abstract InternalLogger newInstance(String name); +} diff --git a/common/src/main/java/common/net/util/internal/logging/JdkLogger.java b/common/src/main/java/common/net/util/internal/logging/JdkLogger.java new file mode 100644 index 0000000..a0e69f6 --- /dev/null +++ b/common/src/main/java/common/net/util/internal/logging/JdkLogger.java @@ -0,0 +1,647 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package common.net.util.internal.logging; + +import java.util.logging.Level; +import java.util.logging.LogRecord; +import java.util.logging.Logger; + +/** + * java.util.logging + * logger. + */ +class JdkLogger extends AbstractInternalLogger { + + private static final long serialVersionUID = -1767272577989225979L; + + final transient Logger logger; + + JdkLogger(Logger logger) { + super(logger.getName()); + this.logger = logger; + } + + /** + * Is this logger instance enabled for the FINEST level? + * + * @return True if this Logger is enabled for level FINEST, false otherwise. + */ + @Override + public boolean isTraceEnabled() { + return logger.isLoggable(Level.FINEST); + } + + /** + * Log a message object at level FINEST. + * + * @param msg + * - the message object to be logged + */ + @Override + public void trace(String msg) { + if (logger.isLoggable(Level.FINEST)) { + log(SELF, Level.FINEST, msg, null); + } + } + + /** + * Log a message at level FINEST according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for level FINEST. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + @Override + public void trace(String format, Object arg) { + if (logger.isLoggable(Level.FINEST)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level FINEST according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the FINEST level. + *

+ * + * @param format + * the format string + * @param argA + * the first argument + * @param argB + * the second argument + */ + @Override + public void trace(String format, Object argA, Object argB) { + if (logger.isLoggable(Level.FINEST)) { + FormattingTuple ft = MessageFormatter.format(format, argA, argB); + log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level FINEST according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the FINEST level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + @Override + public void trace(String format, Object... argArray) { + if (logger.isLoggable(Level.FINEST)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.FINEST, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at level FINEST with an accompanying message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + @Override + public void trace(String msg, Throwable t) { + if (logger.isLoggable(Level.FINEST)) { + log(SELF, Level.FINEST, msg, t); + } + } + + /** + * Is this logger instance enabled for the FINE level? + * + * @return True if this Logger is enabled for level FINE, false otherwise. + */ + @Override + public boolean isDebugEnabled() { + return logger.isLoggable(Level.FINE); + } + + /** + * Log a message object at level FINE. + * + * @param msg + * - the message object to be logged + */ + @Override + public void debug(String msg) { + if (logger.isLoggable(Level.FINE)) { + log(SELF, Level.FINE, msg, null); + } + } + + /** + * Log a message at level FINE according to the specified format and argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for level FINE. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + @Override + public void debug(String format, Object arg) { + if (logger.isLoggable(Level.FINE)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level FINE according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the FINE level. + *

+ * + * @param format + * the format string + * @param argA + * the first argument + * @param argB + * the second argument + */ + @Override + public void debug(String format, Object argA, Object argB) { + if (logger.isLoggable(Level.FINE)) { + FormattingTuple ft = MessageFormatter.format(format, argA, argB); + log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level FINE according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the FINE level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + @Override + public void debug(String format, Object... argArray) { + if (logger.isLoggable(Level.FINE)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.FINE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at level FINE with an accompanying message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + @Override + public void debug(String msg, Throwable t) { + if (logger.isLoggable(Level.FINE)) { + log(SELF, Level.FINE, msg, t); + } + } + + /** + * Is this logger instance enabled for the INFO level? + * + * @return True if this Logger is enabled for the INFO level, false otherwise. + */ + @Override + public boolean isInfoEnabled() { + return logger.isLoggable(Level.INFO); + } + + /** + * Log a message object at the INFO level. + * + * @param msg + * - the message object to be logged + */ + @Override + public void info(String msg) { + if (logger.isLoggable(Level.INFO)) { + log(SELF, Level.INFO, msg, null); + } + } + + /** + * Log a message at level INFO according to the specified format and argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + @Override + public void info(String format, Object arg) { + if (logger.isLoggable(Level.INFO)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at the INFO level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param argA + * the first argument + * @param argB + * the second argument + */ + @Override + public void info(String format, Object argA, Object argB) { + if (logger.isLoggable(Level.INFO)) { + FormattingTuple ft = MessageFormatter.format(format, argA, argB); + log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level INFO according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the INFO level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + @Override + public void info(String format, Object... argArray) { + if (logger.isLoggable(Level.INFO)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.INFO, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at the INFO level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + @Override + public void info(String msg, Throwable t) { + if (logger.isLoggable(Level.INFO)) { + log(SELF, Level.INFO, msg, t); + } + } + + /** + * Is this logger instance enabled for the WARNING level? + * + * @return True if this Logger is enabled for the WARNING level, false + * otherwise. + */ + @Override + public boolean isWarnEnabled() { + return logger.isLoggable(Level.WARNING); + } + + /** + * Log a message object at the WARNING level. + * + * @param msg + * - the message object to be logged + */ + @Override + public void warn(String msg) { + if (logger.isLoggable(Level.WARNING)) { + log(SELF, Level.WARNING, msg, null); + } + } + + /** + * Log a message at the WARNING level according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARNING level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + @Override + public void warn(String format, Object arg) { + if (logger.isLoggable(Level.WARNING)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at the WARNING level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARNING level. + *

+ * + * @param format + * the format string + * @param argA + * the first argument + * @param argB + * the second argument + */ + @Override + public void warn(String format, Object argA, Object argB) { + if (logger.isLoggable(Level.WARNING)) { + FormattingTuple ft = MessageFormatter.format(format, argA, argB); + log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level WARNING according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the WARNING level. + *

+ * + * @param format + * the format string + * @param argArray + * an array of arguments + */ + @Override + public void warn(String format, Object... argArray) { + if (logger.isLoggable(Level.WARNING)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); + log(SELF, Level.WARNING, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at the WARNING level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + @Override + public void warn(String msg, Throwable t) { + if (logger.isLoggable(Level.WARNING)) { + log(SELF, Level.WARNING, msg, t); + } + } + + /** + * Is this logger instance enabled for level SEVERE? + * + * @return True if this Logger is enabled for level SEVERE, false otherwise. + */ + @Override + public boolean isErrorEnabled() { + return logger.isLoggable(Level.SEVERE); + } + + /** + * Log a message object at the SEVERE level. + * + * @param msg + * - the message object to be logged + */ + @Override + public void error(String msg) { + if (logger.isLoggable(Level.SEVERE)) { + log(SELF, Level.SEVERE, msg, null); + } + } + + /** + * Log a message at the SEVERE level according to the specified format and + * argument. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the SEVERE level. + *

+ * + * @param format + * the format string + * @param arg + * the argument + */ + @Override + public void error(String format, Object arg) { + if (logger.isLoggable(Level.SEVERE)) { + FormattingTuple ft = MessageFormatter.format(format, arg); + log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at the SEVERE level according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the SEVERE level. + *

+ * + * @param format + * the format string + * @param argA + * the first argument + * @param argB + * the second argument + */ + @Override + public void error(String format, Object argA, Object argB) { + if (logger.isLoggable(Level.SEVERE)) { + FormattingTuple ft = MessageFormatter.format(format, argA, argB); + log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log a message at level SEVERE according to the specified format and + * arguments. + * + *

+ * This form avoids superfluous object creation when the logger is disabled + * for the SEVERE level. + *

+ * + * @param format + * the format string + * @param arguments + * an array of arguments + */ + @Override + public void error(String format, Object... arguments) { + if (logger.isLoggable(Level.SEVERE)) { + FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); + log(SELF, Level.SEVERE, ft.getMessage(), ft.getThrowable()); + } + } + + /** + * Log an exception (throwable) at the SEVERE level with an accompanying + * message. + * + * @param msg + * the message accompanying the exception + * @param t + * the exception (throwable) to log + */ + @Override + public void error(String msg, Throwable t) { + if (logger.isLoggable(Level.SEVERE)) { + log(SELF, Level.SEVERE, msg, t); + } + } + + /** + * Log the message at the specified level with the specified throwable if any. + * This method creates a LogRecord and fills in caller date before calling + * this instance's JDK14 logger. + * + * See bug report #13 for more details. + */ + private void log(String callerFQCN, Level level, String msg, Throwable t) { + // millis and thread are filled by the constructor + LogRecord record = new LogRecord(level, msg); + record.setLoggerName(name()); + record.setThrown(t); + fillCallerData(callerFQCN, record); + logger.log(record); + } + + static final String SELF = JdkLogger.class.getName(); + static final String SUPER = AbstractInternalLogger.class.getName(); + + /** + * Fill in caller data if possible. + * + * @param record + * The record to update + */ + private static void fillCallerData(String callerFQCN, LogRecord record) { + StackTraceElement[] steArray = new Throwable().getStackTrace(); + + int selfIndex = -1; + for (int i = 0; i < steArray.length; i++) { + final String className = steArray[i].getClassName(); + if (className.equals(callerFQCN) || className.equals(SUPER)) { + selfIndex = i; + break; + } + } + + int found = -1; + for (int i = selfIndex + 1; i < steArray.length; i++) { + final String className = steArray[i].getClassName(); + if (!(className.equals(callerFQCN) || className.equals(SUPER))) { + found = i; + break; + } + } + + if (found != -1) { + StackTraceElement ste = steArray[found]; + // setting the class name has the side effect of setting + // the needToInferCaller variable to false. + record.setSourceClassName(ste.getClassName()); + record.setSourceMethodName(ste.getMethodName()); + } + } +} diff --git a/common/src/main/java/common/net/util/internal/logging/JdkLoggerFactory.java b/common/src/main/java/common/net/util/internal/logging/JdkLoggerFactory.java new file mode 100644 index 0000000..a1e88dd --- /dev/null +++ b/common/src/main/java/common/net/util/internal/logging/JdkLoggerFactory.java @@ -0,0 +1,32 @@ +/* + * Copyright 2012 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +package common.net.util.internal.logging; + + +import java.util.logging.Logger; + +/** + * Logger factory which creates a + * java.util.logging + * logger. + */ +public class JdkLoggerFactory extends InternalLoggerFactory { + + @Override + public InternalLogger newInstance(String name) { + return new JdkLogger(Logger.getLogger(name)); + } +} diff --git a/common/src/main/java/common/net/util/internal/logging/MessageFormatter.java b/common/src/main/java/common/net/util/internal/logging/MessageFormatter.java new file mode 100644 index 0000000..a1e956a --- /dev/null +++ b/common/src/main/java/common/net/util/internal/logging/MessageFormatter.java @@ -0,0 +1,427 @@ +/* + * Copyright 2013 The Netty Project + * + * The Netty Project licenses this file to you under the Apache License, + * version 2.0 (the "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at: + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations + * under the License. + */ +/** + * Copyright (c) 2004-2011 QOS.ch + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * + * The above copyright notice and this permission notice shall be + * included in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND + * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE + * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION + * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION + * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + * + */ +package common.net.util.internal.logging; + +import java.util.HashMap; +import java.util.Map; + +// contributors: lizongbo: proposed special treatment of array parameter values +// Joern Huxhorn: pointed out double[] omission, suggested deep array copy + +/** + * Formats messages according to very simple substitution rules. Substitutions + * can be made 1, 2 or more arguments. + *

+ *

+ * For example, + *

+ *

+ * MessageFormatter.format("Hi {}.", "there")
+ * 
+ *

+ * will return the string "Hi there.". + *

+ * The {} pair is called the formatting anchor. It serves to designate + * the location where arguments need to be substituted within the message + * pattern. + *

+ * In case your message contains the '{' or the '}' character, you do not have + * to do anything special unless the '}' character immediately follows '{'. For + * example, + *

+ *

+ * MessageFormatter.format("Set {1,2,3} is not equal to {}.", "1,2");
+ * 
+ *

+ * will return the string "Set {1,2,3} is not equal to 1,2.". + *

+ *

+ * If for whatever reason you need to place the string "{}" in the message + * without its formatting anchor meaning, then you need to escape the + * '{' character with '\', that is the backslash character. Only the '{' + * character should be escaped. There is no need to escape the '}' character. + * For example, + *

+ *

+ * MessageFormatter.format("Set \\{} is not equal to {}.", "1,2");
+ * 
+ *

+ * will return the string "Set {} is not equal to 1,2.". + *

+ *

+ * The escaping behavior just described can be overridden by escaping the escape + * character '\'. Calling + *

+ *

+ * MessageFormatter.format("File name is C:\\\\{}.", "file.zip");
+ * 
+ *

+ * will return the string "File name is C:\file.zip". + *

+ *

+ * The formatting conventions are different than those of {@link MessageFormat} + * which ships with the Java platform. This is justified by the fact that + * SLF4J's implementation is 10 times faster than that of {@link MessageFormat}. + * This local performance difference is both measurable and significant in the + * larger context of the complete logging processing chain. + *

+ *

+ * See also {@link #format(String, Object)}, + * {@link #format(String, Object, Object)} and + * {@link #arrayFormat(String, Object[])} methods for more details. + */ +final class MessageFormatter { + static final char DELIM_START = '{'; + static final char DELIM_STOP = '}'; + static final String DELIM_STR = "{}"; + private static final char ESCAPE_CHAR = '\\'; + + /** + * Performs single argument substitution for the 'messagePattern' passed as + * parameter. + *

+ * For example, + *

+ *

+     * MessageFormatter.format("Hi {}.", "there");
+     * 
+ *

+ * will return the string "Hi there.". + *

+ * + * @param messagePattern The message pattern which will be parsed and formatted + * @param arg The argument to be substituted in place of the formatting anchor + * @return The formatted message + */ + static FormattingTuple format(String messagePattern, Object arg) { + return arrayFormat(messagePattern, new Object[]{arg}); + } + + /** + * Performs a two argument substitution for the 'messagePattern' passed as + * parameter. + *

+ * For example, + *

+ *

+     * MessageFormatter.format("Hi {}. My name is {}.", "Alice", "Bob");
+     * 
+ *

+ * will return the string "Hi Alice. My name is Bob.". + * + * @param messagePattern The message pattern which will be parsed and formatted + * @param argA The argument to be substituted in place of the first formatting + * anchor + * @param argB The argument to be substituted in place of the second formatting + * anchor + * @return The formatted message + */ + static FormattingTuple format(final String messagePattern, + Object argA, Object argB) { + return arrayFormat(messagePattern, new Object[]{argA, argB}); + } + + static Throwable getThrowableCandidate(Object[] argArray) { + if (argArray == null || argArray.length == 0) { + return null; + } + + final Object lastEntry = argArray[argArray.length - 1]; + if (lastEntry instanceof Throwable) { + return (Throwable) lastEntry; + } + return null; + } + + /** + * Same principle as the {@link #format(String, Object)} and + * {@link #format(String, Object, Object)} methods except that any number of + * arguments can be passed in an array. + * + * @param messagePattern The message pattern which will be parsed and formatted + * @param argArray An array of arguments to be substituted in place of formatting + * anchors + * @return The formatted message + */ + static FormattingTuple arrayFormat(final String messagePattern, + final Object[] argArray) { + + Throwable throwableCandidate = getThrowableCandidate(argArray); + + if (messagePattern == null) { + return new FormattingTuple(null, argArray, throwableCandidate); + } + + if (argArray == null) { + return new FormattingTuple(messagePattern); + } + + int i = 0; + int j; + StringBuffer sbuf = new StringBuffer(messagePattern.length() + 50); + + int L; + for (L = 0; L < argArray.length; L++) { + + j = messagePattern.indexOf(DELIM_STR, i); + + if (j == -1) { + // no more variables + if (i == 0) { // this is a simple string + return new FormattingTuple(messagePattern, argArray, + throwableCandidate); + } else { // add the tail string which contains no variables and return + // the result. + sbuf.append(messagePattern.substring(i, messagePattern.length())); + return new FormattingTuple(sbuf.toString(), argArray, + throwableCandidate); + } + } else { + if (isEscapedDelimeter(messagePattern, j)) { + if (!isDoubleEscaped(messagePattern, j)) { + L--; // DELIM_START was escaped, thus should not be incremented + sbuf.append(messagePattern.substring(i, j - 1)); + sbuf.append(DELIM_START); + i = j + 1; + } else { + // The escape character preceding the delimiter start is + // itself escaped: "abc x:\\{}" + // we have to consume one backward slash + sbuf.append(messagePattern.substring(i, j - 1)); + deeplyAppendParameter(sbuf, argArray[L], new HashMap()); + i = j + 2; + } + } else { + // normal case + sbuf.append(messagePattern.substring(i, j)); + deeplyAppendParameter(sbuf, argArray[L], new HashMap()); + i = j + 2; + } + } + } + // append the characters following the last {} pair. + sbuf.append(messagePattern.substring(i, messagePattern.length())); + if (L < argArray.length - 1) { + return new FormattingTuple(sbuf.toString(), argArray, throwableCandidate); + } else { + return new FormattingTuple(sbuf.toString(), argArray, null); + } + } + + static boolean isEscapedDelimeter(String messagePattern, + int delimeterStartIndex) { + + if (delimeterStartIndex == 0) { + return false; + } + return messagePattern.charAt(delimeterStartIndex - 1) == ESCAPE_CHAR; + } + + static boolean isDoubleEscaped(String messagePattern, + int delimeterStartIndex) { + return delimeterStartIndex >= 2 && messagePattern.charAt(delimeterStartIndex - 2) == ESCAPE_CHAR; + } + + // special treatment of array values was suggested by 'lizongbo' + private static void deeplyAppendParameter(StringBuffer sbuf, Object o, + Map seenMap) { + if (o == null) { + sbuf.append("null"); + return; + } + if (!o.getClass().isArray()) { + safeObjectAppend(sbuf, o); + } else { + // check for primitive array types because they + // unfortunately cannot be cast to Object[] + if (o instanceof boolean[]) { + booleanArrayAppend(sbuf, (boolean[]) o); + } else if (o instanceof byte[]) { + byteArrayAppend(sbuf, (byte[]) o); + } else if (o instanceof char[]) { + charArrayAppend(sbuf, (char[]) o); + } else if (o instanceof short[]) { + shortArrayAppend(sbuf, (short[]) o); + } else if (o instanceof int[]) { + intArrayAppend(sbuf, (int[]) o); + } else if (o instanceof long[]) { + longArrayAppend(sbuf, (long[]) o); + } else if (o instanceof float[]) { + floatArrayAppend(sbuf, (float[]) o); + } else if (o instanceof double[]) { + doubleArrayAppend(sbuf, (double[]) o); + } else { + objectArrayAppend(sbuf, (Object[]) o, seenMap); + } + } + } + + private static void safeObjectAppend(StringBuffer sbuf, Object o) { + try { + String oAsString = o.toString(); + sbuf.append(oAsString); + } catch (Throwable t) { + System.err + .println("SLF4J: Failed toString() invocation on an object of type [" + + o.getClass().getName() + ']'); + t.printStackTrace(); + sbuf.append("[FAILED toString()]"); + } + } + + private static void objectArrayAppend(StringBuffer sbuf, Object[] a, + Map seenMap) { + sbuf.append('['); + if (!seenMap.containsKey(a)) { + seenMap.put(a, null); + final int len = a.length; + for (int i = 0; i < len; i++) { + deeplyAppendParameter(sbuf, a[i], seenMap); + if (i != len - 1) { + sbuf.append(", "); + } + } + // allow repeats in siblings + seenMap.remove(a); + } else { + sbuf.append("..."); + } + sbuf.append(']'); + } + + private static void booleanArrayAppend(StringBuffer sbuf, boolean[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) { + sbuf.append(", "); + } + } + sbuf.append(']'); + } + + private static void byteArrayAppend(StringBuffer sbuf, byte[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) { + sbuf.append(", "); + } + } + sbuf.append(']'); + } + + private static void charArrayAppend(StringBuffer sbuf, char[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) { + sbuf.append(", "); + } + } + sbuf.append(']'); + } + + private static void shortArrayAppend(StringBuffer sbuf, short[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) { + sbuf.append(", "); + } + } + sbuf.append(']'); + } + + private static void intArrayAppend(StringBuffer sbuf, int[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) { + sbuf.append(", "); + } + } + sbuf.append(']'); + } + + private static void longArrayAppend(StringBuffer sbuf, long[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) { + sbuf.append(", "); + } + } + sbuf.append(']'); + } + + private static void floatArrayAppend(StringBuffer sbuf, float[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) { + sbuf.append(", "); + } + } + sbuf.append(']'); + } + + private static void doubleArrayAppend(StringBuffer sbuf, double[] a) { + sbuf.append('['); + final int len = a.length; + for (int i = 0; i < len; i++) { + sbuf.append(a[i]); + if (i != len - 1) { + sbuf.append(", "); + } + } + sbuf.append(']'); + } + + private MessageFormatter() { + } +} diff --git a/common/src/main/java/common/network/CompressionDecoder.java b/common/src/main/java/common/network/CompressionDecoder.java new file mode 100755 index 0000000..702aa11 --- /dev/null +++ b/common/src/main/java/common/network/CompressionDecoder.java @@ -0,0 +1,47 @@ +package common.network; + +import java.util.List; +import java.util.zip.DataFormatException; +import java.util.zip.Inflater; + +import common.net.buffer.ByteBuf; +import common.net.buffer.Unpooled; +import common.net.channel.ChannelHandlerContext; +import common.net.handler.codec.ByteToMessageDecoder; +import common.net.handler.codec.DecoderException; + +public class CompressionDecoder extends ByteToMessageDecoder { + private final Inflater inflater; + private int treshold; + + public CompressionDecoder(int treshold) { + this.treshold = treshold; + this.inflater = new Inflater(); + } + + protected void decode(ChannelHandlerContext context, ByteBuf buffer, List output) throws DataFormatException, Exception { + if(buffer.readableBytes() == 0) + return; + PacketBuffer pbuf = new PacketBuffer(buffer); + int len = pbuf.readVarInt(); + if(len == 0) { + output.add(pbuf.readBytes(pbuf.readableBytes())); + return; + } + if(len < this.treshold) + throw new DecoderException("Badly compressed packet - size of " + len + " is below server threshold of " + this.treshold); + if(len > 20971520) + throw new DecoderException("Badly compressed packet - size of " + len + " is larger than protocol maximum of " + 20971520); + byte[] comp = new byte[pbuf.readableBytes()]; + pbuf.readBytes(comp); + this.inflater.setInput(comp); + byte[] data = new byte[len]; + this.inflater.inflate(data); + output.add(Unpooled.wrappedBuffer(data)); + this.inflater.reset(); + } + + public void setTreshold(int treshold) { + this.treshold = treshold; + } +} diff --git a/common/src/main/java/common/network/CompressionEncoder.java b/common/src/main/java/common/network/CompressionEncoder.java new file mode 100755 index 0000000..c2cf62f --- /dev/null +++ b/common/src/main/java/common/network/CompressionEncoder.java @@ -0,0 +1,42 @@ +package common.network; + +import java.util.zip.Deflater; + +import common.net.buffer.ByteBuf; +import common.net.channel.ChannelHandlerContext; +import common.net.handler.codec.MessageToByteEncoder; + +public class CompressionEncoder extends MessageToByteEncoder { + private final byte[] buffer = new byte[8192]; + private final Deflater deflater; + private int treshold; + + public CompressionEncoder(int treshold) { + this.treshold = treshold; + this.deflater = new Deflater(); + } + + protected void encode(ChannelHandlerContext context, ByteBuf buffer, ByteBuf output) throws Exception { + int len = buffer.readableBytes(); + PacketBuffer pbuf = new PacketBuffer(output); + if(len < this.treshold) { + pbuf.writeVarInt(0); + pbuf.writeBuffer(buffer); + return; + } + byte[] data = new byte[len]; + buffer.readBytes(data); + pbuf.writeVarInt(data.length); + this.deflater.setInput(data, 0, len); + this.deflater.finish(); + while(!this.deflater.finished()) { + int size = this.deflater.deflate(this.buffer); + pbuf.writeBytes(this.buffer, 0, size); + } + this.deflater.reset(); + } + + public void setTreshold(int treshold) { + this.treshold = treshold; + } +} diff --git a/common/src/main/java/common/network/EncryptionCodec.java b/common/src/main/java/common/network/EncryptionCodec.java new file mode 100644 index 0000000..4a6d981 --- /dev/null +++ b/common/src/main/java/common/network/EncryptionCodec.java @@ -0,0 +1,42 @@ +package common.network; + +import javax.crypto.Cipher; +import javax.crypto.ShortBufferException; + +import common.net.buffer.ByteBuf; +import common.net.channel.ChannelHandlerContext; + +public class EncryptionCodec { + private final Cipher cipher; + private byte[] receiveBuf = new byte[0]; + private byte[] encodeBuf = new byte[0]; + + protected EncryptionCodec(Cipher cipher) { + this.cipher = cipher; + } + + private byte[] readBuffer(ByteBuf buf) { + int size = buf.readableBytes(); + if(this.receiveBuf.length < size) + this.receiveBuf = new byte[size]; + buf.readBytes((byte[])this.receiveBuf, 0, size); + return this.receiveBuf; + } + + protected ByteBuf decipher(ChannelHandlerContext ctx, ByteBuf buffer) throws ShortBufferException { + int size = buffer.readableBytes(); + byte[] data = this.readBuffer(buffer); + ByteBuf buf = ctx.alloc().heapBuffer(this.cipher.getOutputSize(size)); + buf.writerIndex(this.cipher.update(data, 0, size, buf.array(), buf.arrayOffset())); + return buf; + } + + protected void cipher(ByteBuf in, ByteBuf out) throws ShortBufferException { + int size = in.readableBytes(); + byte[] data = this.readBuffer(in); + int csize = this.cipher.getOutputSize(size); + if(this.encodeBuf.length < csize) + this.encodeBuf = new byte[csize]; + out.writeBytes((byte[])this.encodeBuf, 0, this.cipher.update(data, 0, size, this.encodeBuf)); + } +} diff --git a/common/src/main/java/common/network/EncryptionDecoder.java b/common/src/main/java/common/network/EncryptionDecoder.java new file mode 100644 index 0000000..7c4bdb8 --- /dev/null +++ b/common/src/main/java/common/network/EncryptionDecoder.java @@ -0,0 +1,21 @@ +package common.network; + +import java.util.List; +import javax.crypto.Cipher; +import javax.crypto.ShortBufferException; + +import common.net.buffer.ByteBuf; +import common.net.channel.ChannelHandlerContext; +import common.net.handler.codec.MessageToMessageDecoder; + +public class EncryptionDecoder extends MessageToMessageDecoder { + private final EncryptionCodec codec; + + public EncryptionDecoder(Cipher cipher) { + this.codec = new EncryptionCodec(cipher); + } + + protected void decode(ChannelHandlerContext context, ByteBuf buffer, List output) throws ShortBufferException, Exception { + output.add(this.codec.decipher(context, buffer)); + } +} diff --git a/common/src/main/java/common/network/EncryptionEncoder.java b/common/src/main/java/common/network/EncryptionEncoder.java new file mode 100644 index 0000000..522c815 --- /dev/null +++ b/common/src/main/java/common/network/EncryptionEncoder.java @@ -0,0 +1,20 @@ +package common.network; + +import javax.crypto.Cipher; +import javax.crypto.ShortBufferException; + +import common.net.buffer.ByteBuf; +import common.net.channel.ChannelHandlerContext; +import common.net.handler.codec.MessageToByteEncoder; + +public class EncryptionEncoder extends MessageToByteEncoder { + private final EncryptionCodec codec; + + public EncryptionEncoder(Cipher cipher) { + this.codec = new EncryptionCodec(cipher); + } + + protected void encode(ChannelHandlerContext context, ByteBuf buffer, ByteBuf output) throws ShortBufferException, Exception { + this.codec.cipher(buffer, output); + } +} diff --git a/common/src/main/java/common/network/IClientLoginHandler.java b/common/src/main/java/common/network/IClientLoginHandler.java new file mode 100644 index 0000000..4048077 --- /dev/null +++ b/common/src/main/java/common/network/IClientLoginHandler.java @@ -0,0 +1,19 @@ +package common.network; + +import common.packet.RPacketChallenge; +import common.packet.RPacketDisconnect; +import common.packet.RPacketEnableCompression; +import common.packet.RPacketLoginSuccess; +import common.packet.RPacketRequestEncrypt; +import common.packet.RPacketResponse; +import common.packet.RPacketServerConfig; + +public interface IClientLoginHandler extends NetHandler { + void handleDisconnect(RPacketDisconnect packet); + void handleLoginSuccess(RPacketLoginSuccess packet); + void handleEnableCompression(RPacketEnableCompression packet); + void handleEncrypt(RPacketRequestEncrypt packet); + void handleConfig(RPacketServerConfig packet); + void handleResponse(RPacketResponse packet); + void handleChallenge(RPacketChallenge packet); +} diff --git a/common/src/main/java/common/network/IClientPlayer.java b/common/src/main/java/common/network/IClientPlayer.java new file mode 100644 index 0000000..da6a2bc --- /dev/null +++ b/common/src/main/java/common/network/IClientPlayer.java @@ -0,0 +1,143 @@ +package common.network; + +import common.entity.Entity; +import common.model.ParticleType; +import common.packet.SPacketEntity; +import common.packet.SPacketEntityTeleport; +import common.packet.SPacketEntityHeadLook; +import common.packet.SPacketEntityStatus; +import common.packet.SPacketEntityAttach; +import common.packet.SPacketEntityMetadata; +import common.packet.SPacketEntityEffect; +import common.packet.SPacketRemoveEntityEffect; +import common.packet.SPacketExplosion; +import common.packet.SPacketEffect; +import common.packet.SPacketSoundEffect; +import common.packet.SPacketParticles; +import common.packet.SPacketChangeGameState; +import common.packet.SPacketSpawnGlobalEntity; +import common.packet.SPacketOpenWindow; +import common.packet.SPacketCloseWindow; +import common.packet.SPacketSetSlot; +import common.packet.SPacketWindowItems; +import common.packet.SPacketWindowProperty; +import common.packet.SPacketConfirmTransaction; +import common.packet.SPacketUpdateSign; +import common.packet.SPacketUpdateTileEntity; +import common.packet.SPacketSignEditorOpen; +import common.packet.SPacketPlayerListItem; +import common.packet.SPacketPlayerAbilities; +import common.packet.SPacketTabComplete; +import common.packet.SPacketUpdateEntityTags; +import common.packet.SPacketAnimation; +import common.packet.SPacketBiome; +import common.packet.SPacketBlockAction; +import common.packet.SPacketBlockBreakAnim; +import common.packet.SPacketBlockChange; +import common.packet.SPacketCamera; +import common.packet.SPacketCharacterList; +import common.packet.SPacketChunkData; +import common.packet.SPacketCollectItem; +import common.packet.SPacketDestroyEntities; +import common.packet.SPacketDimensionName; +import common.packet.SPacketDisconnect; +import common.packet.SPacketDisplayForm; +import common.packet.SPacketEntityEquipment; +import common.packet.SPacketEntityVelocity; +import common.packet.SPacketHeldItemChange; +import common.packet.SPacketJoinGame; +import common.packet.SPacketKeepAlive; +import common.packet.SPacketLoading; +import common.packet.SPacketMapChunkBulk; +import common.packet.SPacketMessage; +import common.packet.SPacketMultiBlockChange; +import common.packet.SPacketPlayerPosLook; +import common.packet.SPacketRespawn; +import common.packet.SPacketServerTick; +import common.packet.SPacketSetExperience; +import common.packet.SPacketSkin; +import common.packet.SPacketSpawnMob; +import common.packet.SPacketSpawnObject; +import common.packet.SPacketSpawnPlayer; +import common.packet.SPacketTimeUpdate; +import common.packet.SPacketTrades; +import common.packet.SPacketUpdateHealth; +import common.packet.SPacketWorld; +import common.sound.Sound; + +public interface IClientPlayer extends NetHandler { + void playSound(Sound sound); + boolean isRenderViewEntity(Entity entity); + void updatePlayerMoveState(); + void emitParticleAtEntity(Entity entity, ParticleType particleTypes); + boolean isJumping(); + boolean isSprinting(); + boolean isSneaking(); + float getMoveForward(); + float getMoveStrafe(); + void setMoveForward(float value); + void setMoveStrafe(float value); + void addToSendQueue(Packet packet); + + void handleJoinGame(SPacketJoinGame packet); + void handleSpawnObject(SPacketSpawnObject packet); + void handleSpawnGlobalEntity(SPacketSpawnGlobalEntity packet); + void handleEntityVelocity(SPacketEntityVelocity packet); + void handleEntityMetadata(SPacketEntityMetadata packet); + void handleSpawnPlayer(SPacketSpawnPlayer packet); + void handleEntityTeleport(SPacketEntityTeleport packet); + void handleHeldItemChange(SPacketHeldItemChange packet); + void handleEntityMovement(SPacketEntity packet); + void handleEntityHeadLook(SPacketEntityHeadLook packet); + void handleDestroyEntities(SPacketDestroyEntities packet); + void handlePlayerPosLook(SPacketPlayerPosLook packet); + void handleMultiBlockChange(SPacketMultiBlockChange packet); + void handleChunkData(SPacketChunkData packet); + void handleBiomes(SPacketBiome packet); + void handleBlockChange(SPacketBlockChange packet); + void handleDisconnect(SPacketDisconnect packet); + void handleCollectItem(SPacketCollectItem packet); + void handleMessage(SPacketMessage packet); + void handleLoading(SPacketLoading packet); + void handleAnimation(SPacketAnimation packet); + void handleSpawnMob(SPacketSpawnMob packet); + void handleTimeUpdate(SPacketTimeUpdate packet); + void handleServerTick(SPacketServerTick packet); + void handleEntityAttach(SPacketEntityAttach packet); + void handleEntityStatus(SPacketEntityStatus packet); + void handleUpdateHealth(SPacketUpdateHealth packet); + void handleSetExperience(SPacketSetExperience packet); + void handleRespawn(SPacketRespawn packet); + void handleExplosion(SPacketExplosion packet); + void handleOpenWindow(SPacketOpenWindow packet); + void handleSetSlot(SPacketSetSlot packet); + void handleConfirmTransaction(SPacketConfirmTransaction packet); + void handleWindowItems(SPacketWindowItems packet); + void handleSignEditorOpen(SPacketSignEditorOpen packet); + void handleUpdateSign(SPacketUpdateSign packet); + void handleUpdateTileEntity(SPacketUpdateTileEntity packet); + void handleWindowProperty(SPacketWindowProperty packet); + void handleEntityEquipment(SPacketEntityEquipment packet); + void handleCloseWindow(SPacketCloseWindow packet); + void handleBlockAction(SPacketBlockAction packet); + void handleBlockBreakAnim(SPacketBlockBreakAnim packet); + void handleMapChunkBulk(SPacketMapChunkBulk packet); + void handleChangeGameState(SPacketChangeGameState packet); + void handleEffect(SPacketEffect packet); + void handleEntityEffect(SPacketEntityEffect packet); + void handleCamera(SPacketCamera packet); + void handleRemoveEntityEffect(SPacketRemoveEntityEffect packet); + void handlePlayerListItem(SPacketPlayerListItem packet); + void handleCharacterList(SPacketCharacterList packet); + void handleKeepAlive(SPacketKeepAlive packet); + void handlePlayerAbilities(SPacketPlayerAbilities packet); + void handleTabComplete(SPacketTabComplete packet); + void handleSoundEffect(SPacketSoundEffect packet); + void handleEntityTags(SPacketUpdateEntityTags packet); + void handleParticles(SPacketParticles packet); + void handleSkin(SPacketSkin packet); + void handleTrades(SPacketTrades packet); + void handleWorld(SPacketWorld packet); + void handleDimName(SPacketDimensionName packet); + void handleForm(SPacketDisplayForm packet); +} \ No newline at end of file diff --git a/common/src/main/java/common/network/IHandshakeHandler.java b/common/src/main/java/common/network/IHandshakeHandler.java new file mode 100644 index 0000000..ce6426f --- /dev/null +++ b/common/src/main/java/common/network/IHandshakeHandler.java @@ -0,0 +1,7 @@ +package common.network; + +import common.packet.HPacketHandshake; + +public interface IHandshakeHandler extends NetHandler { + void processHandshake(HPacketHandshake packet); +} diff --git a/common/src/main/java/common/network/ILoginHandler.java b/common/src/main/java/common/network/ILoginHandler.java new file mode 100644 index 0000000..ff5d881 --- /dev/null +++ b/common/src/main/java/common/network/ILoginHandler.java @@ -0,0 +1,15 @@ +package common.network; + +import common.packet.LPacketChallenge; +import common.packet.LPacketPassword; +import common.packet.LPacketPubkey; +import common.packet.LPacketResponse; +import common.packet.LPacketStartEncrypt; + +public interface ILoginHandler extends NetHandler { + void processEncryption(LPacketStartEncrypt packet); + void processPassword(LPacketPassword packet); + void processPubkey(LPacketPubkey packet); + void processResponse(LPacketResponse packet); + void processChallenge(LPacketChallenge packet); +} diff --git a/common/src/main/java/common/network/IPlayer.java b/common/src/main/java/common/network/IPlayer.java new file mode 100644 index 0000000..41d069e --- /dev/null +++ b/common/src/main/java/common/network/IPlayer.java @@ -0,0 +1,121 @@ +package common.network; + +import java.util.List; + +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.SoundEvent; +import common.inventory.Container; +import common.inventory.IInventory; +import common.item.ItemStack; +import common.packet.CPacketAction; +import common.packet.CPacketBreak; +import common.packet.CPacketCheat; +import common.packet.CPacketClick; +import common.packet.CPacketComplete; +import common.packet.CPacketForm; +import common.packet.CPacketInput; +import common.packet.CPacketKeepAlive; +import common.packet.CPacketMessage; +import common.packet.CPacketPlace; +import common.packet.CPacketPlayer; +import common.packet.CPacketSign; +import common.packet.CPacketSkin; +import common.potion.PotionEffect; +import common.tileentity.IInteractionObject; +import common.tileentity.TileEntitySign; +import common.util.BlockPos; +import common.util.CharValidator; +import common.util.ChunkPos; +import common.util.PortalType; + +public interface IPlayer extends NetHandler { + public static class UserValidator implements CharValidator { + public boolean valid(char ch) { + return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-'; + } + } + + public static class NickValidator implements CharValidator { + public boolean valid(char ch) { + return (ch <= 0xff && Character.isLetterOrDigit(ch)) || (ch >= 32 && ch < 126); + } + } + + public static final int MAX_USER_LENGTH = 16; + public static final int MAX_NICK_LENGTH = 32; + public static final int MAX_PASS_LENGTH = 64; + public static final int MAX_CMD_LENGTH = 1024; + public static final int MAX_INFO_LENGTH = 4096; + public static final int MAX_SKIN_SIZE = 65536; + public static final CharValidator VALID_USER = new IPlayer.UserValidator(); + public static final CharValidator VALID_NICK = new IPlayer.NickValidator(); + + public static boolean isValidNick(String user) { + return VALID_NICK.valid(user); + } + + public static boolean isValidUser(String user) { + return VALID_USER.valid(user); + } + + void onEntityDeath(); + boolean isInEditor(); + EntityNPC getPresentEntity(); + String getUser(); + int getLatency(); + boolean isAdmin(); + void addToPlayerScore(EntityLiving entity); + void displayTradeGui(EntityNPC entity); + void setPlayerHealthUpdated(); + void removeEntity(Entity entity); + void sendPlayerAbilities(); + void addFeed(String msg); + void addHotbar(String msg); + void addHotbar(String format, Object... args); + void sendThrowMessage(ItemStack stack); + void resetLastExperience(); + void travelToDimension(int dimension, BlockPos pos, float yaw, float pitch, PortalType portal); + void teleport(double x, double y, double z, float yaw, float pitch, int dimension); + void onItemPickup(Entity entity, int amount); + void mountEntity(Entity entity); + void openEditSign(TileEntitySign signTile); + void displayGui(IInteractionObject guiOwner); + void displayGUIChest(IInventory chestInventory); + void displayEntityGui(Entity entity, IInventory inventory); + void closeScreen(); + void onItemUseFinish(); + void onNewEffect(PotionEffect id); + void onChangedEffect(PotionEffect id, boolean added); + void onFinishedEffect(PotionEffect effect); + void setPositionAndUpdate(double x, double y, double z); + void onCriticalHit(Entity entity); + void onEnchantmentCritical(Entity entity); + void updateEffectMeta(); + void playSound(SoundEvent name, float volume); + void sendContainerToPlayer(Container container); + void updateEntity(); + void setSelection(boolean primary, BlockPos pos); + void setSelectMode(); + void sendPacket(Packet packet); + void setPlayerLocation(double x, double y, double z, float yaw, float pitch); + List getLoadedChunkList(); + double getManagedX(); + double getManagedZ(); + void setManagedPos(double x, double z); + + void processKeepAlive(CPacketKeepAlive packet); + void processMessage(CPacketMessage packet); + void processComplete(CPacketComplete packet); + void processPlayer(CPacketPlayer packet); + void processBreak(CPacketBreak packet); + void processPlace(CPacketPlace packet); + void processAction(CPacketAction packet); + void processInput(CPacketInput packet); + void processClick(CPacketClick packet); + void processCheat(CPacketCheat packet); + void processSign(CPacketSign packet); + void processSkin(CPacketSkin packet); + void processForm(CPacketForm packet); +} diff --git a/java/src/game/network/IThreadListener.java b/common/src/main/java/common/network/IThreadListener.java similarity index 59% rename from java/src/game/network/IThreadListener.java rename to common/src/main/java/common/network/IThreadListener.java index 2f19842..646777a 100755 --- a/java/src/game/network/IThreadListener.java +++ b/common/src/main/java/common/network/IThreadListener.java @@ -1,9 +1,8 @@ -package game.network; +package common.network; -import game.future.ListenableFuture; +import common.future.ListenableFuture; -public interface IThreadListener -{ +public interface IThreadListener { ListenableFuture schedule(Runnable run); boolean isMainThread(); default void log(String prefixed, String line) { diff --git a/common/src/main/java/common/network/NetConnection.java b/common/src/main/java/common/network/NetConnection.java new file mode 100755 index 0000000..6a742a1 --- /dev/null +++ b/common/src/main/java/common/network/NetConnection.java @@ -0,0 +1,284 @@ +package common.network; + +import java.io.IOException; +import java.net.SocketAddress; +import java.nio.channels.ClosedChannelException; +import java.util.Queue; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.locks.ReentrantReadWriteLock; +import java.util.regex.Pattern; + +import javax.crypto.Cipher; +import javax.crypto.SecretKey; + +import common.log.Log; +import common.net.channel.Channel; +import common.net.channel.ChannelFuture; +import common.net.channel.ChannelFutureListener; +import common.net.channel.ChannelHandlerContext; +import common.net.channel.SimpleChannelInboundHandler; +import common.net.handler.timeout.TimeoutException; +import common.net.util.AttributeKey; +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; +import common.network.NetHandler.ThreadQuickExitException; +import common.util.EncryptUtil; + +public class NetConnection extends SimpleChannelInboundHandler { + private static final boolean DEBUG = System.getProperty("network.debug") != null; + private static final Pattern IP_REPLACER = Pattern.compile("([0-9]*)\\.([0-9]*)\\.[0-9]*\\.[0-9]*"); + public static final AttributeKey ATTR_STATE = AttributeKey.valueOf("protocol"); + + private final Queue queue = new ConcurrentLinkedQueue(); + private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock(); + + private Channel channel; + private SocketAddress address; + private NetHandler handler; + private String exitReason; + private boolean disconnected; + + public void channelActive(ChannelHandlerContext context) throws Exception { + super.channelActive(context); + this.channel = context.channel(); + this.address = this.channel.remoteAddress(); + + try { + this.setConnectionState(PacketRegistry.HANDSHAKE); + } + catch(Throwable t) { + Log.NETWORK.error(t, "Fehler beim Aufbauen der Verbindung für Handshake"); + } + } + + public void setConnectionState(PacketRegistry newState) { + this.channel.attr(ATTR_STATE).set(newState); + this.channel.config().setAutoRead(true); + if(DEBUG) + Log.NETWORK.info("Automatisches Lesen eingeschaltet"); + } + + public void channelInactive(ChannelHandlerContext context) throws Exception { + this.closeChannel("Ende der Datenübertragung"); + } + + public void exceptionCaught(ChannelHandlerContext context, Throwable throwable) throws Exception { + String comp; + + if(throwable instanceof TimeoutException) { + comp = "Zeitüberschreitung"; + } + else { + comp = "Interner Fehler: " + throwable; + if(!(throwable instanceof ClosedChannelException || throwable instanceof IOException)) + Log.NETWORK.error(throwable, "Fehler in der Verbindung mit %s", this.getCutAddress()); + } + + this.closeChannel(comp); + } + + protected void channelRead0(ChannelHandlerContext context, Packet packet) throws Exception { + if(DEBUG) + Log.NETWORK.info("EIN: [" + context.channel().attr(NetConnection.ATTR_STATE).get() + "] " + packet.getClass().getName()); + if(this.channel.isOpen()) { + try { + packet.processPacket(this.handler); + } + catch(ThreadQuickExitException e) { + ; + } + } + } + + public void setNetHandler(NetHandler handler) { + if(handler == null) { + throw new NullPointerException("Handler ist Null"); + } +// Log.debug("Setze Handler von " + this + " auf " + handler); + this.handler = handler; + } + + public void sendPacket(Packet packet) { + if(this.isChannelOpen()) { + this.flushOutboundQueue(); + this.dispatchPacket(packet, null); + } + else { + this.lock.writeLock().lock(); + + try { + this.queue.add(new NetConnection.InboundHandlerTuplePacketListener(packet, null)); + } + finally { + this.lock.writeLock().unlock(); + } + } + } + + public void sendPacket(Packet packet, GenericFutureListener> listener) { + if(this.isChannelOpen()) { + this.flushOutboundQueue(); + this.dispatchPacket(packet, new GenericFutureListener[] {listener}); + } + else { + this.lock.writeLock().lock(); + + try { + this.queue.add(new NetConnection.InboundHandlerTuplePacketListener(packet, listener)); + } + finally { + this.lock.writeLock().unlock(); + } + } + } + + private void dispatchPacket(final Packet packet, final GenericFutureListener>[] listeners) { + final PacketRegistry state = PacketRegistry.getType(packet); + final PacketRegistry current = this.channel.attr(ATTR_STATE).get(); + + if(current != state) { + if(DEBUG) + Log.NETWORK.info("Automatisches Lesen ausgeschaltet"); + this.channel.config().setAutoRead(false); + } + + if(this.channel.eventLoop().inEventLoop()) { + if(state != current) { + this.setConnectionState(state); + } + + if(DEBUG) + Log.NETWORK.info("AUS: [" + this.channel.attr(NetConnection.ATTR_STATE).get() + "] " + packet.getClass().getName()); + ChannelFuture future = this.channel.writeAndFlush(packet); + + if(listeners != null) { + future.addListeners(listeners); + } + + future.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + } + else { + this.channel.eventLoop().execute(new Runnable() { + public void run() { + if(state != current) { + NetConnection.this.setConnectionState(state); + } + + if(DEBUG) + Log.NETWORK.info("AUS: [" + NetConnection.this.channel.attr(NetConnection.ATTR_STATE).get() + "] " + packet.getClass().getName()); + ChannelFuture future = NetConnection.this.channel.writeAndFlush(packet); + + if(listeners != null) { + future.addListeners(listeners); + } + + future.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); + } + }); + } + } + + private void flushOutboundQueue() { + if(this.channel != null && this.channel.isOpen()) { + this.lock.readLock().lock(); + + try { + while(!this.queue.isEmpty()) { + NetConnection.InboundHandlerTuplePacketListener entry = this.queue.poll(); + if(entry != null) // NPE Fix + this.dispatchPacket(entry.packet, entry.listeners); + } + } + finally { + this.lock.readLock().unlock(); + } + } + } + + public void processReceivedPackets() { + this.flushOutboundQueue(); + this.handler.update(); + if(this.channel != null) + this.channel.flush(); + if(DEBUG) + Log.NETWORK.info("Pakete synchronisiert"); + } + + public String getCutAddress() { + return this.address == null ? "?.?.*.*" : IP_REPLACER.matcher(this.address.toString()).replaceAll("$1.$2.*.*"); + } + + public void closeChannel(String message) { + if(this.channel.isOpen()) { + this.channel.close().awaitUninterruptibly(); + this.exitReason = message; + } + } + + public boolean isChannelOpen() { + return this.channel != null && this.channel.isOpen(); + } + + public boolean hasNoChannel() { + return this.channel == null; + } + + public void disableAutoRead() { + this.channel.config().setAutoRead(false); + } + + public void setCompressionTreshold(int treshold) { + if(treshold >= 0) { + if(this.channel.pipeline().get("decompress") instanceof CompressionDecoder) { + ((CompressionDecoder)this.channel.pipeline().get("decompress")).setTreshold(treshold); + } + else { + this.channel.pipeline().addBefore("decoder", "decompress", new CompressionDecoder(treshold)); + } + + if(this.channel.pipeline().get("compress") instanceof CompressionEncoder) { + ((CompressionEncoder)this.channel.pipeline().get("compress")).setTreshold(treshold); + } + else { + this.channel.pipeline().addBefore("encoder", "compress", new CompressionEncoder(treshold)); + } + } + else { + if(this.channel.pipeline().get("decompress") instanceof CompressionDecoder) { + this.channel.pipeline().remove("decompress"); + } + + if(this.channel.pipeline().get("compress") instanceof CompressionEncoder) { + this.channel.pipeline().remove("compress"); + } + } + } + + public void checkDisconnected() { + if(this.channel != null && !this.channel.isOpen()) { + if(!this.disconnected) { + this.disconnected = true; + if(this.handler != null) + this.handler.onDisconnect(this.exitReason != null ? this.exitReason : "Verbindung getrennt"); + } + else { + Log.NETWORK.warn("handleDisconnection() zweifach aufgerufen"); + } + } + } + + public void startEncryption(SecretKey key) { + this.channel.pipeline().addBefore("splitter", "decrypt", new EncryptionDecoder(EncryptUtil.createCipher(Cipher.DECRYPT_MODE, key))); + this.channel.pipeline().addBefore("prepender", "encrypt", new EncryptionEncoder(EncryptUtil.createCipher(Cipher.ENCRYPT_MODE, key))); + } + + private static class InboundHandlerTuplePacketListener { + private final Packet packet; + private final GenericFutureListener>[] listeners; + + public InboundHandlerTuplePacketListener(Packet packet, GenericFutureListener> listener) { + this.packet = packet; + this.listeners = listener == null ? null : new GenericFutureListener[] {listener}; + } + } +} diff --git a/common/src/main/java/common/network/NetHandler.java b/common/src/main/java/common/network/NetHandler.java new file mode 100755 index 0000000..2d8808b --- /dev/null +++ b/common/src/main/java/common/network/NetHandler.java @@ -0,0 +1,38 @@ +package common.network; + +public interface NetHandler { + public static final class ThreadQuickExitException extends RuntimeException { + private static final ThreadQuickExitException EXIT = new ThreadQuickExitException(); + + private ThreadQuickExitException() { + this.setStackTrace(new StackTraceElement[0]); + } + + public synchronized Throwable fillInStackTrace() { + this.setStackTrace(new StackTraceElement[0]); + return this; + } + } + + void onDisconnect(String reason); + + default void update() { + } + + public static void checkThread(final Packet packet, final T handler, IThreadListener listener) throws ThreadQuickExitException { + if(!listener.isMainThread()) { + listener.schedule(new Runnable() { + public void run() { + packet.processPacket(handler); + } + }); + throw ThreadQuickExitException.EXIT; + } + } + + public static void checkThread(final Packet packet, final T handler, IThreadListener listener, Object check) throws ThreadQuickExitException { + if(check == null && listener.isMainThread()) + throw ThreadQuickExitException.EXIT; + checkThread(packet, handler, listener); + } +} diff --git a/java/src/game/network/Packet.java b/common/src/main/java/common/network/Packet.java similarity index 73% rename from java/src/game/network/Packet.java rename to common/src/main/java/common/network/Packet.java index 2adea92..bc9c9d9 100755 --- a/java/src/game/network/Packet.java +++ b/common/src/main/java/common/network/Packet.java @@ -1,9 +1,8 @@ -package game.network; +package common.network; import java.io.IOException; -public interface Packet -{ +public interface Packet { void readPacketData(PacketBuffer buf) throws IOException; void writePacketData(PacketBuffer buf) throws IOException; void processPacket(T handler); diff --git a/common/src/main/java/common/network/PacketBuffer.java b/common/src/main/java/common/network/PacketBuffer.java new file mode 100755 index 0000000..5de7b2f --- /dev/null +++ b/common/src/main/java/common/network/PacketBuffer.java @@ -0,0 +1,262 @@ +package common.network; + +import java.io.IOException; +import java.nio.charset.Charset; + +import common.init.ItemRegistry; +import common.item.ItemStack; +import common.net.buffer.ByteBuf; +import common.net.buffer.ByteBufInputStream; +import common.net.buffer.ByteBufOutputStream; +import common.net.handler.codec.DecoderException; +import common.net.handler.codec.EncoderException; +import common.tags.TagObject; +import common.util.BlockPos; + +public class PacketBuffer { + private static final Charset UTF_8 = Charset.forName("UTF-8"); + + private final ByteBuf buf; + + public PacketBuffer(ByteBuf wrapped) { + this.buf = wrapped; + } + + public static int getVarIntSize(int input) { + for(int i = 1; i < 5; ++i) { + if((input & -1 << i * 7) == 0) + return i; + } + return 5; + } + + public void writeByteArray(byte[] data) { + this.writeVarInt(data.length); + this.writeBytes(data); + } + + public byte[] readByteArray() { + byte[] data = new byte[this.readVarInt()]; + this.readBytes(data); + return data; + } + + public void writeBlockPos(BlockPos pos) { + this.writeInt(pos.getX()); + this.writeInt(pos.getY()); + this.writeInt(pos.getZ()); + } + + public BlockPos readBlockPos() { + return new BlockPos(this.readInt(), this.readInt(), this.readInt()); + } + + public void writeEnumValue(Enum value) { + this.writeVarInt(value.ordinal()); + } + + public > T readEnumValue(Class clazz) { + return (T)((Enum[])clazz.getEnumConstants())[this.readVarInt()]; + } + + public void writeEnumOrNull(Enum value) { + this.writeVarInt(value == null ? -1 : value.ordinal()); + } + + public > T readEnumOrNull(Class clazz) { + int n = this.readVarInt(); + return n < 0 ? null : (T)((Enum[])clazz.getEnumConstants())[n]; + } + + public void writeVarInt(int value) { + while((value & -128) != 0) { + this.writeByte(value & 127 | 128); + value >>>= 7; + } + this.writeByte(value); + } + + public int readVarInt() { + int v = 0; + int c = 0; + while(true) { + byte b = this.readByte(); + v |= (b & 127) << c++ * 7; + if(c > 5) + throw new RuntimeException("VarInt too big"); + if((b & 128) != 128) + break; + } + return v; + } + + public void writeTag(TagObject tag) { + if(tag == null) { + this.writeByte(0); + return; + } + try { + TagObject.write(tag, new ByteBufOutputStream(this.buf)); + } + catch(IOException e) { + throw new EncoderException(e); + } + } + + public TagObject readTag() throws IOException { + int i = this.buf.readerIndex(); + byte b = this.readByte(); + if(b == 0) + return null; + this.buf.readerIndex(i); + return TagObject.read(new ByteBufInputStream(this.buf), 2097152); + } + + public void writeItemStack(ItemStack stack) { + if(stack == null) { + this.writeShort(-1); + return; + } + this.writeShort(ItemRegistry.getIdFromItem(stack.getItem())); + this.writeVarInt(stack.size); + this.writeShort(stack.getMetadata()); + this.writeTag(stack.getTagCompound()); + } + + public ItemStack readItemStack() throws IOException { + int id = this.readShort(); + if(id < 0) + return null; + int amt = this.readVarInt(); + int meta = this.readShort(); + ItemStack stack = new ItemStack(ItemRegistry.getItemById(id), amt, meta); + stack.setTagCompound(this.readTag()); + return stack; + } + + public void writeString(String str) { + byte[] data = str.getBytes(UTF_8); + if(data.length > 32767) + throw new EncoderException("String too big (was " + str.length() + " bytes encoded, max " + 32767 + ")"); + this.writeVarInt(data.length); + this.writeBytes(data); + } + + public String readString(int limit) { + int len = this.readVarInt(); + if(len > limit * 4) + throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + len + " > " + limit * 4 + ")"); + else if(len < 0) + throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!"); + byte[] data = new byte[len]; + this.readBytes(data); + String str = new String(data, UTF_8); + if(str.length() > limit) + throw new DecoderException("The received string length is longer than maximum allowed (" + len + " > " + limit + ")"); + return str; + } + + public void writeBoolean(boolean value) { + this.buf.writeBoolean(value); + } + + public boolean readBoolean() { + return this.buf.readBoolean(); + } + + public void writeByte(int value) { + this.buf.writeByte(value); + } + + public byte readByte() { + return this.buf.readByte(); + } + + public short readUnsignedByte() { + return this.buf.readUnsignedByte(); + } + + public void writeShort(int value) { + this.buf.writeShort(value); + } + + public short readShort() { + return this.buf.readShort(); + } + + public int readUnsignedShort() { + return this.buf.readUnsignedShort(); + } + + public void writeInt(int value) { + this.buf.writeInt(value); + } + + public int readInt() { + return this.buf.readInt(); + } + + public long readUnsignedInt() { + return this.buf.readUnsignedInt(); + } + + public void writeLong(long value) { + this.buf.writeLong(value); + } + + public long readLong() { + return this.buf.readLong(); + } + + public void writeFloat(float value) { + this.buf.writeFloat(value); + } + + public float readFloat() { + return this.buf.readFloat(); + } + + public void writeDouble(double value) { + this.buf.writeDouble(value); + } + + public double readDouble() { + return this.buf.readDouble(); + } + + public ByteBuf readBytes(int size) { + return this.buf.readBytes(size); + } + + public void writeBytes(byte[] data) { + this.buf.writeBytes(data); + } + + public void readBytes(byte[] buffer) { + this.buf.readBytes(buffer); + } + + public void writeBytes(byte[] data, int offset, int length) { + this.buf.writeBytes(data, offset, length); + } + + public void writeBuffer(ByteBuf buf) { + this.buf.writeBytes(buf); + } + + public void writeBuffer(ByteBuf buf, int offset, int length) { + this.buf.writeBytes(buf, offset, length); + } + + public int readableBytes() { + return this.buf.readableBytes(); + } + + public void ensureWritable(int size) { + this.buf.ensureWritable(size); + } + + public void release() { + this.buf.release(); + } +} diff --git a/common/src/main/java/common/network/PacketDecoder.java b/common/src/main/java/common/network/PacketDecoder.java new file mode 100755 index 0000000..121e34d --- /dev/null +++ b/common/src/main/java/common/network/PacketDecoder.java @@ -0,0 +1,31 @@ +package common.network; + +import java.io.IOException; +import java.util.List; + +import common.net.buffer.ByteBuf; +import common.net.channel.ChannelHandlerContext; +import common.net.handler.codec.ByteToMessageDecoder; + +public class PacketDecoder extends ByteToMessageDecoder { + private final boolean client; + + public PacketDecoder(boolean client) { + this.client = client; + } + + protected void decode(ChannelHandlerContext context, ByteBuf buffer, List output) throws IOException, InstantiationException, IllegalAccessException, Exception { + if(buffer.readableBytes() == 0) + return; + PacketBuffer pbuf = new PacketBuffer(buffer); + int id = pbuf.readVarInt(); + Packet packet = context.channel().attr(NetConnection.ATTR_STATE).get().getPacket(this.client, id); + if(packet == null) + throw new IOException("Ungültige Paket-ID " + id); + packet.readPacketData(pbuf); + if(pbuf.readableBytes() > 0) + throw new IOException("Paket " + ((PacketRegistry)context.channel().attr(NetConnection.ATTR_STATE).get()).ordinal() + "/" + id + " (" + + packet.getClass() + ") war größer als erwartet, " + pbuf.readableBytes() + " weitere Bytes wurden beim Lesen von Paket " + id + " gefunden"); + output.add(packet); + } +} diff --git a/common/src/main/java/common/network/PacketEncoder.java b/common/src/main/java/common/network/PacketEncoder.java new file mode 100755 index 0000000..0f123ef --- /dev/null +++ b/common/src/main/java/common/network/PacketEncoder.java @@ -0,0 +1,29 @@ +package common.network; + +import java.io.IOException; + +import common.net.buffer.ByteBuf; +import common.net.channel.ChannelHandlerContext; +import common.net.handler.codec.MessageToByteEncoder; + +public class PacketEncoder extends MessageToByteEncoder { + private final boolean client; + + public PacketEncoder(boolean client) { + this.client = client; + } + + protected void encode(ChannelHandlerContext context, Packet packet, ByteBuf output) throws IOException, Exception { + Integer id = context.channel().attr(NetConnection.ATTR_STATE).get().getId(this.client, packet); + if(id == null) + throw new IOException("Kann nicht registriertes Paket nicht serialisieren"); + PacketBuffer pbuf = new PacketBuffer(output); + pbuf.writeVarInt(id); + try { + packet.writePacketData(pbuf); + } + catch(Throwable t) { + throw new IOException("Fehler beim Schreiben der Paketdaten", t); + } + } +} diff --git a/common/src/main/java/common/network/PacketPrepender.java b/common/src/main/java/common/network/PacketPrepender.java new file mode 100755 index 0000000..943257c --- /dev/null +++ b/common/src/main/java/common/network/PacketPrepender.java @@ -0,0 +1,18 @@ +package common.network; + +import common.net.buffer.ByteBuf; +import common.net.channel.ChannelHandlerContext; +import common.net.handler.codec.MessageToByteEncoder; + +public class PacketPrepender extends MessageToByteEncoder { + protected void encode(ChannelHandlerContext context, ByteBuf buffer, ByteBuf output) throws Exception { + int len = buffer.readableBytes(); + int vs = PacketBuffer.getVarIntSize(len); + if(vs > 3) + throw new IllegalArgumentException("unable to fit " + len + " into " + 3); + PacketBuffer pbuf = new PacketBuffer(output); + pbuf.ensureWritable(vs + len); + pbuf.writeVarInt(len); + pbuf.writeBuffer(buffer, buffer.readerIndex(), len); + } +} diff --git a/common/src/main/java/common/network/PacketRegistry.java b/common/src/main/java/common/network/PacketRegistry.java new file mode 100755 index 0000000..7467719 --- /dev/null +++ b/common/src/main/java/common/network/PacketRegistry.java @@ -0,0 +1,253 @@ +package common.network; + +import java.lang.reflect.InvocationTargetException; +import java.util.Map; + +import common.collect.BiMap; +import common.collect.HashBiMap; +import common.collect.Maps; +import common.packet.CPacketPlayerPosition; +import common.packet.CPacketPlayerLook; +import common.packet.CPacketPlayerPosLook; +import common.packet.CPacketAction; +import common.packet.CPacketBreak; +import common.packet.CPacketCheat; +import common.packet.CPacketClick; +import common.packet.CPacketComplete; +import common.packet.CPacketForm; +import common.packet.CPacketInput; +import common.packet.CPacketKeepAlive; +import common.packet.CPacketMessage; +import common.packet.CPacketPlace; +import common.packet.CPacketPlayer; +import common.packet.CPacketSign; +import common.packet.CPacketSkin; +import common.packet.HPacketHandshake; +import common.packet.LPacketChallenge; +import common.packet.LPacketPassword; +import common.packet.LPacketPubkey; +import common.packet.LPacketResponse; +import common.packet.LPacketStartEncrypt; +import common.packet.RPacketChallenge; +import common.packet.RPacketDisconnect; +import common.packet.RPacketEnableCompression; +import common.packet.RPacketLoginSuccess; +import common.packet.RPacketRequestEncrypt; +import common.packet.RPacketResponse; +import common.packet.RPacketServerConfig; +import common.packet.SPacketEntityRelMove; +import common.packet.SPacketEntityLook; +import common.packet.SPacketEntityLookMove; +import common.packet.SPacketEntity; +import common.packet.SPacketEntityTeleport; +import common.packet.SPacketEntityHeadLook; +import common.packet.SPacketEntityStatus; +import common.packet.SPacketEntityAttach; +import common.packet.SPacketEntityMetadata; +import common.packet.SPacketEntityEffect; +import common.packet.SPacketRemoveEntityEffect; +import common.packet.SPacketExplosion; +import common.packet.SPacketEffect; +import common.packet.SPacketSoundEffect; +import common.packet.SPacketParticles; +import common.packet.SPacketChangeGameState; +import common.packet.SPacketSpawnGlobalEntity; +import common.packet.SPacketOpenWindow; +import common.packet.SPacketCloseWindow; +import common.packet.SPacketSetSlot; +import common.packet.SPacketWindowItems; +import common.packet.SPacketWindowProperty; +import common.packet.SPacketConfirmTransaction; +import common.packet.SPacketUpdateSign; +import common.packet.SPacketUpdateTileEntity; +import common.packet.SPacketSignEditorOpen; +import common.packet.SPacketPlayerListItem; +import common.packet.SPacketPlayerAbilities; +import common.packet.SPacketTabComplete; +import common.packet.SPacketUpdateEntityTags; +import common.packet.SPacketAnimation; +import common.packet.SPacketBiome; +import common.packet.SPacketBlockAction; +import common.packet.SPacketBlockBreakAnim; +import common.packet.SPacketBlockChange; +import common.packet.SPacketCamera; +import common.packet.SPacketCharacterList; +import common.packet.SPacketChunkData; +import common.packet.SPacketCollectItem; +import common.packet.SPacketDestroyEntities; +import common.packet.SPacketDimensionName; +import common.packet.SPacketDisconnect; +import common.packet.SPacketDisplayForm; +import common.packet.SPacketEntityEquipment; +import common.packet.SPacketEntityVelocity; +import common.packet.SPacketHeldItemChange; +import common.packet.SPacketJoinGame; +import common.packet.SPacketKeepAlive; +import common.packet.SPacketLoading; +import common.packet.SPacketMapChunkBulk; +import common.packet.SPacketMessage; +import common.packet.SPacketMultiBlockChange; +import common.packet.SPacketPlayerPosLook; +import common.packet.SPacketRespawn; +import common.packet.SPacketServerTick; +import common.packet.SPacketSetExperience; +import common.packet.SPacketSkin; +import common.packet.SPacketSpawnMob; +import common.packet.SPacketSpawnObject; +import common.packet.SPacketSpawnPlayer; +import common.packet.SPacketTimeUpdate; +import common.packet.SPacketTrades; +import common.packet.SPacketUpdateHealth; +import common.packet.SPacketWorld; + +public enum PacketRegistry { + HANDSHAKE {{ + this.client(HPacketHandshake.class); + }}, + LOGIN {{ + this.server(RPacketDisconnect.class); + this.server(RPacketRequestEncrypt.class); + this.server(RPacketResponse.class); + this.server(RPacketChallenge.class); + this.server(RPacketServerConfig.class); + this.server(RPacketLoginSuccess.class); + this.server(RPacketEnableCompression.class); + + this.client(LPacketStartEncrypt.class); + this.client(LPacketPassword.class); + this.client(LPacketChallenge.class); + this.client(LPacketPubkey.class); + this.client(LPacketResponse.class); + }}, + PLAY {{ + this.server(SPacketKeepAlive.class); + this.server(SPacketJoinGame.class); + this.server(SPacketMessage.class); + this.server(SPacketTimeUpdate.class); + this.server(SPacketEntityEquipment.class); + this.server(SPacketUpdateHealth.class); + this.server(SPacketRespawn.class); + this.server(SPacketPlayerPosLook.class); + this.server(SPacketHeldItemChange.class); + this.server(SPacketAnimation.class); + this.server(SPacketSpawnPlayer.class); + this.server(SPacketCollectItem.class); + this.server(SPacketSpawnObject.class); + this.server(SPacketSpawnMob.class); + this.server(SPacketEntityVelocity.class); + this.server(SPacketDestroyEntities.class); + this.server(SPacketEntity.class); + this.server(SPacketEntityRelMove.class); + this.server(SPacketEntityLook.class); + this.server(SPacketEntityLookMove.class); + this.server(SPacketEntityTeleport.class); + this.server(SPacketEntityHeadLook.class); + this.server(SPacketEntityStatus.class); + this.server(SPacketEntityAttach.class); + this.server(SPacketEntityMetadata.class); + this.server(SPacketEntityEffect.class); + this.server(SPacketRemoveEntityEffect.class); + this.server(SPacketSetExperience.class); + this.server(SPacketChunkData.class); + this.server(SPacketMultiBlockChange.class); + this.server(SPacketBlockChange.class); + this.server(SPacketBlockAction.class); + this.server(SPacketBlockBreakAnim.class); + this.server(SPacketMapChunkBulk.class); + this.server(SPacketExplosion.class); + this.server(SPacketEffect.class); + this.server(SPacketSoundEffect.class); + this.server(SPacketParticles.class); + this.server(SPacketChangeGameState.class); + this.server(SPacketSpawnGlobalEntity.class); + this.server(SPacketOpenWindow.class); + this.server(SPacketCloseWindow.class); + this.server(SPacketSetSlot.class); + this.server(SPacketWindowItems.class); + this.server(SPacketWindowProperty.class); + this.server(SPacketConfirmTransaction.class); + this.server(SPacketUpdateSign.class); + this.server(SPacketUpdateTileEntity.class); + this.server(SPacketSignEditorOpen.class); + this.server(SPacketPlayerListItem.class); + this.server(SPacketPlayerAbilities.class); + this.server(SPacketTabComplete.class); + this.server(SPacketSkin.class); + this.server(SPacketDisconnect.class); + this.server(SPacketWorld.class); + this.server(SPacketCamera.class); + this.server(SPacketBiome.class); + this.server(SPacketUpdateEntityTags.class); + this.server(SPacketTrades.class); + this.server(SPacketDimensionName.class); + this.server(SPacketCharacterList.class); + this.server(SPacketServerTick.class); + this.server(SPacketLoading.class); + this.server(SPacketDisplayForm.class); + + this.client(CPacketKeepAlive.class); + this.client(CPacketMessage.class); + this.client(CPacketAction.class); + this.client(CPacketPlayer.class); + this.client(CPacketPlayerPosition.class); + this.client(CPacketPlayerLook.class); + this.client(CPacketPlayerPosLook.class); + this.client(CPacketBreak.class); + this.client(CPacketPlace.class); + this.client(CPacketInput.class); + this.client(CPacketClick.class); + this.client(CPacketCheat.class); + this.client(CPacketComplete.class); + this.client(CPacketSkin.class); + this.client(CPacketSign.class); + this.client(CPacketForm.class); + }}; + + private static final Map, PacketRegistry> STATES = Maps., PacketRegistry>newHashMap(); + + private final BiMap> server = HashBiMap.>create(); + private final BiMap> client = HashBiMap.>create(); + + protected void server(Class clazz) { + if(this.server.containsValue(clazz)) + throw new IllegalArgumentException("S-Paket " + clazz + " ist bereits bekannt unter ID " + this.server.inverse().get(clazz)); + this.server.put(Integer.valueOf(this.server.size()), clazz); + } + + protected void client(Class clazz) { + if(this.client.containsValue(clazz)) + throw new IllegalArgumentException("C-Paket " + clazz + " ist bereits bekannt unter ID " + this.client.inverse().get(clazz)); + this.client.put(Integer.valueOf(this.client.size()), clazz); + } + + public Integer getId(boolean client, Packet packet) { + return (client ? this.client : this.server).inverse().get(packet.getClass()); + } + + public Packet getPacket(boolean client, int id) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { + Class oclass = (client ? this.client : this.server).get(id); + return oclass == null ? null : oclass.getConstructor().newInstance(); + } + + public static PacketRegistry getType(Packet packet) { + return STATES.get(packet.getClass()); + } + + static { + for(PacketRegistry reg : values()) { + for(BiMap> map : new BiMap[] {reg.server, reg.client}) { + for(Class clazz : map.values()) { + if(STATES.containsKey(clazz) && STATES.get(clazz) != reg) + throw new Error("Paket " + clazz + " ist bereits zu ID " + STATES.get(clazz) + " zugewiesen - kann nicht auf " + reg + " neu zuweisen"); + try { + clazz.getConstructor().newInstance(); + } + catch(Throwable e) { + throw new Error("Paket " + clazz + " kann nicht instanziert werden!"); + } + STATES.put(clazz, reg); + } + } + } + } +} diff --git a/common/src/main/java/common/network/PacketSplitter.java b/common/src/main/java/common/network/PacketSplitter.java new file mode 100755 index 0000000..3874408 --- /dev/null +++ b/common/src/main/java/common/network/PacketSplitter.java @@ -0,0 +1,39 @@ +package common.network; + +import java.util.List; + +import common.net.buffer.ByteBuf; +import common.net.buffer.Unpooled; +import common.net.channel.ChannelHandlerContext; +import common.net.handler.codec.ByteToMessageDecoder; +import common.net.handler.codec.CorruptedFrameException; + +public class PacketSplitter extends ByteToMessageDecoder { + protected void decode(ChannelHandlerContext context, ByteBuf buffer, List output) throws Exception { + buffer.markReaderIndex(); + byte[] data = new byte[3]; + for(int z = 0; z < data.length; z++) { + if(!buffer.isReadable()) { + buffer.resetReaderIndex(); + return; + } + data[z] = buffer.readByte(); + if(data[z] < 0) + continue; + PacketBuffer pbuf = new PacketBuffer(Unpooled.wrappedBuffer(data)); + try { + int len = pbuf.readVarInt(); + if(buffer.readableBytes() >= len) { + output.add(buffer.readBytes(len)); + return; + } + buffer.resetReaderIndex(); + } + finally { + pbuf.release(); + } + return; + } + throw new CorruptedFrameException("length wider than 21-bit"); + } +} diff --git a/java/src/game/packet/APacketVarInt.java b/common/src/main/java/common/packet/APacketVarInt.java similarity index 56% rename from java/src/game/packet/APacketVarInt.java rename to common/src/main/java/common/packet/APacketVarInt.java index 44f58a2..f68d407 100755 --- a/java/src/game/packet/APacketVarInt.java +++ b/common/src/main/java/common/packet/APacketVarInt.java @@ -1,12 +1,11 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.NetHandler; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.Packet; +import common.network.PacketBuffer; -public abstract class APacketVarInt implements Packet { +public abstract class APacketVarInt implements Packet { private int value; public APacketVarInt() { @@ -17,11 +16,11 @@ public abstract class APacketVarInt implements Packet { } public final void readPacketData(PacketBuffer buf) throws IOException { - this.value = buf.readVarIntFromBuffer(); + this.value = buf.readVarInt(); } public final void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.value); + buf.writeVarInt(this.value); } public final int getValue() { diff --git a/java/src/game/packet/CPacketAction.java b/common/src/main/java/common/packet/CPacketAction.java similarity index 84% rename from java/src/game/packet/CPacketAction.java rename to common/src/main/java/common/packet/CPacketAction.java index 5a93ea9..9aceb60 100755 --- a/java/src/game/packet/CPacketAction.java +++ b/common/src/main/java/common/packet/CPacketAction.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class CPacketAction implements Packet +public class CPacketAction implements Packet { private Action action; private int auxData; @@ -29,16 +29,16 @@ public class CPacketAction implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.action = buf.readEnumValue(Action.class); - this.auxData = buf.readVarIntFromBuffer(); + this.auxData = buf.readVarInt(); } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeEnumValue(this.action); - buf.writeVarIntToBuffer(this.auxData); + buf.writeVarInt(this.auxData); } - public void processPacket(Player handler) + public void processPacket(IPlayer handler) { handler.processAction(this); } @@ -57,6 +57,7 @@ public class CPacketAction implements Packet { OPEN_EDITOR, CLOSE_EDITOR, + CANCEL_EDITOR, SELECT_CHARACTER, DELETE_CHARACTER, SWING_ARM, diff --git a/java/src/game/packet/CPacketBreak.java b/common/src/main/java/common/packet/CPacketBreak.java similarity index 82% rename from java/src/game/packet/CPacketBreak.java rename to common/src/main/java/common/packet/CPacketBreak.java index 07e67d8..64dc2e4 100755 --- a/java/src/game/packet/CPacketBreak.java +++ b/common/src/main/java/common/packet/CPacketBreak.java @@ -1,14 +1,14 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; -import game.world.Facing; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; +import common.util.Facing; -public class CPacketBreak implements Packet +public class CPacketBreak implements Packet { private BlockPos position; private Facing facing; @@ -39,7 +39,7 @@ public class CPacketBreak implements Packet buf.writeByte(this.facing.getIndex()); } - public void processPacket(Player handler) + public void processPacket(IPlayer handler) { handler.processBreak(this); } diff --git a/java/src/game/packet/CPacketCheat.java b/common/src/main/java/common/packet/CPacketCheat.java similarity index 63% rename from java/src/game/packet/CPacketCheat.java rename to common/src/main/java/common/packet/CPacketCheat.java index 7faa62d..eb02559 100755 --- a/java/src/game/packet/CPacketCheat.java +++ b/common/src/main/java/common/packet/CPacketCheat.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.item.ItemStack; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; +import common.item.ItemStack; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class CPacketCheat implements Packet +public class CPacketCheat implements Packet { private ItemStack stack; private int slot; @@ -20,23 +20,23 @@ public class CPacketCheat implements Packet { this.stack = stackIn.copy(); this.slot = slot; - this.stack.stackSize = full ? this.stack.getMaxStackSize() : 1; + this.stack.size = full ? this.stack.getMaxStackSize() : 1; } - public void processPacket(Player handler) + public void processPacket(IPlayer handler) { handler.processCheat(this); } public void readPacketData(PacketBuffer buf) throws IOException { - this.stack = buf.readItemStackFromBuffer(); + this.stack = buf.readItemStack(); this.slot = buf.readByte(); } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeItemStackToBuffer(this.stack); + buf.writeItemStack(this.stack); buf.writeByte(this.slot); } diff --git a/java/src/game/packet/CPacketClick.java b/common/src/main/java/common/packet/CPacketClick.java similarity index 84% rename from java/src/game/packet/CPacketClick.java rename to common/src/main/java/common/packet/CPacketClick.java index ae6078d..efdf80f 100755 --- a/java/src/game/packet/CPacketClick.java +++ b/common/src/main/java/common/packet/CPacketClick.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.item.ItemStack; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; +import common.item.ItemStack; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class CPacketClick implements Packet +public class CPacketClick implements Packet { /** The id of the window which was clicked. 0 for player inventory. */ private int windowId; @@ -41,7 +41,7 @@ public class CPacketClick implements Packet this.mode = mode; } - public void processPacket(Player handler) + public void processPacket(IPlayer handler) { handler.processClick(this); } @@ -53,7 +53,7 @@ public class CPacketClick implements Packet this.usedButton = buf.readByte(); this.actionNumber = buf.readShort(); this.mode = buf.readByte(); - this.clickedItem = buf.readItemStackFromBuffer(); + this.clickedItem = buf.readItemStack(); } public void writePacketData(PacketBuffer buf) throws IOException @@ -63,7 +63,7 @@ public class CPacketClick implements Packet buf.writeByte(this.usedButton); buf.writeShort(this.actionNumber); buf.writeByte(this.mode); - buf.writeItemStackToBuffer(this.clickedItem); + buf.writeItemStack(this.clickedItem); } public int getWindowId() diff --git a/java/src/game/packet/CPacketComplete.java b/common/src/main/java/common/packet/CPacketComplete.java similarity index 73% rename from java/src/game/packet/CPacketComplete.java rename to common/src/main/java/common/packet/CPacketComplete.java index d160d13..83fd0f0 100755 --- a/java/src/game/packet/CPacketComplete.java +++ b/common/src/main/java/common/packet/CPacketComplete.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; -public class CPacketComplete implements Packet +public class CPacketComplete implements Packet { private String message; private int entityId; @@ -26,8 +26,8 @@ public class CPacketComplete implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.message = buf.readStringFromBuffer(32767); - this.entityId = buf.readVarIntFromBuffer(); + this.message = buf.readString(32767); + this.entityId = buf.readVarInt(); if(buf.readBoolean()) this.position = buf.readBlockPos(); } @@ -35,13 +35,13 @@ public class CPacketComplete implements Packet public void writePacketData(PacketBuffer buf) throws IOException { buf.writeString(this.message.length() > 32767 ? this.message.substring(0, 32767) : this.message); - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); buf.writeBoolean(this.position != null); if(this.position != null) buf.writeBlockPos(this.position); } - public void processPacket(Player handler) + public void processPacket(IPlayer handler) { handler.processComplete(this); } diff --git a/common/src/main/java/common/packet/CPacketForm.java b/common/src/main/java/common/packet/CPacketForm.java new file mode 100644 index 0000000..5c9e5bf --- /dev/null +++ b/common/src/main/java/common/packet/CPacketForm.java @@ -0,0 +1,86 @@ +package common.packet; + +import java.io.IOException; + +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; + +public class CPacketForm implements Packet +{ + private int id; + private Object[] data; + + public CPacketForm() + { + } + + public CPacketForm(int id, Object[] data) + { + this.id = id; + this.data = data; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + this.id = buf.readVarInt(); + if(!buf.readBoolean()) { + this.data = null; + return; + } + this.data = new Object[buf.readVarInt()]; + for(int z = 0; z < this.data.length; z++) { + Object obj; + switch(buf.readByte()) { + case 0: + obj = buf.readBoolean(); + break; + case 1: + obj = buf.readVarInt(); + break; + default: + obj = buf.readString(1024); + break; + } + this.data[z] = obj; + } + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeVarInt(this.id); + buf.writeBoolean(this.data != null); + if(this.data == null) + return; + buf.writeVarInt(this.data.length); + for(int z = 0; z < this.data.length; z++) { + Object obj = this.data[z]; + if(obj instanceof Boolean) { + buf.writeByte(0); + buf.writeBoolean((Boolean)obj); + } + else if(obj instanceof Integer) { + buf.writeByte(1); + buf.writeVarInt((Integer)obj); + } + else { + buf.writeByte(2); + buf.writeString((String)obj); + } + } + } + + public void processPacket(IPlayer handler) + { + handler.processForm(this); + } + + public Object[] getData() + { + return this.data; + } + + public int getId() { + return this.id; + } +} diff --git a/java/src/game/packet/CPacketInput.java b/common/src/main/java/common/packet/CPacketInput.java similarity index 87% rename from java/src/game/packet/CPacketInput.java rename to common/src/main/java/common/packet/CPacketInput.java index 975a66a..1bc90df 100755 --- a/java/src/game/packet/CPacketInput.java +++ b/common/src/main/java/common/packet/CPacketInput.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class CPacketInput implements Packet +public class CPacketInput implements Packet { private float strafeSpeed; private float forwardSpeed; @@ -53,7 +53,7 @@ public class CPacketInput implements Packet buf.writeByte(b0); } - public void processPacket(Player handler) + public void processPacket(IPlayer handler) { handler.processInput(this); } diff --git a/java/src/game/packet/CPacketKeepAlive.java b/common/src/main/java/common/packet/CPacketKeepAlive.java similarity index 51% rename from java/src/game/packet/CPacketKeepAlive.java rename to common/src/main/java/common/packet/CPacketKeepAlive.java index 096f558..6e6a9ad 100755 --- a/java/src/game/packet/CPacketKeepAlive.java +++ b/common/src/main/java/common/packet/CPacketKeepAlive.java @@ -1,8 +1,8 @@ -package game.packet; +package common.packet; -import game.network.Player; +import common.network.IPlayer; -public class CPacketKeepAlive extends APacketVarInt +public class CPacketKeepAlive extends APacketVarInt { public CPacketKeepAlive() { @@ -13,7 +13,7 @@ public class CPacketKeepAlive extends APacketVarInt super(key); } - public void processPacket(Player handler) + public void processPacket(IPlayer handler) { handler.processKeepAlive(this); } diff --git a/java/src/game/packet/CPacketMessage.java b/common/src/main/java/common/packet/CPacketMessage.java similarity index 69% rename from java/src/game/packet/CPacketMessage.java rename to common/src/main/java/common/packet/CPacketMessage.java index 037f27e..3b34e2d 100755 --- a/java/src/game/packet/CPacketMessage.java +++ b/common/src/main/java/common/packet/CPacketMessage.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class CPacketMessage implements Packet +public class CPacketMessage implements Packet { private Type type; private String message; @@ -24,7 +24,7 @@ public class CPacketMessage implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.type = buf.readEnumValue(Type.class); - this.message = buf.readStringFromBuffer(this.type.length); + this.message = buf.readString(this.type.length); } public void writePacketData(PacketBuffer buf) throws IOException @@ -33,7 +33,7 @@ public class CPacketMessage implements Packet buf.writeString(this.message); } - public void processPacket(Player handler) + public void processPacket(IPlayer handler) { handler.processMessage(this); } @@ -49,10 +49,10 @@ public class CPacketMessage implements Packet } public static enum Type { - COMMAND(Player.MAX_CMD_LENGTH), - CHAT(Player.MAX_CMD_LENGTH), - DISPLAY(Player.MAX_NICK_LENGTH), - INFO(Player.MAX_INFO_LENGTH); + COMMAND(IPlayer.MAX_CMD_LENGTH), + CHAT(IPlayer.MAX_CMD_LENGTH), + DISPLAY(IPlayer.MAX_NICK_LENGTH), + INFO(IPlayer.MAX_INFO_LENGTH); // , ITEM(30); private final int length; diff --git a/java/src/game/packet/CPacketPlace.java b/common/src/main/java/common/packet/CPacketPlace.java similarity index 85% rename from java/src/game/packet/CPacketPlace.java rename to common/src/main/java/common/packet/CPacketPlace.java index 4b5aeaf..a2b8964 100755 --- a/java/src/game/packet/CPacketPlace.java +++ b/common/src/main/java/common/packet/CPacketPlace.java @@ -1,14 +1,14 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.item.ItemStack; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; +import common.item.ItemStack; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; -public class CPacketPlace implements Packet +public class CPacketPlace implements Packet { private static final BlockPos DUMMY_POS = new BlockPos(-1, -1, -1); @@ -42,7 +42,7 @@ public class CPacketPlace implements Packet { this.position = buf.readBlockPos(); this.placedBlockDirection = buf.readUnsignedByte(); - this.stack = buf.readItemStackFromBuffer(); + this.stack = buf.readItemStack(); this.facingX = (float)buf.readUnsignedByte() / 16.0F; this.facingY = (float)buf.readUnsignedByte() / 16.0F; this.facingZ = (float)buf.readUnsignedByte() / 16.0F; @@ -52,13 +52,13 @@ public class CPacketPlace implements Packet { buf.writeBlockPos(this.position); buf.writeByte(this.placedBlockDirection); - buf.writeItemStackToBuffer(this.stack); + buf.writeItemStack(this.stack); buf.writeByte((int)(this.facingX * 16.0F)); buf.writeByte((int)(this.facingY * 16.0F)); buf.writeByte((int)(this.facingZ * 16.0F)); } - public void processPacket(Player handler) + public void processPacket(IPlayer handler) { handler.processPlace(this); } diff --git a/common/src/main/java/common/packet/CPacketPlayer.java b/common/src/main/java/common/packet/CPacketPlayer.java new file mode 100755 index 0000000..ccafdc3 --- /dev/null +++ b/common/src/main/java/common/packet/CPacketPlayer.java @@ -0,0 +1,88 @@ +package common.packet; + +import java.io.IOException; + +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; + +public class CPacketPlayer implements Packet +{ + protected double x; + protected double y; + protected double z; + protected float yaw; + protected float pitch; + protected boolean onGround; + protected boolean moving; + protected boolean rotating; + + public CPacketPlayer() + { + } + + public CPacketPlayer(boolean isOnGround) + { + this.onGround = isOnGround; + } + + public void processPacket(IPlayer handler) + { + handler.processPlayer(this); + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + this.onGround = buf.readUnsignedByte() != 0; + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeByte(this.onGround ? 1 : 0); + } + + public double getPositionX() + { + return this.x; + } + + public double getPositionY() + { + return this.y; + } + + public double getPositionZ() + { + return this.z; + } + + public float getYaw() + { + return this.yaw; + } + + public float getPitch() + { + return this.pitch; + } + + public boolean isOnGround() + { + return this.onGround; + } + + public boolean isMoving() + { + return this.moving; + } + + public boolean getRotating() + { + return this.rotating; + } + + public void setMoving(boolean isMoving) + { + this.moving = isMoving; + } +} diff --git a/common/src/main/java/common/packet/CPacketPlayerLook.java b/common/src/main/java/common/packet/CPacketPlayerLook.java new file mode 100644 index 0000000..47237f7 --- /dev/null +++ b/common/src/main/java/common/packet/CPacketPlayerLook.java @@ -0,0 +1,35 @@ +package common.packet; + +import java.io.IOException; + +import common.network.PacketBuffer; + +public class CPacketPlayerLook extends CPacketPlayer +{ + public CPacketPlayerLook() + { + this.rotating = true; + } + + public CPacketPlayerLook(float playerYaw, float playerPitch, boolean isOnGround) + { + this.yaw = playerYaw; + this.pitch = playerPitch; + this.onGround = isOnGround; + this.rotating = true; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + this.yaw = buf.readFloat(); + this.pitch = buf.readFloat(); + super.readPacketData(buf); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeFloat(this.yaw); + buf.writeFloat(this.pitch); + super.writePacketData(buf); + } +} \ No newline at end of file diff --git a/common/src/main/java/common/packet/CPacketPlayerPosLook.java b/common/src/main/java/common/packet/CPacketPlayerPosLook.java new file mode 100644 index 0000000..9b02b82 --- /dev/null +++ b/common/src/main/java/common/packet/CPacketPlayerPosLook.java @@ -0,0 +1,46 @@ +package common.packet; + +import java.io.IOException; + +import common.network.PacketBuffer; + +public class CPacketPlayerPosLook extends CPacketPlayer +{ + public CPacketPlayerPosLook() + { + this.moving = true; + this.rotating = true; + } + + public CPacketPlayerPosLook(double playerX, double playerY, double playerZ, float playerYaw, float playerPitch, boolean playerIsOnGround) + { + this.x = playerX; + this.y = playerY; + this.z = playerZ; + this.yaw = playerYaw; + this.pitch = playerPitch; + this.onGround = playerIsOnGround; + this.rotating = true; + this.moving = true; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + this.x = buf.readDouble(); + this.y = buf.readDouble(); + this.z = buf.readDouble(); + this.yaw = buf.readFloat(); + this.pitch = buf.readFloat(); + super.readPacketData(buf); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeDouble(this.x); + buf.writeDouble(this.y); + buf.writeDouble(this.z); + buf.writeFloat(this.yaw); + buf.writeFloat(this.pitch); + super.writePacketData(buf); + } +} \ No newline at end of file diff --git a/common/src/main/java/common/packet/CPacketPlayerPosition.java b/common/src/main/java/common/packet/CPacketPlayerPosition.java new file mode 100644 index 0000000..a82ad3e --- /dev/null +++ b/common/src/main/java/common/packet/CPacketPlayerPosition.java @@ -0,0 +1,38 @@ +package common.packet; + +import java.io.IOException; + +import common.network.PacketBuffer; + +public class CPacketPlayerPosition extends CPacketPlayer +{ + public CPacketPlayerPosition() + { + this.moving = true; + } + + public CPacketPlayerPosition(double posX, double posY, double posZ, boolean isOnGround) + { + this.x = posX; + this.y = posY; + this.z = posZ; + this.onGround = isOnGround; + this.moving = true; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + this.x = buf.readDouble(); + this.y = buf.readDouble(); + this.z = buf.readDouble(); + super.readPacketData(buf); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeDouble(this.x); + buf.writeDouble(this.y); + buf.writeDouble(this.z); + super.writePacketData(buf); + } +} \ No newline at end of file diff --git a/java/src/game/packet/CPacketSign.java b/common/src/main/java/common/packet/CPacketSign.java similarity index 80% rename from java/src/game/packet/CPacketSign.java rename to common/src/main/java/common/packet/CPacketSign.java index c8df819..9e01415 100755 --- a/java/src/game/packet/CPacketSign.java +++ b/common/src/main/java/common/packet/CPacketSign.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; -public class CPacketSign implements Packet +public class CPacketSign implements Packet { private BlockPos pos; private String[] lines; @@ -34,7 +34,7 @@ public class CPacketSign implements Packet for (int i = 0; i < 4; ++i) { - this.lines[i] = buf.readStringFromBuffer(50); + this.lines[i] = buf.readString(50); } } @@ -48,7 +48,7 @@ public class CPacketSign implements Packet } } - public void processPacket(Player handler) + public void processPacket(IPlayer handler) { handler.processSign(this); } diff --git a/common/src/main/java/common/packet/CPacketSkin.java b/common/src/main/java/common/packet/CPacketSkin.java new file mode 100755 index 0000000..d587918 --- /dev/null +++ b/common/src/main/java/common/packet/CPacketSkin.java @@ -0,0 +1,53 @@ +package common.packet; + +import java.io.IOException; + +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; + +public class CPacketSkin implements Packet { + private byte[] texture; + private String character; + + public CPacketSkin() { + } + + public CPacketSkin(byte[] texture, String character) { + this.texture = texture; + this.character = character; + } + + public byte[] getCompressed() { + return this.texture; + } + + public String getCharacter() { + return this.character; + } + + public void readPacketData(PacketBuffer buf) throws IOException { + if(buf.readBoolean()) { + this.texture = null; + this.character = buf.readString(64); + } + else { + this.texture = buf.readByteArray(); + this.character = null; + if(this.texture.length == 0 || this.texture.length > IPlayer.MAX_SKIN_SIZE) + this.texture = new byte[IPlayer.MAX_SKIN_SIZE]; + } + } + + public void writePacketData(PacketBuffer buf) throws IOException { + buf.writeBoolean(this.texture == null); + if(this.texture == null) + buf.writeString(this.character); + else + buf.writeByteArray(this.texture); + } + + public void processPacket(IPlayer handler) { + handler.processSkin(this); + } +} diff --git a/java/src/game/packet/HPacketHandshake.java b/common/src/main/java/common/packet/HPacketHandshake.java similarity index 61% rename from java/src/game/packet/HPacketHandshake.java rename to common/src/main/java/common/packet/HPacketHandshake.java index 1d4fb5b..f94e44e 100755 --- a/java/src/game/packet/HPacketHandshake.java +++ b/common/src/main/java/common/packet/HPacketHandshake.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.HandshakeHandler; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IHandshakeHandler; +import common.network.Packet; +import common.network.PacketBuffer; -public class HPacketHandshake implements Packet { +public class HPacketHandshake implements Packet { private int protocol; public HPacketHandshake() { @@ -17,7 +17,7 @@ public class HPacketHandshake implements Packet { } public void readPacketData(PacketBuffer buf) throws IOException { - this.protocol = buf.readVarIntFromBuffer(); + this.protocol = buf.readVarInt(); int r = buf.readableBytes(); if(r > 0) { this.protocol = 0; @@ -27,10 +27,10 @@ public class HPacketHandshake implements Packet { } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.protocol); + buf.writeVarInt(this.protocol); } - public void processPacket(HandshakeHandler handler) { + public void processPacket(IHandshakeHandler handler) { handler.processHandshake(this); } diff --git a/common/src/main/java/common/packet/LPacketChallenge.java b/common/src/main/java/common/packet/LPacketChallenge.java new file mode 100644 index 0000000..11fceec --- /dev/null +++ b/common/src/main/java/common/packet/LPacketChallenge.java @@ -0,0 +1,33 @@ +package common.packet; + +import java.io.IOException; +import common.network.ILoginHandler; +import common.network.Packet; +import common.network.PacketBuffer; + +public class LPacketChallenge implements Packet { + private byte[] token; + + public LPacketChallenge() { + } + + public LPacketChallenge(byte[] token) { + this.token = token; + } + + public final void readPacketData(PacketBuffer buf) throws IOException { + this.token = buf.readByteArray(); + } + + public final void writePacketData(PacketBuffer buf) throws IOException { + buf.writeByteArray(this.token); + } + + public void processPacket(ILoginHandler handler) { + handler.processChallenge(this); + } + + public byte[] getToken() { + return this.token; + } +} diff --git a/java/src/game/packet/LPacketPasswordResponse.java b/common/src/main/java/common/packet/LPacketPassword.java similarity index 55% rename from java/src/game/packet/LPacketPasswordResponse.java rename to common/src/main/java/common/packet/LPacketPassword.java index 4d445df..5436f32 100755 --- a/java/src/game/packet/LPacketPasswordResponse.java +++ b/common/src/main/java/common/packet/LPacketPassword.java @@ -1,26 +1,26 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.LoginHandler; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.ILoginHandler; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class LPacketPasswordResponse implements Packet +public class LPacketPassword implements Packet { private String user; private String access; private String password; - public LPacketPasswordResponse() + public LPacketPassword() { } - public LPacketPasswordResponse(String userIn, String accessIn, String passwordIn) + public LPacketPassword(String user, String access, String passwordIn) { - this.user = userIn; - this.access = accessIn; + this.user = user; + this.access = access; this.password = passwordIn; } @@ -29,9 +29,9 @@ public class LPacketPasswordResponse implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.user = buf.readStringFromBuffer(Player.MAX_USER_LENGTH); - this.access = buf.readStringFromBuffer(Player.MAX_PASS_LENGTH); - this.password = buf.readStringFromBuffer(Player.MAX_PASS_LENGTH); + this.user = buf.readString(IPlayer.MAX_USER_LENGTH); + this.access = buf.readString(IPlayer.MAX_PASS_LENGTH); + this.password = buf.readString(IPlayer.MAX_PASS_LENGTH); } /** @@ -47,9 +47,9 @@ public class LPacketPasswordResponse implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(LoginHandler handler) + public void processPacket(ILoginHandler handler) { - handler.processPasswordResponse(this); + handler.processPassword(this); } public String getUser() diff --git a/common/src/main/java/common/packet/LPacketPubkey.java b/common/src/main/java/common/packet/LPacketPubkey.java new file mode 100644 index 0000000..873a247 --- /dev/null +++ b/common/src/main/java/common/packet/LPacketPubkey.java @@ -0,0 +1,53 @@ +package common.packet; + +import java.io.IOException; +import java.security.PublicKey; + +import common.network.ILoginHandler; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.EncryptUtil; + +public class LPacketPubkey implements Packet { + private String user; + private String access; + private PublicKey key; + + public LPacketPubkey() { + } + + public LPacketPubkey(String user, String access, PublicKey key) { + this.user = user; + this.access = access; + this.key = key; + } + + public final void readPacketData(PacketBuffer buf) throws IOException { + this.user = buf.readString(IPlayer.MAX_USER_LENGTH); + this.access = buf.readString(IPlayer.MAX_PASS_LENGTH); + this.key = EncryptUtil.decodePublicKey(buf.readByteArray()); + } + + public final void writePacketData(PacketBuffer buf) throws IOException { + buf.writeString(this.user); + buf.writeString(this.access); + buf.writeByteArray(this.key.getEncoded()); + } + + public void processPacket(ILoginHandler handler) { + handler.processPubkey(this); + } + + public String getUser() { + return this.user; + } + + public String getAccess() { + return this.access; + } + + public PublicKey getKey() { + return this.key; + } +} diff --git a/common/src/main/java/common/packet/LPacketResponse.java b/common/src/main/java/common/packet/LPacketResponse.java new file mode 100644 index 0000000..554bc1e --- /dev/null +++ b/common/src/main/java/common/packet/LPacketResponse.java @@ -0,0 +1,37 @@ +package common.packet; + +import java.io.IOException; +import java.security.PrivateKey; +import java.security.PublicKey; + +import common.network.ILoginHandler; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.EncryptUtil; + +public class LPacketResponse implements Packet { + private byte[] token = new byte[0]; + + public LPacketResponse() { + } + + public LPacketResponse(PrivateKey key, byte[] token) { + this.token = EncryptUtil.createSignature(key, token); + } + + public void readPacketData(PacketBuffer buf) throws IOException { + this.token = buf.readByteArray(); + } + + public void writePacketData(PacketBuffer buf) throws IOException { + buf.writeByteArray(this.token); + } + + public void processPacket(ILoginHandler handler) { + handler.processResponse(this); + } + + public boolean verifyToken(PublicKey key, byte[] token) { + return EncryptUtil.verifySignature(key, token, this.token); + } +} diff --git a/common/src/main/java/common/packet/LPacketStartEncrypt.java b/common/src/main/java/common/packet/LPacketStartEncrypt.java new file mode 100644 index 0000000..b6d4995 --- /dev/null +++ b/common/src/main/java/common/packet/LPacketStartEncrypt.java @@ -0,0 +1,36 @@ +package common.packet; + +import java.io.IOException; +import java.security.PublicKey; + +import common.network.ILoginHandler; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.EncryptUtil; + +public class LPacketStartEncrypt implements Packet { + private PublicKey key; + + public LPacketStartEncrypt() { + } + + public LPacketStartEncrypt(PublicKey pubkey) { + this.key = pubkey; + } + + public void readPacketData(PacketBuffer buf) throws IOException { + this.key = EncryptUtil.decodeDHPublicKey(buf.readByteArray()); + } + + public void writePacketData(PacketBuffer buf) throws IOException { + buf.writeByteArray(this.key.getEncoded()); + } + + public void processPacket(ILoginHandler handler) { + handler.processEncryption(this); + } + + public PublicKey getKey() { + return this.key; + } +} diff --git a/common/src/main/java/common/packet/RPacketChallenge.java b/common/src/main/java/common/packet/RPacketChallenge.java new file mode 100644 index 0000000..9ae9012 --- /dev/null +++ b/common/src/main/java/common/packet/RPacketChallenge.java @@ -0,0 +1,33 @@ +package common.packet; + +import java.io.IOException; +import common.network.IClientLoginHandler; +import common.network.Packet; +import common.network.PacketBuffer; + +public class RPacketChallenge implements Packet { + private byte[] token; + + public RPacketChallenge() { + } + + public RPacketChallenge(byte[] token) { + this.token = token; + } + + public final void readPacketData(PacketBuffer buf) throws IOException { + this.token = buf.readByteArray(); + } + + public final void writePacketData(PacketBuffer buf) throws IOException { + buf.writeByteArray(this.token); + } + + public void processPacket(IClientLoginHandler handler) { + handler.handleChallenge(this); + } + + public byte[] getToken() { + return this.token; + } +} diff --git a/java/src/game/packet/RPacketDisconnect.java b/common/src/main/java/common/packet/RPacketDisconnect.java similarity index 70% rename from java/src/game/packet/RPacketDisconnect.java rename to common/src/main/java/common/packet/RPacketDisconnect.java index 1aee0bd..36f8aad 100755 --- a/java/src/game/packet/RPacketDisconnect.java +++ b/common/src/main/java/common/packet/RPacketDisconnect.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientLoginHandler; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientLoginHandler; +import common.network.Packet; +import common.network.PacketBuffer; -public class RPacketDisconnect implements Packet +public class RPacketDisconnect implements Packet { private String reason; @@ -24,7 +24,7 @@ public class RPacketDisconnect implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.reason = buf.readStringFromBuffer(8192); + this.reason = buf.readString(8192); } /** @@ -38,7 +38,7 @@ public class RPacketDisconnect implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientLoginHandler handler) + public void processPacket(IClientLoginHandler handler) { handler.handleDisconnect(this); } diff --git a/common/src/main/java/common/packet/RPacketEnableCompression.java b/common/src/main/java/common/packet/RPacketEnableCompression.java new file mode 100755 index 0000000..8aceabb --- /dev/null +++ b/common/src/main/java/common/packet/RPacketEnableCompression.java @@ -0,0 +1,20 @@ +package common.packet; + +import common.network.IClientLoginHandler; + +public class RPacketEnableCompression extends APacketVarInt +{ + public RPacketEnableCompression() + { + } + + public RPacketEnableCompression(int comp) + { + super(comp); + } + + public void processPacket(IClientLoginHandler handler) + { + handler.handleEnableCompression(this); + } +} diff --git a/common/src/main/java/common/packet/RPacketLoginSuccess.java b/common/src/main/java/common/packet/RPacketLoginSuccess.java new file mode 100755 index 0000000..0869607 --- /dev/null +++ b/common/src/main/java/common/packet/RPacketLoginSuccess.java @@ -0,0 +1,22 @@ +package common.packet; + +import java.io.IOException; + +import common.network.IClientLoginHandler; +import common.network.Packet; +import common.network.PacketBuffer; + +public class RPacketLoginSuccess implements Packet { + public RPacketLoginSuccess() { + } + + public final void readPacketData(PacketBuffer buf) throws IOException { + } + + public final void writePacketData(PacketBuffer buf) throws IOException { + } + + public void processPacket(IClientLoginHandler handler) { + handler.handleLoginSuccess(this); + } +} diff --git a/common/src/main/java/common/packet/RPacketRequestEncrypt.java b/common/src/main/java/common/packet/RPacketRequestEncrypt.java new file mode 100644 index 0000000..4492a17 --- /dev/null +++ b/common/src/main/java/common/packet/RPacketRequestEncrypt.java @@ -0,0 +1,44 @@ +package common.packet; + +import java.io.IOException; +import java.security.PublicKey; + +import common.network.IClientLoginHandler; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.EncryptUtil; + +public class RPacketRequestEncrypt implements Packet { + private PublicKey key; + private PublicKey tempKey; + + public RPacketRequestEncrypt() { + } + + public RPacketRequestEncrypt(PublicKey key, PublicKey tempKey) { + this.key = key; + this.tempKey = tempKey; + } + + public final void readPacketData(PacketBuffer buf) throws IOException { + this.key = EncryptUtil.decodePublicKey(buf.readByteArray()); + this.tempKey = EncryptUtil.decodeDHPublicKey(buf.readByteArray()); + } + + public final void writePacketData(PacketBuffer buf) throws IOException { + buf.writeByteArray(this.key.getEncoded()); + buf.writeByteArray(this.tempKey.getEncoded()); + } + + public void processPacket(IClientLoginHandler handler) { + handler.handleEncrypt(this); + } + + public PublicKey getKey() { + return this.key; + } + + public PublicKey getTempKey() { + return this.tempKey; + } +} diff --git a/common/src/main/java/common/packet/RPacketResponse.java b/common/src/main/java/common/packet/RPacketResponse.java new file mode 100644 index 0000000..aa3e490 --- /dev/null +++ b/common/src/main/java/common/packet/RPacketResponse.java @@ -0,0 +1,37 @@ +package common.packet; + +import java.io.IOException; +import java.security.PrivateKey; +import java.security.PublicKey; + +import common.network.IClientLoginHandler; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.EncryptUtil; + +public class RPacketResponse implements Packet { + private byte[] token = new byte[0]; + + public RPacketResponse() { + } + + public RPacketResponse(PrivateKey key, byte[] token) { + this.token = EncryptUtil.createSignature(key, token); + } + + public void readPacketData(PacketBuffer buf) throws IOException { + this.token = buf.readByteArray(); + } + + public void writePacketData(PacketBuffer buf) throws IOException { + buf.writeByteArray(this.token); + } + + public void processPacket(IClientLoginHandler handler) { + handler.handleResponse(this); + } + + public boolean verifyToken(PublicKey key, byte[] token) { + return EncryptUtil.verifySignature(key, token, this.token); + } +} diff --git a/common/src/main/java/common/packet/RPacketServerConfig.java b/common/src/main/java/common/packet/RPacketServerConfig.java new file mode 100644 index 0000000..5c5a2e9 --- /dev/null +++ b/common/src/main/java/common/packet/RPacketServerConfig.java @@ -0,0 +1,60 @@ +package common.packet; + +import java.io.IOException; +import common.network.IClientLoginHandler; +import common.network.Packet; +import common.network.PacketBuffer; + +public class RPacketServerConfig implements Packet { + private boolean requiresAccess; + private boolean requiresAuth; + private boolean passwordAuth; + private boolean pubkeyAuth; + + public RPacketServerConfig() { + } + + public RPacketServerConfig(boolean requiresAccess, boolean requiresAuth, boolean passwordAuth, boolean pubkeyAuth) { + this.requiresAccess = requiresAccess; + this.requiresAuth = requiresAuth; + this.passwordAuth = passwordAuth; + this.pubkeyAuth = pubkeyAuth; + } + + public final void readPacketData(PacketBuffer buf) throws IOException { + byte flags = buf.readByte(); + this.requiresAccess = (flags & 1) != 0; + this.requiresAuth = (flags & 2) != 0; + this.passwordAuth = (flags & 4) != 0; + this.pubkeyAuth = (flags & 8) != 0; + } + + public final void writePacketData(PacketBuffer buf) throws IOException { + byte flags = 0; + flags |= this.requiresAccess ? 1 : 0; + flags |= this.requiresAuth ? 2 : 0; + flags |= this.passwordAuth ? 4 : 0; + flags |= this.pubkeyAuth ? 8 : 0; + buf.writeByte(flags); + } + + public void processPacket(IClientLoginHandler handler) { + handler.handleConfig(this); + } + + public boolean hasAccessPassword() { + return this.requiresAccess; + } + + public boolean isAuthenticating() { + return this.requiresAuth; + } + + public boolean canUsePassword() { + return this.passwordAuth; + } + + public boolean canUsePubkey() { + return this.pubkeyAuth; + } +} diff --git a/java/src/game/packet/SPacketAnimation.java b/common/src/main/java/common/packet/SPacketAnimation.java similarity index 75% rename from java/src/game/packet/SPacketAnimation.java rename to common/src/main/java/common/packet/SPacketAnimation.java index 0593b16..de8b50d 100755 --- a/java/src/game/packet/SPacketAnimation.java +++ b/common/src/main/java/common/packet/SPacketAnimation.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.entity.Entity; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketAnimation implements Packet +public class SPacketAnimation implements Packet { private int entityId; private int type; @@ -33,19 +33,19 @@ public class SPacketAnimation implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarInt(); this.type = buf.readUnsignedByte(); // this.par = buf.readVarIntFromBuffer(); } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); buf.writeByte(this.type); // buf.writeVarIntToBuffer(this.par); } - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleAnimation(this); } diff --git a/common/src/main/java/common/packet/SPacketBiome.java b/common/src/main/java/common/packet/SPacketBiome.java new file mode 100755 index 0000000..9991545 --- /dev/null +++ b/common/src/main/java/common/packet/SPacketBiome.java @@ -0,0 +1,56 @@ +package common.packet; + +import java.io.IOException; + +import common.biome.Biome; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; + +public class SPacketBiome implements Packet { + private int posX; + private int posZ; + private Biome biome; + + public SPacketBiome() { + } + + public SPacketBiome(BlockPos pos, Biome biome) { + this.posX = pos.getX(); + this.posZ = pos.getZ(); + this.biome = biome; + } + + public void readPacketData(PacketBuffer buf) throws IOException { + this.posX = buf.readInt(); + this.posZ = buf.readInt(); + this.biome = buf.readEnumValue(Biome.class); + } + + public void writePacketData(PacketBuffer buf) throws IOException { + buf.writeInt(this.posX); + buf.writeInt(this.posZ); + buf.writeEnumValue(this.biome); + } + + public void processPacket(IClientPlayer handler) { + handler.handleBiomes(this); + } + + public int getChunkX() { + return this.posX >> 4; + } + + public int getChunkZ() { + return this.posZ >> 4; + } + + public BlockPos getPos() { + return new BlockPos(this.posX, 0, this.posZ); + } + + public Biome getBiome() { + return this.biome; + } +} diff --git a/java/src/game/packet/SPacketBlockAction.java b/common/src/main/java/common/packet/SPacketBlockAction.java similarity index 76% rename from java/src/game/packet/SPacketBlockAction.java rename to common/src/main/java/common/packet/SPacketBlockAction.java index 3a5bfb8..083cf7f 100755 --- a/java/src/game/packet/SPacketBlockAction.java +++ b/common/src/main/java/common/packet/SPacketBlockAction.java @@ -1,15 +1,15 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.block.Block; -import game.init.BlockRegistry; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; +import common.block.Block; +import common.init.BlockRegistry; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; -public class SPacketBlockAction implements Packet +public class SPacketBlockAction implements Packet { private BlockPos blockPosition; private int instrument; @@ -36,7 +36,7 @@ public class SPacketBlockAction implements Packet this.blockPosition = buf.readBlockPos(); this.instrument = buf.readUnsignedByte(); this.pitch = buf.readUnsignedByte(); - this.block = BlockRegistry.getBlockById(buf.readVarIntFromBuffer() & 4095); + this.block = BlockRegistry.getBlockById(buf.readVarInt() & 4095); } /** @@ -47,13 +47,13 @@ public class SPacketBlockAction implements Packet buf.writeBlockPos(this.blockPosition); buf.writeByte(this.instrument); buf.writeByte(this.pitch); - buf.writeVarIntToBuffer(BlockRegistry.getIdFromBlock(this.block) & 4095); + buf.writeVarInt(BlockRegistry.getIdFromBlock(this.block) & 4095); } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleBlockAction(this); } diff --git a/java/src/game/packet/SPacketBlockBreakAnim.java b/common/src/main/java/common/packet/SPacketBlockBreakAnim.java similarity index 76% rename from java/src/game/packet/SPacketBlockBreakAnim.java rename to common/src/main/java/common/packet/SPacketBlockBreakAnim.java index 13c487f..1b1acec 100755 --- a/java/src/game/packet/SPacketBlockBreakAnim.java +++ b/common/src/main/java/common/packet/SPacketBlockBreakAnim.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; -public class SPacketBlockBreakAnim implements Packet +public class SPacketBlockBreakAnim implements Packet { private int breakerId; private BlockPos position; @@ -29,7 +29,7 @@ public class SPacketBlockBreakAnim implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.breakerId = buf.readVarIntFromBuffer(); + this.breakerId = buf.readVarInt(); this.position = buf.readBlockPos(); this.progress = buf.readUnsignedByte(); } @@ -39,7 +39,7 @@ public class SPacketBlockBreakAnim implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.breakerId); + buf.writeVarInt(this.breakerId); buf.writeBlockPos(this.position); buf.writeByte(this.progress); } @@ -47,7 +47,7 @@ public class SPacketBlockBreakAnim implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleBlockBreakAnim(this); } diff --git a/java/src/game/packet/SPacketBlockChange.java b/common/src/main/java/common/packet/SPacketBlockChange.java similarity index 70% rename from java/src/game/packet/SPacketBlockChange.java rename to common/src/main/java/common/packet/SPacketBlockChange.java index 3924844..ca79376 100755 --- a/java/src/game/packet/SPacketBlockChange.java +++ b/common/src/main/java/common/packet/SPacketBlockChange.java @@ -1,16 +1,16 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.init.BlockRegistry; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.init.BlockRegistry; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; +import common.world.State; +import common.world.World; -public class SPacketBlockChange implements Packet +public class SPacketBlockChange implements Packet { private BlockPos blockPosition; private State blockState; @@ -31,7 +31,7 @@ public class SPacketBlockChange implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.blockPosition = buf.readBlockPos(); - this.blockState = (State)BlockRegistry.STATEMAP.getByValue(buf.readVarIntFromBuffer()); + this.blockState = (State)BlockRegistry.STATEMAP.getByValue(buf.readVarInt()); } /** @@ -40,13 +40,13 @@ public class SPacketBlockChange implements Packet public void writePacketData(PacketBuffer buf) throws IOException { buf.writeBlockPos(this.blockPosition); - buf.writeVarIntToBuffer(BlockRegistry.STATEMAP.get(this.blockState)); + buf.writeVarInt(BlockRegistry.STATEMAP.get(this.blockState)); } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleBlockChange(this); } diff --git a/java/src/game/packet/SPacketCamera.java b/common/src/main/java/common/packet/SPacketCamera.java similarity index 58% rename from java/src/game/packet/SPacketCamera.java rename to common/src/main/java/common/packet/SPacketCamera.java index 8b8c932..d72765c 100755 --- a/java/src/game/packet/SPacketCamera.java +++ b/common/src/main/java/common/packet/SPacketCamera.java @@ -1,14 +1,14 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.entity.Entity; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.World; +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.world.World; -public class SPacketCamera implements Packet +public class SPacketCamera implements Packet { public int entityId; @@ -23,15 +23,15 @@ public class SPacketCamera implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarInt(); } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); } - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleCamera(this); } diff --git a/java/src/game/packet/S2BPacketChangeGameState.java b/common/src/main/java/common/packet/SPacketChangeGameState.java similarity index 64% rename from java/src/game/packet/S2BPacketChangeGameState.java rename to common/src/main/java/common/packet/SPacketChangeGameState.java index 3a29de1..2485d8a 100755 --- a/java/src/game/packet/S2BPacketChangeGameState.java +++ b/common/src/main/java/common/packet/SPacketChangeGameState.java @@ -1,32 +1,32 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.util.ExtMath; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.ExtMath; -public class S2BPacketChangeGameState implements Packet +public class SPacketChangeGameState implements Packet { private Action action; private int param; - public S2BPacketChangeGameState() + public SPacketChangeGameState() { } - public S2BPacketChangeGameState(Action action) + public SPacketChangeGameState(Action action) { this(action, 0); } - public S2BPacketChangeGameState(Action action, float param) + public SPacketChangeGameState(Action action, float param) { this(action, (int)(param * 1000.0f)); } - public S2BPacketChangeGameState(Action action, int param) + public SPacketChangeGameState(Action action, int param) { this.action = action; this.param = param; @@ -35,16 +35,16 @@ public class S2BPacketChangeGameState implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.action = buf.readEnumValue(Action.class); - this.param = buf.readVarIntFromBuffer(); + this.param = buf.readVarInt(); } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeEnumValue(this.action); - buf.writeVarIntToBuffer(this.param); + buf.writeVarInt(this.param); } - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleChangeGameState(this); } diff --git a/java/src/game/packet/SPacketCharacterList.java b/common/src/main/java/common/packet/SPacketCharacterList.java similarity index 56% rename from java/src/game/packet/SPacketCharacterList.java rename to common/src/main/java/common/packet/SPacketCharacterList.java index f375a4b..88777b8 100644 --- a/java/src/game/packet/SPacketCharacterList.java +++ b/common/src/main/java/common/packet/SPacketCharacterList.java @@ -1,20 +1,20 @@ -package game.packet; +package common.packet; import java.io.IOException; import java.util.Collection; import java.util.Map; import java.util.Map.Entry; -import game.collect.Maps; -import game.entity.npc.Alignment; -import game.entity.npc.PlayerCharacter; -import game.network.ClientPlayer; -import game.network.Player; -import game.world.BlockPos; -import game.network.Packet; -import game.network.PacketBuffer; +import common.collect.Maps; +import common.entity.npc.Alignment; +import common.entity.npc.PlayerCharacter; +import common.network.IClientPlayer; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; -public class SPacketCharacterList implements Packet { +public class SPacketCharacterList implements Packet { private final Map players = Maps.newHashMap(); private int selected; @@ -40,47 +40,47 @@ public class SPacketCharacterList implements Packet { } public void readPacketData(PacketBuffer buf) throws IOException { - int n = buf.readVarIntFromBuffer(); + int n = buf.readVarInt(); for(int z = 0; z < n; z++) { - int id = buf.readVarIntFromBuffer(); - String name = buf.readStringFromBuffer(Player.MAX_NICK_LENGTH); + int id = buf.readVarInt(); + String name = buf.readString(IPlayer.MAX_NICK_LENGTH); if(name.isEmpty()) { this.players.put(id, null); continue; } - String info = buf.readStringFromBuffer(Player.MAX_INFO_LENGTH); + String info = buf.readString(IPlayer.MAX_INFO_LENGTH); info = info.isEmpty() ? null : info; Alignment align = buf.readEnumValue(Alignment.class); - String dim = buf.readStringFromBuffer(256); + String dim = buf.readString(256); BlockPos pos = buf.readBlockPos(); - String type = buf.readStringFromBuffer(256); - int level = buf.readVarIntFromBuffer(); + String type = buf.readString(256); + int level = buf.readVarInt(); this.players.put(id, new PlayerCharacter(name, info, align, dim, pos, type, level)); } - this.selected = buf.readVarIntFromBuffer(); + this.selected = buf.readVarInt(); } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.players.size()); + buf.writeVarInt(this.players.size()); for(Entry data : this.players.entrySet()) { PlayerCharacter chr = data.getValue(); - buf.writeVarIntToBuffer(data.getKey()); + buf.writeVarInt(data.getKey()); if(chr == null) { buf.writeString(""); continue; } - buf.writeString(chr.name); - buf.writeString(chr.info == null ? "" : chr.info); - buf.writeEnumValue(chr.align); - buf.writeString(chr.dim); - buf.writeBlockPos(chr.pos); - buf.writeString(chr.type); - buf.writeVarIntToBuffer(chr.level); + buf.writeString(chr.name()); + buf.writeString(chr.info() == null ? "" : chr.info()); + buf.writeEnumValue(chr.align()); + buf.writeString(chr.dim()); + buf.writeBlockPos(chr.pos()); + buf.writeString(chr.type()); + buf.writeVarInt(chr.level()); } - buf.writeVarIntToBuffer(this.selected); + buf.writeVarInt(this.selected); } - public void processPacket(ClientPlayer handler) { + public void processPacket(IClientPlayer handler) { handler.handleCharacterList(this); } diff --git a/common/src/main/java/common/packet/SPacketChunkData.java b/common/src/main/java/common/packet/SPacketChunkData.java new file mode 100755 index 0000000..3aac135 --- /dev/null +++ b/common/src/main/java/common/packet/SPacketChunkData.java @@ -0,0 +1,105 @@ +package common.packet; + +import java.io.IOException; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; + +public class SPacketChunkData implements Packet +{ + private int chunkX; + private int chunkZ; + private SPacketChunkData.Extracted extractedData; + private boolean biomes; + + public SPacketChunkData() + { + } + + public SPacketChunkData(int x, int z, boolean biomes, SPacketChunkData.Extracted data) + { + this.chunkX = x; + this.chunkZ = z; + this.biomes = biomes; + this.extractedData = data; + } + + /** + * Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer buf) throws IOException + { + this.chunkX = buf.readInt(); + this.chunkZ = buf.readInt(); + this.biomes = buf.readBoolean(); + this.extractedData = new SPacketChunkData.Extracted(); + this.extractedData.data = buf.readByteArray(); + this.extractedData.extend = new int[buf.readVarInt()]; + for(int z = 0; z < this.extractedData.extend.length; z++) { + this.extractedData.extend[z] = buf.readVarInt(); + } + } + + /** + * Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeInt(this.chunkX); + buf.writeInt(this.chunkZ); + buf.writeBoolean(this.biomes); + buf.writeByteArray(this.extractedData.data); + buf.writeVarInt(this.extractedData.extend.length); + for(int z = 0; z < this.extractedData.extend.length; z++) { + buf.writeVarInt(this.extractedData.extend[z]); + } + } + + /** + * Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(IClientPlayer handler) + { + handler.handleChunkData(this); + } + + public byte[] getExtractedDataBytes() + { + return this.extractedData.data; + } + + public static int getSize(int segments, boolean overworld, boolean biomes) + { + int i = segments * 2 * 16 * 16 * 16; + int j = segments * 16 * 16 * 16 / 2; + int k = overworld ? segments * 16 * 16 * 16 / 2 : 0; + int l = biomes ? 256 : 0; + return i + j + k + l; + } + + public int getChunkX() + { + return this.chunkX; + } + + public int getChunkZ() + { + return this.chunkZ; + } + + public int[] getExtractedExtend() + { + return this.extractedData.extend; + } + + public boolean hasBiomes() + { + return this.biomes; + } + + public static class Extracted + { + public byte[] data; + public int[] extend; + } +} diff --git a/java/src/game/packet/S2EPacketCloseWindow.java b/common/src/main/java/common/packet/SPacketCloseWindow.java similarity index 66% rename from java/src/game/packet/S2EPacketCloseWindow.java rename to common/src/main/java/common/packet/SPacketCloseWindow.java index fedeedd..28b01f9 100755 --- a/java/src/game/packet/S2EPacketCloseWindow.java +++ b/common/src/main/java/common/packet/SPacketCloseWindow.java @@ -1,20 +1,20 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class S2EPacketCloseWindow implements Packet +public class SPacketCloseWindow implements Packet { private int windowId; - public S2EPacketCloseWindow() + public SPacketCloseWindow() { } - public S2EPacketCloseWindow(int windowIdIn) + public SPacketCloseWindow(int windowIdIn) { this.windowId = windowIdIn; } @@ -22,7 +22,7 @@ public class S2EPacketCloseWindow implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleCloseWindow(this); } diff --git a/java/src/game/packet/SPacketCollectItem.java b/common/src/main/java/common/packet/SPacketCollectItem.java similarity index 67% rename from java/src/game/packet/SPacketCollectItem.java rename to common/src/main/java/common/packet/SPacketCollectItem.java index b6103e9..ea5d18f 100755 --- a/java/src/game/packet/SPacketCollectItem.java +++ b/common/src/main/java/common/packet/SPacketCollectItem.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketCollectItem implements Packet +public class SPacketCollectItem implements Packet { private int collectedItemEntityId; private int entityId; @@ -26,8 +26,8 @@ public class SPacketCollectItem implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.collectedItemEntityId = buf.readVarIntFromBuffer(); - this.entityId = buf.readVarIntFromBuffer(); + this.collectedItemEntityId = buf.readVarInt(); + this.entityId = buf.readVarInt(); } /** @@ -35,14 +35,14 @@ public class SPacketCollectItem implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.collectedItemEntityId); - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.collectedItemEntityId); + buf.writeVarInt(this.entityId); } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleCollectItem(this); } diff --git a/java/src/game/packet/S32PacketConfirmTransaction.java b/common/src/main/java/common/packet/SPacketConfirmTransaction.java similarity index 75% rename from java/src/game/packet/S32PacketConfirmTransaction.java rename to common/src/main/java/common/packet/SPacketConfirmTransaction.java index a639e29..e09cd3e 100755 --- a/java/src/game/packet/S32PacketConfirmTransaction.java +++ b/common/src/main/java/common/packet/SPacketConfirmTransaction.java @@ -1,22 +1,22 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class S32PacketConfirmTransaction implements Packet +public class SPacketConfirmTransaction implements Packet { private int windowId; private short actionNumber; private boolean matching; - public S32PacketConfirmTransaction() + public SPacketConfirmTransaction() { } - public S32PacketConfirmTransaction(int windowIdIn, short actionNumberIn, boolean matching) + public SPacketConfirmTransaction(int windowIdIn, short actionNumberIn, boolean matching) { this.windowId = windowIdIn; this.actionNumber = actionNumberIn; @@ -26,7 +26,7 @@ public class S32PacketConfirmTransaction implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleConfirmTransaction(this); } diff --git a/java/src/game/packet/SPacketDestroyEntities.java b/common/src/main/java/common/packet/SPacketDestroyEntities.java similarity index 65% rename from java/src/game/packet/SPacketDestroyEntities.java rename to common/src/main/java/common/packet/SPacketDestroyEntities.java index 2124150..aafef94 100755 --- a/java/src/game/packet/SPacketDestroyEntities.java +++ b/common/src/main/java/common/packet/SPacketDestroyEntities.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketDestroyEntities implements Packet +public class SPacketDestroyEntities implements Packet { private int[] entityIDs; @@ -24,11 +24,11 @@ public class SPacketDestroyEntities implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityIDs = new int[buf.readVarIntFromBuffer()]; + this.entityIDs = new int[buf.readVarInt()]; for (int i = 0; i < this.entityIDs.length; ++i) { - this.entityIDs[i] = buf.readVarIntFromBuffer(); + this.entityIDs[i] = buf.readVarInt(); } } @@ -37,18 +37,18 @@ public class SPacketDestroyEntities implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityIDs.length); + buf.writeVarInt(this.entityIDs.length); for (int i = 0; i < this.entityIDs.length; ++i) { - buf.writeVarIntToBuffer(this.entityIDs[i]); + buf.writeVarInt(this.entityIDs[i]); } } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleDestroyEntities(this); } diff --git a/java/src/game/packet/SPacketDimensionName.java b/common/src/main/java/common/packet/SPacketDimensionName.java similarity index 69% rename from java/src/game/packet/SPacketDimensionName.java rename to common/src/main/java/common/packet/SPacketDimensionName.java index 6f9110b..2523147 100755 --- a/java/src/game/packet/SPacketDimensionName.java +++ b/common/src/main/java/common/packet/SPacketDimensionName.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.dimension.Dimension; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.dimension.Dimension; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketDimensionName implements Packet { +public class SPacketDimensionName implements Packet { private String fullName; private String customName; @@ -20,13 +20,13 @@ public class SPacketDimensionName implements Packet { dim.getCustomName(); } - public void processPacket(ClientPlayer handler) { + public void processPacket(IClientPlayer handler) { handler.handleDimName(this); } public void readPacketData(PacketBuffer buf) throws IOException { - this.fullName = buf.readStringFromBuffer(64); - this.customName = buf.readStringFromBuffer(64); + this.fullName = buf.readString(64); + this.customName = buf.readString(64); this.customName = this.customName.isEmpty() ? null : this.customName; } diff --git a/common/src/main/java/common/packet/SPacketDisconnect.java b/common/src/main/java/common/packet/SPacketDisconnect.java new file mode 100755 index 0000000..f558fc0 --- /dev/null +++ b/common/src/main/java/common/packet/SPacketDisconnect.java @@ -0,0 +1,34 @@ +package common.packet; + +import java.io.IOException; + +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; + +public class SPacketDisconnect implements Packet { + private String message; + + public SPacketDisconnect() { + } + + public SPacketDisconnect(String message) { + this.message = message; + } + + public void readPacketData(PacketBuffer buf) throws IOException { + this.message = buf.readString(2048); + } + + public void writePacketData(PacketBuffer buf) throws IOException { + buf.writeString(this.message); + } + + public void processPacket(IClientPlayer handler) { + handler.handleDisconnect(this); + } + + public String getMessage() { + return this.message; + } +} diff --git a/common/src/main/java/common/packet/SPacketDisplayForm.java b/common/src/main/java/common/packet/SPacketDisplayForm.java new file mode 100644 index 0000000..7532ab5 --- /dev/null +++ b/common/src/main/java/common/packet/SPacketDisplayForm.java @@ -0,0 +1,99 @@ +package common.packet; + +import java.io.IOException; + +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.Triplet; + +public class SPacketDisplayForm implements Packet +{ + private int id; + private String title; + private Triplet[] data; + + public SPacketDisplayForm() + { + } + + public SPacketDisplayForm(int id, String title, Triplet[] data) + { + this.id = id; + this.title = title; + this.data = data; + } + + public void processPacket(IClientPlayer handler) + { + handler.handleForm(this); + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + this.id = buf.readVarInt(); + this.title = buf.readString(256); + this.data = new Triplet[buf.readVarInt()]; + for(int z = 0; z < this.data.length; z++) { + String name = buf.readString(64); + Object obj; + switch(buf.readByte()) { + case 0: + obj = buf.readBoolean(); + break; + case 1: + String[] strs = new String[buf.readVarInt()]; + obj = strs; + for(int n = 0; n < strs.length; n++) { + strs[n] = buf.readString(128); + } + break; + default: + obj = buf.readString(256); + break; + } + this.data[z] = new Triplet(name, obj, buf.readVarInt()); + } + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeVarInt(this.id); + buf.writeString(this.title); + buf.writeVarInt(this.data.length); + for(int z = 0; z < this.data.length; z++) { + buf.writeString(this.data[z].first()); + Object obj = this.data[z].second(); + if(obj instanceof Boolean) { + buf.writeByte(0); + buf.writeBoolean((Boolean)obj); + } + else if(obj instanceof String[]) { + buf.writeByte(1); + String[] strs = (String[])obj; + buf.writeVarInt(strs.length); + for(int n = 0; n < strs.length; n++) { + buf.writeString(strs[n]); + } + } + else { + buf.writeByte(2); + buf.writeString((String)obj); + } + buf.writeVarInt(this.data[z].third()); + } + } + + public Triplet[] getData() + { + return this.data; + } + + public String getTitle() { + return this.title; + } + + public int getId() { + return this.id; + } +} diff --git a/java/src/game/packet/S28PacketEffect.java b/common/src/main/java/common/packet/SPacketEffect.java similarity index 67% rename from java/src/game/packet/S28PacketEffect.java rename to common/src/main/java/common/packet/SPacketEffect.java index 263e148..9c81fb1 100755 --- a/java/src/game/packet/S28PacketEffect.java +++ b/common/src/main/java/common/packet/SPacketEffect.java @@ -1,21 +1,21 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; -public class S28PacketEffect implements Packet { +public class SPacketEffect implements Packet { private int soundType; private BlockPos soundPos; private int soundData; - public S28PacketEffect() { + public SPacketEffect() { } - public S28PacketEffect(int soundTypeIn, BlockPos soundPosIn, int soundDataIn) { + public SPacketEffect(int soundTypeIn, BlockPos soundPosIn, int soundDataIn) { this.soundType = soundTypeIn; this.soundPos = soundPosIn; this.soundData = soundDataIn; @@ -33,7 +33,7 @@ public class S28PacketEffect implements Packet { buf.writeInt(this.soundData); } - public void processPacket(ClientPlayer handler) { + public void processPacket(IClientPlayer handler) { handler.handleEffect(this); } diff --git a/common/src/main/java/common/packet/SPacketEntity.java b/common/src/main/java/common/packet/SPacketEntity.java new file mode 100755 index 0000000..7b05088 --- /dev/null +++ b/common/src/main/java/common/packet/SPacketEntity.java @@ -0,0 +1,99 @@ +package common.packet; + +import java.io.IOException; + +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.world.World; + +public class SPacketEntity implements Packet +{ + protected int entityId; + protected byte posX; + protected byte posY; + protected byte posZ; + protected byte yaw; + protected byte pitch; + protected boolean onGround; + protected boolean rotation; + + public SPacketEntity() + { + } + + public SPacketEntity(int entityIdIn) + { + this.entityId = entityIdIn; + } + + /** + * Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer buf) throws IOException + { + this.entityId = buf.readVarInt(); + } + + /** + * Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeVarInt(this.entityId); + } + + /** + * Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(IClientPlayer handler) + { + handler.handleEntityMovement(this); + } + + public String toString() + { + return "Entity_" + super.toString(); + } + + public Entity getEntity(World worldIn) + { + return worldIn.getEntityByID(this.entityId); + } + + public byte getPosX() + { + return this.posX; + } + + public byte getPosY() + { + return this.posY; + } + + public byte getPosZ() + { + return this.posZ; + } + + public byte getYaw() + { + return this.yaw; + } + + public byte getPitch() + { + return this.pitch; + } + + public boolean hasRotations() + { + return this.rotation; + } + + public boolean getOnGround() + { + return this.onGround; + } +} diff --git a/java/src/game/packet/S1BPacketEntityAttach.java b/common/src/main/java/common/packet/SPacketEntityAttach.java similarity index 75% rename from java/src/game/packet/S1BPacketEntityAttach.java rename to common/src/main/java/common/packet/SPacketEntityAttach.java index 7b30497..618311a 100755 --- a/java/src/game/packet/S1BPacketEntityAttach.java +++ b/common/src/main/java/common/packet/SPacketEntityAttach.java @@ -1,23 +1,23 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.entity.Entity; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class S1BPacketEntityAttach implements Packet +public class SPacketEntityAttach implements Packet { private int leash; private int entityId; private int vehicleEntityId; - public S1BPacketEntityAttach() + public SPacketEntityAttach() { } - public S1BPacketEntityAttach(int leashIn, Entity entityIn, Entity vehicle) + public SPacketEntityAttach(int leashIn, Entity entityIn, Entity vehicle) { this.leash = leashIn; this.entityId = entityIn.getId(); @@ -47,7 +47,7 @@ public class S1BPacketEntityAttach implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleEntityAttach(this); } diff --git a/java/src/game/packet/S1DPacketEntityEffect.java b/common/src/main/java/common/packet/SPacketEntityEffect.java similarity index 68% rename from java/src/game/packet/S1DPacketEntityEffect.java rename to common/src/main/java/common/packet/SPacketEntityEffect.java index 418d84b..ce38939 100755 --- a/java/src/game/packet/S1DPacketEntityEffect.java +++ b/common/src/main/java/common/packet/SPacketEntityEffect.java @@ -1,14 +1,14 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.potion.Potion; -import game.potion.PotionEffect; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.potion.Potion; +import common.potion.PotionEffect; -public class S1DPacketEntityEffect implements Packet +public class SPacketEntityEffect implements Packet { private int entityId; private Potion effectId; @@ -17,11 +17,11 @@ public class S1DPacketEntityEffect implements Packet private int remaining; private boolean particles; - public S1DPacketEntityEffect() + public SPacketEntityEffect() { } - public S1DPacketEntityEffect(int entityIdIn, PotionEffect effect) + public SPacketEntityEffect(int entityIdIn, PotionEffect effect) { this.entityId = entityIdIn; this.effectId = effect.getPotion(); @@ -45,11 +45,11 @@ public class S1DPacketEntityEffect implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarInt(); this.effectId = buf.readEnumValue(Potion.class); - this.amplifier = buf.readVarIntFromBuffer(); - this.duration = buf.readVarIntFromBuffer(); - this.remaining = buf.readVarIntFromBuffer(); + this.amplifier = buf.readVarInt(); + this.duration = buf.readVarInt(); + this.remaining = buf.readVarInt(); this.particles = buf.readBoolean(); } @@ -58,18 +58,18 @@ public class S1DPacketEntityEffect implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); buf.writeEnumValue(this.effectId); - buf.writeVarIntToBuffer(this.amplifier); - buf.writeVarIntToBuffer(this.duration); - buf.writeVarIntToBuffer(this.remaining); + buf.writeVarInt(this.amplifier); + buf.writeVarInt(this.duration); + buf.writeVarInt(this.remaining); buf.writeBoolean(this.particles); } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleEntityEffect(this); } diff --git a/java/src/game/packet/SPacketEntityEquipment.java b/common/src/main/java/common/packet/SPacketEntityEquipment.java similarity index 71% rename from java/src/game/packet/SPacketEntityEquipment.java rename to common/src/main/java/common/packet/SPacketEntityEquipment.java index 07425c7..8497508 100755 --- a/java/src/game/packet/SPacketEntityEquipment.java +++ b/common/src/main/java/common/packet/SPacketEntityEquipment.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.item.ItemStack; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.item.ItemStack; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketEntityEquipment implements Packet +public class SPacketEntityEquipment implements Packet { private int entityID; private int equipmentSlot; @@ -29,9 +29,9 @@ public class SPacketEntityEquipment implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityID = buf.readVarIntFromBuffer(); + this.entityID = buf.readVarInt(); this.equipmentSlot = buf.readShort(); - this.itemStack = buf.readItemStackFromBuffer(); + this.itemStack = buf.readItemStack(); } /** @@ -39,15 +39,15 @@ public class SPacketEntityEquipment implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityID); + buf.writeVarInt(this.entityID); buf.writeShort(this.equipmentSlot); - buf.writeItemStackToBuffer(this.itemStack); + buf.writeItemStack(this.itemStack); } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleEntityEquipment(this); } diff --git a/java/src/game/packet/S19PacketEntityHeadLook.java b/common/src/main/java/common/packet/SPacketEntityHeadLook.java similarity index 63% rename from java/src/game/packet/S19PacketEntityHeadLook.java rename to common/src/main/java/common/packet/SPacketEntityHeadLook.java index d4c012e..76f5ddf 100755 --- a/java/src/game/packet/S19PacketEntityHeadLook.java +++ b/common/src/main/java/common/packet/SPacketEntityHeadLook.java @@ -1,23 +1,23 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.entity.Entity; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.World; +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.world.World; -public class S19PacketEntityHeadLook implements Packet +public class SPacketEntityHeadLook implements Packet { private int entityId; private byte yaw; - public S19PacketEntityHeadLook() + public SPacketEntityHeadLook() { } - public S19PacketEntityHeadLook(Entity entityIn, byte p_i45214_2_) + public SPacketEntityHeadLook(Entity entityIn, byte p_i45214_2_) { this.entityId = entityIn.getId(); this.yaw = p_i45214_2_; @@ -28,7 +28,7 @@ public class S19PacketEntityHeadLook implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarInt(); this.yaw = buf.readByte(); } @@ -37,14 +37,14 @@ public class S19PacketEntityHeadLook implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); buf.writeByte(this.yaw); } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleEntityHeadLook(this); } diff --git a/common/src/main/java/common/packet/SPacketEntityLook.java b/common/src/main/java/common/packet/SPacketEntityLook.java new file mode 100644 index 0000000..e9ffbb0 --- /dev/null +++ b/common/src/main/java/common/packet/SPacketEntityLook.java @@ -0,0 +1,38 @@ +package common.packet; + +import java.io.IOException; + +import common.network.PacketBuffer; + +public class SPacketEntityLook extends SPacketEntity +{ + public SPacketEntityLook() + { + this.rotation = true; + } + + public SPacketEntityLook(int entityIdIn, byte yawIn, byte pitchIn, boolean onGroundIn) + { + super(entityIdIn); + this.yaw = yawIn; + this.pitch = pitchIn; + this.rotation = true; + this.onGround = onGroundIn; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + super.readPacketData(buf); + this.yaw = buf.readByte(); + this.pitch = buf.readByte(); + this.onGround = buf.readBoolean(); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + super.writePacketData(buf); + buf.writeByte(this.yaw); + buf.writeByte(this.pitch); + buf.writeBoolean(this.onGround); + } +} \ No newline at end of file diff --git a/common/src/main/java/common/packet/SPacketEntityLookMove.java b/common/src/main/java/common/packet/SPacketEntityLookMove.java new file mode 100644 index 0000000..878aa46 --- /dev/null +++ b/common/src/main/java/common/packet/SPacketEntityLookMove.java @@ -0,0 +1,47 @@ +package common.packet; + +import java.io.IOException; + +import common.network.PacketBuffer; + +public class SPacketEntityLookMove extends SPacketEntity +{ + public SPacketEntityLookMove() + { + this.rotation = true; + } + + public SPacketEntityLookMove(int p_i45973_1_, byte p_i45973_2_, byte p_i45973_3_, byte p_i45973_4_, byte p_i45973_5_, byte p_i45973_6_, boolean p_i45973_7_) + { + super(p_i45973_1_); + this.posX = p_i45973_2_; + this.posY = p_i45973_3_; + this.posZ = p_i45973_4_; + this.yaw = p_i45973_5_; + this.pitch = p_i45973_6_; + this.onGround = p_i45973_7_; + this.rotation = true; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + super.readPacketData(buf); + this.posX = buf.readByte(); + this.posY = buf.readByte(); + this.posZ = buf.readByte(); + this.yaw = buf.readByte(); + this.pitch = buf.readByte(); + this.onGround = buf.readBoolean(); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + super.writePacketData(buf); + buf.writeByte(this.posX); + buf.writeByte(this.posY); + buf.writeByte(this.posZ); + buf.writeByte(this.yaw); + buf.writeByte(this.pitch); + buf.writeBoolean(this.onGround); + } +} \ No newline at end of file diff --git a/java/src/game/packet/S1CPacketEntityMetadata.java b/common/src/main/java/common/packet/SPacketEntityMetadata.java similarity index 70% rename from java/src/game/packet/S1CPacketEntityMetadata.java rename to common/src/main/java/common/packet/SPacketEntityMetadata.java index 9662fca..fc748e1 100755 --- a/java/src/game/packet/S1CPacketEntityMetadata.java +++ b/common/src/main/java/common/packet/SPacketEntityMetadata.java @@ -1,23 +1,23 @@ -package game.packet; +package common.packet; import java.io.IOException; import java.util.List; -import game.entity.DataWatcher; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.entity.DataWatcher; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class S1CPacketEntityMetadata implements Packet +public class SPacketEntityMetadata implements Packet { private int entityId; private List field_149378_b; - public S1CPacketEntityMetadata() + public SPacketEntityMetadata() { } - public S1CPacketEntityMetadata(int entityIdIn, DataWatcher p_i45217_2_, boolean p_i45217_3_) + public SPacketEntityMetadata(int entityIdIn, DataWatcher p_i45217_2_, boolean p_i45217_3_) { this.entityId = entityIdIn; @@ -36,7 +36,7 @@ public class S1CPacketEntityMetadata implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarInt(); this.field_149378_b = DataWatcher.readWatchedListFromPacketBuffer(buf); } @@ -45,14 +45,14 @@ public class S1CPacketEntityMetadata implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); DataWatcher.writeWatchedListToPacketBuffer(this.field_149378_b, buf); } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleEntityMetadata(this); } diff --git a/common/src/main/java/common/packet/SPacketEntityRelMove.java b/common/src/main/java/common/packet/SPacketEntityRelMove.java new file mode 100644 index 0000000..4c5a9fa --- /dev/null +++ b/common/src/main/java/common/packet/SPacketEntityRelMove.java @@ -0,0 +1,39 @@ +package common.packet; + +import java.io.IOException; + +import common.network.PacketBuffer; + +public class SPacketEntityRelMove extends SPacketEntity +{ + public SPacketEntityRelMove() + { + } + + public SPacketEntityRelMove(int entityIdIn, byte x, byte y, byte z, boolean onGroundIn) + { + super(entityIdIn); + this.posX = x; + this.posY = y; + this.posZ = z; + this.onGround = onGroundIn; + } + + public void readPacketData(PacketBuffer buf) throws IOException + { + super.readPacketData(buf); + this.posX = buf.readByte(); + this.posY = buf.readByte(); + this.posZ = buf.readByte(); + this.onGround = buf.readBoolean(); + } + + public void writePacketData(PacketBuffer buf) throws IOException + { + super.writePacketData(buf); + buf.writeByte(this.posX); + buf.writeByte(this.posY); + buf.writeByte(this.posZ); + buf.writeBoolean(this.onGround); + } +} \ No newline at end of file diff --git a/java/src/game/packet/S1APacketEntityStatus.java b/common/src/main/java/common/packet/SPacketEntityStatus.java similarity index 71% rename from java/src/game/packet/S1APacketEntityStatus.java rename to common/src/main/java/common/packet/SPacketEntityStatus.java index 2771749..6c201c1 100755 --- a/java/src/game/packet/S1APacketEntityStatus.java +++ b/common/src/main/java/common/packet/SPacketEntityStatus.java @@ -1,23 +1,23 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.entity.Entity; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.World; +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.world.World; -public class S1APacketEntityStatus implements Packet +public class SPacketEntityStatus implements Packet { private int entityId; private byte logicOpcode; - public S1APacketEntityStatus() + public SPacketEntityStatus() { } - public S1APacketEntityStatus(Entity entityIn, byte opCodeIn) + public SPacketEntityStatus(Entity entityIn, byte opCodeIn) { this.entityId = entityIn.getId(); this.logicOpcode = opCodeIn; @@ -44,7 +44,7 @@ public class S1APacketEntityStatus implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleEntityStatus(this); } diff --git a/java/src/game/packet/S18PacketEntityTeleport.java b/common/src/main/java/common/packet/SPacketEntityTeleport.java similarity index 78% rename from java/src/game/packet/S18PacketEntityTeleport.java rename to common/src/main/java/common/packet/SPacketEntityTeleport.java index d5e26f0..204fa21 100755 --- a/java/src/game/packet/S18PacketEntityTeleport.java +++ b/common/src/main/java/common/packet/SPacketEntityTeleport.java @@ -1,14 +1,14 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.entity.Entity; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.util.ExtMath; +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.ExtMath; -public class S18PacketEntityTeleport implements Packet +public class SPacketEntityTeleport implements Packet { private int entityId; private int posX; @@ -18,11 +18,11 @@ public class S18PacketEntityTeleport implements Packet private byte pitch; private boolean onGround; - public S18PacketEntityTeleport() + public SPacketEntityTeleport() { } - public S18PacketEntityTeleport(Entity entityIn) + public SPacketEntityTeleport(Entity entityIn) { this.entityId = entityIn.getId(); this.posX = ExtMath.floord(entityIn.posX * 32.0D); @@ -33,7 +33,7 @@ public class S18PacketEntityTeleport implements Packet this.onGround = entityIn.onGround; } - public S18PacketEntityTeleport(int entityIdIn, int posXIn, int posYIn, int posZIn, byte yawIn, byte pitchIn, boolean onGroundIn) + public SPacketEntityTeleport(int entityIdIn, int posXIn, int posYIn, int posZIn, byte yawIn, byte pitchIn, boolean onGroundIn) { this.entityId = entityIdIn; this.posX = posXIn; @@ -49,7 +49,7 @@ public class S18PacketEntityTeleport implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarInt(); this.posX = buf.readInt(); this.posY = buf.readInt(); this.posZ = buf.readInt(); @@ -63,7 +63,7 @@ public class S18PacketEntityTeleport implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); buf.writeInt(this.posX); buf.writeInt(this.posY); buf.writeInt(this.posZ); @@ -75,7 +75,7 @@ public class S18PacketEntityTeleport implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleEntityTeleport(this); } diff --git a/java/src/game/packet/SPacketEntityVelocity.java b/common/src/main/java/common/packet/SPacketEntityVelocity.java similarity index 85% rename from java/src/game/packet/SPacketEntityVelocity.java rename to common/src/main/java/common/packet/SPacketEntityVelocity.java index 5cb59bb..60818b0 100755 --- a/java/src/game/packet/SPacketEntityVelocity.java +++ b/common/src/main/java/common/packet/SPacketEntityVelocity.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.entity.Entity; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketEntityVelocity implements Packet +public class SPacketEntityVelocity implements Packet { private int entityID; private int motionX; @@ -68,7 +68,7 @@ public class SPacketEntityVelocity implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityID = buf.readVarIntFromBuffer(); + this.entityID = buf.readVarInt(); this.motionX = buf.readShort(); this.motionY = buf.readShort(); this.motionZ = buf.readShort(); @@ -79,7 +79,7 @@ public class SPacketEntityVelocity implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityID); + buf.writeVarInt(this.entityID); buf.writeShort(this.motionX); buf.writeShort(this.motionY); buf.writeShort(this.motionZ); @@ -88,7 +88,7 @@ public class SPacketEntityVelocity implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleEntityVelocity(this); } diff --git a/java/src/game/packet/S27PacketExplosion.java b/common/src/main/java/common/packet/SPacketExplosion.java similarity index 87% rename from java/src/game/packet/S27PacketExplosion.java rename to common/src/main/java/common/packet/SPacketExplosion.java index 1124ab6..d9fa7cf 100755 --- a/java/src/game/packet/S27PacketExplosion.java +++ b/common/src/main/java/common/packet/SPacketExplosion.java @@ -1,18 +1,17 @@ -package game.packet; +package common.packet; import java.io.IOException; import java.util.ArrayList; import java.util.List; -import game.collect.Lists; +import common.collect.Lists; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; +import common.util.Vec3; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; -import game.world.Vec3; - -public class S27PacketExplosion implements Packet +public class SPacketExplosion implements Packet { private double posX; private double posY; @@ -24,11 +23,11 @@ public class S27PacketExplosion implements Packet private float field_149159_h; private boolean altSound; - public S27PacketExplosion() + public SPacketExplosion() { } - public S27PacketExplosion(double p_i45193_1_, double y, double z, float strengthIn, List affectedBlocksIn, Vec3 p_i45193_9_, boolean altSound) + public SPacketExplosion(double p_i45193_1_, double y, double z, float strengthIn, List affectedBlocksIn, Vec3 p_i45193_9_, boolean altSound) { this.posX = p_i45193_1_; this.posY = y; @@ -107,7 +106,7 @@ public class S27PacketExplosion implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleExplosion(this); } diff --git a/java/src/game/packet/SPacketHeldItemChange.java b/common/src/main/java/common/packet/SPacketHeldItemChange.java similarity index 77% rename from java/src/game/packet/SPacketHeldItemChange.java rename to common/src/main/java/common/packet/SPacketHeldItemChange.java index b0b8e37..a2066f1 100755 --- a/java/src/game/packet/SPacketHeldItemChange.java +++ b/common/src/main/java/common/packet/SPacketHeldItemChange.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketHeldItemChange implements Packet +public class SPacketHeldItemChange implements Packet { private int heldItemHotbarIndex; @@ -38,7 +38,7 @@ public class SPacketHeldItemChange implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleHeldItemChange(this); } diff --git a/java/src/game/packet/SPacketJoinGame.java b/common/src/main/java/common/packet/SPacketJoinGame.java similarity index 63% rename from java/src/game/packet/SPacketJoinGame.java rename to common/src/main/java/common/packet/SPacketJoinGame.java index 59568d8..2d6606d 100755 --- a/java/src/game/packet/SPacketJoinGame.java +++ b/common/src/main/java/common/packet/SPacketJoinGame.java @@ -1,16 +1,16 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.dimension.Dimension; -import game.nbt.NBTTagCompound; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.dimension.Dimension; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.tags.TagObject; -public class SPacketJoinGame implements Packet { +public class SPacketJoinGame implements Packet { private int entityId; - private NBTTagCompound dimension; + private TagObject dimension; private int type; private boolean editor; @@ -19,26 +19,26 @@ public class SPacketJoinGame implements Packet { public SPacketJoinGame(int entityIdIn, Dimension dimensionIn, int type, boolean editor) { this.entityId = entityIdIn; - this.dimension = dimensionIn.toNbt(false); + this.dimension = dimensionIn.toTags(false); this.type = type; this.editor = editor; } public void readPacketData(PacketBuffer buf) throws IOException { this.entityId = buf.readInt(); - this.dimension = buf.readNBTTagCompoundFromBuffer(); + this.dimension = buf.readTag(); this.type = buf.readUnsignedShort(); this.editor = buf.readBoolean(); } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeInt(this.entityId); - buf.writeNBTTagCompoundToBuffer(this.dimension); + buf.writeTag(this.dimension); buf.writeShort(this.type & 65535); buf.writeBoolean(this.editor); } - public void processPacket(ClientPlayer handler) { + public void processPacket(IClientPlayer handler) { handler.handleJoinGame(this); } @@ -47,7 +47,7 @@ public class SPacketJoinGame implements Packet { } public Dimension getDimension() { - return Dimension.getByNbt(this.dimension, false); + return Dimension.getByTag(this.dimension, false); } public int getEntityType() { diff --git a/common/src/main/java/common/packet/SPacketKeepAlive.java b/common/src/main/java/common/packet/SPacketKeepAlive.java new file mode 100755 index 0000000..6451e5e --- /dev/null +++ b/common/src/main/java/common/packet/SPacketKeepAlive.java @@ -0,0 +1,20 @@ +package common.packet; + +import common.network.IClientPlayer; + +public class SPacketKeepAlive extends APacketVarInt +{ + public SPacketKeepAlive() + { + } + + public SPacketKeepAlive(int key) + { + super(key); + } + + public void processPacket(IClientPlayer handler) + { + handler.handleKeepAlive(this); + } +} diff --git a/java/src/game/packet/SPacketLoading.java b/common/src/main/java/common/packet/SPacketLoading.java similarity index 79% rename from java/src/game/packet/SPacketLoading.java rename to common/src/main/java/common/packet/SPacketLoading.java index 827c67e..2a090f9 100644 --- a/java/src/game/packet/SPacketLoading.java +++ b/common/src/main/java/common/packet/SPacketLoading.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketLoading implements Packet { +public class SPacketLoading implements Packet { private String message; private String task; private int total = -1; @@ -29,10 +29,10 @@ public class SPacketLoading implements Packet { } public void readPacketData(PacketBuffer buf) throws IOException { - this.message = buf.readStringFromBuffer(128); + this.message = buf.readString(128); this.message = this.message != null && this.message.isEmpty() ? null : this.message; if(this.message == null) { - this.task = buf.readStringFromBuffer(128); + this.task = buf.readString(128); this.task = this.task != null && this.task.isEmpty() ? null : this.task; this.total = buf.readInt(); this.progress = buf.readInt(); @@ -48,7 +48,7 @@ public class SPacketLoading implements Packet { } } - public void processPacket(ClientPlayer handler) { + public void processPacket(IClientPlayer handler) { handler.handleLoading(this); } diff --git a/java/src/game/packet/SPacketMapChunkBulk.java b/common/src/main/java/common/packet/SPacketMapChunkBulk.java similarity index 55% rename from java/src/game/packet/SPacketMapChunkBulk.java rename to common/src/main/java/common/packet/SPacketMapChunkBulk.java index e8948ab..8adceef 100755 --- a/java/src/game/packet/SPacketMapChunkBulk.java +++ b/common/src/main/java/common/packet/SPacketMapChunkBulk.java @@ -1,49 +1,36 @@ -package game.packet; +package common.packet; import java.io.IOException; -import java.util.List; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.Chunk; - -public class SPacketMapChunkBulk implements Packet +public class SPacketMapChunkBulk implements Packet { private int[] xPositions; private int[] zPositions; private SPacketChunkData.Extracted[] chunksData; - private boolean isOverworld; + private boolean sky; public SPacketMapChunkBulk() { } - public SPacketMapChunkBulk(List chunks) + public SPacketMapChunkBulk(int[] x, int[] z, SPacketChunkData.Extracted[] chunks, boolean sky) { - int i = chunks.size(); - this.xPositions = new int[i]; - this.zPositions = new int[i]; - this.chunksData = new SPacketChunkData.Extracted[i]; - this.isOverworld = !((Chunk)chunks.get(0)).getWorld().dimension.hasNoLight(); - - for (int j = 0; j < i; ++j) - { - Chunk chunk = (Chunk)chunks.get(j); - SPacketChunkData.Extracted s21packetchunkdata$extracted = SPacketChunkData.getExtractedData(chunk, true, this.isOverworld, 0xffffffff); - this.xPositions[j] = chunk.xPos; - this.zPositions[j] = chunk.zPos; - this.chunksData[j] = s21packetchunkdata$extracted; - } + this.xPositions = x; + this.zPositions = z; + this.chunksData = chunks; + this.sky = sky; } - + /** * Reads the raw packet data from the data stream. */ public void readPacketData(PacketBuffer buf) throws IOException { - this.isOverworld = buf.readBoolean(); - int i = buf.readVarIntFromBuffer(); + this.sky = buf.readBoolean(); + int i = buf.readVarInt(); this.xPositions = new int[i]; this.zPositions = new int[i]; this.chunksData = new SPacketChunkData.Extracted[i]; @@ -53,8 +40,11 @@ public class SPacketMapChunkBulk implements Packet this.xPositions[j] = buf.readInt(); this.zPositions[j] = buf.readInt(); this.chunksData[j] = new SPacketChunkData.Extracted(); - this.chunksData[j].dataSize = buf.readInt(); - this.chunksData[j].data = new byte[SPacketChunkData.getSize(Integer.bitCount(this.chunksData[j].dataSize), this.isOverworld, true)]; + this.chunksData[j].extend = new int[buf.readVarInt()]; + for(int z = 0; z < this.chunksData[j].extend.length; z++) { + this.chunksData[j].extend[z] = buf.readVarInt(); + } + this.chunksData[j].data = new byte[SPacketChunkData.getSize(this.chunksData[j].extend.length, this.sky, true)]; } for (int k = 0; k < i; ++k) @@ -68,14 +58,17 @@ public class SPacketMapChunkBulk implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeBoolean(this.isOverworld); - buf.writeVarIntToBuffer(this.chunksData.length); + buf.writeBoolean(this.sky); + buf.writeVarInt(this.chunksData.length); for (int i = 0; i < this.xPositions.length; ++i) { buf.writeInt(this.xPositions[i]); buf.writeInt(this.zPositions[i]); - buf.writeInt(this.chunksData[i].dataSize); + buf.writeVarInt(this.chunksData[i].extend.length); + for(int z = 0; z < this.chunksData[i].extend.length; z++) { + buf.writeVarInt(this.chunksData[i].extend[z]); + } } for (int j = 0; j < this.xPositions.length; ++j) @@ -87,7 +80,7 @@ public class SPacketMapChunkBulk implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleMapChunkBulk(this); } @@ -111,9 +104,9 @@ public class SPacketMapChunkBulk implements Packet { return this.chunksData[p_149256_1_].data; } - - public int getChunkSize(int p_179754_1_) + + public int[] getChunkExtend(int index) { - return this.chunksData[p_179754_1_].dataSize; + return this.chunksData[index].extend; } } diff --git a/java/src/game/packet/SPacketMessage.java b/common/src/main/java/common/packet/SPacketMessage.java similarity index 70% rename from java/src/game/packet/SPacketMessage.java rename to common/src/main/java/common/packet/SPacketMessage.java index 52bfa0f..4b72178 100755 --- a/java/src/game/packet/SPacketMessage.java +++ b/common/src/main/java/common/packet/SPacketMessage.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketMessage implements Packet { +public class SPacketMessage implements Packet { public static enum Type { CONSOLE, CHAT, FEED, HOTBAR; } @@ -23,7 +23,7 @@ public class SPacketMessage implements Packet { } public void readPacketData(PacketBuffer buf) throws IOException { - this.message = buf.readStringFromBuffer(32767); + this.message = buf.readString(32767); this.type = buf.readEnumValue(Type.class); } @@ -32,7 +32,7 @@ public class SPacketMessage implements Packet { buf.writeEnumValue(this.type); } - public void processPacket(ClientPlayer handler) { + public void processPacket(IClientPlayer handler) { handler.handleMessage(this); } diff --git a/common/src/main/java/common/packet/SPacketMultiBlockChange.java b/common/src/main/java/common/packet/SPacketMultiBlockChange.java new file mode 100755 index 0000000..df86ebb --- /dev/null +++ b/common/src/main/java/common/packet/SPacketMultiBlockChange.java @@ -0,0 +1,101 @@ +package common.packet; + +import java.io.IOException; + +import common.init.BlockRegistry; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; +import common.util.ChunkPos; +import common.world.State; + +public class SPacketMultiBlockChange implements Packet +{ + private ChunkPos chunkPosCoord; + private SPacketMultiBlockChange.BlockUpdateData[] changedBlocks; + + public static BlockPos getPos(ChunkPos pos, long position) + { + return new BlockPos(new BlockPos((pos.x << 4) + (int)(position >> 36 & 15L), (int)(position & 4294967295L), (pos.z << 4) + (int)(position >> 32 & 15L))); + } + + public SPacketMultiBlockChange() + { + } + + public SPacketMultiBlockChange(ChunkPos pos, SPacketMultiBlockChange.BlockUpdateData[] changes) { + this.chunkPosCoord = pos; + this.changedBlocks = changes; + } + + /** + * Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer buf) throws IOException + { + this.chunkPosCoord = new ChunkPos(buf.readInt(), buf.readInt()); + this.changedBlocks = new SPacketMultiBlockChange.BlockUpdateData[buf.readVarInt()]; + + for (int i = 0; i < this.changedBlocks.length; ++i) + { + this.changedBlocks[i] = new SPacketMultiBlockChange.BlockUpdateData(buf.readLong(), (State)BlockRegistry.STATEMAP.getByValue(buf.readVarInt())); + } + } + + /** + * Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeInt(this.chunkPosCoord.x); + buf.writeInt(this.chunkPosCoord.z); + buf.writeVarInt(this.changedBlocks.length); + + for (SPacketMultiBlockChange.BlockUpdateData s22packetmultiblockchange$blockupdatedata : this.changedBlocks) + { + buf.writeLong(s22packetmultiblockchange$blockupdatedata.getRawPos()); + buf.writeVarInt(BlockRegistry.STATEMAP.get(s22packetmultiblockchange$blockupdatedata.getBlockState())); + } + } + + /** + * Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(IClientPlayer handler) + { + handler.handleMultiBlockChange(this); + } + + public SPacketMultiBlockChange.BlockUpdateData[] getChangedBlocks() + { + return this.changedBlocks; + } + + public ChunkPos getChunkPos() + { + return this.chunkPosCoord; + } + + public static class BlockUpdateData + { + private final long position; + private final State blockState; + + public BlockUpdateData(long raw, State state) + { + this.position = raw; + this.blockState = state; + } + + public long getRawPos() + { + return this.position; + } + + public State getBlockState() + { + return this.blockState; + } + } +} diff --git a/java/src/game/packet/S2DPacketOpenWindow.java b/common/src/main/java/common/packet/SPacketOpenWindow.java similarity index 63% rename from java/src/game/packet/S2DPacketOpenWindow.java rename to common/src/main/java/common/packet/SPacketOpenWindow.java index 7ac73fc..1ec413e 100755 --- a/java/src/game/packet/S2DPacketOpenWindow.java +++ b/common/src/main/java/common/packet/SPacketOpenWindow.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; -public class S2DPacketOpenWindow implements Packet +public class SPacketOpenWindow implements Packet { private int windowId; private String inventoryType; @@ -16,16 +16,16 @@ public class S2DPacketOpenWindow implements Packet private int entityId; private BlockPos tilePos; - public S2DPacketOpenWindow() + public SPacketOpenWindow() { } - public S2DPacketOpenWindow(int incomingWindowId, String incomingWindowTitle, String windowTitleIn) + public SPacketOpenWindow(int incomingWindowId, String incomingWindowTitle, String windowTitleIn) { this(incomingWindowId, incomingWindowTitle, windowTitleIn, 0); } - public S2DPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn) + public SPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn) { this.windowId = windowIdIn; this.inventoryType = guiId; @@ -33,13 +33,13 @@ public class S2DPacketOpenWindow implements Packet this.slotCount = slotCountIn; } - public S2DPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn, int incomingEntityId) + public SPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn, int incomingEntityId) { this(windowIdIn, guiId, windowTitleIn, slotCountIn); this.entityId = incomingEntityId; } - public S2DPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn, BlockPos incomingTilePos) + public SPacketOpenWindow(int windowIdIn, String guiId, String windowTitleIn, int slotCountIn, BlockPos incomingTilePos) { this(windowIdIn, guiId, windowTitleIn, slotCountIn); this.tilePos = incomingTilePos; @@ -48,7 +48,7 @@ public class S2DPacketOpenWindow implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleOpenWindow(this); } @@ -59,15 +59,15 @@ public class S2DPacketOpenWindow implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.windowId = buf.readUnsignedByte(); - this.inventoryType = buf.readStringFromBuffer(32); - this.windowTitle = buf.readStringFromBuffer(256); + this.inventoryType = buf.readString(32); + this.windowTitle = buf.readString(256); this.slotCount = buf.readUnsignedByte(); - if (this.inventoryType.equals("EntityHorse")) + if (this.inventoryType.equals("entity")) { this.entityId = buf.readInt(); } - else if(this.inventoryType.startsWith("machine_")) { + else if(this.inventoryType.equals("tile")) { this.tilePos = buf.readBlockPos(); } } @@ -82,11 +82,11 @@ public class S2DPacketOpenWindow implements Packet buf.writeString(this.windowTitle); buf.writeByte(this.slotCount); - if (this.inventoryType.equals("EntityHorse")) + if (this.inventoryType.equals("entity")) { buf.writeInt(this.entityId); } - else if(this.inventoryType.startsWith("machine_")) { + else if(this.inventoryType.equals("tile")) { buf.writeBlockPos(this.tilePos); } } @@ -120,9 +120,4 @@ public class S2DPacketOpenWindow implements Packet { return this.tilePos; } - - public boolean hasSlots() - { - return this.slotCount > 0 || this.inventoryType.startsWith("machine_"); - } } diff --git a/java/src/game/packet/S2APacketParticles.java b/common/src/main/java/common/packet/SPacketParticles.java similarity index 86% rename from java/src/game/packet/S2APacketParticles.java rename to common/src/main/java/common/packet/SPacketParticles.java index d1bb616..f2fd4ba 100755 --- a/java/src/game/packet/S2APacketParticles.java +++ b/common/src/main/java/common/packet/SPacketParticles.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.renderer.particle.ParticleType; +import common.model.ParticleType; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class S2APacketParticles implements Packet +public class SPacketParticles implements Packet { private ParticleType particleType; private float xCoord; @@ -25,11 +25,11 @@ public class S2APacketParticles implements Packet */ private int[] particleArguments; - public S2APacketParticles() + public SPacketParticles() { } - public S2APacketParticles(ParticleType particleTypeIn, boolean longDistanceIn, float x, float y, float z, float xOffsetIn, float yOffset, float zOffset, float particleSpeedIn, int particleCountIn, int[] particleArgumentsIn) + public SPacketParticles(ParticleType particleTypeIn, boolean longDistanceIn, float x, float y, float z, float xOffsetIn, float yOffset, float zOffset, float particleSpeedIn, int particleCountIn, int[] particleArgumentsIn) { this.particleType = particleTypeIn; this.longDistance = longDistanceIn; @@ -70,7 +70,7 @@ public class S2APacketParticles implements Packet for (int j = 0; j < i; ++j) { - this.particleArguments[j] = buf.readVarIntFromBuffer(); + this.particleArguments[j] = buf.readVarInt(); } } @@ -93,7 +93,7 @@ public class S2APacketParticles implements Packet for (int j = 0; j < i; ++j) { - buf.writeVarIntToBuffer(this.particleArguments[j]); + buf.writeVarInt(this.particleArguments[j]); } } @@ -183,7 +183,7 @@ public class S2APacketParticles implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleParticles(this); } diff --git a/java/src/game/packet/S39PacketPlayerAbilities.java b/common/src/main/java/common/packet/SPacketPlayerAbilities.java similarity index 64% rename from java/src/game/packet/S39PacketPlayerAbilities.java rename to common/src/main/java/common/packet/SPacketPlayerAbilities.java index 1dae15f..d7b7d34 100755 --- a/java/src/game/packet/S39PacketPlayerAbilities.java +++ b/common/src/main/java/common/packet/SPacketPlayerAbilities.java @@ -1,20 +1,20 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.entity.npc.EntityNPC; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.entity.npc.EntityNPC; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class S39PacketPlayerAbilities implements Packet { +public class SPacketPlayerAbilities implements Packet { private boolean flying; private boolean noClip; - public S39PacketPlayerAbilities() { + public SPacketPlayerAbilities() { } - public S39PacketPlayerAbilities(EntityNPC capabilities) { + public SPacketPlayerAbilities(EntityNPC capabilities) { this.flying = capabilities.flying; this.noClip = capabilities.noclip; } @@ -39,7 +39,7 @@ public class S39PacketPlayerAbilities implements Packet { buf.writeByte(bt); } - public void processPacket(ClientPlayer handler) { + public void processPacket(IClientPlayer handler) { handler.handlePlayerAbilities(this); } diff --git a/common/src/main/java/common/packet/SPacketPlayerListItem.java b/common/src/main/java/common/packet/SPacketPlayerListItem.java new file mode 100755 index 0000000..2bc0601 --- /dev/null +++ b/common/src/main/java/common/packet/SPacketPlayerListItem.java @@ -0,0 +1,54 @@ +package common.packet; + +import java.io.IOException; +import java.util.Collection; +import java.util.Map; +import java.util.Map.Entry; + +import common.collect.Maps; +import common.network.IClientPlayer; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; + +public class SPacketPlayerListItem implements Packet { + private final Map players = Maps.newHashMap(); + + public SPacketPlayerListItem() { + } + + public SPacketPlayerListItem(boolean remove, IPlayer... conns) { + for(IPlayer conn : conns) { + this.players.put(conn.getUser(), remove ? -1 : conn.getLatency()); + } + } + + public SPacketPlayerListItem(Iterable conns) { + for(IPlayer conn : conns) { + this.players.put(((IPlayer)conn).getUser(), ((IPlayer)conn).getLatency()); + } + } + + public void readPacketData(PacketBuffer buf) throws IOException { + int n = buf.readVarInt(); + for(int z = 0; z < n; z++) { + this.players.put(buf.readString(16), buf.readVarInt()); + } + } + + public void writePacketData(PacketBuffer buf) throws IOException { + buf.writeVarInt(this.players.size()); + for(Entry data : this.players.entrySet()) { + buf.writeString(data.getKey()); + buf.writeVarInt(data.getValue()); + } + } + + public void processPacket(IClientPlayer handler) { + handler.handlePlayerListItem(this); + } + + public Collection> getEntries() { + return this.players.entrySet(); + } +} diff --git a/java/src/game/packet/SPacketPlayerPosLook.java b/common/src/main/java/common/packet/SPacketPlayerPosLook.java similarity index 93% rename from java/src/game/packet/SPacketPlayerPosLook.java rename to common/src/main/java/common/packet/SPacketPlayerPosLook.java index 1458e9d..29d51ba 100755 --- a/java/src/game/packet/SPacketPlayerPosLook.java +++ b/common/src/main/java/common/packet/SPacketPlayerPosLook.java @@ -1,14 +1,14 @@ -package game.packet; +package common.packet; import java.io.IOException; import java.util.EnumSet; import java.util.Set; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketPlayerPosLook implements Packet +public class SPacketPlayerPosLook implements Packet { private double x; private double y; @@ -60,7 +60,7 @@ public class SPacketPlayerPosLook implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handlePlayerPosLook(this); } diff --git a/java/src/game/packet/S1EPacketRemoveEntityEffect.java b/common/src/main/java/common/packet/SPacketRemoveEntityEffect.java similarity index 63% rename from java/src/game/packet/S1EPacketRemoveEntityEffect.java rename to common/src/main/java/common/packet/SPacketRemoveEntityEffect.java index 76af411..7a27c9d 100755 --- a/java/src/game/packet/S1EPacketRemoveEntityEffect.java +++ b/common/src/main/java/common/packet/SPacketRemoveEntityEffect.java @@ -1,23 +1,23 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.potion.Potion; -import game.potion.PotionEffect; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.potion.Potion; +import common.potion.PotionEffect; -public class S1EPacketRemoveEntityEffect implements Packet +public class SPacketRemoveEntityEffect implements Packet { private int entityId; private Potion effectId; - public S1EPacketRemoveEntityEffect() + public SPacketRemoveEntityEffect() { } - public S1EPacketRemoveEntityEffect(int entityIdIn, PotionEffect effect) + public SPacketRemoveEntityEffect(int entityIdIn, PotionEffect effect) { this.entityId = entityIdIn; this.effectId = effect.getPotion(); @@ -28,7 +28,7 @@ public class S1EPacketRemoveEntityEffect implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarInt(); this.effectId = buf.readEnumValue(Potion.class); } @@ -37,14 +37,14 @@ public class S1EPacketRemoveEntityEffect implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); buf.writeEnumValue(this.effectId); } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleRemoveEntityEffect(this); } diff --git a/java/src/game/packet/SPacketRespawn.java b/common/src/main/java/common/packet/SPacketRespawn.java similarity index 60% rename from java/src/game/packet/SPacketRespawn.java rename to common/src/main/java/common/packet/SPacketRespawn.java index 4366f0f..fba7d5a 100755 --- a/java/src/game/packet/SPacketRespawn.java +++ b/common/src/main/java/common/packet/SPacketRespawn.java @@ -1,16 +1,16 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.dimension.Dimension; -import game.nbt.NBTTagCompound; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.dimension.Dimension; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.tags.TagObject; -public class SPacketRespawn implements Packet +public class SPacketRespawn implements Packet { - private NBTTagCompound dimension; + private TagObject dimension; private int type; private boolean editor; @@ -20,33 +20,33 @@ public class SPacketRespawn implements Packet public SPacketRespawn(Dimension dimensionIn, int type, boolean editor) { - this.dimension = dimensionIn.toNbt(false); + this.dimension = dimensionIn.toTags(false); this.type = type; this.editor = editor; } - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleRespawn(this); } public void readPacketData(PacketBuffer buf) throws IOException { - this.dimension = buf.readNBTTagCompoundFromBuffer(); + this.dimension = buf.readTag(); this.type = buf.readUnsignedShort(); this.editor = buf.readBoolean(); } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeNBTTagCompoundToBuffer(this.dimension); + buf.writeTag(this.dimension); buf.writeShort(this.type & 65535); buf.writeBoolean(this.editor); } public Dimension getDimension() { - return Dimension.getByNbt(this.dimension, false); + return Dimension.getByTag(this.dimension, false); } public int getEntityType() diff --git a/java/src/game/packet/SPacketServerTick.java b/common/src/main/java/common/packet/SPacketServerTick.java similarity index 64% rename from java/src/game/packet/SPacketServerTick.java rename to common/src/main/java/common/packet/SPacketServerTick.java index 14dcaea..0a9eac1 100644 --- a/java/src/game/packet/SPacketServerTick.java +++ b/common/src/main/java/common/packet/SPacketServerTick.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketServerTick implements Packet { +public class SPacketServerTick implements Packet { private int time; public SPacketServerTick() { @@ -24,7 +24,7 @@ public class SPacketServerTick implements Packet { buf.writeInt(this.time); } - public void processPacket(ClientPlayer handler) { + public void processPacket(IClientPlayer handler) { handler.handleServerTick(this); } diff --git a/java/src/game/packet/SPacketSetExperience.java b/common/src/main/java/common/packet/SPacketSetExperience.java similarity index 71% rename from java/src/game/packet/SPacketSetExperience.java rename to common/src/main/java/common/packet/SPacketSetExperience.java index de31d5f..b2f2b06 100755 --- a/java/src/game/packet/SPacketSetExperience.java +++ b/common/src/main/java/common/packet/SPacketSetExperience.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketSetExperience implements Packet +public class SPacketSetExperience implements Packet { private float progress; private int totalExperience; @@ -29,8 +29,8 @@ public class SPacketSetExperience implements Packet public void readPacketData(PacketBuffer buf) throws IOException { this.progress = buf.readFloat(); - this.level = buf.readVarIntFromBuffer(); - this.totalExperience = buf.readVarIntFromBuffer(); + this.level = buf.readVarInt(); + this.totalExperience = buf.readVarInt(); } /** @@ -39,14 +39,14 @@ public class SPacketSetExperience implements Packet public void writePacketData(PacketBuffer buf) throws IOException { buf.writeFloat(this.progress); - buf.writeVarIntToBuffer(this.level); - buf.writeVarIntToBuffer(this.totalExperience); + buf.writeVarInt(this.level); + buf.writeVarInt(this.totalExperience); } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleSetExperience(this); } diff --git a/java/src/game/packet/S2FPacketSetSlot.java b/common/src/main/java/common/packet/SPacketSetSlot.java similarity index 69% rename from java/src/game/packet/S2FPacketSetSlot.java rename to common/src/main/java/common/packet/SPacketSetSlot.java index ca30800..0eaf219 100755 --- a/java/src/game/packet/S2FPacketSetSlot.java +++ b/common/src/main/java/common/packet/SPacketSetSlot.java @@ -1,23 +1,23 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.item.ItemStack; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.item.ItemStack; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class S2FPacketSetSlot implements Packet +public class SPacketSetSlot implements Packet { private int windowId; private int slot; private ItemStack item; - public S2FPacketSetSlot() + public SPacketSetSlot() { } - public S2FPacketSetSlot(int windowIdIn, int slotIn, ItemStack itemIn) + public SPacketSetSlot(int windowIdIn, int slotIn, ItemStack itemIn) { this.windowId = windowIdIn; this.slot = slotIn; @@ -27,7 +27,7 @@ public class S2FPacketSetSlot implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleSetSlot(this); } @@ -39,7 +39,7 @@ public class S2FPacketSetSlot implements Packet { this.windowId = buf.readByte(); this.slot = buf.readShort(); - this.item = buf.readItemStackFromBuffer(); + this.item = buf.readItemStack(); } /** @@ -49,7 +49,7 @@ public class S2FPacketSetSlot implements Packet { buf.writeByte(this.windowId); buf.writeShort(this.slot); - buf.writeItemStackToBuffer(this.item); + buf.writeItemStack(this.item); } public int getWindowId() diff --git a/java/src/game/packet/S36PacketSignEditorOpen.java b/common/src/main/java/common/packet/SPacketSignEditorOpen.java similarity index 67% rename from java/src/game/packet/S36PacketSignEditorOpen.java rename to common/src/main/java/common/packet/SPacketSignEditorOpen.java index 70d0560..b7b09e9 100755 --- a/java/src/game/packet/S36PacketSignEditorOpen.java +++ b/common/src/main/java/common/packet/SPacketSignEditorOpen.java @@ -1,21 +1,21 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; -public class S36PacketSignEditorOpen implements Packet +public class SPacketSignEditorOpen implements Packet { private BlockPos signPosition; - public S36PacketSignEditorOpen() + public SPacketSignEditorOpen() { } - public S36PacketSignEditorOpen(BlockPos signPositionIn) + public SPacketSignEditorOpen(BlockPos signPositionIn) { this.signPosition = signPositionIn; } @@ -23,7 +23,7 @@ public class S36PacketSignEditorOpen implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleSignEditorOpen(this); } diff --git a/java/src/game/packet/SPacketSkin.java b/common/src/main/java/common/packet/SPacketSkin.java similarity index 66% rename from java/src/game/packet/SPacketSkin.java rename to common/src/main/java/common/packet/SPacketSkin.java index 546b913..4cf14f1 100755 --- a/java/src/game/packet/SPacketSkin.java +++ b/common/src/main/java/common/packet/SPacketSkin.java @@ -1,15 +1,15 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.entity.Entity; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.renderer.texture.EntityTexManager; -import game.world.World; +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.world.World; -public class SPacketSkin implements Packet +public class SPacketSkin implements Packet { private int id; // private ModelType model; @@ -40,25 +40,25 @@ public class SPacketSkin implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.id = buf.readVarIntFromBuffer(); + this.id = buf.readVarInt(); // this.model = buf.readEnumValue(ModelType.class); this.texture = buf.readByteArray(); if(this.texture.length == 0) { this.texture = null; } - else if(this.texture.length > EntityTexManager.MAX_SKIN_SIZE) { - this.texture = new byte[EntityTexManager.MAX_SKIN_SIZE]; + else if(this.texture.length > IPlayer.MAX_SKIN_SIZE) { + this.texture = new byte[IPlayer.MAX_SKIN_SIZE]; } } public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.id); + buf.writeVarInt(this.id); // buf.writeEnumValue(this.model); buf.writeByteArray(this.texture == null ? new byte[0] : this.texture); } - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleSkin(this); } diff --git a/java/src/game/packet/S29PacketSoundEffect.java b/common/src/main/java/common/packet/SPacketSoundEffect.java similarity index 81% rename from java/src/game/packet/S29PacketSoundEffect.java rename to common/src/main/java/common/packet/SPacketSoundEffect.java index e80a9af..d6ecedf 100755 --- a/java/src/game/packet/S29PacketSoundEffect.java +++ b/common/src/main/java/common/packet/SPacketSoundEffect.java @@ -1,13 +1,13 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.init.SoundEvent; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.init.SoundEvent; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class S29PacketSoundEffect implements Packet +public class SPacketSoundEffect implements Packet { private SoundEvent sound; private int posX; @@ -15,12 +15,12 @@ public class S29PacketSoundEffect implements Packet private int posZ; private float soundVolume; - public S29PacketSoundEffect() + public SPacketSoundEffect() { this.sound = null; } - public S29PacketSoundEffect(SoundEvent sound, double soundX, double soundY, double soundZ, float volume) + public SPacketSoundEffect(SoundEvent sound, double soundX, double soundY, double soundZ, float volume) { this.sound = sound; if(this.sound == null) { @@ -86,7 +86,7 @@ public class S29PacketSoundEffect implements Packet return this.soundVolume; } - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleSoundEffect(this); } diff --git a/java/src/game/packet/S2CPacketSpawnGlobalEntity.java b/common/src/main/java/common/packet/SPacketSpawnGlobalEntity.java similarity index 71% rename from java/src/game/packet/S2CPacketSpawnGlobalEntity.java rename to common/src/main/java/common/packet/SPacketSpawnGlobalEntity.java index 74bdb84..baf214a 100755 --- a/java/src/game/packet/S2CPacketSpawnGlobalEntity.java +++ b/common/src/main/java/common/packet/SPacketSpawnGlobalEntity.java @@ -1,14 +1,14 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.entity.Entity; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.util.ExtMath; +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.ExtMath; -public class S2CPacketSpawnGlobalEntity implements Packet +public class SPacketSpawnGlobalEntity implements Packet { private int entityId; private int x; @@ -17,11 +17,11 @@ public class S2CPacketSpawnGlobalEntity implements Packet private int type; private int data; - public S2CPacketSpawnGlobalEntity() + public SPacketSpawnGlobalEntity() { } - public S2CPacketSpawnGlobalEntity(Entity entityIn, int type, int data) + public SPacketSpawnGlobalEntity(Entity entityIn, int type, int data) { this.entityId = entityIn.getId(); this.x = ExtMath.floord(entityIn.posX * 32.0D); @@ -36,12 +36,12 @@ public class S2CPacketSpawnGlobalEntity implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarInt(); this.type = buf.readByte(); this.x = buf.readInt(); this.y = buf.readInt(); this.z = buf.readInt(); - this.data = buf.readVarIntFromBuffer(); + this.data = buf.readVarInt(); } /** @@ -49,18 +49,18 @@ public class S2CPacketSpawnGlobalEntity implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); buf.writeByte(this.type); buf.writeInt(this.x); buf.writeInt(this.y); buf.writeInt(this.z); - buf.writeVarIntToBuffer(this.data); + buf.writeVarInt(this.data); } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleSpawnGlobalEntity(this); } diff --git a/java/src/game/packet/SPacketSpawnMob.java b/common/src/main/java/common/packet/SPacketSpawnMob.java similarity index 89% rename from java/src/game/packet/SPacketSpawnMob.java rename to common/src/main/java/common/packet/SPacketSpawnMob.java index 2fa62b3..5542cb0 100755 --- a/java/src/game/packet/SPacketSpawnMob.java +++ b/common/src/main/java/common/packet/SPacketSpawnMob.java @@ -1,17 +1,17 @@ -package game.packet; +package common.packet; import java.io.IOException; import java.util.List; -import game.entity.DataWatcher; -import game.entity.types.EntityLiving; -import game.init.EntityRegistry; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.util.ExtMath; +import common.entity.DataWatcher; +import common.entity.types.EntityLiving; +import common.init.EntityRegistry; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.ExtMath; -public class SPacketSpawnMob implements Packet +public class SPacketSpawnMob implements Packet { private int entityId; private int type; @@ -84,7 +84,7 @@ public class SPacketSpawnMob implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarInt(); this.type = buf.readUnsignedShort(); this.x = buf.readInt(); this.y = buf.readInt(); @@ -100,7 +100,7 @@ public class SPacketSpawnMob implements Packet public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); buf.writeShort(this.type & 65535); buf.writeInt(this.x); buf.writeInt(this.y); @@ -114,7 +114,7 @@ public class SPacketSpawnMob implements Packet this.writeWatcher.writeTo(buf); } - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleSpawnMob(this); } diff --git a/java/src/game/packet/SPacketSpawnObject.java b/common/src/main/java/common/packet/SPacketSpawnObject.java similarity index 87% rename from java/src/game/packet/SPacketSpawnObject.java rename to common/src/main/java/common/packet/SPacketSpawnObject.java index aa697dd..6ae2456 100755 --- a/java/src/game/packet/SPacketSpawnObject.java +++ b/common/src/main/java/common/packet/SPacketSpawnObject.java @@ -1,20 +1,20 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.entity.Entity; -import game.entity.item.EntityLeashKnot; -import game.entity.projectile.EntityProjectile; -import game.entity.types.IObjectData; -import game.init.EntityRegistry; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Vec3; +import common.entity.Entity; +import common.entity.item.EntityLeashKnot; +import common.entity.projectile.EntityProjectile; +import common.entity.types.IObjectData; +import common.init.EntityRegistry; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Vec3; -public class SPacketSpawnObject implements Packet +public class SPacketSpawnObject implements Packet { private int entityId; private int x; @@ -106,7 +106,7 @@ public class SPacketSpawnObject implements Packet public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarInt(); this.type = buf.readUnsignedShort(); this.x = buf.readInt(); this.y = buf.readInt(); @@ -123,7 +123,7 @@ public class SPacketSpawnObject implements Packet public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); buf.writeShort(this.type & 65535); buf.writeInt(this.x); buf.writeInt(this.y); @@ -139,7 +139,7 @@ public class SPacketSpawnObject implements Packet } } - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleSpawnObject(this); } diff --git a/java/src/game/packet/SPacketSpawnPlayer.java b/common/src/main/java/common/packet/SPacketSpawnPlayer.java similarity index 82% rename from java/src/game/packet/SPacketSpawnPlayer.java rename to common/src/main/java/common/packet/SPacketSpawnPlayer.java index 2f989f3..a12ede6 100755 --- a/java/src/game/packet/SPacketSpawnPlayer.java +++ b/common/src/main/java/common/packet/SPacketSpawnPlayer.java @@ -1,20 +1,20 @@ -package game.packet; +package common.packet; import java.io.IOException; import java.util.List; -import game.entity.DataWatcher; -import game.entity.npc.EntityNPC; -import game.init.EntityRegistry; -import game.init.ItemRegistry; -import game.item.ItemStack; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.renderer.texture.EntityTexManager; -import game.util.ExtMath; +import common.entity.DataWatcher; +import common.entity.npc.EntityNPC; +import common.init.EntityRegistry; +import common.init.ItemRegistry; +import common.item.ItemStack; +import common.network.IClientPlayer; +import common.network.IPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.ExtMath; -public class SPacketSpawnPlayer implements Packet +public class SPacketSpawnPlayer implements Packet { private int entityId; private int type; @@ -52,7 +52,7 @@ public class SPacketSpawnPlayer implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.entityId = buf.readVarIntFromBuffer(); + this.entityId = buf.readVarInt(); this.type = buf.readUnsignedShort(); this.x = buf.readInt(); this.y = buf.readInt(); @@ -65,8 +65,8 @@ public class SPacketSpawnPlayer implements Packet if(this.texture.length == 0) { this.texture = null; } - else if(this.texture.length > EntityTexManager.MAX_SKIN_SIZE) { - this.texture = new byte[EntityTexManager.MAX_SKIN_SIZE]; + else if(this.texture.length > IPlayer.MAX_SKIN_SIZE) { + this.texture = new byte[IPlayer.MAX_SKIN_SIZE]; } } @@ -75,7 +75,7 @@ public class SPacketSpawnPlayer implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.entityId); + buf.writeVarInt(this.entityId); buf.writeShort(this.type & 65535); buf.writeInt(this.x); buf.writeInt(this.y); @@ -90,7 +90,7 @@ public class SPacketSpawnPlayer implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleSpawnPlayer(this); } diff --git a/java/src/game/packet/S3APacketTabComplete.java b/common/src/main/java/common/packet/SPacketTabComplete.java similarity index 61% rename from java/src/game/packet/S3APacketTabComplete.java rename to common/src/main/java/common/packet/SPacketTabComplete.java index 09a7ebc..88ef0e2 100755 --- a/java/src/game/packet/S3APacketTabComplete.java +++ b/common/src/main/java/common/packet/SPacketTabComplete.java @@ -1,20 +1,20 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class S3APacketTabComplete implements Packet +public class SPacketTabComplete implements Packet { private String[] matches; - public S3APacketTabComplete() + public SPacketTabComplete() { } - public S3APacketTabComplete(String[] matchesIn) + public SPacketTabComplete(String[] matchesIn) { this.matches = matchesIn; } @@ -24,11 +24,11 @@ public class S3APacketTabComplete implements Packet */ public void readPacketData(PacketBuffer buf) throws IOException { - this.matches = new String[buf.readVarIntFromBuffer()]; + this.matches = new String[buf.readVarInt()]; for (int i = 0; i < this.matches.length; ++i) { - this.matches[i] = buf.readStringFromBuffer(32767); + this.matches[i] = buf.readString(32767); } } @@ -37,7 +37,7 @@ public class S3APacketTabComplete implements Packet */ public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.matches.length); + buf.writeVarInt(this.matches.length); for (String s : this.matches) { @@ -48,7 +48,7 @@ public class S3APacketTabComplete implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleTabComplete(this); } diff --git a/java/src/game/packet/SPacketTimeUpdate.java b/common/src/main/java/common/packet/SPacketTimeUpdate.java similarity index 68% rename from java/src/game/packet/SPacketTimeUpdate.java rename to common/src/main/java/common/packet/SPacketTimeUpdate.java index 47ec0ae..4ed2a98 100755 --- a/java/src/game/packet/SPacketTimeUpdate.java +++ b/common/src/main/java/common/packet/SPacketTimeUpdate.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketTimeUpdate implements Packet { +public class SPacketTimeUpdate implements Packet { private long worldTime; private String serverInfo; @@ -20,7 +20,7 @@ public class SPacketTimeUpdate implements Packet { public void readPacketData(PacketBuffer buf) throws IOException { this.worldTime = buf.readLong(); - this.serverInfo = buf.readStringFromBuffer(512); + this.serverInfo = buf.readString(512); } public void writePacketData(PacketBuffer buf) throws IOException { @@ -28,7 +28,7 @@ public class SPacketTimeUpdate implements Packet { buf.writeString(this.serverInfo); } - public void processPacket(ClientPlayer handler) { + public void processPacket(IClientPlayer handler) { handler.handleTimeUpdate(this); } diff --git a/java/src/game/packet/SPacketTrades.java b/common/src/main/java/common/packet/SPacketTrades.java similarity index 72% rename from java/src/game/packet/SPacketTrades.java rename to common/src/main/java/common/packet/SPacketTrades.java index 98ea171..1ef9a4c 100755 --- a/java/src/game/packet/SPacketTrades.java +++ b/common/src/main/java/common/packet/SPacketTrades.java @@ -1,15 +1,15 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.item.ItemStack; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.village.MerchantRecipe; -import game.village.MerchantRecipeList; +import common.item.ItemStack; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.village.MerchantRecipe; +import common.village.MerchantRecipeList; -public class SPacketTrades implements Packet +public class SPacketTrades implements Packet { private MerchantRecipeList recipes; private int windowId; @@ -35,13 +35,13 @@ public class SPacketTrades implements Packet for (int j = 0; j < i; ++j) { - ItemStack itemstack = buf.readItemStackFromBuffer(); - ItemStack itemstack1 = buf.readItemStackFromBuffer(); + ItemStack itemstack = buf.readItemStack(); + ItemStack itemstack1 = buf.readItemStack(); ItemStack itemstack2 = null; if (buf.readBoolean()) { - itemstack2 = buf.readItemStackFromBuffer(); + itemstack2 = buf.readItemStack(); } // boolean flag = buf.readBoolean(); @@ -69,14 +69,14 @@ public class SPacketTrades implements Packet for (int i = 0; i < this.recipes.size(); ++i) { MerchantRecipe merchantrecipe = (MerchantRecipe)this.recipes.get(i); - buf.writeItemStackToBuffer(merchantrecipe.getItemToBuy()); - buf.writeItemStackToBuffer(merchantrecipe.getItemToSell()); - ItemStack itemstack = merchantrecipe.getSecondItemToBuy(); + buf.writeItemStack(merchantrecipe.first()); + buf.writeItemStack(merchantrecipe.result()); + ItemStack itemstack = merchantrecipe.second(); buf.writeBoolean(itemstack != null); if (itemstack != null) { - buf.writeItemStackToBuffer(itemstack); + buf.writeItemStack(itemstack); } // buf.writeBoolean(merchantrecipe.isRecipeDisabled()); @@ -88,7 +88,7 @@ public class SPacketTrades implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleTrades(this); } diff --git a/common/src/main/java/common/packet/SPacketUpdateEntityTags.java b/common/src/main/java/common/packet/SPacketUpdateEntityTags.java new file mode 100755 index 0000000..0a3f15a --- /dev/null +++ b/common/src/main/java/common/packet/SPacketUpdateEntityTags.java @@ -0,0 +1,62 @@ +package common.packet; + +import java.io.IOException; + +import common.entity.Entity; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.tags.TagObject; +import common.world.World; + +public class SPacketUpdateEntityTags implements Packet +{ + private int entityId; + private TagObject tagCompound; + + public SPacketUpdateEntityTags() + { + } + + public SPacketUpdateEntityTags(int entityIdIn, TagObject tagCompoundIn) + { + this.entityId = entityIdIn; + this.tagCompound = tagCompoundIn; + } + + /** + * Reads the raw packet data from the data stream. + */ + public void readPacketData(PacketBuffer buf) throws IOException + { + this.entityId = buf.readVarInt(); + this.tagCompound = buf.readTag(); + } + + /** + * Writes the raw packet data to the data stream. + */ + public void writePacketData(PacketBuffer buf) throws IOException + { + buf.writeVarInt(this.entityId); + buf.writeTag(this.tagCompound); + } + + /** + * Passes this Packet on to the NetHandler for processing. + */ + public void processPacket(IClientPlayer handler) + { + handler.handleEntityTags(this); + } + + public TagObject getTagCompound() + { + return this.tagCompound; + } + + public Entity getEntity(World worldIn) + { + return worldIn.getEntityByID(this.entityId); + } +} diff --git a/java/src/game/packet/SPacketUpdateHealth.java b/common/src/main/java/common/packet/SPacketUpdateHealth.java similarity index 64% rename from java/src/game/packet/SPacketUpdateHealth.java rename to common/src/main/java/common/packet/SPacketUpdateHealth.java index 059c8a1..532f069 100755 --- a/java/src/game/packet/SPacketUpdateHealth.java +++ b/common/src/main/java/common/packet/SPacketUpdateHealth.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketUpdateHealth implements Packet { +public class SPacketUpdateHealth implements Packet { private int health; public SPacketUpdateHealth() { @@ -24,7 +24,7 @@ public class SPacketUpdateHealth implements Packet { buf.writeInt(this.health); } - public void processPacket(ClientPlayer handler) { + public void processPacket(IClientPlayer handler) { handler.handleUpdateHealth(this); } diff --git a/java/src/game/packet/S33PacketUpdateSign.java b/common/src/main/java/common/packet/SPacketUpdateSign.java similarity index 77% rename from java/src/game/packet/S33PacketUpdateSign.java rename to common/src/main/java/common/packet/SPacketUpdateSign.java index cd49fb9..25a586b 100755 --- a/java/src/game/packet/S33PacketUpdateSign.java +++ b/common/src/main/java/common/packet/SPacketUpdateSign.java @@ -1,25 +1,25 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; -import game.world.World; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.util.BlockPos; +import common.world.World; -public class S33PacketUpdateSign implements Packet +public class SPacketUpdateSign implements Packet { private World world; private BlockPos blockPos; private String[] lines; // private String command; - public S33PacketUpdateSign() + public SPacketUpdateSign() { } - public S33PacketUpdateSign(World worldIn, BlockPos blockPosIn, String[] linesIn) + public SPacketUpdateSign(World worldIn, BlockPos blockPosIn, String[] linesIn) { this.world = worldIn; this.blockPos = blockPosIn; @@ -37,7 +37,7 @@ public class S33PacketUpdateSign implements Packet for (int i = 0; i < 4; ++i) { - this.lines[i] = buf.readStringFromBuffer(64); + this.lines[i] = buf.readString(64); } // this.command = buf.readStringFromBuffer(1024); @@ -62,7 +62,7 @@ public class S33PacketUpdateSign implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleUpdateSign(this); } diff --git a/java/src/game/packet/S35PacketUpdateTileEntity.java b/common/src/main/java/common/packet/SPacketUpdateTileEntity.java similarity index 51% rename from java/src/game/packet/S35PacketUpdateTileEntity.java rename to common/src/main/java/common/packet/SPacketUpdateTileEntity.java index f0237ad..f1420cf 100755 --- a/java/src/game/packet/S35PacketUpdateTileEntity.java +++ b/common/src/main/java/common/packet/SPacketUpdateTileEntity.java @@ -1,30 +1,30 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.init.TileRegistry; -import game.nbt.NBTTagCompound; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.tileentity.TileEntity; -import game.world.BlockPos; +import common.init.TileRegistry; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; +import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.util.BlockPos; -public class S35PacketUpdateTileEntity implements Packet +public class SPacketUpdateTileEntity implements Packet { private BlockPos blockPos; private int type; - private NBTTagCompound nbt; + private TagObject tag; - public S35PacketUpdateTileEntity() + public SPacketUpdateTileEntity() { } - public S35PacketUpdateTileEntity(TileEntity tile) + public SPacketUpdateTileEntity(TileEntity tile) { this.blockPos = tile.getPos(); - this.type = TileRegistry.classToIdMap.get(tile.getClass()); - tile.writeToNBT(this.nbt = new NBTTagCompound()); + this.type = TileRegistry.CLASS_TO_ID.get(tile.getClass()); + tile.writeTags(this.tag = new TagObject()); } /** @@ -34,7 +34,7 @@ public class S35PacketUpdateTileEntity implements Packet { this.blockPos = buf.readBlockPos(); this.type = buf.readUnsignedByte(); - this.nbt = buf.readNBTTagCompoundFromBuffer(); + this.tag = buf.readTag(); } /** @@ -44,13 +44,13 @@ public class S35PacketUpdateTileEntity implements Packet { buf.writeBlockPos(this.blockPos); buf.writeByte((byte)this.type); - buf.writeNBTTagCompoundToBuffer(this.nbt); + buf.writeTag(this.tag); } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleUpdateTileEntity(this); } @@ -62,11 +62,11 @@ public class S35PacketUpdateTileEntity implements Packet public boolean isTileEntityType(TileEntity tile) { - return this.type == TileRegistry.classToIdMap.get(tile.getClass()); + return this.type == TileRegistry.CLASS_TO_ID.get(tile.getClass()); } - public NBTTagCompound getNbtCompound() + public TagObject getTags() { - return this.nbt; + return this.tag; } } diff --git a/java/src/game/packet/S30PacketWindowItems.java b/common/src/main/java/common/packet/SPacketWindowItems.java similarity index 74% rename from java/src/game/packet/S30PacketWindowItems.java rename to common/src/main/java/common/packet/SPacketWindowItems.java index a0aca09..ad38bca 100755 --- a/java/src/game/packet/S30PacketWindowItems.java +++ b/common/src/main/java/common/packet/SPacketWindowItems.java @@ -1,23 +1,23 @@ -package game.packet; +package common.packet; import java.io.IOException; import java.util.List; -import game.item.ItemStack; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.item.ItemStack; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class S30PacketWindowItems implements Packet +public class SPacketWindowItems implements Packet { private int windowId; private ItemStack[] itemStacks; - public S30PacketWindowItems() + public SPacketWindowItems() { } - public S30PacketWindowItems(int windowIdIn, List p_i45186_2_) + public SPacketWindowItems(int windowIdIn, List p_i45186_2_) { this.windowId = windowIdIn; this.itemStacks = new ItemStack[p_i45186_2_.size()]; @@ -40,7 +40,7 @@ public class S30PacketWindowItems implements Packet for (int j = 0; j < i; ++j) { - this.itemStacks[j] = buf.readItemStackFromBuffer(); + this.itemStacks[j] = buf.readItemStack(); } } @@ -54,14 +54,14 @@ public class S30PacketWindowItems implements Packet for (ItemStack itemstack : this.itemStacks) { - buf.writeItemStackToBuffer(itemstack); + buf.writeItemStack(itemstack); } } /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleWindowItems(this); } diff --git a/java/src/game/packet/S31PacketWindowProperty.java b/common/src/main/java/common/packet/SPacketWindowProperty.java similarity index 75% rename from java/src/game/packet/S31PacketWindowProperty.java rename to common/src/main/java/common/packet/SPacketWindowProperty.java index 5d0d0a1..ef546c5 100755 --- a/java/src/game/packet/S31PacketWindowProperty.java +++ b/common/src/main/java/common/packet/SPacketWindowProperty.java @@ -1,22 +1,22 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class S31PacketWindowProperty implements Packet +public class SPacketWindowProperty implements Packet { private int windowId; private int varIndex; private int varValue; - public S31PacketWindowProperty() + public SPacketWindowProperty() { } - public S31PacketWindowProperty(int windowIdIn, int varIndexIn, int varValueIn) + public SPacketWindowProperty(int windowIdIn, int varIndexIn, int varValueIn) { this.windowId = windowIdIn; this.varIndex = varIndexIn; @@ -26,7 +26,7 @@ public class S31PacketWindowProperty implements Packet /** * Passes this Packet on to the NetHandler for processing. */ - public void processPacket(ClientPlayer handler) + public void processPacket(IClientPlayer handler) { handler.handleWindowProperty(this); } diff --git a/java/src/game/packet/SPacketWorld.java b/common/src/main/java/common/packet/SPacketWorld.java similarity index 72% rename from java/src/game/packet/SPacketWorld.java rename to common/src/main/java/common/packet/SPacketWorld.java index 0f8ff25..6b79517 100755 --- a/java/src/game/packet/SPacketWorld.java +++ b/common/src/main/java/common/packet/SPacketWorld.java @@ -1,12 +1,12 @@ -package game.packet; +package common.packet; import java.io.IOException; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; +import common.network.IClientPlayer; +import common.network.Packet; +import common.network.PacketBuffer; -public class SPacketWorld implements Packet { +public class SPacketWorld implements Packet { private float gravity; private int timeFactor; private boolean dayCycle; @@ -20,20 +20,20 @@ public class SPacketWorld implements Packet { this.dayCycle = dayCycle; } - public void processPacket(ClientPlayer handler) { + public void processPacket(IClientPlayer handler) { handler.handleWorld(this); } public void readPacketData(PacketBuffer buf) throws IOException { this.gravity = buf.readFloat(); - this.timeFactor = buf.readVarIntFromBuffer(); + this.timeFactor = buf.readVarInt(); int flags = buf.readUnsignedByte(); this.dayCycle = (flags & 1) > 0; } public void writePacketData(PacketBuffer buf) throws IOException { buf.writeFloat(this.gravity); - buf.writeVarIntToBuffer(this.timeFactor); + buf.writeVarInt(this.timeFactor); buf.writeByte(this.dayCycle ? 1 : 0); } diff --git a/java/src/game/pathfinding/NodeProcessor.java b/common/src/main/java/common/pathfinding/NodeProcessor.java similarity index 93% rename from java/src/game/pathfinding/NodeProcessor.java rename to common/src/main/java/common/pathfinding/NodeProcessor.java index 3bf08d0..ba397bc 100755 --- a/java/src/game/pathfinding/NodeProcessor.java +++ b/common/src/main/java/common/pathfinding/NodeProcessor.java @@ -1,8 +1,8 @@ -package game.pathfinding; +package common.pathfinding; -import game.entity.Entity; -import game.util.ExtMath; -import game.world.IntHashMap; +import common.entity.Entity; +import common.util.ExtMath; +import common.util.IntHashMap; public abstract class NodeProcessor { diff --git a/java/src/game/pathfinding/Path.java b/common/src/main/java/common/pathfinding/Path.java similarity index 99% rename from java/src/game/pathfinding/Path.java rename to common/src/main/java/common/pathfinding/Path.java index 65e0cf9..ed5d9c3 100755 --- a/java/src/game/pathfinding/Path.java +++ b/common/src/main/java/common/pathfinding/Path.java @@ -1,4 +1,4 @@ -package game.pathfinding; +package common.pathfinding; public class Path { diff --git a/common/src/main/java/common/pathfinding/PathCache.java b/common/src/main/java/common/pathfinding/PathCache.java new file mode 100755 index 0000000..b33d97b --- /dev/null +++ b/common/src/main/java/common/pathfinding/PathCache.java @@ -0,0 +1,52 @@ +package common.pathfinding; + +import common.init.Blocks; +import common.util.BlockPos; +import common.world.Chunk; +import common.world.IBlockAccess; +import common.world.State; +import common.world.World; + +public class PathCache implements IBlockAccess +{ + protected final int chunkX; + protected final int chunkZ; + protected final Chunk[][] data; + + public PathCache(World world, BlockPos pos1, BlockPos pos2) + { + this.chunkX = pos1.getX() >> 4; + this.chunkZ = pos1.getZ() >> 4; + int cx2 = pos2.getX() >> 4; + int cz2 = pos2.getZ() >> 4; + this.data = new Chunk[cx2 - this.chunkX + 1][cz2 - this.chunkZ + 1]; + for (int x = this.chunkX; x <= cx2; ++x) + { + for (int z = this.chunkZ; z <= cz2; ++z) + { + this.data[x - this.chunkX][z - this.chunkZ] = world.getChunk(x, z); + } + } + } + + public State getState(BlockPos pos) + { + if (pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) + { + int i = (pos.getX() >> 4) - this.chunkX; + int j = (pos.getZ() >> 4) - this.chunkZ; + + if (i >= 0 && i < this.data.length && j >= 0 && j < this.data[i].length) + { + Chunk chunk = this.data[i][j]; + + if (chunk != null) + { + return chunk.getState(pos); + } + } + } + + return Blocks.air.getState(); + } +} diff --git a/java/src/game/pathfinding/PathEntity.java b/common/src/main/java/common/pathfinding/PathEntity.java similarity index 97% rename from java/src/game/pathfinding/PathEntity.java rename to common/src/main/java/common/pathfinding/PathEntity.java index 6f71dc7..85f8e74 100755 --- a/java/src/game/pathfinding/PathEntity.java +++ b/common/src/main/java/common/pathfinding/PathEntity.java @@ -1,7 +1,7 @@ -package game.pathfinding; +package common.pathfinding; -import game.entity.Entity; -import game.world.Vec3; +import common.entity.Entity; +import common.util.Vec3; public class PathEntity { diff --git a/java/src/game/pathfinding/PathFinder.java b/common/src/main/java/common/pathfinding/PathFinder.java similarity index 98% rename from java/src/game/pathfinding/PathFinder.java rename to common/src/main/java/common/pathfinding/PathFinder.java index a18a568..52b4569 100755 --- a/java/src/game/pathfinding/PathFinder.java +++ b/common/src/main/java/common/pathfinding/PathFinder.java @@ -1,7 +1,7 @@ -package game.pathfinding; +package common.pathfinding; -import game.entity.Entity; -import game.world.BlockPos; +import common.entity.Entity; +import common.util.BlockPos; public class PathFinder { diff --git a/java/src/game/pathfinding/PathNavigate.java b/common/src/main/java/common/pathfinding/PathNavigate.java similarity index 93% rename from java/src/game/pathfinding/PathNavigate.java rename to common/src/main/java/common/pathfinding/PathNavigate.java index 484e8ce..605a176 100755 --- a/java/src/game/pathfinding/PathNavigate.java +++ b/common/src/main/java/common/pathfinding/PathNavigate.java @@ -1,16 +1,14 @@ -package game.pathfinding; +package common.pathfinding; import java.util.List; -import game.entity.Entity; -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Vec3; -import game.world.World; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Vec3; +import common.world.World; public abstract class PathNavigate { @@ -21,11 +19,6 @@ public abstract class PathNavigate protected PathEntity currentPath; protected double speed; - /** - * The number of blocks (extra) +/- in each axis that get pulled out as cache for the pathfinder's search space - */ - private final AttributeInstance pathSearchRange; - /** Time, in number of ticks, following the current path */ private int totalTicks; @@ -45,7 +38,6 @@ public abstract class PathNavigate { this.theEntity = entitylivingIn; this.worldObj = worldIn; - this.pathSearchRange = entitylivingIn.getEntityAttribute(Attributes.FOLLOW_RANGE); this.pathFinder = this.getPathFinder(); } @@ -64,7 +56,7 @@ public abstract class PathNavigate */ public float getPathSearchRange() { - return (float)this.pathSearchRange.getAttributeValue(); + return (float)this.theEntity.getPathingRange(); } /** diff --git a/java/src/game/pathfinding/PathNavigateClimber.java b/common/src/main/java/common/pathfinding/PathNavigateClimber.java similarity index 92% rename from java/src/game/pathfinding/PathNavigateClimber.java rename to common/src/main/java/common/pathfinding/PathNavigateClimber.java index 45d1726..0632fe2 100755 --- a/java/src/game/pathfinding/PathNavigateClimber.java +++ b/common/src/main/java/common/pathfinding/PathNavigateClimber.java @@ -1,10 +1,10 @@ -package game.pathfinding; +package common.pathfinding; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.World; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.World; public class PathNavigateClimber extends PathNavigateGround { diff --git a/java/src/game/pathfinding/PathNavigateGround.java b/common/src/main/java/common/pathfinding/PathNavigateGround.java similarity index 95% rename from java/src/game/pathfinding/PathNavigateGround.java rename to common/src/main/java/common/pathfinding/PathNavigateGround.java index 989c21f..7a6c5de 100755 --- a/java/src/game/pathfinding/PathNavigateGround.java +++ b/common/src/main/java/common/pathfinding/PathNavigateGround.java @@ -1,14 +1,15 @@ -package game.pathfinding; +package common.pathfinding; -import game.block.Block; -import game.entity.animal.EntityChicken; -import game.entity.npc.EntityZombie; -import game.entity.types.EntityLiving; -import game.material.Material; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Vec3; -import game.world.World; +import common.block.Block; +import common.block.Material; +import common.entity.animal.EntityChicken; +import common.entity.npc.EntityZombie; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Vec3; +import common.world.World; public class PathNavigateGround extends PathNavigate { @@ -206,7 +207,7 @@ public class PathNavigateGround extends PathNavigate Block block = this.worldObj.getState(new BlockPos(k, y - 1, l)).getBlock(); Material material = block.getMaterial(); - if (material == Material.air) + if (block == Blocks.air) { return false; } diff --git a/java/src/game/pathfinding/PathPoint.java b/common/src/main/java/common/pathfinding/PathPoint.java similarity index 97% rename from java/src/game/pathfinding/PathPoint.java rename to common/src/main/java/common/pathfinding/PathPoint.java index 453383c..92e9731 100755 --- a/java/src/game/pathfinding/PathPoint.java +++ b/common/src/main/java/common/pathfinding/PathPoint.java @@ -1,6 +1,6 @@ -package game.pathfinding; +package common.pathfinding; -import game.util.ExtMath; +import common.util.ExtMath; public class PathPoint { diff --git a/java/src/game/pathfinding/SwimNodeProcessor.java b/common/src/main/java/common/pathfinding/SwimNodeProcessor.java similarity index 94% rename from java/src/game/pathfinding/SwimNodeProcessor.java rename to common/src/main/java/common/pathfinding/SwimNodeProcessor.java index 4790091..cebffbb 100755 --- a/java/src/game/pathfinding/SwimNodeProcessor.java +++ b/common/src/main/java/common/pathfinding/SwimNodeProcessor.java @@ -1,10 +1,10 @@ -package game.pathfinding; +package common.pathfinding; -import game.block.Block; -import game.entity.Entity; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; +import common.block.Block; +import common.entity.Entity; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Facing; public class SwimNodeProcessor extends NodeProcessor { diff --git a/java/src/game/pathfinding/WalkNodeProcessor.java b/common/src/main/java/common/pathfinding/WalkNodeProcessor.java similarity index 94% rename from java/src/game/pathfinding/WalkNodeProcessor.java rename to common/src/main/java/common/pathfinding/WalkNodeProcessor.java index 815abec..cfe84a6 100755 --- a/java/src/game/pathfinding/WalkNodeProcessor.java +++ b/common/src/main/java/common/pathfinding/WalkNodeProcessor.java @@ -1,17 +1,17 @@ -package game.pathfinding; +package common.pathfinding; -import game.block.Block; -import game.block.BlockDoor; -import game.block.BlockFence; -import game.block.BlockFenceGate; -import game.block.BlockRailBase; -import game.block.BlockWall; -import game.entity.Entity; -import game.init.Blocks; -import game.material.Material; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.IBlockAccess; +import common.block.Block; +import common.block.Material; +import common.block.artificial.BlockDoor; +import common.block.artificial.BlockFence; +import common.block.artificial.BlockFenceGate; +import common.block.artificial.BlockWall; +import common.block.tech.BlockRailBase; +import common.entity.Entity; +import common.init.Blocks; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.IBlockAccess; public class WalkNodeProcessor extends NodeProcessor { @@ -205,13 +205,13 @@ public class WalkNodeProcessor extends NodeProcessor mpos.set(i, j, k); Block block = world.getState(mpos).getBlock(); - if (block.getMaterial() != Material.air) + if (block != Blocks.air) { if (block != Blocks.trapdoor && block != Blocks.iron_trapdoor) { if (!block.getMaterial().isColdLiquid()) { - if (!enterDoors && block instanceof BlockDoor && block.getMaterial() == Material.wood) + if (!enterDoors && block instanceof BlockDoor && block.getMaterial() == Material.WOOD) { return 0; } @@ -238,7 +238,7 @@ public class WalkNodeProcessor extends NodeProcessor return -3; } } - else if (!block.isPassable(world, mpos) && (!breakDoors || !(block instanceof BlockDoor) || block.getMaterial() != Material.wood)) + else if (!block.isPassable(world, mpos) && (!breakDoors || !(block instanceof BlockDoor) || block.getMaterial() != Material.WOOD)) { if (block instanceof BlockFence || block instanceof BlockFenceGate || block instanceof BlockWall) { diff --git a/java/src/game/potion/Potion.java b/common/src/main/java/common/potion/Potion.java similarity index 54% rename from java/src/game/potion/Potion.java rename to common/src/main/java/common/potion/Potion.java index f1a413d..f711c42 100755 --- a/java/src/game/potion/Potion.java +++ b/common/src/main/java/common/potion/Potion.java @@ -1,41 +1,44 @@ -package game.potion; +package common.potion; import java.util.Map; -import java.util.Map.Entry; -import game.collect.Maps; - -import game.entity.DamageSource; -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.AttributeMap; -import game.entity.attributes.AttributeModifier; -import game.entity.attributes.Attributes; -import game.entity.projectile.EntityPotion; -import game.entity.types.EntityLiving; -import game.init.Config; +import common.collect.Maps; +import common.color.TextColor; +import common.entity.DamageSource; +import common.entity.npc.EntityNPC; +import common.entity.projectile.EntityPotion; +import common.entity.types.EntityLiving; +import common.vars.Vars; public enum Potion { - SPEED("speed", "Schnelligkeit", "Trank der Schnelligkeit", false, 8171462, new PotionModifier(Attributes.MOVEMENT_SPEED, "PotSpd", 0.2, true)), - SLOWNESS("slowness", "Langsamkeit", "Trank der Langsamkeit", true, 5926017, new PotionModifier(Attributes.MOVEMENT_SPEED, "PotSlow", -0.15, true)), + SPEED("speed", "Schnelligkeit", "Trank der Schnelligkeit", false, 8171462) { + public String getTooltip(int amp) { + return String.format(TextColor.BLUE + "+%d%% Geschwindigkeit", 20 * (amp + 1)); + } + }, + SLOWNESS("slowness", "Langsamkeit", "Trank der Langsamkeit", true, 5926017) { + public String getTooltip(int amp) { + return String.format(TextColor.RED + "-%d%% Geschwindigkeit", 15 * (amp + 1)); + } + }, HASTE("haste", "Eile", "Trank der Eile", false, 14270531) { public double getEffectiveness() { return 1.5; } }, FATIGUE("mining_fatigue", "Abbaulähmung", "Trank der Trägheit", true, 4866583), - STRENGTH("strength", "Stärke", "Trank der Stärke", false, 9643043, new PotionModifier(Attributes.ATTACK_DAMAGE, "PotDmg", 2.5, true)) { - public double getAmount(int amp, AttributeModifier modifier) { - return 1.3D * (double)(amp + 1); - } + STRENGTH("strength", "Stärke", "Trank der Stärke", false, 9643043) { + public String getTooltip(int amp) { + return String.format(TextColor.BLUE + "+%d%% Angriffsschaden", 50 * (amp + 1)); + } }, - HEAL("instant_health", "Direktheilung", "Trank der Heilung", false, 16262179) { + HEAL("health", "Direktheilung", "Trank der Heilung", false, 16262179) { public boolean isInstant() { return true; } public void onImpact(EntityPotion potion, EntityLiving thrower, EntityLiving entity, int amp, double effect) { if(entity.arePotionsInverted()) { - if(Config.damagePotion) { + if(Vars.damagePotion) { int dmg = (int)(effect * (double)(6 << amp) + 0.5D); if(potion == null) entity.attackEntityFrom(DamageSource.magic, dmg); @@ -48,14 +51,14 @@ public enum Potion { } } }, - DAMAGE("instant_damage", "Direktschaden", "Trank des Schadens", true, 4393481) { + DAMAGE("damage", "Direktschaden", "Trank des Schadens", true, 4393481) { public boolean isInstant() { return true; } public void onImpact(EntityPotion potion, EntityLiving thrower, EntityLiving entity, int amp, double effect) { if(!entity.arePotionsInverted()) { - if(Config.damagePotion) { + if(Vars.damagePotion) { int dmg = (int)(effect * (double)(6 << amp) + 0.5D); if(potion == null) entity.attackEntityFrom(DamageSource.magic, dmg); @@ -87,30 +90,40 @@ public enum Potion { }, RESISTANCE("resistance", "Resistenz", "Trank des Widerstandes", false, 10044730), FIRE_RESISTANCE("fire_resistance", "Feuerschutz", "Trank der Feuerresistenz", false, 14981690), - MANA("mana_boost", "Manaschub", "Trank des Manaschubes", false, 3035801) { + MANA_GENERATION("mana_generation", "Manaschub", "Trank des Manaschubes", false, 3035801) { public void onUpdate(EntityLiving entity, int duration, int amp) { + if(!(entity instanceof EntityNPC npc)) + return; int k = 40 >> amp; - if((k <= 0 || duration % k == 0) && entity.getManaPoints() < entity.getMaxMana()) - entity.healMana(1); + if((k <= 0 || duration % k == 0) && npc.getManaPoints() < npc.getMaxMana()) + npc.healMana(1); } }, - FLYING("flying", "Schweben", "Trank des Schwebens", false, 8356754), + FLYING("flying", null, null, false, 8356754) { + public String getDisplay(int amplifier) { + return amplifier <= 0 ? "Schweben" : "Flugkraft"; + } + + public String getPotionDisplay(int amplifier) { + return amplifier <= 0 ? "Trank des Schwebens" : "Trank der Flugkraft"; + } + }, BLINDNESS("blindness", "Blindheit", "Trank der Blindheit", true, 2039587) { public double getEffectiveness() { return 0.25; } }, NIGHT_VISION("night_vision", "Nachtsicht", "Trank der Nachtsicht", false, 2039713), - STABILITY("stability", "Stabilität", "Trank der Standfestigkeit", false, 5797459, new PotionModifier(Attributes.KNOCKBACK_RESISTANCE, "PotStbl", 1.0, false)), - WEAKNESS("weakness", "Schwäche", "Trank der Schwäche", true, 4738376, new PotionModifier(Attributes.ATTACK_DAMAGE, "PotWeak", 2.0, false)) { - public double getAmount(int amp, AttributeModifier modifier) { - return (double)(-0.5F * (float)(amp + 1)); - } + STABILITY("stability", "Stabilität", "Trank der Standfestigkeit", false, 5797459), + WEAKNESS("weakness", "Schwäche", "Trank der Schwäche", true, 4738376) { + public String getTooltip(int amp) { + return String.format(TextColor.RED + "-%d%% Angriffsschaden", 20 * (amp + 1)); + } }, POISON("poison", "Vergiftung", "Trank der Vergiftung", true, 5149489) { public void onUpdate(EntityLiving entity, int duration, int amp) { int j = 25 >> amp; - if((j <= 0 || duration % j == 0) && (entity.worldObj.client || Config.damagePoison) && entity.getHealth() > 1) + if((j <= 0 || duration % j == 0) && (entity.worldObj.client || Vars.damagePoison) && entity.getHealth() > 1) entity.attackEntityFrom(DamageSource.magic, 1); } @@ -118,48 +131,34 @@ public enum Potion { return 0.25; } }, - HEALTH("health_boost", "Extraenergie", "Trank der Extraenergie", false, 16284963, new PotionModifier(Attributes.MAX_HEALTH, "PotHp", 4.0, false)) { - public void removeModifiers(EntityLiving entity, AttributeMap map, int amp) { - super.removeModifiers(entity, map, amp); - if(entity.getHealth() > entity.getMaxHealth()) - entity.setHealth(entity.getMaxHealth()); - } - }, ABSORPTION("absorption", "Absorption", "Trank der Absorption", false, 2445989) { - public void removeModifiers(EntityLiving entity, AttributeMap map, int amp) { + public void removeModifiers(EntityLiving entity, int amp) { entity.setAbsorptionAmount(entity.getAbsorptionAmount() - (4 * (amp + 1))); - super.removeModifiers(entity, map, amp); } - public void addModifiers(EntityLiving entity, AttributeMap map, int amp) { + public void addModifiers(EntityLiving entity, int amp) { entity.setAbsorptionAmount(entity.getAbsorptionAmount() + (4 * (amp + 1))); - super.addModifiers(entity, map, amp); } }, RADIATION("radiation", "Strahlung", "Radioaktiver Trank", true, 0x00ff00) { public void onUpdate(EntityLiving entity, int duration, int amp) { - if(entity.ticksExisted % 20 == 0 && (entity.worldObj.client || Config.damageRadiation)) // && entityLivingBaseIn.getHealth() > 1.0F) + if(entity.ticksExisted % 20 == 0 && (entity.worldObj.client || Vars.damageRadiation)) // && entityLivingBaseIn.getHealth() > 1.0F) entity.attackEntityFrom(DamageSource.radiation, 1 + amp); } - }; - - private static class PotionModifier { - private final Attribute attribute; - private final String id; - private final double value; - private final boolean multiply; - - public PotionModifier(Attribute attr, String id, double value, boolean multiply) { - this.attribute = attr; - this.id = id; - this.value = value; - this.multiply = multiply; + }, + MANA("mana", "Mana", "Manatrank", false, 0x0000ff) { + public boolean isInstant() { + return true; } - } + + public void onImpact(EntityPotion potion, EntityLiving thrower, EntityLiving entity, int amp, double effect) { + if(entity instanceof EntityNPC npc) + npc.healMana(Math.max((int)(effect * (double)(4 << amp) + 0.5D), 0)); + } + }; private static final Map LOOKUP = Maps.newHashMap(); - private final Map modifiers = Maps.newHashMap(); private final String name; private final String effectDisplay; private final String potionDisplay; @@ -176,15 +175,12 @@ public enum Potion { return LOOKUP.get(name); } - private Potion(String name, String effectDisplay, String potionDisplay, boolean bad, int color, PotionModifier ... modifiers) { + private Potion(String name, String effectDisplay, String potionDisplay, boolean bad, int color) { this.name = name; this.bad = bad; this.color = color; this.effectDisplay = effectDisplay; this.potionDisplay = potionDisplay; - for(PotionModifier modifier : modifiers) { - this.modifiers.put(modifier.attribute, new AttributeModifier(AttributeModifier.getModifierId(modifier.id), "potion." + name, modifier.value, modifier.multiply)); - } } public String getName() { @@ -195,11 +191,11 @@ public enum Potion { return this.name; } - public String getDisplay() { - return this.effectDisplay; + public String getDisplay(int amplifier) { + return this.effectDisplay + PotionHelper.getPotionPotency(amplifier); } - public String getPotionDisplay() { + public String getPotionDisplay(int amplifier) { return this.potionDisplay; } @@ -211,10 +207,6 @@ public enum Potion { return this.color; } - public Map getModifiers() { - return this.modifiers; - } - public void onUpdate(EntityLiving entity, int duration, int amp) { } @@ -224,31 +216,18 @@ public enum Potion { public boolean isInstant() { return false; } - - public double getAmount(int amp, AttributeModifier modifier) { - return modifier.getAmount() * (double)(amp + 1); + + public String getTooltip(int amp) { + return null; } public double getEffectiveness() { return this.bad ? 0.5 : 1.0; } - public void removeModifiers(EntityLiving entity, AttributeMap map, int amp) { - for(Entry entry : this.modifiers.entrySet()) { - AttributeInstance attr = map.getAttributeInstance(entry.getKey()); - if(attr != null) - attr.removeModifier(entry.getValue()); - } + public void removeModifiers(EntityLiving entity, int amp) { } - public void addModifiers(EntityLiving entity, AttributeMap map, int amp) { - for(Entry entry : this.modifiers.entrySet()) { - AttributeInstance attr = map.getAttributeInstance(entry.getKey()); - if(attr != null) { - AttributeModifier mod = entry.getValue(); - attr.removeModifier(mod); - attr.applyModifier(new AttributeModifier(mod.getID(), "potion." + this.name + " " + amp, this.getAmount(amp, mod), mod.isMultiplied())); - } - } + public void addModifiers(EntityLiving entity, int amp) { } } diff --git a/java/src/game/potion/PotionEffect.java b/common/src/main/java/common/potion/PotionEffect.java similarity index 76% rename from java/src/game/potion/PotionEffect.java rename to common/src/main/java/common/potion/PotionEffect.java index fdc7468..861e034 100755 --- a/java/src/game/potion/PotionEffect.java +++ b/common/src/main/java/common/potion/PotionEffect.java @@ -1,8 +1,8 @@ -package game.potion; +package common.potion; -import game.entity.types.EntityLiving; -import game.log.Log; -import game.nbt.NBTTagCompound; +import common.entity.types.EntityLiving; +import common.log.Log; +import common.tags.TagObject; public class PotionEffect { private final Potion potion; @@ -36,7 +36,7 @@ public class PotionEffect { public PotionEffect combine(PotionEffect other) { if(this.potion != other.potion) - Log.JNI.warn("PotionEffect.combine(): Diese Methode sollte nur für gleiche Effekte aufgerufen werden!"); + Log.TICK.warn("PotionEffect.combine(): Diese Methode sollte nur für gleiche Effekte aufgerufen werden!"); int duration = this.duration; int amplifier = this.amplifier; int remaining = this.remaining; @@ -105,11 +105,11 @@ public class PotionEffect { } public String getEffectName() { - return this.potion.getDisplay(); + return this.potion.getDisplay(this.amplifier); } public String getPotionName() { - return this.potion.getPotionDisplay(); + return this.potion.getPotionDisplay(this.amplifier); } public String getDurationString() { @@ -135,20 +135,20 @@ public class PotionEffect { && this.thrown == other.thrown && this.remaining == other.remaining && this.ambient == other.ambient; } - public NBTTagCompound toNbt() { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setString("Type", this.potion.getName()); - nbt.setByte("Amplifier", (byte)this.amplifier); - nbt.setInteger("Duration", this.duration); - nbt.setInteger("Remaining", this.remaining); - nbt.setBoolean("Ambient", this.ambient); - nbt.setBoolean("Particles", this.particles); - return nbt; + public TagObject toTags() { + TagObject tag = new TagObject(); + tag.setString("Type", this.potion.getName()); + tag.setByte("Amplifier", (byte)this.amplifier); + tag.setInt("Duration", this.duration); + tag.setInt("Remaining", this.remaining); + tag.setBool("Ambient", this.ambient); + tag.setBool("Particles", this.particles); + return tag; } - public static PotionEffect fromNbt(NBTTagCompound nbt) { - Potion potion = Potion.getByName(nbt.getString("Type")); - return potion == null ? null : new PotionEffect(potion, nbt.getInteger("Duration"), (int)(nbt.getByte("Amplifier") & 255), nbt.getBoolean("Ambient"), nbt.getBoolean("Particles")) - .setRemaining(nbt.getInteger("Remaining")); + public static PotionEffect fromTags(TagObject tag) { + Potion potion = Potion.getByName(tag.getString("Type")); + return potion == null ? null : new PotionEffect(potion, tag.getInt("Duration"), (int)(tag.getByte("Amplifier") & 255), tag.getBool("Ambient"), tag.getBool("Particles")) + .setRemaining(tag.getInt("Remaining")); } } diff --git a/java/src/game/potion/PotionHelper.java b/common/src/main/java/common/potion/PotionHelper.java similarity index 99% rename from java/src/game/potion/PotionHelper.java rename to common/src/main/java/common/potion/PotionHelper.java index a907121..967a346 100755 --- a/java/src/game/potion/PotionHelper.java +++ b/common/src/main/java/common/potion/PotionHelper.java @@ -1,11 +1,11 @@ -package game.potion; +package common.potion; import java.util.Collection; import java.util.List; import java.util.Map; -import game.collect.Lists; -import game.collect.Maps; +import common.collect.Lists; +import common.collect.Maps; public class PotionHelper { diff --git a/java/src/game/properties/IProperty.java b/common/src/main/java/common/properties/IProperty.java similarity index 90% rename from java/src/game/properties/IProperty.java rename to common/src/main/java/common/properties/IProperty.java index 8869760..af1e388 100755 --- a/java/src/game/properties/IProperty.java +++ b/common/src/main/java/common/properties/IProperty.java @@ -1,4 +1,4 @@ -package game.properties; +package common.properties; import java.util.Collection; diff --git a/java/src/game/properties/PropertyBool.java b/common/src/main/java/common/properties/PropertyBool.java similarity index 91% rename from java/src/game/properties/PropertyBool.java rename to common/src/main/java/common/properties/PropertyBool.java index 4d3a8a5..2db7c37 100755 --- a/java/src/game/properties/PropertyBool.java +++ b/common/src/main/java/common/properties/PropertyBool.java @@ -1,8 +1,8 @@ -package game.properties; +package common.properties; import java.util.Collection; -import game.collect.ImmutableSet; +import common.collect.ImmutableSet; public class PropertyBool extends PropertyHelper { diff --git a/java/src/game/properties/PropertyDirection.java b/common/src/main/java/common/properties/PropertyDirection.java similarity index 87% rename from java/src/game/properties/PropertyDirection.java rename to common/src/main/java/common/properties/PropertyDirection.java index 52b3ff5..88ba891 100755 --- a/java/src/game/properties/PropertyDirection.java +++ b/common/src/main/java/common/properties/PropertyDirection.java @@ -1,13 +1,12 @@ -package game.properties; +package common.properties; import java.util.Collection; - import java.util.function.Predicate; -import game.util.Predicates; -import game.collect.Filter; -import game.collect.Lists; -import game.world.Facing; +import common.collect.Filter; +import common.collect.Lists; +import common.util.Facing; +import common.util.Predicates; public class PropertyDirection extends PropertyEnum { diff --git a/java/src/game/properties/PropertyEnum.java b/common/src/main/java/common/properties/PropertyEnum.java similarity index 58% rename from java/src/game/properties/PropertyEnum.java rename to common/src/main/java/common/properties/PropertyEnum.java index 9fe4fec..eccbeeb 100755 --- a/java/src/game/properties/PropertyEnum.java +++ b/common/src/main/java/common/properties/PropertyEnum.java @@ -1,16 +1,17 @@ -package game.properties; +package common.properties; import java.util.Collection; import java.util.Map; - import java.util.function.Predicate; -import game.util.Predicates; -import game.collect.Filter; -import game.collect.ImmutableSet; -import game.collect.Lists; -import game.collect.Maps; -public class PropertyEnum & IStringSerializable> extends PropertyHelper +import common.collect.Filter; +import common.collect.ImmutableSet; +import common.collect.Lists; +import common.collect.Maps; +import common.util.Identifyable; +import common.util.Predicates; + +public class PropertyEnum & Identifyable> extends PropertyHelper { private final ImmutableSet allowedValues; private final Map nameToValue = Maps.newHashMap(); @@ -22,7 +23,7 @@ public class PropertyEnum & IStringSerializable> extends Prope for (T t : allowedValues) { - String s = ((IStringSerializable)t).getName(); + String s = ((Identifyable)t).getName(); if (this.nameToValue.containsKey(s)) { @@ -43,25 +44,25 @@ public class PropertyEnum & IStringSerializable> extends Prope */ public String getName(T value) { - return ((IStringSerializable)value).getName(); + return ((Identifyable)value).getName(); } - public static & IStringSerializable> PropertyEnum create(String name, Class clazz) + public static & Identifyable> PropertyEnum create(String name, Class clazz) { return create(name, clazz, Predicates.alwaysTrue()); } - public static & IStringSerializable> PropertyEnum create(String name, Class clazz, Predicate filter) + public static & Identifyable> PropertyEnum create(String name, Class clazz, Predicate filter) { return create(name, clazz, Filter.filter(Lists.newArrayList(clazz.getEnumConstants()), filter)); } - public static & IStringSerializable> PropertyEnum create(String name, Class clazz, T... values) + public static & Identifyable> PropertyEnum create(String name, Class clazz, T... values) { return create(name, clazz, Lists.newArrayList(values)); } - public static & IStringSerializable> PropertyEnum create(String name, Class clazz, Collection values) + public static & Identifyable> PropertyEnum create(String name, Class clazz, Collection values) { return new PropertyEnum(name, clazz, values); } diff --git a/java/src/game/properties/PropertyHelper.java b/common/src/main/java/common/properties/PropertyHelper.java similarity index 97% rename from java/src/game/properties/PropertyHelper.java rename to common/src/main/java/common/properties/PropertyHelper.java index 5de1517..671ff28 100755 --- a/java/src/game/properties/PropertyHelper.java +++ b/common/src/main/java/common/properties/PropertyHelper.java @@ -1,4 +1,4 @@ -package game.properties; +package common.properties; public abstract class PropertyHelper> implements IProperty { diff --git a/java/src/game/properties/PropertyInteger.java b/common/src/main/java/common/properties/PropertyInteger.java similarity index 95% rename from java/src/game/properties/PropertyInteger.java rename to common/src/main/java/common/properties/PropertyInteger.java index d3ff44f..c6bd59b 100755 --- a/java/src/game/properties/PropertyInteger.java +++ b/common/src/main/java/common/properties/PropertyInteger.java @@ -1,10 +1,10 @@ -package game.properties; +package common.properties; import java.util.Collection; import java.util.Set; -import game.collect.ImmutableSet; -import game.collect.Sets; +import common.collect.ImmutableSet; +import common.collect.Sets; public class PropertyInteger extends PropertyHelper { diff --git a/java/src/game/rng/ImprovedGen.java b/common/src/main/java/common/rng/ImprovedGen.java similarity index 99% rename from java/src/game/rng/ImprovedGen.java rename to common/src/main/java/common/rng/ImprovedGen.java index a709119..d86559b 100755 --- a/java/src/game/rng/ImprovedGen.java +++ b/common/src/main/java/common/rng/ImprovedGen.java @@ -1,4 +1,4 @@ -package game.rng; +package common.rng; class ImprovedGen { private static final double[] dir3X = new double[] { 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 1.0D, -1.0D, 0.0D, 0.0D, 0.0D, 0.0D, 1.0D, 0.0D, diff --git a/java/src/game/rng/ImprovedGenOld.java b/common/src/main/java/common/rng/ImprovedGenOld.java similarity index 96% rename from java/src/game/rng/ImprovedGenOld.java rename to common/src/main/java/common/rng/ImprovedGenOld.java index 2809b54..fb3c406 100755 --- a/java/src/game/rng/ImprovedGenOld.java +++ b/common/src/main/java/common/rng/ImprovedGenOld.java @@ -1,4 +1,4 @@ -package game.rng; +package common.rng; class ImprovedGenOld { private final int permutations[]; diff --git a/java/src/game/rng/NoiseGen.java b/common/src/main/java/common/rng/NoiseGen.java similarity index 95% rename from java/src/game/rng/NoiseGen.java rename to common/src/main/java/common/rng/NoiseGen.java index cb247f9..114d7f4 100755 --- a/java/src/game/rng/NoiseGen.java +++ b/common/src/main/java/common/rng/NoiseGen.java @@ -1,4 +1,4 @@ -package game.rng; +package common.rng; public abstract class NoiseGen { public abstract void generate(double[] noise, int xoff, int yoff, int zoff, int xsize, int ysize, int zsize, double xscale, double yscale, diff --git a/java/src/game/rng/OctaveGen.java b/common/src/main/java/common/rng/OctaveGen.java similarity index 98% rename from java/src/game/rng/OctaveGen.java rename to common/src/main/java/common/rng/OctaveGen.java index df68d2a..6e58b5a 100755 --- a/java/src/game/rng/OctaveGen.java +++ b/common/src/main/java/common/rng/OctaveGen.java @@ -1,4 +1,4 @@ -package game.rng; +package common.rng; public class OctaveGen extends NoiseGen { private final ImprovedGen[] generators; diff --git a/java/src/game/rng/OctaveGenOld.java b/common/src/main/java/common/rng/OctaveGenOld.java similarity index 94% rename from java/src/game/rng/OctaveGenOld.java rename to common/src/main/java/common/rng/OctaveGenOld.java index ebca8c7..f8a8787 100755 --- a/java/src/game/rng/OctaveGenOld.java +++ b/common/src/main/java/common/rng/OctaveGenOld.java @@ -1,4 +1,4 @@ -package game.rng; +package common.rng; public class OctaveGenOld extends NoiseGen { private final ImprovedGenOld generators[]; diff --git a/java/src/game/rng/PerlinGen.java b/common/src/main/java/common/rng/PerlinGen.java similarity index 98% rename from java/src/game/rng/PerlinGen.java rename to common/src/main/java/common/rng/PerlinGen.java index e2513cc..0149806 100755 --- a/java/src/game/rng/PerlinGen.java +++ b/common/src/main/java/common/rng/PerlinGen.java @@ -1,4 +1,4 @@ -package game.rng; +package common.rng; public class PerlinGen { private final SimplexGen[] generators; diff --git a/java/src/game/rng/PerlinGenOld.java b/common/src/main/java/common/rng/PerlinGenOld.java similarity index 94% rename from java/src/game/rng/PerlinGenOld.java rename to common/src/main/java/common/rng/PerlinGenOld.java index 44d5002..02ff25b 100755 --- a/java/src/game/rng/PerlinGenOld.java +++ b/common/src/main/java/common/rng/PerlinGenOld.java @@ -1,4 +1,4 @@ -package game.rng; +package common.rng; public class PerlinGenOld { private final SimplexGenOld generators[]; diff --git a/java/src/game/rng/Random.java b/common/src/main/java/common/rng/Random.java similarity index 99% rename from java/src/game/rng/Random.java rename to common/src/main/java/common/rng/Random.java index b9a6c5a..875f2f1 100755 --- a/java/src/game/rng/Random.java +++ b/common/src/main/java/common/rng/Random.java @@ -1,4 +1,4 @@ -package game.rng; +package common.rng; import java.util.List; import java.util.concurrent.atomic.AtomicLong; diff --git a/java/src/game/rng/RngItem.java b/common/src/main/java/common/rng/RngItem.java similarity index 84% rename from java/src/game/rng/RngItem.java rename to common/src/main/java/common/rng/RngItem.java index f74db06..920d53c 100755 --- a/java/src/game/rng/RngItem.java +++ b/common/src/main/java/common/rng/RngItem.java @@ -1,4 +1,4 @@ -package game.rng; +package common.rng; public abstract class RngItem { public final int weight; diff --git a/java/src/game/rng/SimplexGen.java b/common/src/main/java/common/rng/SimplexGen.java similarity index 99% rename from java/src/game/rng/SimplexGen.java rename to common/src/main/java/common/rng/SimplexGen.java index f29c828..a1f3b20 100755 --- a/java/src/game/rng/SimplexGen.java +++ b/common/src/main/java/common/rng/SimplexGen.java @@ -1,4 +1,4 @@ -package game.rng; +package common.rng; class SimplexGen { private static final int[][] DIRS = new int[][] { { 1, 1, 0 }, { -1, 1, 0 }, { 1, -1, 0 }, { -1, -1, 0 }, { 1, 0, 1 }, { -1, 0, 1 }, { 1, 0, -1 }, diff --git a/java/src/game/rng/SimplexGenOld.java b/common/src/main/java/common/rng/SimplexGenOld.java similarity index 95% rename from java/src/game/rng/SimplexGenOld.java rename to common/src/main/java/common/rng/SimplexGenOld.java index 3ac1dd2..e597895 100755 --- a/java/src/game/rng/SimplexGenOld.java +++ b/common/src/main/java/common/rng/SimplexGenOld.java @@ -1,4 +1,4 @@ -package game.rng; +package common.rng; class SimplexGenOld { private static final int DIRS[][] = { { 1, 1, 0 }, { -1, 1, 0 }, { 1, -1, 0 }, { -1, -1, 0 }, { 1, 0, 1 }, { -1, 0, 1 }, { 1, 0, -1 }, diff --git a/java/src/game/rng/WeightedList.java b/common/src/main/java/common/rng/WeightedList.java similarity index 99% rename from java/src/game/rng/WeightedList.java rename to common/src/main/java/common/rng/WeightedList.java index f08fd42..2eb9f3e 100755 --- a/java/src/game/rng/WeightedList.java +++ b/common/src/main/java/common/rng/WeightedList.java @@ -1,11 +1,10 @@ -package game.rng; +package common.rng; import java.util.ArrayList; import java.util.Collection; import java.util.Comparator; -import java.util.function.UnaryOperator; - import java.util.function.Predicate; +import java.util.function.UnaryOperator; public class WeightedList extends ArrayList { protected boolean modified; diff --git a/common/src/main/java/common/sound/EventType.java b/common/src/main/java/common/sound/EventType.java new file mode 100644 index 0000000..5028abc --- /dev/null +++ b/common/src/main/java/common/sound/EventType.java @@ -0,0 +1,5 @@ +package common.sound; + +public enum EventType { + SOUND_EFFECT, UI_INTERFACE; +} diff --git a/java/src/game/audio/MovingSound.java b/common/src/main/java/common/sound/MovingSound.java similarity index 84% rename from java/src/game/audio/MovingSound.java rename to common/src/main/java/common/sound/MovingSound.java index f2a18b2..b8dc64c 100755 --- a/java/src/game/audio/MovingSound.java +++ b/common/src/main/java/common/sound/MovingSound.java @@ -1,6 +1,6 @@ -package game.audio; +package common.sound; -import game.init.SoundEvent; +import common.init.SoundEvent; public abstract class MovingSound extends Sound { diff --git a/java/src/game/audio/MovingSoundMinecart.java b/common/src/main/java/common/sound/MovingSoundMinecart.java similarity index 90% rename from java/src/game/audio/MovingSoundMinecart.java rename to common/src/main/java/common/sound/MovingSoundMinecart.java index fc95eb3..605044b 100755 --- a/java/src/game/audio/MovingSoundMinecart.java +++ b/common/src/main/java/common/sound/MovingSoundMinecart.java @@ -1,8 +1,8 @@ -package game.audio; +package common.sound; -import game.entity.item.EntityCart; -import game.init.SoundEvent; -import game.util.ExtMath; +import common.entity.item.EntityCart; +import common.init.SoundEvent; +import common.util.ExtMath; public class MovingSoundMinecart extends MovingSound { diff --git a/java/src/game/audio/MovingSoundMinecartRiding.java b/common/src/main/java/common/sound/MovingSoundMinecartRiding.java similarity index 87% rename from java/src/game/audio/MovingSoundMinecartRiding.java rename to common/src/main/java/common/sound/MovingSoundMinecartRiding.java index 12521b1..ec4c6ab 100755 --- a/java/src/game/audio/MovingSoundMinecartRiding.java +++ b/common/src/main/java/common/sound/MovingSoundMinecartRiding.java @@ -1,9 +1,9 @@ -package game.audio; +package common.sound; -import game.entity.item.EntityCart; -import game.entity.npc.EntityNPC; -import game.init.SoundEvent; -import game.util.ExtMath; +import common.entity.item.EntityCart; +import common.entity.npc.EntityNPC; +import common.init.SoundEvent; +import common.util.ExtMath; public class MovingSoundMinecartRiding extends MovingSound { diff --git a/java/src/game/audio/PositionedSound.java b/common/src/main/java/common/sound/PositionedSound.java similarity index 84% rename from java/src/game/audio/PositionedSound.java rename to common/src/main/java/common/sound/PositionedSound.java index 53f03c2..86a76c9 100755 --- a/java/src/game/audio/PositionedSound.java +++ b/common/src/main/java/common/sound/PositionedSound.java @@ -1,9 +1,9 @@ -package game.audio; +package common.sound; -import game.init.SoundEvent; +import common.init.SoundEvent; public class PositionedSound extends Sound { - public PositionedSound(SoundEvent event, Volume type) { + public PositionedSound(SoundEvent event, EventType type) { this(event, 1.0F, false, 0.0F, 0.0F, 0.0F); this.type = type; } diff --git a/java/src/game/audio/Sound.java b/common/src/main/java/common/sound/Sound.java similarity index 86% rename from java/src/game/audio/Sound.java rename to common/src/main/java/common/sound/Sound.java index 72b5ac9..d7b8477 100755 --- a/java/src/game/audio/Sound.java +++ b/common/src/main/java/common/sound/Sound.java @@ -1,11 +1,11 @@ -package game.audio; +package common.sound; -import game.init.SoundEvent; +import common.init.SoundEvent; public abstract class Sound { protected final SoundEvent event; - protected Volume type = Volume.SFX; + protected EventType type = EventType.SOUND_EFFECT; protected float volume = 1.0F; protected float xPosF; protected float yPosF; @@ -53,7 +53,7 @@ public abstract class Sound return this.attenuationType; } - public Volume getChannelType() + public EventType getChannelType() { return this.type; } diff --git a/common/src/main/java/common/tags/SizeTracker.java b/common/src/main/java/common/tags/SizeTracker.java new file mode 100755 index 0000000..26040d3 --- /dev/null +++ b/common/src/main/java/common/tags/SizeTracker.java @@ -0,0 +1,22 @@ +package common.tags; + +class SizeTracker { + public static final SizeTracker INFINITE = new SizeTracker(0) { + public void read(int bytes) { + } + }; + + private final int max; + + private int read; + + public SizeTracker(int max) { + this.max = max; + } + + public void read(int bytes) { + this.read += bytes; + if(this.read > this.max) + throw new RuntimeException("Versuchte einen Tag zu lesen, der zu groß war: Habe " + this.read + " Bytes, " + this.max + " Bytes maximal erlaubt"); + } +} diff --git a/common/src/main/java/common/tags/Tag.java b/common/src/main/java/common/tags/Tag.java new file mode 100755 index 0000000..fffc364 --- /dev/null +++ b/common/src/main/java/common/tags/Tag.java @@ -0,0 +1,25 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +abstract class Tag { + abstract void write(DataOutput output) throws IOException; + abstract void read(DataInput input, int depth, SizeTracker tracker) throws IOException; + public abstract String toString(); + abstract TagType getType(); + public abstract Tag copy(); + + String toString(int indent, int depth) { + return this.toString(); + } + + public boolean equals(Object other) { + return other instanceof Tag && this.getType() == ((Tag)other).getType(); + } + + public int hashCode() { + return this.getType().getId(); + } +} diff --git a/common/src/main/java/common/tags/TagBool.java b/common/src/main/java/common/tags/TagBool.java new file mode 100644 index 0000000..2ee2a80 --- /dev/null +++ b/common/src/main/java/common/tags/TagBool.java @@ -0,0 +1,49 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +class TagBool extends Tag { + private boolean data; + + TagBool() { + } + + public TagBool(boolean data) { + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeBoolean(this.data); + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(9); + this.data = input.readBoolean(); + } + + TagType getType() { + return TagType.BOOLEAN; + } + + public String toString() { + return "" + this.data; + } + + public Tag copy() { + return new TagBool(this.data); + } + + public boolean equals(Object other) { + return super.equals(other) && this.data == ((TagBool)other).data; + } + + public int hashCode() { + return super.hashCode() ^ (this.data ? 1 : 0); + } + + public boolean getBool() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagByte.java b/common/src/main/java/common/tags/TagByte.java new file mode 100755 index 0000000..12f86ec --- /dev/null +++ b/common/src/main/java/common/tags/TagByte.java @@ -0,0 +1,49 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +class TagByte extends Tag { + private byte data; + + TagByte() { + } + + public TagByte(byte data) { + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeByte(this.data); + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(9); + this.data = input.readByte(); + } + + TagType getType() { + return TagType.BYTE; + } + + public String toString() { + return "" + this.data + "b"; + } + + public Tag copy() { + return new TagByte(this.data); + } + + public boolean equals(Object other) { + return super.equals(other) && this.data == ((TagByte)other).data; + } + + public int hashCode() { + return super.hashCode() ^ this.data; + } + + public byte getByte() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagByteArray.java b/common/src/main/java/common/tags/TagByteArray.java new file mode 100755 index 0000000..e619211 --- /dev/null +++ b/common/src/main/java/common/tags/TagByteArray.java @@ -0,0 +1,60 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Arrays; + +class TagByteArray extends Tag { + private byte[] data; + + TagByteArray() { + } + + public TagByteArray(byte[] data) { + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeInt(this.data.length); + output.write(this.data); + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(24); + int len = input.readInt(); + tracker.read(len); + this.data = new byte[len]; + input.readFully(this.data); + } + + TagType getType() { + return TagType.BYTE_ARRAY; + } + + public String toString() { + StringBuilder sb = new StringBuilder("[0x"); + for(int z = 0; z < this.data.length; z++) { + sb.append(String.format("%02x", this.data[z])); + } + return sb.append("]").toString(); + } + + public Tag copy() { + byte[] data = new byte[this.data.length]; + System.arraycopy(this.data, 0, data, 0, this.data.length); + return new TagByteArray(data); + } + + public boolean equals(Object other) { + return super.equals(other) && Arrays.equals(this.data, ((TagByteArray)other).data); + } + + public int hashCode() { + return super.hashCode() ^ Arrays.hashCode(this.data); + } + + public byte[] getByteArray() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagChar.java b/common/src/main/java/common/tags/TagChar.java new file mode 100644 index 0000000..ec281f8 --- /dev/null +++ b/common/src/main/java/common/tags/TagChar.java @@ -0,0 +1,49 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +class TagChar extends Tag { + private char data; + + TagChar() { + } + + public TagChar(char data) { + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeChar(this.data); + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(10); + this.data = input.readChar(); + } + + TagType getType() { + return TagType.CHAR; + } + + public String toString() { + return String.format(Character.isLetterOrDigit(this.data) ? "'%c'" : (this.data >= 256 ? "'\\u%04x'" : "'\\x%02x'"), this.data); + } + + public Tag copy() { + return new TagChar(this.data); + } + + public boolean equals(Object other) { + return super.equals(other) && this.data == ((TagChar)other).data; + } + + public int hashCode() { + return super.hashCode() ^ this.data; + } + + public char getChar() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagDouble.java b/common/src/main/java/common/tags/TagDouble.java new file mode 100755 index 0000000..a4b3ed1 --- /dev/null +++ b/common/src/main/java/common/tags/TagDouble.java @@ -0,0 +1,50 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +class TagDouble extends Tag { + private double data; + + TagDouble() { + } + + public TagDouble(double data) { + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeDouble(this.data); + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(16); + this.data = input.readDouble(); + } + + TagType getType() { + return TagType.DOUBLE; + } + + public String toString() { + return "" + this.data + "d"; + } + + public Tag copy() { + return new TagDouble(this.data); + } + + public boolean equals(Object other) { + return super.equals(other) && this.data == ((TagDouble)other).data; + } + + public int hashCode() { + long l = Double.doubleToLongBits(this.data); + return super.hashCode() ^ (int)(l ^ l >>> 32); + } + + public double getDouble() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagException.java b/common/src/main/java/common/tags/TagException.java new file mode 100755 index 0000000..1b11ebc --- /dev/null +++ b/common/src/main/java/common/tags/TagException.java @@ -0,0 +1,7 @@ +package common.tags; + +class TagException extends IllegalArgumentException { + public TagException(String message) { + super(message); + } +} diff --git a/common/src/main/java/common/tags/TagFloat.java b/common/src/main/java/common/tags/TagFloat.java new file mode 100755 index 0000000..0aae9f3 --- /dev/null +++ b/common/src/main/java/common/tags/TagFloat.java @@ -0,0 +1,49 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +class TagFloat extends Tag { + private float data; + + TagFloat() { + } + + public TagFloat(float data) { + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeFloat(this.data); + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(12); + this.data = input.readFloat(); + } + + TagType getType() { + return TagType.FLOAT; + } + + public String toString() { + return "" + this.data + "f"; + } + + public Tag copy() { + return new TagFloat(this.data); + } + + public boolean equals(Object other) { + return super.equals(other) && this.data == ((TagFloat)other).data; + } + + public int hashCode() { + return super.hashCode() ^ Float.floatToIntBits(this.data); + } + + public float getFloat() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagInt.java b/common/src/main/java/common/tags/TagInt.java new file mode 100755 index 0000000..0d3a6b3 --- /dev/null +++ b/common/src/main/java/common/tags/TagInt.java @@ -0,0 +1,49 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +class TagInt extends Tag { + private int data; + + TagInt() { + } + + public TagInt(int data) { + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeInt(this.data); + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(12); + this.data = input.readInt(); + } + + TagType getType() { + return TagType.INT; + } + + public String toString() { + return "" + this.data; + } + + public Tag copy() { + return new TagInt(this.data); + } + + public boolean equals(Object other) { + return super.equals(other) && this.data == ((TagInt)other).data; + } + + public int hashCode() { + return super.hashCode() ^ this.data; + } + + public int getInt() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagIntArray.java b/common/src/main/java/common/tags/TagIntArray.java new file mode 100755 index 0000000..6259e5d --- /dev/null +++ b/common/src/main/java/common/tags/TagIntArray.java @@ -0,0 +1,66 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Arrays; + +class TagIntArray extends Tag { + private int[] data; + + TagIntArray() { + } + + public TagIntArray(int[] data) { + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeInt(this.data.length); + for(int z = 0; z < this.data.length; z++) { + output.writeInt(this.data[z]); + } + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(24); + int len = input.readInt(); + tracker.read(4 * len); + this.data = new int[len]; + for(int z = 0; z < len; z++) { + this.data[z] = input.readInt(); + } + } + + TagType getType() { + return TagType.INT_ARRAY; + } + + public String toString() { + StringBuilder sb = new StringBuilder("["); + for(int z = 0; z < this.data.length; z++) { + if(z != 0) + sb.append(','); + sb.append(this.data[z]); + } + return sb.append("]").toString(); + } + + public Tag copy() { + int[] data = new int[this.data.length]; + System.arraycopy(this.data, 0, data, 0, this.data.length); + return new TagIntArray(data); + } + + public boolean equals(Object other) { + return super.equals(other) && Arrays.equals(this.data, ((TagIntArray)other).data); + } + + public int hashCode() { + return super.hashCode() ^ Arrays.hashCode(this.data); + } + + public int[] getIntArray() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagInterpreter.java b/common/src/main/java/common/tags/TagInterpreter.java new file mode 100755 index 0000000..c364287 --- /dev/null +++ b/common/src/main/java/common/tags/TagInterpreter.java @@ -0,0 +1,593 @@ +package common.tags; + +import java.util.ArrayList; +import java.util.Stack; +import java.util.regex.Pattern; + +import common.collect.Lists; + +class TagInterpreter +{ + private static final Pattern INT_BYTE_ARRAY = Pattern.compile("\\[[-+\\d|,\\s]+\\]"); + private static final Pattern BYTE_ARRAY = Pattern.compile("\\[0x[a-fA-F\\d]*\\]"); + + static TagObject parseTag(String tag) throws TagException + { + if (!tag.startsWith("{")) + { + throw new TagException("Invalid tag encountered, expected \'{\' as first char."); + } + else if (countTags(tag) != 1) + { + throw new TagException("Encountered multiple top tags, only one expected"); + } + else + { + return (TagObject)parseSection("tag", tag).parse(); + } + } + + static int countTags(String str) throws TagException + { + int count = 0; + boolean quote = false; + Stack stack = new Stack(); + + for (int z = 0; z < str.length(); z++) + { + char ch = str.charAt(z); + + if (ch == '"') + { + if (isEscaped(str, z)) + { + if (!quote) + { + throw new TagException("Illegal use of \\\": " + str); + } + } + else + { + quote = !quote; + } + } + else if (!quote) + { + if (ch != '{' && ch != '[') + { + if (ch == '}' && (stack.isEmpty() || ((Character)stack.pop()).charValue() != '{')) + { + throw new TagException("Unbalanced curly brackets {}: " + str); + } + + if (ch == ']' && (stack.isEmpty() || ((Character)stack.pop()).charValue() != '[')) + { + throw new TagException("Unbalanced square brackets []: " + str); + } + } + else + { + if (stack.isEmpty()) + { + ++count; + } + + stack.push(Character.valueOf(ch)); + } + } + } + + if (quote) + { + throw new TagException("Unbalanced quotation: " + str); + } + else if (!stack.isEmpty()) + { + throw new TagException("Unbalanced brackets: " + str); + } + else + { + if (count == 0 && !str.isEmpty()) + { + count = 1; + } + + return count; + } + } + + static TagInterpreter.Parser parseSection(String id, String str) throws TagException + { + str = str.trim(); + + if (str.startsWith("{")) + { + str = str.substring(1, str.length() - 1); + TagInterpreter.Compound tag; + String section; + + for (tag = new TagInterpreter.Compound(id); str.length() > 0; str = str.substring(section.length() + 1)) + { + section = splitSection(str, true); + + if (section.length() > 0) + { + tag.parsers.add(parseSubsection(section, false)); + } + + if (str.length() < section.length() + 1) + { + break; + } + + char ch = str.charAt(section.length()); + + if (ch != ',' && ch != '{' && ch != '}' && ch != '[' && ch != ']') + { + throw new TagException("Unexpected token \'" + ch + "\' at: " + str.substring(section.length())); + } + } + + return tag; + } + else if (str.startsWith("[") && !INT_BYTE_ARRAY.matcher(str).matches() && !BYTE_ARRAY.matcher(str).matches()) + { + str = str.substring(1, str.length() - 1); + TagInterpreter.List list; + String section; + + for (list = new TagInterpreter.List(id); str.length() > 0; str = str.substring(section.length() + 1)) + { + section = splitSection(str, false); + + if (section.length() > 0) + { + list.parsers.add(parseSubsection(section, true)); + } + + if (str.length() < section.length() + 1) + { + break; + } + + char ch = str.charAt(section.length()); + + if (ch != ',' && ch != '{' && ch != '}' && ch != '[' && ch != ']') + { + throw new TagException("Unexpected token \'" + ch + "\' at: " + str.substring(section.length())); + } + } + + return list; + } + else + { + return new TagInterpreter.Primitive(id, str); + } + } + + private static TagInterpreter.Parser parseSubsection(String str, boolean list) throws TagException + { + String key = getKey(str, list); + String value = getValue(str, list); + return parseSection(key, value); + } + + private static String splitSection(String str, boolean noList) throws TagException + { + int colon = findSeparator(str, ':'); + int comma = findSeparator(str, ','); + + if (noList) + { + if (colon == -1) + { + throw new TagException("Unable to locate name/value separator for string: " + str); + } + + if (comma != -1 && comma < colon) + { + throw new TagException("Name error at: " + str); + } + } + else if (colon == -1 || colon > comma) + { + colon = -1; + } + + return split(str, colon); + } + + private static String split(String str, int index) throws TagException + { + Stack stack = new Stack(); + int idx = index + 1; + boolean quote = false; + boolean quoteFirst = false; + boolean printable = false; + + for (int quoteEnd = 0; idx < str.length(); ++idx) + { + char ch = str.charAt(idx); + + if (ch == '"') + { + if (isEscaped(str, idx)) + { + if (!quote) + { + throw new TagException("Illegal use of \\\": " + str); + } + } + else + { + quote = !quote; + + if (quote && !printable) + { + quoteFirst = true; + } + + if (!quote) + { + quoteEnd = idx; + } + } + } + else if (!quote) + { + if (ch != '{' && ch != '[') + { + if (ch == '}' && (stack.isEmpty() || ((Character)stack.pop()).charValue() != '{')) + { + throw new TagException("Unbalanced curly brackets {}: " + str); + } + + if (ch == ']' && (stack.isEmpty() || ((Character)stack.pop()).charValue() != '[')) + { + throw new TagException("Unbalanced square brackets []: " + str); + } + + if (ch == ',' && stack.isEmpty()) + { + return str.substring(0, idx); + } + } + else + { + stack.push(Character.valueOf(ch)); + } + } + + if (!Character.isWhitespace(ch)) + { + if (!quote && quoteFirst && quoteEnd != idx) + { + return str.substring(0, quoteEnd + 1); + } + + printable = true; + } + } + + return str.substring(0, idx); + } + + private static String getKey(String str, boolean list) throws TagException + { + if (list) + { + str = str.trim(); + + if (str.startsWith("{") || str.startsWith("[")) + { + return ""; + } + } + + int colon = findSeparator(str, ':'); + + if (colon == -1) + { + if (list) + { + return ""; + } + else + { + throw new TagException("Unable to locate name/value separator for string: " + str); + } + } + else + { + return str.substring(0, colon).trim(); + } + } + + private static String getValue(String str, boolean list) throws TagException + { + if (list) + { + str = str.trim(); + + if (str.startsWith("{") || str.startsWith("[")) + { + return str; + } + } + + int colon = findSeparator(str, ':'); + + if (colon == -1) + { + if (list) + { + return str; + } + else + { + throw new TagException("Unable to locate name/value separator for string: " + str); + } + } + else + { + return str.substring(colon + 1).trim(); + } + } + + private static int findSeparator(String str, char separator) + { + int idx = 0; + + for (boolean noQuote = true; idx < str.length(); idx++) + { + char ch = str.charAt(idx); + + if (ch == '"') + { + if (!isEscaped(str, idx)) + { + noQuote = !noQuote; + } + } + else if (noQuote) + { + if (ch == separator) + { + return idx; + } + + if (ch == '{' || ch == '[') + { + return -1; + } + } + } + + return -1; + } + + private static boolean isEscaped(String str, int index) + { + return index > 0 && str.charAt(index - 1) == '\\' && !isEscaped(str, index - 1); + } + + abstract static class Parser + { + protected String section; + + public abstract Tag parse() throws TagException; + } + + static class Compound extends TagInterpreter.Parser + { + protected java.util.List parsers = Lists.newArrayList(); + + public Compound(String section) + { + this.section = section; + } + + public Tag parse() throws TagException + { + TagObject tag = new TagObject(); + + for (TagInterpreter.Parser any : this.parsers) + { + tag.set(any.section, any.parse()); + } + + return tag; + } + } + + static class List extends TagInterpreter.Parser + { + protected java.util.List parsers = Lists.newArrayList(); + + public List(String section) + { + this.section = section; + } + + public Tag parse() throws TagException + { + TagList list = null; + java.util.List strs = null; + + for (TagInterpreter.Parser any : this.parsers) + { + Tag tag = any.parse(); + if(tag.getType() == TagType.STRING) { + if(list != null) + throw new TagException("Cannot use mixed types for list: " + any.section); + if(strs == null) + strs = new ArrayList(this.parsers.size()); + strs.add(((TagString)tag).getString()); + } + else if(tag.getType() == TagType.OBJECT) { + if(strs != null) + throw new TagException("Cannot use mixed types for list: " + any.section); + if(list == null) + list = new TagList(new ArrayList(this.parsers.size())); + list.getList().add(((TagObject)tag)); + } + else { + throw new TagException("Type cannot be put in a list: " + any.section); + } + } + + return strs != null ? new TagStringArray(strs.toArray(new String[strs.size()])) : (list != null ? list : new TagList(Lists.newArrayList())); + } + } + + static class Primitive extends TagInterpreter.Parser + { + private static final Pattern DOUBLE = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[d|D]"); + private static final Pattern FLOAT = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[f|F]"); + private static final Pattern BYTE = Pattern.compile("[-+]?[0-9]+[b|B]"); + private static final Pattern LONG = Pattern.compile("[-+]?[0-9]+[l|L]"); + private static final Pattern SHORT = Pattern.compile("[-+]?[0-9]+[s|S]"); + private static final Pattern INTEGER = Pattern.compile("[-+]?[0-9]+"); + private static final Pattern DOUBLE_UNTYPED = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+"); + + protected String value; + + public Primitive(String section, String value) + { + this.section = section; + this.value = value; + } + + public Tag parse() throws TagException + { + try + { + if (DOUBLE.matcher(this.value).matches()) + { + return new TagDouble(Double.parseDouble(this.value.substring(0, this.value.length() - 1))); + } + + if (FLOAT.matcher(this.value).matches()) + { + return new TagFloat(Float.parseFloat(this.value.substring(0, this.value.length() - 1))); + } + + if (BYTE.matcher(this.value).matches()) + { + return new TagByte(Byte.parseByte(this.value.substring(0, this.value.length() - 1))); + } + + if (LONG.matcher(this.value).matches()) + { + return new TagLong(Long.parseLong(this.value.substring(0, this.value.length() - 1))); + } + + if (SHORT.matcher(this.value).matches()) + { + return new TagShort(Short.parseShort(this.value.substring(0, this.value.length() - 1))); + } + + if (INTEGER.matcher(this.value).matches()) + { + return new TagInt(Integer.parseInt(this.value)); + } + + if (DOUBLE_UNTYPED.matcher(this.value).matches()) + { + return new TagDouble(Double.parseDouble(this.value)); + } + + if (this.value.equalsIgnoreCase("true") || this.value.equalsIgnoreCase("false")) + { + return new TagBool(Boolean.parseBoolean(this.value)); + } + } + catch (NumberFormatException e) + { + this.value = this.value.replaceAll("\\\\\"", "\""); + return new TagString(this.value); + } + + if (this.value.startsWith("[") && this.value.endsWith("]")) + { + String str = this.value.substring(1, this.value.length() - 1); + try + { + if(str.startsWith("0x")) { + str = str.substring(2); + if((str.length() & 1) == 1) + str = "0" + str; + byte[] bytes = new byte[str.length() / 2]; + for (int z = 0; z < bytes.length; z++) + { + bytes[z] = (byte)Integer.parseUnsignedInt(str.substring(z * 2, (z + 1) * 2), 16); + } + return new TagByteArray(bytes); + } + else { + String[] elems = str.split(","); + int[] ints = new int[elems.length]; + for (int z = 0; z < elems.length; z++) + { + ints[z] = Integer.parseInt(elems[z].trim()); + } + return new TagIntArray(ints); + } + } + catch (NumberFormatException e) + { + return new TagString(this.value); + } + } + else + { + if (this.value.startsWith("'") && this.value.endsWith("'")) + { + String str = this.value.substring(1, this.value.length() - 1); + if(str.length() == 1 && str.charAt(0) != '\\') { + return new TagChar(str.charAt(0)); + } + else if(str.length() == 2 && str.charAt(0) == '\\') { + switch(str.charAt(1)) { + case '\\': + return new TagChar('\\'); + case 'n': + return new TagChar('\n'); + } + } + else if((str.length() == 4 && str.startsWith("\\x")) || (str.length() == 6 && str.startsWith("\\u"))) { + try { + return new TagChar((char)Integer.parseUnsignedInt(str.substring(2), 16)); + } + catch(NumberFormatException e) { + } + } + } + + if (this.value.startsWith("\"") && this.value.endsWith("\"")) + { + this.value = this.value.substring(1, this.value.length() - 1); + } + + this.value = this.value.replaceAll("\\\\\"", "\""); + StringBuilder sb = new StringBuilder(); + + for (int z = 0; z < this.value.length(); z++) + { + if (z < this.value.length() - 1 && this.value.charAt(z) == '\\' && this.value.charAt(z + 1) == '\\') + { + sb.append('\\'); + ++z; + } + else + { + sb.append(this.value.charAt(z)); + } + } + + return new TagString(sb.toString()); + } + } + } +} diff --git a/common/src/main/java/common/tags/TagList.java b/common/src/main/java/common/tags/TagList.java new file mode 100644 index 0000000..67fa035 --- /dev/null +++ b/common/src/main/java/common/tags/TagList.java @@ -0,0 +1,85 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import common.util.Util; + +class TagList extends Tag { + private List list; + + TagList() { + } + + public TagList(List list) { + this.list = list; + } + + void write(DataOutput output) throws IOException { + output.writeInt(this.list.size()); + for(int z = 0; z < this.list.size(); z++) { + this.list.get(z).write(output); + } + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(36); + if(depth > 256) + throw new IOException("Objekt ist zu komplex, die Tiefe ist größer als 256"); + int len = input.readInt(); + tracker.read(4 * len); + this.list = new ArrayList(len); + for(int z = 0; z < len; z++) { + TagObject tag = new TagObject(); + tag.read(input, depth + 1, tracker); + this.list.add(tag); + } + } + + TagType getType() { + return TagType.LIST; + } + + public String toString() { + StringBuilder sb = new StringBuilder("["); + for(int z = 0; z < this.list.size(); z++) { + if(z != 0) + sb.append(','); + sb.append(this.list.get(z).toString()); + } + return sb.append(']').toString(); + } + + String toString(int indent, int depth) { + StringBuilder sb = new StringBuilder("["); + String prefix = Util.repeatString(' ', indent * (depth + 1)); + for(int z = 0; z < this.list.size(); z++) { + if(z != 0) + sb.append(','); + sb.append('\n').append(prefix).append(this.list.get(z).toString(indent, depth + 1)); + } + return sb.append('\n').append(Util.repeatString(' ', indent * depth)).append(']').toString(); + } + + public Tag copy() { + TagList list = new TagList(new ArrayList(this.list.size())); + for(TagObject tag : this.list) { + list.list.add(tag.copy()); + } + return list; + } + + public boolean equals(Object other) { + return super.equals(other) && this.list.equals(((TagList)other).list); + } + + public int hashCode() { + return super.hashCode() ^ this.list.hashCode(); + } + + public List getList() { + return this.list; + } +} diff --git a/common/src/main/java/common/tags/TagLong.java b/common/src/main/java/common/tags/TagLong.java new file mode 100755 index 0000000..ac2d2b3 --- /dev/null +++ b/common/src/main/java/common/tags/TagLong.java @@ -0,0 +1,49 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +class TagLong extends Tag { + private long data; + + TagLong() { + } + + public TagLong(long data) { + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeLong(this.data); + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(16); + this.data = input.readLong(); + } + + TagType getType() { + return TagType.LONG; + } + + public String toString() { + return "" + this.data + "L"; + } + + public Tag copy() { + return new TagLong(this.data); + } + + public boolean equals(Object other) { + return super.equals(other) && this.data == ((TagLong)other).data; + } + + public int hashCode() { + return super.hashCode() ^ (int)(this.data ^ this.data >>> 32); + } + + public long getLong() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagObject.java b/common/src/main/java/common/tags/TagObject.java new file mode 100755 index 0000000..dd80354 --- /dev/null +++ b/common/src/main/java/common/tags/TagObject.java @@ -0,0 +1,398 @@ +package common.tags; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.DataInput; +import java.io.DataInputStream; +import java.io.DataOutput; +import java.io.DataOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import common.collect.Lists; +import common.collect.Maps; +import common.util.Util; + +import java.util.Set; +import java.util.zip.GZIPInputStream; +import java.util.zip.GZIPOutputStream; + +/** + * compressed data tree / CDT + * (ids 0..15) + */ +public class TagObject extends Tag { + private Map tags = Maps.newHashMap(); + + void write(DataOutput output) throws IOException { + for(String key : this.tags.keySet()) { + Tag tag = this.tags.get(key); + output.writeByte(tag.getType().getId()); + if(tag.getType() != TagType.NULL) { + output.writeUTF(key); + tag.write(output); + } + } + output.writeByte(0); + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(48); + if(depth > 256) + throw new IOException("Objekt ist zu komplex, die Tiefe ist größer als 256"); + this.tags.clear(); + byte id; + while((id = input.readByte()) != 0) { + String key = input.readUTF(); + tracker.read(28 + 2 * key.length()); + Tag tag = TagType.create(id); + tag.read(input, depth + 1, tracker); + if(this.tags.put(key, tag) != null) + throw new IOException("Objekt ist ungültig, Tag '" + key + "' ist mehrfach vorhanden"); + } + } + + public Set keySet() { + return this.tags.keySet(); + } + + TagType getType() { + return TagType.OBJECT; + } + + void set(String key, Tag value) { + this.tags.put(key, value); + } + + public void setObject(String key, TagObject value) { + this.tags.put(key, value); + } + + public void setStringArray(String key, String[] value) { + this.tags.put(key, new TagStringArray(value)); + } + + public void setList(String key, List value) { + this.tags.put(key, new TagList(value)); + } + + public void setBool(String key, boolean value) { + this.tags.put(key, new TagBool(value)); + } + + public void setByte(String key, byte value) { + this.tags.put(key, new TagByte(value)); + } + + public void setShort(String key, short value) { + this.tags.put(key, new TagShort(value)); + } + + public void setChar(String key, char value) { + this.tags.put(key, new TagChar(value)); + } + + public void setInt(String key, int value) { + this.tags.put(key, new TagInt(value)); + } + + public void setLong(String key, long value) { + this.tags.put(key, new TagLong(value)); + } + + public void setFloat(String key, float value) { + this.tags.put(key, new TagFloat(value)); + } + + public void setDouble(String key, double value) { + this.tags.put(key, new TagDouble(value)); + } + + public void setString(String key, String value) { + this.tags.put(key, new TagString(value)); + } + + public void setByteArray(String key, byte[] value) { + this.tags.put(key, new TagByteArray(value)); + } + + public void setIntArray(String key, int[] value) { + this.tags.put(key, new TagIntArray(value)); + } + + Tag get(String key) { + return this.tags.get(key); + } + + private boolean has(String key, TagType type) { + Tag tag = this.tags.get(key); + return tag != null && tag.getType() == type; + } + + public boolean hasBool(String key) { + return this.has(key, TagType.BOOLEAN); + } + + public boolean hasByte(String key) { + return this.has(key, TagType.BYTE); + } + + public boolean hasShort(String key) { + return this.has(key, TagType.SHORT); + } + + public boolean hasChar(String key) { + return this.has(key, TagType.CHAR); + } + + public boolean hasInt(String key) { + return this.has(key, TagType.INT); + } + + public boolean hasLong(String key) { + return this.has(key, TagType.LONG); + } + + public boolean hasFloat(String key) { + return this.has(key, TagType.FLOAT); + } + + public boolean hasDouble(String key) { + return this.has(key, TagType.DOUBLE); + } + + public boolean hasString(String key) { + return this.has(key, TagType.STRING); + } + + public boolean hasByteArray(String key) { + return this.has(key, TagType.BYTE_ARRAY); + } + + public boolean hasIntArray(String key) { + return this.has(key, TagType.INT_ARRAY); + } + + public boolean hasObject(String key) { + return this.has(key, TagType.OBJECT); + } + + public boolean hasStringArray(String key) { + return this.has(key, TagType.STRING_ARRAY); + } + + public boolean hasList(String key) { + return this.has(key, TagType.LIST); + } + + public boolean getBool(String key) { + return !this.has(key, TagType.BOOLEAN) ? false : ((TagBool)this.tags.get(key)).getBool(); + } + + public byte getByte(String key) { + return !this.has(key, TagType.BYTE) ? 0 : ((TagByte)this.tags.get(key)).getByte(); + } + + public short getShort(String key) { + return !this.has(key, TagType.SHORT) ? 0 : ((TagShort)this.tags.get(key)).getShort(); + } + + public char getChar(String key) { + return !this.has(key, TagType.CHAR) ? 0 : ((TagChar)this.tags.get(key)).getChar(); + } + + public int getInt(String key) { + return !this.has(key, TagType.INT) ? 0 : ((TagInt)this.tags.get(key)).getInt(); + } + + public long getLong(String key) { + return !this.has(key, TagType.LONG) ? 0L : ((TagLong)this.tags.get(key)).getLong(); + } + + public float getFloat(String key) { + return !this.has(key, TagType.FLOAT) ? 0.0f : ((TagFloat)this.tags.get(key)).getFloat(); + } + + public double getDouble(String key) { + return !this.has(key, TagType.DOUBLE) ? 0.0 : ((TagDouble)this.tags.get(key)).getDouble(); + } + + public String getString(String key) { + return !this.has(key, TagType.STRING) ? "" : ((TagString)this.tags.get(key)).getString(); + } + + public byte[] getByteArray(String key) { + return !this.has(key, TagType.BYTE_ARRAY) ? new byte[0] : ((TagByteArray)this.tags.get(key)).getByteArray(); + } + + public int[] getIntArray(String key) { + return !this.has(key, TagType.INT_ARRAY) ? new int[0] : ((TagIntArray)this.tags.get(key)).getIntArray(); + } + + public TagObject getObject(String key) { + return !this.has(key, TagType.OBJECT) ? new TagObject() : (TagObject)this.tags.get(key); + } + + public String[] getStringArray(String key) { + return !this.has(key, TagType.STRING_ARRAY) ? new String[0] : ((TagStringArray)this.tags.get(key)).getStringArray(); + } + + public List getList(String key) { + return !this.has(key, TagType.LIST) ? Lists.newArrayList() : ((TagList)this.tags.get(key)).getList(); + } + + public void remove(String key) { + this.tags.remove(key); + } + + private List> getSortedEntries() { + List> list = Lists.newArrayList(this.tags.entrySet()); + Collections.sort(list, (e1, e2) -> e1.getValue().getType() == TagType.OBJECT && e2.getValue().getType() != TagType.OBJECT ? 1 : ( + e2.getValue().getType() == TagType.OBJECT && e1.getValue().getType() != TagType.OBJECT ? -1 : ( + (e1.getValue().getType() == TagType.LIST || e1.getValue().getType() == TagType.STRING_ARRAY) && + e2.getValue().getType() != TagType.LIST && e2.getValue().getType() != TagType.STRING_ARRAY ? 1 : ( + (e2.getValue().getType() == TagType.LIST || e2.getValue().getType() == TagType.STRING_ARRAY) && + e1.getValue().getType() != TagType.LIST && e1.getValue().getType() != TagType.STRING_ARRAY ? -1 : e1.getKey().compareTo(e2.getKey()))))); + return list; + } + + public String toString() { + StringBuilder sb = new StringBuilder("{"); + for(Entry entry : this.getSortedEntries()) { + if(sb.length() != 1) + sb.append(','); + sb.append(entry.getKey()).append(':').append(entry.getValue().toString()); + } + return sb.append('}').toString(); + } + + String toString(int indent, int depth) { + StringBuilder sb = new StringBuilder("{"); + String prefix = Util.repeatString(' ', indent * (depth + 1)); + for(Entry entry : this.getSortedEntries()) { + if(sb.length() != 1) + sb.append(','); + sb.append('\n').append(prefix).append(entry.getKey()).append(": ").append(entry.getValue().toString(indent, depth + 1)); + } + return sb.append('\n').append(Util.repeatString(' ', indent * depth)).append('}').toString(); + } + + public boolean isEmpty() { + return this.tags.isEmpty(); + } + + public TagObject copy() { + TagObject tag = new TagObject(); + for(String s : this.tags.keySet()) { + tag.set(s, this.tags.get(s).copy()); + } + return tag; + } + + public boolean equals(Object other) { + return super.equals(other) && this.tags.entrySet().equals(((TagObject)other).tags.entrySet()); + } + + public int hashCode() { + return super.hashCode() ^ this.tags.hashCode(); + } + + /** + * Merges this tag with the given compound. Any sub-compounds are + * merged using the same methods, other types of tags are overwritten from the + * given compound. + */ + public void merge(TagObject other) { + for(String key : other.tags.keySet()) { + Tag tag = other.tags.get(key); + if(tag.getType() == TagType.OBJECT) { + if(this.has(key, TagType.OBJECT)) { + TagObject comp = this.getObject(key); + comp.merge((TagObject)tag); + } + else { + this.set(key, tag.copy()); + } + } + else { + this.set(key, tag.copy()); + } + } + } + + public String format(int indent) { + return indent == 0 ? this.toString() : this.toString(indent, 0); + } + + public static void write(TagObject tag, DataOutput out) throws IOException { + tag.write(out); + } + + public static TagObject read(DataInput in) throws IOException { + return read(in, SizeTracker.INFINITE); + } + + public static TagObject read(DataInput in, int limit) throws IOException { + return read(in, new SizeTracker(limit)); + } + + private static TagObject read(DataInput in, SizeTracker tracker) throws IOException { + TagObject tag = new TagObject(); + tag.read(in, 0, tracker); + return tag; + } + + public static void writeGZip(TagObject tag, File file) throws IOException { + DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(file)))); + try { + TagObject.write(tag, out); + } + finally { + out.close(); + } + } + + public static TagObject readGZip(File file) throws IOException { + DataInputStream in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)))); + TagObject tag; + try { + tag = TagObject.read(in, SizeTracker.INFINITE); + } + finally { + in.close(); + } + return tag; + } + + public static boolean compare(TagObject tag1, TagObject tag2) { + return compareTags(tag1, tag2); + } + + private static boolean compareTags(Tag tag1, Tag tag2) { + if(tag1 == tag2 || tag1 == null) + return true; + else if(tag2 == null || !tag1.getClass().equals(tag2.getClass())) + return false; + else if(tag1 instanceof TagObject) { + TagObject comp1 = (TagObject)tag1; + TagObject comp2 = (TagObject)tag2; + for(String key : comp1.keySet()) { + Tag tag = comp1.get(key); + if(!compareTags(tag, comp2.get(key))) + return false; + } + return true; + } + return tag1.equals(tag2); + } + + public static TagObject parse(String tag) throws IllegalArgumentException { + return TagInterpreter.parseTag(tag.trim()); + } +} diff --git a/common/src/main/java/common/tags/TagShort.java b/common/src/main/java/common/tags/TagShort.java new file mode 100755 index 0000000..15ed3e2 --- /dev/null +++ b/common/src/main/java/common/tags/TagShort.java @@ -0,0 +1,49 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +class TagShort extends Tag { + private short data; + + TagShort() { + } + + public TagShort(short data) { + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeShort(this.data); + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(10); + this.data = input.readShort(); + } + + TagType getType() { + return TagType.SHORT; + } + + public String toString() { + return "" + this.data + "s"; + } + + public Tag copy() { + return new TagShort(this.data); + } + + public boolean equals(Object other) { + return super.equals(other) && this.data == ((TagShort)other).data; + } + + public int hashCode() { + return super.hashCode() ^ this.data; + } + + public short getShort() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagString.java b/common/src/main/java/common/tags/TagString.java new file mode 100755 index 0000000..bb0b814 --- /dev/null +++ b/common/src/main/java/common/tags/TagString.java @@ -0,0 +1,56 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; + +class TagString extends Tag { + private String data; + + TagString() { + this.data = ""; + } + + public TagString(String data) { + if(data == null) + throw new IllegalArgumentException("Eine Zeichenkette aus null ist nicht erlaubt"); + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeUTF(this.data); + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(36); + this.data = input.readUTF(); + tracker.read(2 * this.data.length()); + } + + TagType getType() { + return TagType.STRING; + } + + public String toString() { + return "\"" + this.data.replace("\"", "\\\"") + "\""; + } + + public Tag copy() { + return new TagString(this.data); + } + + public boolean equals(Object other) { + if(!super.equals(other)) + return false; + TagString tag = (TagString)other; + return this.data == null && tag.data == null || this.data != null && this.data.equals(tag.data); + } + + public int hashCode() { + return super.hashCode() ^ this.data.hashCode(); + } + + public String getString() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagStringArray.java b/common/src/main/java/common/tags/TagStringArray.java new file mode 100644 index 0000000..eefd2b2 --- /dev/null +++ b/common/src/main/java/common/tags/TagStringArray.java @@ -0,0 +1,79 @@ +package common.tags; + +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.Arrays; + +import common.util.Util; + +class TagStringArray extends Tag { + private String[] data; + + TagStringArray() { + } + + public TagStringArray(String[] data) { + this.data = data; + } + + void write(DataOutput output) throws IOException { + output.writeInt(this.data.length); + for(int z = 0; z < this.data.length; z++) { + output.writeUTF(this.data[z]); + } + } + + void read(DataInput input, int depth, SizeTracker tracker) throws IOException { + tracker.read(24); + int len = input.readInt(); + this.data = new String[len]; + for(int z = 0; z < len; z++) { + this.data[z] = input.readUTF(); + tracker.read(2 * this.data[z].length()); + } + } + + TagType getType() { + return TagType.STRING_ARRAY; + } + + public String toString() { + StringBuilder sb = new StringBuilder("["); + for(int z = 0; z < this.data.length; z++) { + if(z != 0) + sb.append(','); + sb.append("\"" + this.data[z].replace("\"", "\\\"") + "\""); + } + return sb.append("]").toString(); + } + + String toString(int indent, int depth) { + StringBuilder sb = new StringBuilder("["); + String prefix = Util.repeatString(' ', indent * (depth + 1)); + for(int z = 0; z < this.data.length; z++) { + if(z != 0) + sb.append(','); + sb.append('\n').append(prefix).append("\"" + this.data[z].replace("\"", "\\\"") + "\""); + } + return sb.append('\n').append(Util.repeatString(' ', indent * depth)).append("]").toString(); + } + + public Tag copy() { + String[] data = new String[this.data.length]; + System.arraycopy(this.data, 0, data, 0, this.data.length); + return new TagStringArray(data); + } + + public boolean equals(Object other) { + return super.equals(other) && Arrays.equals(this.data, ((TagStringArray)other).data); + } + + public int hashCode() { + return super.hashCode() ^ Arrays.hashCode(this.data); + } + + public String[] getStringArray() { + return this.data; + } +} diff --git a/common/src/main/java/common/tags/TagType.java b/common/src/main/java/common/tags/TagType.java new file mode 100644 index 0000000..c29db1d --- /dev/null +++ b/common/src/main/java/common/tags/TagType.java @@ -0,0 +1,105 @@ +package common.tags; + +import java.io.IOException; + +enum TagType { + NULL { // 0 + protected Tag createTag() { + return null; + } + }, + OBJECT { // 1 + protected Tag createTag() { + return new TagObject(); + } + }, + BOOLEAN { // 2 + protected Tag createTag() { + return new TagBool(); + } + }, + BYTE { // 3 + protected Tag createTag() { + return new TagByte(); + } + }, + SHORT { // 4 + protected Tag createTag() { + return new TagShort(); + } + }, + CHAR { // 5 + protected Tag createTag() { + return new TagChar(); + } + }, + INT { // 6 + protected Tag createTag() { + return new TagInt(); + } + }, + LONG { // 7 + protected Tag createTag() { + return new TagLong(); + } + }, + FLOAT { // 8 + protected Tag createTag() { + return new TagFloat(); + } + }, + DOUBLE { // 9 + protected Tag createTag() { + return new TagDouble(); + } + }, + STRING { // 10 + protected Tag createTag() { + return new TagString(); + } + }, + LIST { // 11 + protected Tag createTag() { + return new TagList(); + } + }, + BYTE_ARRAY { // 12 + protected Tag createTag() { + return new TagByteArray(); + } + }, + INT_ARRAY { // 13 + protected Tag createTag() { + return new TagIntArray(); + } + }, + STRING_ARRAY { // 14 + protected Tag createTag() { + return new TagStringArray(); + } + }; + + private static final TagType[] TYPES; + + private final byte id; + + static { + TYPES = values(); + } + + static Tag create(byte id) throws IOException { + if(id <= 0 || id >= TYPES.length) + throw new IOException("Kann keinen gültigen Tag mit ID #" + id + " lesen"); + return TYPES[id].createTag(); + } + + private TagType() { + this.id = (byte)this.ordinal(); + } + + protected abstract Tag createTag(); + + public byte getId() { + return this.id; + } +} diff --git a/java/src/game/tileentity/IHopper.java b/common/src/main/java/common/tileentity/IHopper.java similarity index 82% rename from java/src/game/tileentity/IHopper.java rename to common/src/main/java/common/tileentity/IHopper.java index 0990c7a..a314d15 100755 --- a/java/src/game/tileentity/IHopper.java +++ b/common/src/main/java/common/tileentity/IHopper.java @@ -1,7 +1,7 @@ -package game.tileentity; +package common.tileentity; -import game.inventory.IInventory; -import game.world.World; +import common.inventory.IInventory; +import common.world.World; public interface IHopper extends IInventory { diff --git a/java/src/game/tileentity/IInteractionObject.java b/common/src/main/java/common/tileentity/IInteractionObject.java similarity index 55% rename from java/src/game/tileentity/IInteractionObject.java rename to common/src/main/java/common/tileentity/IInteractionObject.java index 5b273e6..fc0e98e 100755 --- a/java/src/game/tileentity/IInteractionObject.java +++ b/common/src/main/java/common/tileentity/IInteractionObject.java @@ -1,8 +1,8 @@ -package game.tileentity; +package common.tileentity; -import game.entity.npc.EntityNPC; -import game.inventory.Container; -import game.inventory.InventoryPlayer; +import common.entity.npc.EntityNPC; +import common.inventory.Container; +import common.inventory.InventoryPlayer; public interface IInteractionObject extends IWorldNameable { diff --git a/common/src/main/java/common/tileentity/ILockableContainer.java b/common/src/main/java/common/tileentity/ILockableContainer.java new file mode 100755 index 0000000..f534a92 --- /dev/null +++ b/common/src/main/java/common/tileentity/ILockableContainer.java @@ -0,0 +1,12 @@ +package common.tileentity; + +import common.inventory.IInventory; + +public interface ILockableContainer extends IInventory, IInteractionObject +{ + boolean isLocked(); + + void setLockCode(Passcode code); + + Passcode getLockCode(); +} diff --git a/java/src/game/tileentity/ITickable.java b/common/src/main/java/common/tileentity/ITickable.java similarity index 65% rename from java/src/game/tileentity/ITickable.java rename to common/src/main/java/common/tileentity/ITickable.java index 65c97a4..7227b5e 100755 --- a/java/src/game/tileentity/ITickable.java +++ b/common/src/main/java/common/tileentity/ITickable.java @@ -1,4 +1,4 @@ -package game.tileentity; +package common.tileentity; public interface ITickable { diff --git a/java/src/game/tileentity/IWorldNameable.java b/common/src/main/java/common/tileentity/IWorldNameable.java similarity index 70% rename from java/src/game/tileentity/IWorldNameable.java rename to common/src/main/java/common/tileentity/IWorldNameable.java index 48d70eb..4fa737b 100755 --- a/java/src/game/tileentity/IWorldNameable.java +++ b/common/src/main/java/common/tileentity/IWorldNameable.java @@ -1,4 +1,4 @@ -package game.tileentity; +package common.tileentity; public interface IWorldNameable { diff --git a/java/src/game/tileentity/MachineResource.java b/common/src/main/java/common/tileentity/MachineResource.java similarity index 75% rename from java/src/game/tileentity/MachineResource.java rename to common/src/main/java/common/tileentity/MachineResource.java index 72390f1..b56840c 100755 --- a/java/src/game/tileentity/MachineResource.java +++ b/common/src/main/java/common/tileentity/MachineResource.java @@ -1,6 +1,6 @@ -package game.tileentity; +package common.tileentity; -import game.nbt.NBTTagCompound; +import common.tags.TagObject; public class MachineResource { public static enum Type { @@ -23,20 +23,20 @@ public class MachineResource { this.overcharge = over; } - public void readFromNbt(NBTTagCompound tag) { - this.amount = tag.getInteger("Amount"); - this.capacity = tag.getInteger("Capacity"); - this.undercharge = tag.getInteger("Under"); - this.overcharge = tag.getInteger("Over"); - this.entropy = tag.getInteger("Entropy"); + public void readFromNbt(TagObject tag) { + this.amount = tag.getInt("Amount"); + this.capacity = tag.getInt("Capacity"); + this.undercharge = tag.getInt("Under"); + this.overcharge = tag.getInt("Over"); + this.entropy = tag.getInt("Entropy"); } - public void writeToNbt(NBTTagCompound tag) { - tag.setInteger("Amount", this.amount); - tag.setInteger("Capacity", this.capacity); - tag.setInteger("Under", this.undercharge); - tag.setInteger("Over", this.overcharge); - tag.setInteger("Entropy", this.entropy); + public void writeToNbt(TagObject tag) { + tag.setInt("Amount", this.amount); + tag.setInt("Capacity", this.capacity); + tag.setInt("Under", this.undercharge); + tag.setInt("Over", this.overcharge); + tag.setInt("Entropy", this.entropy); } public void setValue(int value) { diff --git a/common/src/main/java/common/tileentity/Passcode.java b/common/src/main/java/common/tileentity/Passcode.java new file mode 100755 index 0000000..1b3b45e --- /dev/null +++ b/common/src/main/java/common/tileentity/Passcode.java @@ -0,0 +1,19 @@ +package common.tileentity; + +import common.tags.TagObject; + +public record Passcode(String code) { + public static final Passcode EMPTY_CODE = new Passcode(""); + + public boolean empty() { + return this.code == null || this.code.isEmpty(); + } + + public void toNBT(TagObject tag) { + tag.setString("Lock", this.code); + } + + public static Passcode fromNBT(TagObject tag) { + return tag.hasString("Lock") ? new Passcode(tag.getString("Lock")) : EMPTY_CODE; + } +} diff --git a/java/src/game/tileentity/TileEntity.java b/common/src/main/java/common/tileentity/TileEntity.java similarity index 79% rename from java/src/game/tileentity/TileEntity.java rename to common/src/main/java/common/tileentity/TileEntity.java index 8b25565..4892eaa 100755 --- a/java/src/game/tileentity/TileEntity.java +++ b/common/src/main/java/common/tileentity/TileEntity.java @@ -1,14 +1,15 @@ -package game.tileentity; +package common.tileentity; -import game.block.Block; -import game.init.Blocks; -import game.init.TileRegistry; -import game.log.Log; -import game.nbt.NBTTagCompound; -import game.network.Packet; -import game.world.BlockPos; -import game.world.State; -import game.world.World; +import common.block.Block; +import common.init.Blocks; +import common.init.TileRegistry; +import common.log.Log; +import common.network.Packet; +import common.tags.TagObject; +import common.util.BlockPos; +import common.world.AWorldServer; +import common.world.State; +import common.world.World; public abstract class TileEntity { @@ -52,14 +53,14 @@ public abstract class TileEntity return this.worldObj != null; } - public void readFromNBT(NBTTagCompound compound) + public void readTags(TagObject compound) { - this.pos = new BlockPos(compound.getInteger("x"), compound.getInteger("y"), compound.getInteger("z")); + this.pos = new BlockPos(compound.getInt("x"), compound.getInt("y"), compound.getInt("z")); } - public void writeToNBT(NBTTagCompound compound) + public void writeTags(TagObject compound) { - String s = (String)TileRegistry.classToNameMap.get(this.getClass()); + String s = (String)TileRegistry.CLASS_TO_NAME.get(this.getClass()); if (s == null) { @@ -68,26 +69,26 @@ public abstract class TileEntity else { compound.setString("id", s); - compound.setInteger("x", this.pos.getX()); - compound.setInteger("y", this.pos.getY()); - compound.setInteger("z", this.pos.getZ()); + compound.setInt("x", this.pos.getX()); + compound.setInt("y", this.pos.getY()); + compound.setInt("z", this.pos.getZ()); } } /** * Creates a new entity and loads its data from the specified NBT. */ - public static TileEntity createAndLoadEntity(NBTTagCompound nbt) + public static TileEntity createAndLoadEntity(TagObject nbt) { TileEntity tileentity = null; try { - Class oclass = (Class)TileRegistry.nameToClassMap.get(nbt.getString("id")); + Class oclass = (Class)TileRegistry.NAME_TO_CLASS.get(nbt.getString("id")); if (oclass != null) { - tileentity = (TileEntity)oclass.newInstance(); + tileentity = (TileEntity)oclass.getConstructor().newInstance(); } } catch (Exception exception) @@ -97,11 +98,11 @@ public abstract class TileEntity if (tileentity != null) { - tileentity.readFromNBT(nbt); + tileentity.readTags(nbt); } else { - Log.JNI.warn("Ignoriere Block-Objekt mit ID " + nbt.getString("id")); + Log.TICK.warn("Ignoriere Block-Objekt mit ID " + nbt.getString("id")); } return tileentity; @@ -128,7 +129,8 @@ public abstract class TileEntity { State iblockstate = this.worldObj.getState(this.pos); this.blockMetadata = iblockstate.getBlock().getMetaFromState(iblockstate); - this.worldObj.markChunkDirty(this.pos, this); + if(!this.worldObj.client) + ((AWorldServer)this.worldObj).markChunkDirty(this.pos); if (this.getBlockType() != Blocks.air) { diff --git a/java/src/game/tileentity/TileEntityBanner.java b/common/src/main/java/common/tileentity/TileEntityBanner.java similarity index 80% rename from java/src/game/tileentity/TileEntityBanner.java rename to common/src/main/java/common/tileentity/TileEntityBanner.java index 03a20a5..6f09ac2 100755 --- a/java/src/game/tileentity/TileEntityBanner.java +++ b/common/src/main/java/common/tileentity/TileEntityBanner.java @@ -1,25 +1,23 @@ -package game.tileentity; +package common.tileentity; import java.util.List; -import game.collect.Lists; - -import game.block.BlockFlower; -import game.color.DyeColor; -import game.init.Blocks; -import game.init.Items; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.network.Packet; -import game.packet.S35PacketUpdateTileEntity; +import common.block.foliage.BlockFlower; +import common.collect.Lists; +import common.color.DyeColor; +import common.init.Blocks; +import common.init.Items; +import common.item.ItemStack; +import common.network.Packet; +import common.packet.SPacketUpdateTileEntity; +import common.tags.TagObject; public class TileEntityBanner extends TileEntity { private int baseColor; /** A list of all the banner patterns. */ - private NBTTagList patterns; + private List patterns; private boolean field_175119_g; private List patternList; private List colorList; @@ -33,18 +31,21 @@ public class TileEntityBanner extends TileEntity { this.patterns = null; - if (stack.hasTagCompound() && stack.getTagCompound().hasKey("BlockEntityTag", 10)) + if (stack.hasTagCompound() && stack.getTagCompound().hasObject("BlockEntityTag")) { - NBTTagCompound nbttagcompound = stack.getTagCompound().getCompoundTag("BlockEntityTag"); + TagObject nbttagcompound = stack.getTagCompound().getObject("BlockEntityTag"); - if (nbttagcompound.hasKey("Patterns")) + if (nbttagcompound.hasList("Patterns")) { - this.patterns = (NBTTagList)nbttagcompound.getTagList("Patterns", 10).copy(); + this.patterns = Lists.newArrayList(); + for(TagObject pattern : nbttagcompound.getList("Patterns")) { + this.patterns.add(pattern.copy()); + } } - if (nbttagcompound.hasKey("Base", 99)) + if (nbttagcompound.hasInt("Base")) { - this.baseColor = nbttagcompound.getInteger("Base"); + this.baseColor = nbttagcompound.getInt("Base"); } else { @@ -62,27 +63,27 @@ public class TileEntityBanner extends TileEntity this.field_175119_g = true; } - public void writeToNBT(NBTTagCompound compound) + public void writeTags(TagObject compound) { - super.writeToNBT(compound); + super.writeTags(compound); setBaseColorAndPatterns(compound, this.baseColor, this.patterns); } - public static void setBaseColorAndPatterns(NBTTagCompound compound, int baseColorIn, NBTTagList patternsIn) + public static void setBaseColorAndPatterns(TagObject compound, int baseColorIn, List patternsIn) { - compound.setInteger("Base", baseColorIn); + compound.setInt("Base", baseColorIn); if (patternsIn != null) { - compound.setTag("Patterns", patternsIn); + compound.setList("Patterns", patternsIn); } } - public void readFromNBT(NBTTagCompound compound) + public void readTags(TagObject compound) { - super.readFromNBT(compound); - this.baseColor = compound.getInteger("Base"); - this.patterns = compound.getTagList("Patterns", 10); + super.readTags(compound); + this.baseColor = compound.getInt("Base"); + this.patterns = compound.getList("Patterns"); this.patternList = null; this.colorList = null; this.patternResourceLocation = null; @@ -95,7 +96,7 @@ public class TileEntityBanner extends TileEntity */ public Packet getDescriptionPacket() { - return new S35PacketUpdateTileEntity(this); + return new SPacketUpdateTileEntity(this); } public int getBaseColor() @@ -105,8 +106,8 @@ public class TileEntityBanner extends TileEntity public static int getBaseColor(ItemStack stack) { - NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - return nbttagcompound != null && nbttagcompound.hasKey("Base") ? nbttagcompound.getInteger("Base") : stack.getMetadata(); + TagObject nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + return nbttagcompound != null && nbttagcompound.hasInt("Base") ? nbttagcompound.getInt("Base") : stack.getMetadata(); } /** @@ -114,8 +115,8 @@ public class TileEntityBanner extends TileEntity */ public static int getPatterns(ItemStack stack) { - NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - return nbttagcompound != null && nbttagcompound.hasKey("Patterns") ? nbttagcompound.getTagList("Patterns", 10).tagCount() : 0; + TagObject nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + return nbttagcompound != null && nbttagcompound.hasList("Patterns") ? nbttagcompound.getList("Patterns").size() : 0; } public List getPatternList() @@ -124,7 +125,7 @@ public class TileEntityBanner extends TileEntity return this.patternList; } - public NBTTagList getPatterns() + public List getPatterns() { return this.patterns; } @@ -163,15 +164,15 @@ public class TileEntityBanner extends TileEntity if (this.patterns != null) { - for (int i = 0; i < this.patterns.tagCount(); ++i) + for (int i = 0; i < this.patterns.size(); ++i) { - NBTTagCompound nbttagcompound = this.patterns.getCompoundTagAt(i); + TagObject nbttagcompound = this.patterns.get(i); TileEntityBanner.EnumBannerPattern tileentitybanner$enumbannerpattern = TileEntityBanner.EnumBannerPattern.getPatternByID(nbttagcompound.getString("Pattern")); if (tileentitybanner$enumbannerpattern != null) { this.patternList.add(tileentitybanner$enumbannerpattern); - int j = nbttagcompound.getInteger("Color"); + int j = nbttagcompound.getInt("Color"); this.colorList.add(DyeColor.byDyeDamage(j)); this.patternResourceLocation = this.patternResourceLocation + tileentitybanner$enumbannerpattern.getPatternID() + j; } @@ -190,23 +191,23 @@ public class TileEntityBanner extends TileEntity */ public static void removeBannerData(ItemStack stack) { - NBTTagCompound nbttagcompound = stack.getSubCompound("BlockEntityTag", false); + TagObject nbttagcompound = stack.getSubCompound("BlockEntityTag", false); - if (nbttagcompound != null && nbttagcompound.hasKey("Patterns", 9)) + if (nbttagcompound != null && nbttagcompound.hasList("Patterns")) { - NBTTagList nbttaglist = nbttagcompound.getTagList("Patterns", 10); + List nbttaglist = nbttagcompound.getList("Patterns"); - if (nbttaglist.tagCount() > 0) + if (nbttaglist.size() > 0) { - nbttaglist.removeTag(nbttaglist.tagCount() - 1); + nbttaglist.remove(nbttaglist.size() - 1); - if (nbttaglist.hasNoTags()) + if (nbttaglist.isEmpty()) { - stack.getTagCompound().removeTag("BlockEntityTag"); + stack.getTagCompound().remove("BlockEntityTag"); - if (stack.getTagCompound().hasNoTags()) + if (stack.getTagCompound().isEmpty()) { - stack.setTagCompound((NBTTagCompound)null); + stack.setTagCompound((TagObject)null); } } } diff --git a/java/src/game/tileentity/TileEntityBeacon.java b/common/src/main/java/common/tileentity/TileEntityBeacon.java similarity index 93% rename from java/src/game/tileentity/TileEntityBeacon.java rename to common/src/main/java/common/tileentity/TileEntityBeacon.java index 6b57ffa..da2d009 100755 --- a/java/src/game/tileentity/TileEntityBeacon.java +++ b/common/src/main/java/common/tileentity/TileEntityBeacon.java @@ -1,21 +1,21 @@ -package game.tileentity; +package common.tileentity; import java.util.List; -import game.block.Block; -import game.color.DyeColor; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.nbt.NBTTagCompound; -import game.network.Packet; -import game.packet.S35PacketUpdateTileEntity; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.State; -import game.world.World; -import game.world.WorldServer; +import common.block.Block; +import common.color.DyeColor; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.network.Packet; +import common.packet.SPacketUpdateTileEntity; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.world.State; +import common.world.World; +import common.world.AWorldServer; public class TileEntityBeacon extends TileEntity implements ITickable { @@ -45,7 +45,7 @@ public class TileEntityBeacon extends TileEntity implements ITickable */ public void update() { - if (!this.worldObj.client && ((WorldServer)this.worldObj).getTime() % 80L == 0L) + if (!this.worldObj.client && ((AWorldServer)this.worldObj).getTime() % 80L == 0L) { this.updateBeacon(); } @@ -78,7 +78,7 @@ public class TileEntityBeacon extends TileEntity implements ITickable int j = this.pos.getX(); int k = this.pos.getY(); int l = this.pos.getZ(); - BoundingBox axisalignedbb = (new BoundingBox((double)j, (double)k, (double)l, (double)(j + 1), (double)(k + 1), (double)(l + 1))).expand(d0, d0, d0).addCoord(0.0D, (double)World.HEIGHT, 0.0D); + BoundingBox axisalignedbb = (new BoundingBox((double)j, (double)k, (double)l, (double)(j + 1), (double)(k + 1), (double)(l + 1))).expand(d0, d0, d0).addCoord(0.0D, (double)World.MAX_SIZE_Y, 0.0D); List list = this.worldObj.getEntitiesWithinAABB(EntityLiving.class, axisalignedbb); for (EntityLiving entityplayer : list) @@ -280,7 +280,7 @@ public class TileEntityBeacon extends TileEntity implements ITickable */ public Packet getDescriptionPacket() { - return new S35PacketUpdateTileEntity(this); + return new SPacketUpdateTileEntity(this); } public double getMaxRenderDistanceSquared() @@ -301,12 +301,12 @@ public class TileEntityBeacon extends TileEntity implements ITickable // } } - public void readFromNBT(NBTTagCompound compound) + public void readTags(TagObject compound) { - super.readFromNBT(compound); - this.primaryEffect = compound.hasKey("Primary", 8) ? this.getEffect(compound.getString("Primary")) : null; - this.secondaryEffect = compound.hasKey("Secondary", 8) ? this.getEffect(compound.getString("Secondary")) : null; - this.levels = compound.getInteger("Levels"); + super.readTags(compound); + this.primaryEffect = compound.hasString("Primary") ? this.getEffect(compound.getString("Primary")) : null; + this.secondaryEffect = compound.hasString("Secondary") ? this.getEffect(compound.getString("Secondary")) : null; + this.levels = compound.getInt("Levels"); // try { this.beamColor = DyeColor.getByName(compound.getString("Color")); // } @@ -315,14 +315,14 @@ public class TileEntityBeacon extends TileEntity implements ITickable // } } - public void writeToNBT(NBTTagCompound compound) + public void writeTags(TagObject compound) { - super.writeToNBT(compound); + super.writeTags(compound); if(this.primaryEffect != null) compound.setString("Primary", this.primaryEffect.getName()); if(this.secondaryEffect != null) compound.setString("Secondary", this.secondaryEffect.getName()); - compound.setInteger("Levels", this.levels); + compound.setInt("Levels", this.levels); compound.setString("Color", this.beamColor.getName()); } diff --git a/java/src/game/tileentity/TileEntityBrewingStand.java b/common/src/main/java/common/tileentity/TileEntityBrewingStand.java similarity index 88% rename from java/src/game/tileentity/TileEntityBrewingStand.java rename to common/src/main/java/common/tileentity/TileEntityBrewingStand.java index c24d117..f883e9b 100755 --- a/java/src/game/tileentity/TileEntityBrewingStand.java +++ b/common/src/main/java/common/tileentity/TileEntityBrewingStand.java @@ -1,24 +1,24 @@ -package game.tileentity; +package common.tileentity; import java.util.Arrays; import java.util.List; -import game.block.BlockBrewingStand; -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.inventory.Container; -import game.inventory.ContainerBrewingStand; -import game.inventory.ISidedInventory; -import game.inventory.InventoryPlayer; -import game.item.Item; -import game.item.ItemPotion; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.potion.PotionEffect; -import game.potion.PotionHelper; -import game.world.Facing; -import game.world.State; +import common.block.tech.BlockBrewingStand; +import common.collect.Lists; +import common.entity.npc.EntityNPC; +import common.init.Items; +import common.inventory.Container; +import common.inventory.ContainerBrewingStand; +import common.inventory.ISidedInventory; +import common.inventory.InventoryPlayer; +import common.item.Item; +import common.item.ItemPotion; +import common.item.ItemStack; +import common.potion.PotionEffect; +import common.potion.PotionHelper; +import common.tags.TagObject; +import common.util.Facing; +import common.world.State; public class TileEntityBrewingStand extends TileEntityLockable implements ITickable, ISidedInventory { @@ -129,7 +129,7 @@ public class TileEntityBrewingStand extends TileEntityLockable implements ITicka private boolean canBrew() { - if (this.brewingItemStacks[3] != null && this.brewingItemStacks[3].stackSize > 0) + if (this.brewingItemStacks[3] != null && this.brewingItemStacks[3].size > 0) { ItemStack itemstack = this.brewingItemStacks[3]; @@ -209,9 +209,9 @@ public class TileEntityBrewingStand extends TileEntityLockable implements ITicka } else { - --this.brewingItemStacks[3].stackSize; + --this.brewingItemStacks[3].size; - if (this.brewingItemStacks[3].stackSize <= 0) + if (this.brewingItemStacks[3].size <= 0) { this.brewingItemStacks[3] = null; } @@ -227,49 +227,49 @@ public class TileEntityBrewingStand extends TileEntityLockable implements ITicka return stack == null ? meta : (stack.getItem().isPotionIngredient(stack) ? PotionHelper.applyIngredient(meta, stack.getItem().getPotionEffect(stack)) : meta); } - public void readFromNBT(NBTTagCompound compound) + public void readTags(TagObject compound) { - super.readFromNBT(compound); - NBTTagList nbttaglist = compound.getTagList("Items", 10); + super.readTags(compound); + List nbttaglist = compound.getList("Items"); this.brewingItemStacks = new ItemStack[this.getSizeInventory()]; - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + TagObject nbttagcompound = nbttaglist.get(i); int j = nbttagcompound.getByte("Slot"); if (j >= 0 && j < this.brewingItemStacks.length) { - this.brewingItemStacks[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); + this.brewingItemStacks[j] = ItemStack.readFromTag(nbttagcompound); } } this.brewTime = compound.getShort("BrewTime"); - if (compound.hasKey("CustomName", 8)) + if (compound.hasString("CustomName")) { this.customName = compound.getString("CustomName"); } } - public void writeToNBT(NBTTagCompound compound) + public void writeTags(TagObject compound) { - super.writeToNBT(compound); + super.writeTags(compound); compound.setShort("BrewTime", (short)this.brewTime); - NBTTagList nbttaglist = new NBTTagList(); + List nbttaglist = Lists.newArrayList(); for (int i = 0; i < this.brewingItemStacks.length; ++i) { if (this.brewingItemStacks[i] != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject nbttagcompound = new TagObject(); nbttagcompound.setByte("Slot", (byte)i); - this.brewingItemStacks[i].writeToNBT(nbttagcompound); - nbttaglist.appendTag(nbttagcompound); + this.brewingItemStacks[i].writeTags(nbttagcompound); + nbttaglist.add(nbttagcompound); } } - compound.setTag("Items", nbttaglist); + compound.setList("Items", nbttaglist); if (this.hasCustomName()) { diff --git a/java/src/game/tileentity/TileEntityChest.java b/common/src/main/java/common/tileentity/TileEntityChest.java similarity index 89% rename from java/src/game/tileentity/TileEntityChest.java rename to common/src/main/java/common/tileentity/TileEntityChest.java index e0481a8..2e5357c 100755 --- a/java/src/game/tileentity/TileEntityChest.java +++ b/common/src/main/java/common/tileentity/TileEntityChest.java @@ -1,20 +1,21 @@ -package game.tileentity; +package common.tileentity; -import game.block.Block; -import game.block.BlockChest; -import game.entity.npc.EntityNPC; -import game.init.SoundEvent; -import game.inventory.Container; -import game.inventory.ContainerChest; -import game.inventory.IInventory; -import game.inventory.InventoryLargeChest; -import game.inventory.InventoryPlayer; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; +import common.block.Block; +import common.block.tech.BlockChest; +import common.collect.Lists; +import common.entity.npc.EntityNPC; +import common.init.SoundEvent; +import common.inventory.Container; +import common.inventory.ContainerChest; +import common.inventory.IInventory; +import common.inventory.InventoryLargeChest; +import common.inventory.InventoryPlayer; +import common.item.ItemStack; +import common.tags.TagObject; +import java.util.List; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.Facing; public class TileEntityChest extends TileEntityLockable implements ITickable, IInventory { @@ -82,7 +83,7 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II { if (this.chestContents[index] != null) { - if (this.chestContents[index].stackSize <= count) + if (this.chestContents[index].size <= count) { ItemStack itemstack1 = this.chestContents[index]; this.chestContents[index] = null; @@ -93,7 +94,7 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II { ItemStack itemstack = this.chestContents[index].splitStack(count); - if (this.chestContents[index].stackSize == 0) + if (this.chestContents[index].size == 0) { this.chestContents[index] = null; } @@ -132,9 +133,9 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II { this.chestContents[index] = stack; - if (stack != null && stack.stackSize > this.getInventoryStackLimit()) + if (stack != null && stack.size > this.getInventoryStackLimit()) { - stack.stackSize = this.getInventoryStackLimit(); + stack.size = this.getInventoryStackLimit(); } this.markDirty(); @@ -161,46 +162,46 @@ public class TileEntityChest extends TileEntityLockable implements ITickable, II this.customName = name; } - public void readFromNBT(NBTTagCompound compound) + public void readTags(TagObject compound) { - super.readFromNBT(compound); - NBTTagList nbttaglist = compound.getTagList("Items", 10); + super.readTags(compound); + List nbttaglist = compound.getList("Items"); this.chestContents = new ItemStack[this.getSizeInventory()]; - if (compound.hasKey("CustomName", 8)) + if (compound.hasString("CustomName")) { this.customName = compound.getString("CustomName"); } - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + TagObject nbttagcompound = nbttaglist.get(i); int j = nbttagcompound.getByte("Slot") & 255; if (j >= 0 && j < this.chestContents.length) { - this.chestContents[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); + this.chestContents[j] = ItemStack.readFromTag(nbttagcompound); } } } - public void writeToNBT(NBTTagCompound compound) + public void writeTags(TagObject compound) { - super.writeToNBT(compound); - NBTTagList nbttaglist = new NBTTagList(); + super.writeTags(compound); + List nbttaglist = Lists.newArrayList(); for (int i = 0; i < this.chestContents.length; ++i) { if (this.chestContents[i] != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject nbttagcompound = new TagObject(); nbttagcompound.setByte("Slot", (byte)i); - this.chestContents[i].writeToNBT(nbttagcompound); - nbttaglist.appendTag(nbttagcompound); + this.chestContents[i].writeTags(nbttagcompound); + nbttaglist.add(nbttagcompound); } } - compound.setTag("Items", nbttaglist); + compound.setList("Items", nbttaglist); if (this.hasCustomName()) { diff --git a/common/src/main/java/common/tileentity/TileEntityComparator.java b/common/src/main/java/common/tileentity/TileEntityComparator.java new file mode 100755 index 0000000..67eeb4f --- /dev/null +++ b/common/src/main/java/common/tileentity/TileEntityComparator.java @@ -0,0 +1,34 @@ +package common.tileentity; + +import common.tags.TagObject; + +public class TileEntityComparator extends TileEntity +{ + private int outputSignal; + + public void writeTags(TagObject compound) + { + super.writeTags(compound); + compound.setInt("OutputSignal", this.outputSignal); + } + + public void readTags(TagObject compound) + { + super.readTags(compound); + this.outputSignal = compound.getInt("OutputSignal"); + } + + public int getOutputSignal() + { + return this.outputSignal; + } + + public void setOutputSignal(int p_145995_1_) + { + this.outputSignal = p_145995_1_; + } + + public int getColor() { + return 0xaf0000; + } +} diff --git a/java/src/game/tileentity/TileEntityDaylightDetector.java b/common/src/main/java/common/tileentity/TileEntityDaylightDetector.java similarity index 72% rename from java/src/game/tileentity/TileEntityDaylightDetector.java rename to common/src/main/java/common/tileentity/TileEntityDaylightDetector.java index 493f01c..6355815 100755 --- a/java/src/game/tileentity/TileEntityDaylightDetector.java +++ b/common/src/main/java/common/tileentity/TileEntityDaylightDetector.java @@ -1,7 +1,7 @@ -package game.tileentity; +package common.tileentity; -import game.block.BlockDaylightDetector; -import game.world.WorldServer; +import common.block.tech.BlockDaylightDetector; +import common.world.AWorldServer; public class TileEntityDaylightDetector extends TileEntity implements ITickable { @@ -10,13 +10,13 @@ public class TileEntityDaylightDetector extends TileEntity implements ITickable */ public void update() { - if (this.worldObj != null && !this.worldObj.client && ((WorldServer)this.worldObj).getTime() % 20L == 0L) + if (this.worldObj != null && !this.worldObj.client && ((AWorldServer)this.worldObj).getTime() % 20L == 0L) { this.blockType = this.getBlockType(); if (this.blockType instanceof BlockDaylightDetector) { - ((BlockDaylightDetector)this.blockType).updatePower((WorldServer)this.worldObj, this.pos); + ((BlockDaylightDetector)this.blockType).updatePower((AWorldServer)this.worldObj, this.pos); } } } diff --git a/java/src/game/tileentity/TileEntityMachine.java b/common/src/main/java/common/tileentity/TileEntityDevice.java similarity index 66% rename from java/src/game/tileentity/TileEntityMachine.java rename to common/src/main/java/common/tileentity/TileEntityDevice.java index 367afb6..40d1c1a 100755 --- a/java/src/game/tileentity/TileEntityMachine.java +++ b/common/src/main/java/common/tileentity/TileEntityDevice.java @@ -1,19 +1,20 @@ -package game.tileentity; +package common.tileentity; -import game.color.TextColor; -import game.entity.npc.EntityNPC; -import game.inventory.Container; -import game.inventory.ContainerMachine; -import game.inventory.InventoryPlayer; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.network.Packet; -import game.packet.S35PacketUpdateTileEntity; -import game.rng.Random; -import game.util.ExtMath; +import common.collect.Lists; +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.inventory.Container; +import common.inventory.ContainerTile; +import common.inventory.InventoryPlayer; +import common.item.ItemStack; +import common.network.Packet; +import common.packet.SPacketUpdateTileEntity; +import common.rng.Random; +import common.tags.TagObject; +import java.util.List; +import common.util.ExtMath; -public abstract class TileEntityMachine extends TileEntityLockable implements IHopper, ITickable { +public abstract class TileEntityDevice extends TileEntityLockable implements IHopper, ITickable { public static enum Status { OFF(TextColor.DGRAY, "Inaktiv"), COOLING(TextColor.YELLOW, "Abkühlen ..."), @@ -33,31 +34,31 @@ public abstract class TileEntityMachine extends TileEntityLockable implements IH protected final ItemStack[] inventory; protected final MachineResource[] resources; protected final Random rand = new Random(); -// protected boolean isCreative; protected int temperature; protected Status status = Status.OFF; - protected TileEntityMachine(int slots, MachineResource ... resources) { + protected TileEntityDevice(int slots, MachineResource ... resources) { this.inventory = new ItemStack[slots]; this.resources = resources; } - protected abstract int getTempIncrement(); - protected abstract int getTempDecrement(); - protected abstract int getMaxTemp(); + protected int getTempIncrement() { + return -1; + } + + protected int getTempDecrement() { + return -1; + } + + protected int getMaxTemp() { + return Integer.MAX_VALUE; + } + protected abstract boolean executeFunction(); public MachineResource getResource(int slot) { return this.resources[slot]; } - -// public void setCreative(boolean creative) { -// this.isCreative = creative; -// } -// -// public boolean isCreative() { -// return this.isCreative; -// } public int getNumResources() { return this.resources.length; @@ -79,65 +80,58 @@ public abstract class TileEntityMachine extends TileEntityLockable implements IH this.status = status; } - public void readFromNBT(NBTTagCompound compound) { - super.readFromNBT(compound); + public void readTags(TagObject compound) { + super.readTags(compound); - NBTTagList nbttaglist = compound.getTagList("Items", 10); + List nbttaglist = compound.getList("Items"); this.clear(); - for(int i = 0; i < nbttaglist.tagCount(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + for(int i = 0; i < nbttaglist.size(); ++i) { + TagObject nbttagcompound = nbttaglist.get(i); int j = nbttagcompound.getByte("Slot"); if(j >= 0 && j < this.inventory.length) { - this.inventory[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); + this.inventory[j] = ItemStack.readFromTag(nbttagcompound); } } - nbttaglist = compound.getTagList("Resources", 10); + nbttaglist = compound.getList("Resources"); for(MachineResource res : this.resources) { res.reset(); } - for(int i = 0; i < nbttaglist.tagCount() && i < this.inventory.length; ++i) { - this.resources[i].readFromNbt(nbttaglist.getCompoundTagAt(i)); + for(int i = 0; i < nbttaglist.size() && i < this.inventory.length; ++i) { + this.resources[i].readFromNbt(nbttaglist.get(i)); } -// this.isCreative = compound.getBoolean("Creative"); - this.temperature = compound.getInteger("Temperature"); + this.temperature = compound.getInt("Temperature"); this.status = Status.values()[(int)compound.getByte("Status") % Status.values().length]; } - public void writeToNBT(NBTTagCompound compound) { - super.writeToNBT(compound); + public void writeTags(TagObject compound) { + super.writeTags(compound); - NBTTagList nbttaglist = new NBTTagList(); + List nbttaglist = Lists.newArrayList(); for(int i = 0; i < this.inventory.length; ++i) { if(this.inventory[i] != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject nbttagcompound = new TagObject(); nbttagcompound.setByte("Slot", (byte)i); - this.inventory[i].writeToNBT(nbttagcompound); - nbttaglist.appendTag(nbttagcompound); + this.inventory[i].writeTags(nbttagcompound); + nbttaglist.add(nbttagcompound); } } - compound.setTag("Items", nbttaglist); + compound.setList("Items", nbttaglist); - nbttaglist = new NBTTagList(); + nbttaglist = Lists.newArrayList(); for(int z = 0; z < this.resources.length; z++) { - NBTTagCompound res = new NBTTagCompound(); + TagObject res = new TagObject(); this.resources[z].writeToNbt(res); - nbttaglist.appendTag(res); + nbttaglist.add(res); } - compound.setTag("Resources", nbttaglist); + compound.setList("Resources", nbttaglist); -// compound.setBoolean("Creative", this.isCreative); - compound.setInteger("Temperature", this.temperature); + compound.setInt("Temperature", this.temperature); compound.setByte("Status", (byte)this.status.ordinal()); } -// public void markDirty() -// { -// super.markDirty(); -// } - public int getSizeInventory() { return this.inventory.length; } @@ -148,7 +142,7 @@ public abstract class TileEntityMachine extends TileEntityLockable implements IH public ItemStack decrStackSize(int index, int count) { if(this.inventory[index] != null) { - if(this.inventory[index].stackSize <= count) { + if(this.inventory[index].size <= count) { ItemStack itemstack1 = this.inventory[index]; this.inventory[index] = null; return itemstack1; @@ -156,7 +150,7 @@ public abstract class TileEntityMachine extends TileEntityLockable implements IH else { ItemStack itemstack = this.inventory[index].splitStack(count); - if(this.inventory[index].stackSize == 0) { + if(this.inventory[index].size == 0) { this.inventory[index] = null; } @@ -182,8 +176,8 @@ public abstract class TileEntityMachine extends TileEntityLockable implements IH public void setInventorySlotContents(int index, ItemStack stack) { this.inventory[index] = stack; - if(stack != null && stack.stackSize > this.getInventoryStackLimit()) { - stack.stackSize = this.getInventoryStackLimit(); + if(stack != null && stack.size > this.getInventoryStackLimit()) { + stack.size = this.getInventoryStackLimit(); } } @@ -218,7 +212,10 @@ public abstract class TileEntityMachine extends TileEntityLockable implements IH if(this.worldObj != null && !this.worldObj.client && this.status != Status.BROKEN) { int envTemp = (int)this.worldObj.getTemperatureC(this.getPos()); if(this.executeFunction()) { - this.temperature += this.getTempIncrement(); + if(this.getTempIncrement() < 0) + this.temperature = envTemp; + else + this.temperature += this.getTempIncrement(); this.status = this.temperature >= (this.getMaxTemp() * 9) / 10 ? Status.OVERHEAT : Status.RUNNING; if(this.temperature > this.getMaxTemp()) { this.status = Status.BROKEN; @@ -234,7 +231,10 @@ public abstract class TileEntityMachine extends TileEntityLockable implements IH int dec = this.getTempDecrement(); if(dec != 0) { int prev = this.temperature; - this.temperature -= dec; + if(dec < 0) + this.temperature = envTemp; + else + this.temperature -= dec; this.temperature = ExtMath.clampi(this.temperature, envTemp, Integer.MAX_VALUE); if(prev != this.temperature) this.markDirty(); @@ -264,7 +264,7 @@ public abstract class TileEntityMachine extends TileEntityLockable implements IH return true; } else { - return this.inventory[slot] == null || this.inventory[slot].stackSize <= 0; + return this.inventory[slot] == null || this.inventory[slot].size <= 0; } } @@ -272,19 +272,19 @@ public abstract class TileEntityMachine extends TileEntityLockable implements IH if(slot == -1) { int n = 0; for(ItemStack itemstack : this.inventory) { - if(itemstack != null && itemstack.stackSize >= 1) - n += itemstack.stackSize; + if(itemstack != null && itemstack.size >= 1) + n += itemstack.size; } return n >= amount; } else { - return this.inventory[slot] != null && this.inventory[slot].stackSize >= amount; + return this.inventory[slot] != null && this.inventory[slot].size >= amount; } } public boolean isFull() { for(ItemStack itemstack : this.inventory) { - if(itemstack == null || itemstack.stackSize != itemstack.getMaxStackSize()) { + if(itemstack == null || itemstack.size != itemstack.getMaxStackSize()) { return false; } } @@ -304,7 +304,7 @@ public abstract class TileEntityMachine extends TileEntityLockable implements IH } public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) { - return new ContainerMachine(playerInventory, this, this, playerIn); + return new ContainerTile(playerInventory, this, this, playerIn); } public int getField(int id) { @@ -326,12 +326,12 @@ public abstract class TileEntityMachine extends TileEntityLockable implements IH public Packet getDescriptionPacket() { - return new S35PacketUpdateTileEntity(this); + return new SPacketUpdateTileEntity(this); } public int getColor() { return 0x8080ff; } - public abstract String formatDisplay(); + public abstract String formatDisplay(ContainerTile inv); } diff --git a/java/src/game/tileentity/TileEntityDispenser.java b/common/src/main/java/common/tileentity/TileEntityDispenser.java similarity index 80% rename from java/src/game/tileentity/TileEntityDispenser.java rename to common/src/main/java/common/tileentity/TileEntityDispenser.java index c903470..075f70e 100755 --- a/java/src/game/tileentity/TileEntityDispenser.java +++ b/common/src/main/java/common/tileentity/TileEntityDispenser.java @@ -1,14 +1,15 @@ -package game.tileentity; +package common.tileentity; -import game.entity.npc.EntityNPC; -import game.inventory.Container; -import game.inventory.ContainerDispenser; -import game.inventory.IInventory; -import game.inventory.InventoryPlayer; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.rng.Random; +import common.collect.Lists; +import common.entity.npc.EntityNPC; +import common.inventory.Container; +import common.inventory.ContainerDispenser; +import common.inventory.IInventory; +import common.inventory.InventoryPlayer; +import common.item.ItemStack; +import common.rng.Random; +import common.tags.TagObject; +import java.util.List; public class TileEntityDispenser extends TileEntityLockable implements IInventory { @@ -39,7 +40,7 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor { if (this.stacks[index] != null) { - if (this.stacks[index].stackSize <= count) + if (this.stacks[index].size <= count) { ItemStack itemstack1 = this.stacks[index]; this.stacks[index] = null; @@ -50,7 +51,7 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor { ItemStack itemstack = this.stacks[index].splitStack(count); - if (this.stacks[index].stackSize == 0) + if (this.stacks[index].size == 0) { this.stacks[index] = null; } @@ -105,9 +106,9 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor { this.stacks[index] = stack; - if (stack != null && stack.stackSize > this.getInventoryStackLimit()) + if (stack != null && stack.size > this.getInventoryStackLimit()) { - stack.stackSize = this.getInventoryStackLimit(); + stack.size = this.getInventoryStackLimit(); } this.markDirty(); @@ -152,46 +153,46 @@ public class TileEntityDispenser extends TileEntityLockable implements IInventor return this.customName != null; } - public void readFromNBT(NBTTagCompound compound) + public void readTags(TagObject compound) { - super.readFromNBT(compound); - NBTTagList nbttaglist = compound.getTagList("Items", 10); + super.readTags(compound); + List nbttaglist = compound.getList("Items"); this.stacks = new ItemStack[this.getSizeInventory()]; - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + TagObject nbttagcompound = nbttaglist.get(i); int j = nbttagcompound.getByte("Slot") & 255; if (j >= 0 && j < this.stacks.length) { - this.stacks[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); + this.stacks[j] = ItemStack.readFromTag(nbttagcompound); } } - if (compound.hasKey("CustomName", 8)) + if (compound.hasString("CustomName")) { this.customName = compound.getString("CustomName"); } } - public void writeToNBT(NBTTagCompound compound) + public void writeTags(TagObject compound) { - super.writeToNBT(compound); - NBTTagList nbttaglist = new NBTTagList(); + super.writeTags(compound); + List nbttaglist = Lists.newArrayList(); for (int i = 0; i < this.stacks.length; ++i) { if (this.stacks[i] != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject nbttagcompound = new TagObject(); nbttagcompound.setByte("Slot", (byte)i); - this.stacks[i].writeToNBT(nbttagcompound); - nbttaglist.appendTag(nbttagcompound); + this.stacks[i].writeTags(nbttagcompound); + nbttaglist.add(nbttagcompound); } } - compound.setTag("Items", nbttaglist); + compound.setList("Items", nbttaglist); if (this.hasCustomName()) { diff --git a/java/src/game/tileentity/TileEntityDropper.java b/common/src/main/java/common/tileentity/TileEntityDropper.java similarity index 92% rename from java/src/game/tileentity/TileEntityDropper.java rename to common/src/main/java/common/tileentity/TileEntityDropper.java index e33a09e..7842d1a 100755 --- a/java/src/game/tileentity/TileEntityDropper.java +++ b/common/src/main/java/common/tileentity/TileEntityDropper.java @@ -1,4 +1,4 @@ -package game.tileentity; +package common.tileentity; public class TileEntityDropper extends TileEntityDispenser { diff --git a/java/src/game/tileentity/TileEntityEnchantmentTable.java b/common/src/main/java/common/tileentity/TileEntityEnchantmentTable.java similarity index 89% rename from java/src/game/tileentity/TileEntityEnchantmentTable.java rename to common/src/main/java/common/tileentity/TileEntityEnchantmentTable.java index 8e18c65..1a9faba 100755 --- a/java/src/game/tileentity/TileEntityEnchantmentTable.java +++ b/common/src/main/java/common/tileentity/TileEntityEnchantmentTable.java @@ -1,12 +1,12 @@ -package game.tileentity; +package common.tileentity; -import game.entity.npc.EntityNPC; -import game.inventory.Container; -import game.inventory.ContainerEnchantment; -import game.inventory.InventoryPlayer; -import game.nbt.NBTTagCompound; -import game.rng.Random; -import game.util.ExtMath; +import common.entity.npc.EntityNPC; +import common.inventory.Container; +import common.inventory.ContainerEnchantment; +import common.inventory.InventoryPlayer; +import common.rng.Random; +import common.tags.TagObject; +import common.util.ExtMath; public class TileEntityEnchantmentTable extends TileEntity implements ITickable, IInteractionObject { @@ -23,9 +23,9 @@ public class TileEntityEnchantmentTable extends TileEntity implements ITickable, private static Random rand = new Random(); private String customName; - public void writeToNBT(NBTTagCompound compound) + public void writeTags(TagObject compound) { - super.writeToNBT(compound); + super.writeTags(compound); if (this.hasCustomName()) { @@ -33,11 +33,11 @@ public class TileEntityEnchantmentTable extends TileEntity implements ITickable, } } - public void readFromNBT(NBTTagCompound compound) + public void readTags(TagObject compound) { - super.readFromNBT(compound); + super.readTags(compound); - if (compound.hasKey("CustomName", 8)) + if (compound.hasString("CustomName")) { this.customName = compound.getString("CustomName"); } diff --git a/java/src/game/tileentity/TileEntityFurnace.java b/common/src/main/java/common/tileentity/TileEntityFurnace.java similarity index 84% rename from java/src/game/tileentity/TileEntityFurnace.java rename to common/src/main/java/common/tileentity/TileEntityFurnace.java index a7225f7..519647c 100755 --- a/java/src/game/tileentity/TileEntityFurnace.java +++ b/common/src/main/java/common/tileentity/TileEntityFurnace.java @@ -1,32 +1,33 @@ -package game.tileentity; +package common.tileentity; -import game.block.Block; -import game.block.BlockFurnace; -import game.block.BlockSapling; -import game.block.BlockSlab; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Items; -import game.init.SmeltingRegistry; -import game.init.ToolType; -import game.inventory.Container; -import game.inventory.ContainerFurnace; -import game.inventory.IInventory; -import game.inventory.ISidedInventory; -import game.inventory.InventoryPlayer; -import game.inventory.SlotFurnaceFuel; -import game.item.Item; -import game.item.ItemBlock; -import game.item.ItemBucket; -import game.item.ItemHoe; -import game.item.ItemStack; -import game.item.ItemSword; -import game.item.ItemTool; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.util.ExtMath; -import game.world.Facing; +import common.block.Block; +import common.block.Material; +import common.block.artificial.BlockSlab; +import common.block.foliage.BlockSapling; +import common.block.tech.BlockFurnace; +import common.collect.Lists; +import common.entity.npc.EntityNPC; +import common.init.Blocks; +import common.init.Items; +import common.init.SmeltingRegistry; +import common.init.ToolType; +import common.inventory.Container; +import common.inventory.ContainerFurnace; +import common.inventory.IInventory; +import common.inventory.ISidedInventory; +import common.inventory.InventoryPlayer; +import common.inventory.SlotFurnaceFuel; +import common.item.Item; +import common.item.ItemBlock; +import common.item.ItemBucket; +import common.item.ItemHoe; +import common.item.ItemStack; +import common.item.ItemSword; +import common.item.ItemTool; +import common.tags.TagObject; +import java.util.List; +import common.util.ExtMath; +import common.util.Facing; public class TileEntityFurnace extends TileEntityLockable implements ITickable, ISidedInventory { @@ -73,7 +74,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, { if (this.furnaceItemStacks[index] != null) { - if (this.furnaceItemStacks[index].stackSize <= count) + if (this.furnaceItemStacks[index].size <= count) { ItemStack itemstack1 = this.furnaceItemStacks[index]; this.furnaceItemStacks[index] = null; @@ -83,7 +84,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, { ItemStack itemstack = this.furnaceItemStacks[index].splitStack(count); - if (this.furnaceItemStacks[index].stackSize == 0) + if (this.furnaceItemStacks[index].size == 0) { this.furnaceItemStacks[index] = null; } @@ -122,9 +123,9 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, boolean flag = stack != null && stack.isItemEqual(this.furnaceItemStacks[index]) && ItemStack.areItemStackTagsEqual(stack, this.furnaceItemStacks[index]); this.furnaceItemStacks[index] = stack; - if (stack != null && stack.stackSize > this.getInventoryStackLimit()) + if (stack != null && stack.size > this.getInventoryStackLimit()) { - stack.stackSize = this.getInventoryStackLimit(); + stack.size = this.getInventoryStackLimit(); } if (index == 0 && !flag) @@ -156,20 +157,20 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, this.furnaceCustomName = p_145951_1_; } - public void readFromNBT(NBTTagCompound compound) + public void readTags(TagObject compound) { - super.readFromNBT(compound); - NBTTagList nbttaglist = compound.getTagList("Items", 10); + super.readTags(compound); + List nbttaglist = compound.getList("Items"); this.furnaceItemStacks = new ItemStack[this.getSizeInventory()]; - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + TagObject nbttagcompound = nbttaglist.get(i); int j = nbttagcompound.getByte("Slot"); if (j >= 0 && j < this.furnaceItemStacks.length) { - this.furnaceItemStacks[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); + this.furnaceItemStacks[j] = ItemStack.readFromTag(nbttagcompound); } } @@ -178,32 +179,32 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, this.totalCookTime = compound.getShort("CookTimeTotal"); this.currentItemBurnTime = getItemBurnTime(this.furnaceItemStacks[1]); - if (compound.hasKey("CustomName", 8)) + if (compound.hasString("CustomName")) { this.furnaceCustomName = compound.getString("CustomName"); } } - public void writeToNBT(NBTTagCompound compound) + public void writeTags(TagObject compound) { - super.writeToNBT(compound); + super.writeTags(compound); compound.setShort("BurnTime", (short)this.furnaceBurnTime); compound.setShort("CookTime", (short)this.cookTime); compound.setShort("CookTimeTotal", (short)this.totalCookTime); - NBTTagList nbttaglist = new NBTTagList(); + List nbttaglist = Lists.newArrayList(); for (int i = 0; i < this.furnaceItemStacks.length; ++i) { if (this.furnaceItemStacks[i] != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject nbttagcompound = new TagObject(); nbttagcompound.setByte("Slot", (byte)i); - this.furnaceItemStacks[i].writeToNBT(nbttagcompound); - nbttaglist.appendTag(nbttagcompound); + this.furnaceItemStacks[i].writeTags(nbttagcompound); + nbttaglist.add(nbttagcompound); } } - compound.setTag("Items", nbttaglist); + compound.setList("Items", nbttaglist); if (this.hasCustomName()) { @@ -259,9 +260,9 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, if (this.furnaceItemStacks[1] != null) { - --this.furnaceItemStacks[1].stackSize; + --this.furnaceItemStacks[1].size; - if (this.furnaceItemStacks[1].stackSize == 0) + if (this.furnaceItemStacks[1].size == 0) { Item item = this.furnaceItemStacks[1].getItem().getContainerItem(); this.furnaceItemStacks[1] = item != null ? new ItemStack(item) : null; @@ -322,7 +323,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, else { ItemStack itemstack = SmeltingRegistry.getResult(this.furnaceItemStacks[0]); - return itemstack == null ? false : (this.furnaceItemStacks[2] == null ? true : (!this.furnaceItemStacks[2].isItemEqual(itemstack) ? false : (this.furnaceItemStacks[2].stackSize < this.getInventoryStackLimit() && this.furnaceItemStacks[2].stackSize < this.furnaceItemStacks[2].getMaxStackSize() ? true : this.furnaceItemStacks[2].stackSize < itemstack.getMaxStackSize()))); + return itemstack == null ? false : (this.furnaceItemStacks[2] == null ? true : (!this.furnaceItemStacks[2].isItemEqual(itemstack) ? false : (this.furnaceItemStacks[2].size < this.getInventoryStackLimit() && this.furnaceItemStacks[2].size < this.furnaceItemStacks[2].getMaxStackSize() ? true : this.furnaceItemStacks[2].size < itemstack.getMaxStackSize()))); } } @@ -341,7 +342,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, } else if (this.furnaceItemStacks[2].getItem() == itemstack.getItem()) { - ++this.furnaceItemStacks[2].stackSize; + ++this.furnaceItemStacks[2].size; } // if (this.furnaceItemStacks[0].getItem() == ItemRegistry.getItemFromBlock(Blocks.sponge) && this.furnaceItemStacks[0].getMetadata() == 1 && this.furnaceItemStacks[1] != null && this.furnaceItemStacks[1].getItem() == Items.bucket) @@ -349,9 +350,9 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, // this.furnaceItemStacks[1] = new ItemStack(Items.water_bucket); // } - --this.furnaceItemStacks[0].stackSize; + --this.furnaceItemStacks[0].size; - if (this.furnaceItemStacks[0].stackSize <= 0) + if (this.furnaceItemStacks[0].size <= 0) { this.furnaceItemStacks[0] = null; } @@ -381,7 +382,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, // return 150; // } - if (block.getMaterial() == Material.wood) + if (block.getMaterial() == Material.WOOD) { return block instanceof BlockSlab ? 150 : 300; } @@ -398,7 +399,7 @@ public class TileEntityFurnace extends TileEntityLockable implements ITickable, (item == Items.stick ? 100 : (item == Items.coal ? 1600 : (item instanceof ItemBucket && ((ItemBucket)item).getLiquid() != null && - ((ItemBucket)item).getLiquid().getMaterial() == Material.lava ? 20000 : + ((ItemBucket)item).getLiquid().getMaterial() == Material.LAVA ? 20000 : (item.getBlock() instanceof BlockSapling ? 100 : (item == Items.blaze_rod ? 2400 : 0))))))); } diff --git a/java/src/game/tileentity/TileEntityHopper.java b/common/src/main/java/common/tileentity/TileEntityHopper.java similarity index 86% rename from java/src/game/tileentity/TileEntityHopper.java rename to common/src/main/java/common/tileentity/TileEntityHopper.java index 96a4189..5da8f31 100755 --- a/java/src/game/tileentity/TileEntityHopper.java +++ b/common/src/main/java/common/tileentity/TileEntityHopper.java @@ -1,29 +1,28 @@ -package game.tileentity; +package common.tileentity; import java.util.List; - import java.util.function.Predicate; -import game.block.Block; -import game.block.BlockChest; -import game.block.BlockHopper; -import game.entity.Entity; -import game.entity.item.EntityItem; -import game.entity.npc.EntityNPC; -import game.init.Config; -import game.inventory.Container; -import game.inventory.ContainerHopper; -import game.inventory.IInventory; -import game.inventory.ISidedInventory; -import game.inventory.InventoryPlayer; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.World; +import common.block.Block; +import common.block.tech.BlockChest; +import common.block.tech.BlockHopper; +import common.collect.Lists; +import common.entity.Entity; +import common.entity.item.EntityItem; +import common.entity.npc.EntityNPC; +import common.inventory.Container; +import common.inventory.ContainerHopper; +import common.inventory.IInventory; +import common.inventory.ISidedInventory; +import common.inventory.InventoryPlayer; +import common.item.ItemStack; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Facing; +import common.vars.Vars; +import common.world.World; public class TileEntityHopper extends TileEntityLockable implements IHopper, ITickable { @@ -31,49 +30,49 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi private String customName; private int transferCooldown = -1; - public void readFromNBT(NBTTagCompound compound) + public void readTags(TagObject compound) { - super.readFromNBT(compound); - NBTTagList nbttaglist = compound.getTagList("Items", 10); + super.readTags(compound); + List nbttaglist = compound.getList("Items"); this.inventory = new ItemStack[this.getSizeInventory()]; - if (compound.hasKey("CustomName", 8)) + if (compound.hasString("CustomName")) { this.customName = compound.getString("CustomName"); } - this.transferCooldown = compound.getInteger("TransferCooldown"); + this.transferCooldown = compound.getInt("TransferCooldown"); - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < nbttaglist.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + TagObject nbttagcompound = nbttaglist.get(i); int j = nbttagcompound.getByte("Slot"); if (j >= 0 && j < this.inventory.length) { - this.inventory[j] = ItemStack.loadItemStackFromNBT(nbttagcompound); + this.inventory[j] = ItemStack.readFromTag(nbttagcompound); } } } - public void writeToNBT(NBTTagCompound compound) + public void writeTags(TagObject compound) { - super.writeToNBT(compound); - NBTTagList nbttaglist = new NBTTagList(); + super.writeTags(compound); + List nbttaglist = Lists.newArrayList(); for (int i = 0; i < this.inventory.length; ++i) { if (this.inventory[i] != null) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); + TagObject nbttagcompound = new TagObject(); nbttagcompound.setByte("Slot", (byte)i); - this.inventory[i].writeToNBT(nbttagcompound); - nbttaglist.appendTag(nbttagcompound); + this.inventory[i].writeTags(nbttagcompound); + nbttaglist.add(nbttagcompound); } } - compound.setTag("Items", nbttaglist); - compound.setInteger("TransferCooldown", this.transferCooldown); + compound.setList("Items", nbttaglist); + compound.setInt("TransferCooldown", this.transferCooldown); if (this.hasCustomName()) { @@ -113,7 +112,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { if (this.inventory[index] != null) { - if (this.inventory[index].stackSize <= count) + if (this.inventory[index].size <= count) { ItemStack itemstack1 = this.inventory[index]; this.inventory[index] = null; @@ -123,7 +122,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { ItemStack itemstack = this.inventory[index].splitStack(count); - if (this.inventory[index].stackSize == 0) + if (this.inventory[index].size == 0) { this.inventory[index] = null; } @@ -161,9 +160,9 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { this.inventory[index] = stack; - if (stack != null && stack.stackSize > this.getInventoryStackLimit()) + if (stack != null && stack.size > this.getInventoryStackLimit()) { - stack.stackSize = this.getInventoryStackLimit(); + stack.size = this.getInventoryStackLimit(); } } @@ -257,7 +256,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi if (flag) { - this.setTransferCooldown(Config.hopperDelay); + this.setTransferCooldown(Vars.hopperDelay); this.markDirty(); return true; } @@ -288,7 +287,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { for (ItemStack itemstack : this.inventory) { - if (itemstack == null || itemstack.stackSize != itemstack.getMaxStackSize()) + if (itemstack == null || itemstack.size != itemstack.getMaxStackSize()) { return false; } @@ -322,7 +321,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi ItemStack itemstack = this.getStackInSlot(i).copy(); ItemStack itemstack1 = putStackInInventoryAllSlots(iinventory, this.decrStackSize(i, 1), enumfacing); - if (itemstack1 == null || itemstack1.stackSize == 0) + if (itemstack1 == null || itemstack1.size == 0) { iinventory.markDirty(); return true; @@ -351,7 +350,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { ItemStack itemstack1 = isidedinventory.getStackInSlot(aint[k]); - if (itemstack1 == null || itemstack1.stackSize != itemstack1.getMaxStackSize()) + if (itemstack1 == null || itemstack1.size != itemstack1.getMaxStackSize()) { return false; } @@ -365,7 +364,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { ItemStack itemstack = inventoryIn.getStackInSlot(j); - if (itemstack == null || itemstack.stackSize != itemstack.getMaxStackSize()) + if (itemstack == null || itemstack.size != itemstack.getMaxStackSize()) { return false; } @@ -475,7 +474,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi ItemStack itemstack1 = itemstack.copy(); ItemStack itemstack2 = putStackInInventoryAllSlots(hopper, inventoryIn.decrStackSize(index, 1), (Facing)null); - if (itemstack2 == null || itemstack2.stackSize == 0) + if (itemstack2 == null || itemstack2.size == 0) { inventoryIn.markDirty(); return true; @@ -504,7 +503,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi ItemStack itemstack = itemIn.getEntityItem().copy(); ItemStack itemstack1 = putStackInInventoryAllSlots(p_145898_0_, itemstack, (Facing)null); - if (itemstack1 != null && itemstack1.stackSize != 0) + if (itemstack1 != null && itemstack1.size != 0) { itemIn.setEntityItemStack(itemstack1); } @@ -528,7 +527,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi ISidedInventory isidedinventory = (ISidedInventory)inventoryIn; int[] aint = isidedinventory.getSlotsForFace(side); - for (int k = 0; k < aint.length && stack != null && stack.stackSize > 0; ++k) + for (int k = 0; k < aint.length && stack != null && stack.size > 0; ++k) { stack = insertStack(inventoryIn, stack, aint[k], side); } @@ -537,13 +536,13 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi { int i = inventoryIn.getSizeInventory(); - for (int j = 0; j < i && stack != null && stack.stackSize > 0; ++j) + for (int j = 0; j < i && stack != null && stack.size > 0; ++j) { stack = insertStack(inventoryIn, stack, j, side); } } - if (stack != null && stack.stackSize == 0) + if (stack != null && stack.size == 0) { stack = null; } @@ -586,10 +585,10 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi } else if (canCombine(itemstack, stack)) { - int i = stack.getMaxStackSize() - itemstack.stackSize; - int j = Math.min(stack.stackSize, i); - stack.stackSize -= j; - itemstack.stackSize += j; + int i = stack.getMaxStackSize() - itemstack.size; + int j = Math.min(stack.size, i); + stack.size -= j; + itemstack.size += j; flag = j > 0; } @@ -601,7 +600,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi if (tileentityhopper.mayTransfer()) { - tileentityhopper.setTransferCooldown(Config.hopperDelay); + tileentityhopper.setTransferCooldown(Vars.hopperDelay); } inventoryIn.markDirty(); @@ -686,7 +685,7 @@ public class TileEntityHopper extends TileEntityLockable implements IHopper, ITi public static boolean canCombine(ItemStack stack1, ItemStack stack2) { - return stack1.getItem() != stack2.getItem() ? false : (stack1.getMetadata() != stack2.getMetadata() ? false : (stack1.stackSize > stack1.getMaxStackSize() ? false : ItemStack.areItemStackTagsEqual(stack1, stack2))); + return stack1.getItem() != stack2.getItem() ? false : (stack1.getMetadata() != stack2.getMetadata() ? false : (stack1.size > stack1.getMaxStackSize() ? false : ItemStack.areItemStackTagsEqual(stack1, stack2))); } /** diff --git a/java/src/game/tileentity/TileEntityLockable.java b/common/src/main/java/common/tileentity/TileEntityLockable.java similarity index 61% rename from java/src/game/tileentity/TileEntityLockable.java rename to common/src/main/java/common/tileentity/TileEntityLockable.java index 5b9a1ea..b6ad230 100755 --- a/java/src/game/tileentity/TileEntityLockable.java +++ b/common/src/main/java/common/tileentity/TileEntityLockable.java @@ -1,20 +1,20 @@ -package game.tileentity; +package common.tileentity; -import game.nbt.NBTTagCompound; +import common.tags.TagObject; public abstract class TileEntityLockable extends TileEntity implements IInteractionObject, ILockableContainer { - private LockCode code = LockCode.EMPTY_CODE; + private Passcode code = Passcode.EMPTY_CODE; - public void readFromNBT(NBTTagCompound compound) + public void readTags(TagObject compound) { - super.readFromNBT(compound); - this.code = LockCode.fromNBT(compound); + super.readTags(compound); + this.code = Passcode.fromNBT(compound); } - public void writeToNBT(NBTTagCompound compound) + public void writeTags(TagObject compound) { - super.writeToNBT(compound); + super.writeTags(compound); if (this.code != null) { @@ -24,15 +24,15 @@ public abstract class TileEntityLockable extends TileEntity implements IInteract public boolean isLocked() { - return this.code != null && !this.code.isEmpty(); + return this.code != null && !this.code.empty(); } - public LockCode getLockCode() + public Passcode getLockCode() { return this.code; } - public void setLockCode(LockCode code) + public void setLockCode(Passcode code) { this.code = code; } diff --git a/common/src/main/java/common/tileentity/TileEntityMobSpawner.java b/common/src/main/java/common/tileentity/TileEntityMobSpawner.java new file mode 100755 index 0000000..89ff3d4 --- /dev/null +++ b/common/src/main/java/common/tileentity/TileEntityMobSpawner.java @@ -0,0 +1,108 @@ +package common.tileentity; + +import common.entity.types.EntityLiving; +import common.init.EntityRegistry; +import common.inventory.ContainerTile; +import common.item.ItemMonsterPlacer; +import common.item.ItemNpcSpawner; +import common.item.ItemStack; +import common.tags.TagObject; +import common.vars.Vars; + +public class TileEntityMobSpawner extends TileEntityDevice implements ITickable +{ + public TileEntityMobSpawner() { + super(1); + } + + private int spawnDelay = 20; + private int minSpawnDelay = 200; + private int maxSpawnDelay = 800; + private int spawnRange = 4; + + public boolean isItemValidForSlot(int index, ItemStack stack) { + return index == 0 ? stack.getItem() instanceof ItemMonsterPlacer || stack.getItem() instanceof ItemNpcSpawner : false; + } + + public String getName() { + return "Mob-Spawner"; + } + + public String getGuiID() { + return "mob_spawner"; + } + + public String formatDisplay(ContainerTile inv) { + ItemStack stack = inv.getSlot(0).getStack(); + if(stack == null) + return "Kein Spawner vorhanden"; + return String.format("Erschaffe: %s", stack.getItem() instanceof ItemMonsterPlacer egg ? EntityRegistry.getEntityName(egg.getSpawnedId()) : ((stack.getItem() instanceof ItemNpcSpawner egg ? egg.getCharName() : ""))); + } + + protected boolean executeFunction() { + if(!Vars.mobs || !Vars.spawners || !this.hasAmount(0, 1)) + return false; + if (this.spawnDelay == -1) + this.resetTimer(); + if (this.spawnDelay > 0) { + --this.spawnDelay; + return true; + } + ItemStack stack = this.getStackInSlot(0); + if(stack == null) + return true; + double x = (double)this.pos.getX() + (this.worldObj.rand.doublev() - this.worldObj.rand.doublev()) * (double)this.spawnRange + 0.5D; + double y = (double)(this.pos.getY() + this.worldObj.rand.zrange(3) - 1); + double z = (double)this.pos.getZ() + (this.worldObj.rand.doublev() - this.worldObj.rand.doublev()) * (double)this.spawnRange + 0.5D; + EntityLiving entity = null; + if(stack.getItem() instanceof ItemMonsterPlacer egg) + entity = ItemMonsterPlacer.spawnCreature(this.worldObj, egg.getSpawnedId(), x, y, z, true); + else if(stack.getItem() instanceof ItemNpcSpawner egg) + entity = ItemNpcSpawner.spawnNpc(this.worldObj, egg.getSpawnedChar(), x, y, z, true); + if (entity == null) + return true; + this.decrStackSize(0, 1); + entity.spawnExplosionParticle(); + this.resetTimer(); + return true; + } + + private void resetTimer() + { + if (this.maxSpawnDelay <= this.minSpawnDelay) + { + this.spawnDelay = this.minSpawnDelay; + } + else + { + int i = this.maxSpawnDelay - this.minSpawnDelay; + this.spawnDelay = this.minSpawnDelay + this.worldObj.rand.zrange(i); + } + } + + public void readTags(TagObject nbt) + { + super.readTags(nbt); + this.spawnDelay = nbt.getShort("Delay"); + + if (nbt.hasShort("MinSpawnDelay")) + { + this.minSpawnDelay = nbt.getShort("MinSpawnDelay"); + this.maxSpawnDelay = nbt.getShort("MaxSpawnDelay"); + } + + if (nbt.hasShort("SpawnRange")) + { + this.spawnRange = nbt.getShort("SpawnRange"); + } + } + + public void writeTags(TagObject nbt) + { + super.writeTags(nbt); + nbt.setShort("Delay", (short)this.spawnDelay); + nbt.setShort("MinSpawnDelay", (short)this.minSpawnDelay); + nbt.setShort("MaxSpawnDelay", (short)this.maxSpawnDelay); + nbt.setShort("SpawnRange", (short)this.spawnRange); + } +} diff --git a/java/src/game/tileentity/TileEntityPiston.java b/common/src/main/java/common/tileentity/TileEntityPiston.java similarity index 85% rename from java/src/game/tileentity/TileEntityPiston.java rename to common/src/main/java/common/tileentity/TileEntityPiston.java index 1baff97..3feb89a 100755 --- a/java/src/game/tileentity/TileEntityPiston.java +++ b/common/src/main/java/common/tileentity/TileEntityPiston.java @@ -1,16 +1,15 @@ -package game.tileentity; +package common.tileentity; import java.util.List; -import game.collect.Lists; - -import game.entity.Entity; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.nbt.NBTTagCompound; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.State; +import common.collect.Lists; +import common.entity.Entity; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.tags.TagObject; +import common.util.BoundingBox; +import common.util.Facing; +import common.world.State; public class TileEntityPiston extends TileEntity implements ITickable { @@ -199,23 +198,23 @@ public class TileEntityPiston extends TileEntity implements ITickable } } - public void readFromNBT(NBTTagCompound compound) + public void readTags(TagObject compound) { - super.readFromNBT(compound); - this.pistonState = BlockRegistry.getBlockById(compound.getInteger("blockId")).getStateFromMeta(compound.getInteger("blockData")); - this.pistonFacing = Facing.getFront(compound.getInteger("facing")); + super.readTags(compound); + this.pistonState = BlockRegistry.getRegisteredBlock(compound.getString("blockId")).getStateFromMeta(compound.getInt("blockData")); + this.pistonFacing = Facing.getFront(compound.getInt("facing")); this.lastProgress = this.progress = compound.getFloat("progress"); - this.extending = compound.getBoolean("extending"); + this.extending = compound.getBool("extending"); } - public void writeToNBT(NBTTagCompound compound) + public void writeTags(TagObject compound) { - super.writeToNBT(compound); - compound.setInteger("blockId", BlockRegistry.getIdFromBlock(this.pistonState.getBlock())); - compound.setInteger("blockData", this.pistonState.getBlock().getMetaFromState(this.pistonState)); - compound.setInteger("facing", this.pistonFacing.getIndex()); + super.writeTags(compound); + compound.setString("blockId", BlockRegistry.getNameFromBlock(this.pistonState.getBlock())); + compound.setInt("blockData", this.pistonState.getBlock().getMetaFromState(this.pistonState)); + compound.setInt("facing", this.pistonFacing.getIndex()); compound.setFloat("progress", this.lastProgress); - compound.setBoolean("extending", this.extending); + compound.setBool("extending", this.extending); } public int getColor() { diff --git a/java/src/game/tileentity/TileEntitySign.java b/common/src/main/java/common/tileentity/TileEntitySign.java similarity index 88% rename from java/src/game/tileentity/TileEntitySign.java rename to common/src/main/java/common/tileentity/TileEntitySign.java index b0b9fa7..417359e 100755 --- a/java/src/game/tileentity/TileEntitySign.java +++ b/common/src/main/java/common/tileentity/TileEntitySign.java @@ -1,9 +1,9 @@ -package game.tileentity; +package common.tileentity; -import game.entity.npc.EntityNPC; -import game.nbt.NBTTagCompound; -import game.network.Packet; -import game.packet.S33PacketUpdateSign; +import common.entity.npc.EntityNPC; +import common.network.Packet; +import common.packet.SPacketUpdateSign; +import common.tags.TagObject; public class TileEntitySign extends TileEntity { public final String[] signText = new String[] {"", "", "", ""}; @@ -19,8 +19,8 @@ public class TileEntitySign extends TileEntity { private EntityNPC player; // private boolean oldFormat; - public void writeToNBT(NBTTagCompound compound) { - super.writeToNBT(compound); + public void writeTags(TagObject compound) { + super.writeTags(compound); for(int i = 0; i < 4; ++i) { compound.setString("Text" + (i + 1), this.signText[i]); @@ -30,15 +30,15 @@ public class TileEntitySign extends TileEntity { // compound.setString("Command", this.command); } - public void readFromNBT(NBTTagCompound compound) { + public void readTags(TagObject compound) { // this.isEditable = false; - super.readFromNBT(compound); + super.readTags(compound); for(int i = 0; i < 4; ++i) { this.signText[i] = compound.getString("Text" + (i + 1)); } -// if(compound.hasKey("Command", 8)) +// if(compound.hasString("Command")) // this.command = compound.getString("Command"); // if(!compound.getBoolean("NewFormat")) { @@ -95,7 +95,7 @@ public class TileEntitySign extends TileEntity { String[] aichatcomponent = new String[4]; System.arraycopy(this.signText, 0, aichatcomponent, 0, 4); // Sign sign = Server.getServer().getSigns().getEntry(new WorldPos(this).toString()); - return new S33PacketUpdateSign(this.worldObj, this.pos, aichatcomponent); + return new SPacketUpdateSign(this.worldObj, this.pos, aichatcomponent); } // public boolean hasSpecialNBT() { diff --git a/java/src/game/tileentity/TileEntityTianReactor.java b/common/src/main/java/common/tileentity/TileEntityTianReactor.java similarity index 78% rename from java/src/game/tileentity/TileEntityTianReactor.java rename to common/src/main/java/common/tileentity/TileEntityTianReactor.java index 6896773..f276bde 100755 --- a/java/src/game/tileentity/TileEntityTianReactor.java +++ b/common/src/main/java/common/tileentity/TileEntityTianReactor.java @@ -1,25 +1,24 @@ -package game.tileentity; +package common.tileentity; -import game.init.Blocks; -import game.init.ItemRegistry; -import game.init.Items; -import game.item.ItemStack; -import game.tileentity.MachineResource.Type; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; +import common.inventory.ContainerTile; +import common.item.ItemStack; +import common.tileentity.MachineResource.Type; -public class TileEntityTianReactor extends TileEntityMachine { +public class TileEntityTianReactor extends TileEntityDevice { public TileEntityTianReactor() { super(2, new MachineResource(Type.OUTPUT, "output.energy", 1024, 0, 0)); } protected boolean executeFunction() { - if(!this.hasAmount(0, 2)) // && !this.isCreative) + if(!this.hasAmount(0, 2)) return false; if(this.rand.rarity(5)) return true; -// if(!this.isCreative) { this.decrStackSize(0, 2); this.decrStackSize(1, 1); -// } this.getResource(0).add(this.rand.range(this.temperature / 200, this.temperature / 50), 20, false); return true; } @@ -48,7 +47,7 @@ public class TileEntityTianReactor extends TileEntityMachine { return "tian_reactor"; } - public String formatDisplay() { + public String formatDisplay(ContainerTile inv) { return String.format("Gespeicherte Energie: %d TF", this.getResource(0).getValue()); } diff --git a/java/src/game/world/BlockPos.java b/common/src/main/java/common/util/BlockPos.java similarity index 89% rename from java/src/game/world/BlockPos.java rename to common/src/main/java/common/util/BlockPos.java index 9638c4c..526a1f4 100755 --- a/java/src/game/world/BlockPos.java +++ b/common/src/main/java/common/util/BlockPos.java @@ -1,22 +1,13 @@ -package game.world; +package common.util; import java.util.Iterator; -import game.collect.AbstractIterator; - -import game.entity.Entity; +import common.collect.AbstractIterator; +import common.entity.Entity; public class BlockPos extends Vec3i { public static final BlockPos ORIGIN = new BlockPos(0, 0, 0); - private static final int NUM_X_BITS = 1 + 26; // ExtMath.calculateLogBaseTwo(ExtMath.roundUpToPowerOfTwo(World.MAX_SIZE)); - private static final int NUM_Z_BITS = NUM_X_BITS; - private static final int NUM_Y_BITS = 64 - NUM_X_BITS - NUM_Z_BITS; - private static final int Y_SHIFT = 0 + NUM_Z_BITS; - private static final int X_SHIFT = Y_SHIFT + NUM_Y_BITS; - private static final long X_MASK = (1L << NUM_X_BITS) - 1L; - private static final long Y_MASK = (1L << NUM_Y_BITS) - 1L; - private static final long Z_MASK = (1L << NUM_Z_BITS) - 1L; public BlockPos(int x, int y, int z) { @@ -194,19 +185,6 @@ public class BlockPos extends Vec3i { return new BlockPos(this.getY() * vec.getZ() - this.getZ() * vec.getY(), this.getZ() * vec.getX() - this.getX() * vec.getZ(), this.getX() * vec.getY() - this.getY() * vec.getX()); } - - public long toLong() - { - return ((long)this.getX() & X_MASK) << X_SHIFT | ((long)this.getY() & Y_MASK) << Y_SHIFT | ((long)this.getZ() & Z_MASK) << 0; - } - - public static BlockPos fromLong(long serialized) - { - int i = (int)(serialized << 64 - X_SHIFT - NUM_X_BITS >> 64 - NUM_X_BITS); - int j = (int)(serialized << 64 - Y_SHIFT - NUM_Y_BITS >> 64 - NUM_Y_BITS); - int k = (int)(serialized << 64 - NUM_Z_BITS >> 64 - NUM_Z_BITS); - return new BlockPos(i, j, k); - } public static Iterable getAllInBox(BlockPos from, BlockPos to) { diff --git a/java/src/game/world/BoundingBox.java b/common/src/main/java/common/util/BoundingBox.java similarity index 99% rename from java/src/game/world/BoundingBox.java rename to common/src/main/java/common/util/BoundingBox.java index 1aeb90d..15206f5 100755 --- a/java/src/game/world/BoundingBox.java +++ b/common/src/main/java/common/util/BoundingBox.java @@ -1,6 +1,6 @@ -package game.world; +package common.util; -import game.world.HitPosition.ObjectType; +import common.util.HitPosition.ObjectType; public class BoundingBox { diff --git a/java/src/game/util/CharValidator.java b/common/src/main/java/common/util/CharValidator.java similarity index 95% rename from java/src/game/util/CharValidator.java rename to common/src/main/java/common/util/CharValidator.java index 2a22181..e2c8407 100644 --- a/java/src/game/util/CharValidator.java +++ b/common/src/main/java/common/util/CharValidator.java @@ -1,4 +1,4 @@ -package game.util; +package common.util; public interface CharValidator { boolean valid(char ch); diff --git a/java/src/game/world/ChunkPos.java b/common/src/main/java/common/util/ChunkPos.java similarity index 96% rename from java/src/game/world/ChunkPos.java rename to common/src/main/java/common/util/ChunkPos.java index b97a738..32a1c8e 100755 --- a/java/src/game/world/ChunkPos.java +++ b/common/src/main/java/common/util/ChunkPos.java @@ -1,4 +1,4 @@ -package game.world; +package common.util; public class ChunkPos { public final int x; diff --git a/java/src/game/util/DC32.java b/common/src/main/java/common/util/DC32.java similarity index 99% rename from java/src/game/util/DC32.java rename to common/src/main/java/common/util/DC32.java index 2a22138..1e40cc4 100644 --- a/java/src/game/util/DC32.java +++ b/common/src/main/java/common/util/DC32.java @@ -1,4 +1,4 @@ -package game.util; +package common.util; public class DC32 { public static final byte[] ASCII = { // 0x1f -> AUX1 diff --git a/java/src/game/util/Displayable.java b/common/src/main/java/common/util/Displayable.java similarity index 75% rename from java/src/game/util/Displayable.java rename to common/src/main/java/common/util/Displayable.java index 376ddff..90f83e5 100644 --- a/java/src/game/util/Displayable.java +++ b/common/src/main/java/common/util/Displayable.java @@ -1,4 +1,4 @@ -package game.util; +package common.util; public interface Displayable { public String getDisplay(); diff --git a/common/src/main/java/common/util/EncryptUtil.java b/common/src/main/java/common/util/EncryptUtil.java new file mode 100644 index 0000000..278bc65 --- /dev/null +++ b/common/src/main/java/common/util/EncryptUtil.java @@ -0,0 +1,280 @@ +package common.util; + +import java.security.GeneralSecurityException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.KeyFactory; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.SecureRandom; +import java.security.Signature; +import java.security.SignatureException; +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.EncodedKeySpec; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.KeySpec; +import java.security.spec.PKCS8EncodedKeySpec; +import java.security.spec.X509EncodedKeySpec; +import java.util.Arrays; +import java.util.Base64; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.KeyAgreement; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.SecretKeySpec; + +import common.log.Log; + +public class EncryptUtil { + public static final String KEY_ALGO_NAME = "tcr-ed25519"; + public static final String KEY_ALGO_DISPLAY = "Ed25519"; + + private static final long CRC24_INIT = 0xB704CEL; + private static final long CRC24_POLY = 0x1864CFBL; + + public static SecretKey makeKeyAgreement(PrivateKey key, PublicKey pubkey) { + try { + KeyAgreement agreement = KeyAgreement.getInstance("X25519"); + agreement.init(key); + agreement.doPhase(pubkey, true); + return new SecretKeySpec(agreement.generateSecret(), 0, 16, "AES"); + } + catch(NoSuchAlgorithmException | InvalidKeyException e) { + Log.SYSTEM.error(e, "Konnte Diffie-Hellman-Schlüsselaushandlung nicht absolvieren"); + return null; + } + } + + public static KeyPair createDHKeypair() { + try { + KeyPairGenerator pairgen = KeyPairGenerator.getInstance("X25519"); + return pairgen.generateKeyPair(); + } + catch(NoSuchAlgorithmException e) { + Log.SYSTEM.error(e, "Konnte Schlüsselpaar für Diffie-Hellman nicht generieren"); + return null; + } + } + + public static KeyPair createKeypair() { + try { + KeyPairGenerator pairgen = KeyPairGenerator.getInstance("Ed25519"); + return pairgen.generateKeyPair(); + } + catch(NoSuchAlgorithmException e) { + Log.SYSTEM.error(e, "Konnte Schlüsselpaar nicht generieren"); + return null; + } + } + + public static byte[] createSignature(PrivateKey key, byte[] token) { + try { + Signature sig = Signature.getInstance("Ed25519"); + sig.initSign(key); + sig.update(token); + return sig.sign(); + } + catch(SignatureException | InvalidKeyException | NoSuchAlgorithmException e) { + Log.SYSTEM.error(e, "Konnte Signatur nicht generieren"); + return null; + } + } + + public static boolean verifySignature(PublicKey key, byte[] token, byte[] signature) { + try { + Signature sig = Signature.getInstance("Ed25519"); + sig.initVerify(key); + sig.update(token); + return sig.verify(signature); + } + catch(SignatureException | InvalidKeyException | NoSuchAlgorithmException e) { + Log.SYSTEM.error(e, "Konnte Signatur nicht verifizieren"); + return false; + } + } + + public static PublicKey decodeDHPublicKey(byte[] encoded) { + try { + EncodedKeySpec spec = new X509EncodedKeySpec(encoded); + KeyFactory factory = KeyFactory.getInstance("X25519"); + return factory.generatePublic(spec); + } + catch(NoSuchAlgorithmException | InvalidKeySpecException e) { + Log.SYSTEM.error(e, "Öffentlicher Schlüssel für Diffie-Hellman konnte nicht dekodiert werden"); + return null; + } + } + + public static PublicKey decodePublicKey(byte[] encoded) { + try { + EncodedKeySpec spec = new X509EncodedKeySpec(encoded); + KeyFactory factory = KeyFactory.getInstance("Ed25519"); + return factory.generatePublic(spec); + } + catch(NoSuchAlgorithmException | InvalidKeySpecException e) { + Log.SYSTEM.error(e, "Öffentlicher Schlüssel konnte nicht dekodiert werden"); + return null; + } + } + + public static PrivateKey decodePrivateKey(byte[] encoded) { + try { + EncodedKeySpec spec = new PKCS8EncodedKeySpec(encoded); + KeyFactory factory = KeyFactory.getInstance("Ed25519"); + return factory.generatePrivate(spec); + } + catch(NoSuchAlgorithmException | InvalidKeySpecException e) { + Log.SYSTEM.error(e, "Privater Schlüssel konnte nicht dekodiert werden"); + return null; + } + } + + public static byte[] encryptData(Key key, byte[] data) { + return cipher(Cipher.ENCRYPT_MODE, key, data); + } + + public static byte[] decryptData(Key key, byte[] data) { + return cipher(Cipher.DECRYPT_MODE, key, data); + } + + private static byte[] cipher(int mode, Key key, byte[] data) { + try { + return createCipher(mode, key.getAlgorithm(), key).doFinal(data); + } + catch(IllegalBlockSizeException | BadPaddingException e) { + Log.SYSTEM.error(e, "Konnte Daten nicht ver- oder entschlüsseln"); + return null; + } + } + + private static Cipher createCipher(int mode, String transformation, Key key) { + try { + Cipher cipher = Cipher.getInstance(transformation); + cipher.init(mode, key); + return cipher; + } + catch(InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException e) { + Log.SYSTEM.error(e, "Konnte Verschlüsselungsverfahren nicht initialisieren"); + return null; + } + } + + public static Cipher createCipher(int mode, Key key) { + try { + Cipher cipher = Cipher.getInstance("AES/CFB8/NoPadding"); + cipher.init(mode, (Key)key, (AlgorithmParameterSpec)(new IvParameterSpec(key.getEncoded()))); + return cipher; + } + catch(GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + public static String getXorSha512Hash(byte[] data) { + byte[] hash; + try { + MessageDigest digest = MessageDigest.getInstance("SHA-512"); + hash = digest.digest(data); + } + catch(NoSuchAlgorithmException e) { + Log.SYSTEM.error(e, "Konnte Schlüssel-Prüfwert nicht berechnen"); + return ""; + } + byte[] xor = new byte[8]; + for(int z = 0; z < hash.length / xor.length; z++) { + for(int n = 0; n < xor.length; n++) { + xor[n] ^= hash[z * xor.length + n]; + } + } + return Util.getHexString(xor); + } + + public static String getArmoredPubkey(PublicKey pubkey, String cn) { + StringBuilder sb = new StringBuilder(EncryptUtil.KEY_ALGO_NAME + " "); + sb.append(Base64.getEncoder().encodeToString(pubkey.getEncoded())); + sb.append(' ').append(Base64.getEncoder().encodeToString(crc24(pubkey.getEncoded()))); + return cn == null || cn.isEmpty() ? sb.toString() : sb.append(' ').append(Util.sanitizeCommonName(cn)).toString(); + } + + public static Pair parseArmoredPubkey(String armor) throws IllegalArgumentException { + String[] tok = armor.trim().split(" "); + if(tok.length != 3 && tok.length != 4) + throw new IllegalArgumentException("Key muss aus 3 oder 4 Segmenten bestehen"); + if(!tok[0].equals(EncryptUtil.KEY_ALGO_NAME)) + throw new IllegalArgumentException("Algorithmus '" + tok[0] + "' ist nicht unterstützt, es wird derzeit nur " + EncryptUtil.KEY_ALGO_NAME + " verwendet"); + byte[] key; + try { + key = Base64.getDecoder().decode(tok[1]); + } + catch(IllegalArgumentException e) { + throw new IllegalArgumentException("Schlüssel ist nicht im Base64-Format", e); + } + byte[] hash; + try { + hash = Base64.getDecoder().decode(tok[2]); + } + catch(IllegalArgumentException e) { + throw new IllegalArgumentException("Prüfwert ist nicht im Base64-Format", e); + } + if(hash.length != 3) + throw new IllegalArgumentException("Prüfwert hat die falsche Länge, erwarte 3 Bytes, habe " + hash.length + " Bytes"); + byte[] keyHash = crc24(key); + if(!Arrays.equals(hash, keyHash)) + throw new IllegalArgumentException("Prüfwert ist falsch, erwarte " + Util.getHexString(hash) + ", habe " + Util.getHexString(keyHash)); + PublicKey pubkey; + try { + EncodedKeySpec spec = new X509EncodedKeySpec(key); + KeyFactory factory = KeyFactory.getInstance("Ed25519"); + pubkey = factory.generatePublic(spec); + } + catch(NoSuchAlgorithmException | InvalidKeySpecException e) { + throw new IllegalArgumentException("Öffentlicher Schlüssel konnte nicht dekodiert werden", e); + } + if(tok.length == 4 && !Util.isValidCommonName(tok[3])) + throw new IllegalArgumentException("Name muss aus 'a-z' '0-9' und '-' bestehen, kann keine aufeinander folgenden Bindestriche haben und darf nicht damit beginnen oder darin enden"); + return new Pair(pubkey, tok.length == 4 ? tok[3] : null); + } + + private static byte[] crc24(byte[] data) { + long crc = CRC24_INIT; + for(byte bt : data) { + crc ^= (long)bt << 16; + for(int z = 0; z < 8; z++) { + crc <<= 1; + if((crc & 0x1000000) != 0) + crc ^= CRC24_POLY; + } + } + int value = (int)(crc & 0xFFFFFFL); + return new byte[] {(byte)((value >> 16) & 0xff), (byte)((value >> 8) & 0xff), (byte)(value & 0xff)}; + } + + public static byte[] hashPassword(String password, byte[] salt) { + try { + KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, 65536, 256); + SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); + return factory.generateSecret(spec).getEncoded(); + } + catch(NoSuchAlgorithmException | InvalidKeySpecException e) { + Log.SYSTEM.error(e, "Konnte Passwort-Prüfwert nicht berechnen"); + return null; + } + } + + public static Pair hashPassword(String password) { + SecureRandom rand = new SecureRandom(); + byte[] salt = new byte[64]; + rand.nextBytes(salt); + return new Pair(hashPassword(password, salt), salt); + } +} diff --git a/java/src/game/util/ExtMath.java b/common/src/main/java/common/util/ExtMath.java similarity index 99% rename from java/src/game/util/ExtMath.java rename to common/src/main/java/common/util/ExtMath.java index be7b98b..2554a03 100755 --- a/java/src/game/util/ExtMath.java +++ b/common/src/main/java/common/util/ExtMath.java @@ -1,4 +1,4 @@ -package game.util; +package common.util; public abstract class ExtMath { private static final float[] SIN_TABLE = new float[65536]; diff --git a/java/src/game/world/Facing.java b/common/src/main/java/common/util/Facing.java similarity index 97% rename from java/src/game/world/Facing.java rename to common/src/main/java/common/util/Facing.java index 67ab478..47e093b 100755 --- a/java/src/game/world/Facing.java +++ b/common/src/main/java/common/util/Facing.java @@ -1,17 +1,14 @@ -package game.world; +package common.util; import java.util.Iterator; import java.util.Map; - import java.util.function.Predicate; -import game.collect.Iterators; -import game.collect.Maps; -import game.properties.IStringSerializable; -import game.rng.Random; -import game.util.ExtMath; +import common.collect.Iterators; +import common.collect.Maps; +import common.rng.Random; -public enum Facing implements IStringSerializable +public enum Facing implements Identifyable { DOWN(0, 2, 1, -1, "down", Facing.AxisDirection.NEGATIVE, Facing.Axis.Y, new Vec3i(0, -1, 0)), UP(1, 3, 0, -1, "up", Facing.AxisDirection.POSITIVE, Facing.Axis.Y, new Vec3i(0, 1, 0)), @@ -371,7 +368,7 @@ public enum Facing implements IStringSerializable } } - public static enum Axis implements Predicate, IStringSerializable { + public static enum Axis implements Predicate, Identifyable { X("x", Facing.Plane.HORIZONTAL), Y("y", Facing.Plane.VERTICAL), Z("z", Facing.Plane.HORIZONTAL); diff --git a/java/src/game/world/HitPosition.java b/common/src/main/java/common/util/HitPosition.java similarity index 93% rename from java/src/game/world/HitPosition.java rename to common/src/main/java/common/util/HitPosition.java index 4271e0e..74e90e1 100755 --- a/java/src/game/world/HitPosition.java +++ b/common/src/main/java/common/util/HitPosition.java @@ -1,6 +1,6 @@ -package game.world; +package common.util; -import game.entity.Entity; +import common.entity.Entity; public class HitPosition { public static enum ObjectType { diff --git a/java/src/game/init/IObjectIntIterable.java b/common/src/main/java/common/util/IObjectIntIterable.java similarity index 75% rename from java/src/game/init/IObjectIntIterable.java rename to common/src/main/java/common/util/IObjectIntIterable.java index 201259a..970ee52 100755 --- a/java/src/game/init/IObjectIntIterable.java +++ b/common/src/main/java/common/util/IObjectIntIterable.java @@ -1,4 +1,4 @@ -package game.init; +package common.util; public interface IObjectIntIterable extends Iterable { diff --git a/java/src/game/init/IRegistry.java b/common/src/main/java/common/util/IRegistry.java similarity index 89% rename from java/src/game/init/IRegistry.java rename to common/src/main/java/common/util/IRegistry.java index bec97a9..eaf299b 100755 --- a/java/src/game/init/IRegistry.java +++ b/common/src/main/java/common/util/IRegistry.java @@ -1,4 +1,4 @@ -package game.init; +package common.util; public interface IRegistry extends Iterable { diff --git a/common/src/main/java/common/util/Identifyable.java b/common/src/main/java/common/util/Identifyable.java new file mode 100755 index 0000000..11dee69 --- /dev/null +++ b/common/src/main/java/common/util/Identifyable.java @@ -0,0 +1,6 @@ +package common.util; + +public interface Identifyable +{ + String getName(); +} diff --git a/java/src/game/world/ClassInheritanceMultiMap.java b/common/src/main/java/common/util/InheritanceMultiMap.java similarity index 90% rename from java/src/game/world/ClassInheritanceMultiMap.java rename to common/src/main/java/common/util/InheritanceMultiMap.java index 5137011..49e336e 100755 --- a/java/src/game/world/ClassInheritanceMultiMap.java +++ b/common/src/main/java/common/util/InheritanceMultiMap.java @@ -1,4 +1,4 @@ -package game.world; +package common.util; import java.util.AbstractSet; import java.util.Collections; @@ -8,11 +8,11 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import game.collect.Iterators; -import game.collect.Lists; -import game.collect.Maps; +import common.collect.Iterators; +import common.collect.Lists; +import common.collect.Maps; -public class ClassInheritanceMultiMap extends AbstractSet +public class InheritanceMultiMap extends AbstractSet { private static final Set < Class> CLASSES = Collections.newSetFromMap(new ConcurrentHashMap, Boolean>()); // fix exception @@ -21,7 +21,7 @@ public class ClassInheritanceMultiMap extends AbstractSet private final Class baseClass; private final List values = Lists.newArrayList(); - public ClassInheritanceMultiMap(Class baseClassIn) + public InheritanceMultiMap(Class baseClassIn) { this.baseClass = baseClassIn; this.knownKeys.add(baseClassIn); @@ -124,7 +124,7 @@ public class ClassInheritanceMultiMap extends AbstractSet { public Iterator iterator() { - List list = (List)ClassInheritanceMultiMap.this.map.get(ClassInheritanceMultiMap.this.initializeClassLookup(clazz)); + List list = (List)InheritanceMultiMap.this.map.get(InheritanceMultiMap.this.initializeClassLookup(clazz)); if (list == null) { diff --git a/java/src/game/world/IntHashMap.java b/common/src/main/java/common/util/IntHashMap.java similarity index 99% rename from java/src/game/world/IntHashMap.java rename to common/src/main/java/common/util/IntHashMap.java index 47122b4..885b3a2 100755 --- a/java/src/game/world/IntHashMap.java +++ b/common/src/main/java/common/util/IntHashMap.java @@ -1,4 +1,4 @@ -package game.world; +package common.util; public class IntHashMap { diff --git a/java/src/game/network/LazyLoadBase.java b/common/src/main/java/common/util/LazyLoader.java similarity index 82% rename from java/src/game/network/LazyLoadBase.java rename to common/src/main/java/common/util/LazyLoader.java index 05d41b0..2e6801e 100755 --- a/java/src/game/network/LazyLoadBase.java +++ b/common/src/main/java/common/util/LazyLoader.java @@ -1,6 +1,6 @@ -package game.network; +package common.util; -public abstract class LazyLoadBase +public abstract class LazyLoader { private T value; private boolean isLoaded = false; diff --git a/java/src/game/world/LongHashMap.java b/common/src/main/java/common/util/LongHashMap.java similarity index 97% rename from java/src/game/world/LongHashMap.java rename to common/src/main/java/common/util/LongHashMap.java index c396c47..65faf9b 100755 --- a/java/src/game/world/LongHashMap.java +++ b/common/src/main/java/common/util/LongHashMap.java @@ -1,4 +1,4 @@ -package game.world; +package common.util; public class LongHashMap { @@ -13,6 +13,14 @@ public class LongHashMap return (long)x & 4294967295L | ((long)z & 4294967295L) << 32; } + public static int getX(long v) { + return (int)(v & 4294967295L); + } + + public static int getZ(long v) { + return (int)(v >> 32); + } + public LongHashMap() { this.mask = this.hashArray.length - 1; diff --git a/java/src/game/renderer/Matrix4f.java b/common/src/main/java/common/util/Matrix4f.java similarity index 99% rename from java/src/game/renderer/Matrix4f.java rename to common/src/main/java/common/util/Matrix4f.java index f14cd8e..8e61925 100644 --- a/java/src/game/renderer/Matrix4f.java +++ b/common/src/main/java/common/util/Matrix4f.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package game.renderer; +package common.util; import java.io.Serializable; import java.nio.FloatBuffer; diff --git a/java/src/game/world/NibbleArray.java b/common/src/main/java/common/util/NibbleArray.java similarity index 97% rename from java/src/game/world/NibbleArray.java rename to common/src/main/java/common/util/NibbleArray.java index c5801a2..629be8d 100755 --- a/java/src/game/world/NibbleArray.java +++ b/common/src/main/java/common/util/NibbleArray.java @@ -1,4 +1,4 @@ -package game.world; +package common.util; public class NibbleArray { private final byte[] data; diff --git a/java/src/game/init/ObjectIntIdentityMap.java b/common/src/main/java/common/util/ObjectIntIdentityMap.java similarity index 90% rename from java/src/game/init/ObjectIntIdentityMap.java rename to common/src/main/java/common/util/ObjectIntIdentityMap.java index ea81b20..88b9234 100755 --- a/java/src/game/init/ObjectIntIdentityMap.java +++ b/common/src/main/java/common/util/ObjectIntIdentityMap.java @@ -1,12 +1,11 @@ -package game.init; +package common.util; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.List; -import game.util.Predicates; -import game.collect.Iterators; -import game.collect.Lists; +import common.collect.Iterators; +import common.collect.Lists; public class ObjectIntIdentityMap implements IObjectIntIterable { diff --git a/common/src/main/java/common/util/Pair.java b/common/src/main/java/common/util/Pair.java new file mode 100644 index 0000000..3ac253e --- /dev/null +++ b/common/src/main/java/common/util/Pair.java @@ -0,0 +1,4 @@ +package common.util; + +public record Pair(A first, B second) { +} diff --git a/java/src/game/world/PortalType.java b/common/src/main/java/common/util/PortalType.java similarity index 87% rename from java/src/game/world/PortalType.java rename to common/src/main/java/common/util/PortalType.java index 37ca835..91b7cd4 100755 --- a/java/src/game/world/PortalType.java +++ b/common/src/main/java/common/util/PortalType.java @@ -1,4 +1,4 @@ -package game.world; +package common.util; public enum PortalType { STAND_BLACK, STAND_RED, STAND_YELLOW, STAND_GREEN, STAND_CYAN, STAND_BLUE, STAND_MAGENTA, STAND_WHITE, FLOOR, VOID; diff --git a/common/src/main/java/common/util/Position.java b/common/src/main/java/common/util/Position.java new file mode 100755 index 0000000..ac29267 --- /dev/null +++ b/common/src/main/java/common/util/Position.java @@ -0,0 +1,4 @@ +package common.util; + +public record Position(double x, double y, double z, float yaw, float pitch, int dim) { +} diff --git a/java/src/game/util/Predicates.java b/common/src/main/java/common/util/Predicates.java similarity index 99% rename from java/src/game/util/Predicates.java rename to common/src/main/java/common/util/Predicates.java index 6bdfe63..4570723 100644 --- a/java/src/game/util/Predicates.java +++ b/common/src/main/java/common/util/Predicates.java @@ -14,7 +14,7 @@ * limitations under the License. */ -package game.util; +package common.util; import java.io.Serializable; import java.util.ArrayList; diff --git a/java/src/game/init/RegistryDefaulted.java b/common/src/main/java/common/util/RegistryDefaulted.java similarity index 95% rename from java/src/game/init/RegistryDefaulted.java rename to common/src/main/java/common/util/RegistryDefaulted.java index 08b45a3..8a5d13a 100755 --- a/java/src/game/init/RegistryDefaulted.java +++ b/common/src/main/java/common/util/RegistryDefaulted.java @@ -1,4 +1,4 @@ -package game.init; +package common.util; public class RegistryDefaulted extends RegistrySimple { diff --git a/java/src/game/init/RegistryNamespaced.java b/common/src/main/java/common/util/RegistryNamespaced.java similarity index 96% rename from java/src/game/init/RegistryNamespaced.java rename to common/src/main/java/common/util/RegistryNamespaced.java index 0b48909..e6e40d7 100755 --- a/java/src/game/init/RegistryNamespaced.java +++ b/common/src/main/java/common/util/RegistryNamespaced.java @@ -1,10 +1,10 @@ -package game.init; +package common.util; import java.util.Iterator; import java.util.Map; -import game.collect.BiMap; -import game.collect.HashBiMap; +import common.collect.BiMap; +import common.collect.HashBiMap; public class RegistryNamespaced extends RegistrySimple implements IObjectIntIterable { diff --git a/java/src/game/init/RegistryNamespacedDefaultedByKey.java b/common/src/main/java/common/util/RegistryNamespacedDefaultedByKey.java similarity index 98% rename from java/src/game/init/RegistryNamespacedDefaultedByKey.java rename to common/src/main/java/common/util/RegistryNamespacedDefaultedByKey.java index 8d8d89c..cd41360 100755 --- a/java/src/game/init/RegistryNamespacedDefaultedByKey.java +++ b/common/src/main/java/common/util/RegistryNamespacedDefaultedByKey.java @@ -1,4 +1,4 @@ -package game.init; +package common.util; public class RegistryNamespacedDefaultedByKey extends RegistryNamespaced { diff --git a/java/src/game/init/RegistrySimple.java b/common/src/main/java/common/util/RegistrySimple.java similarity index 96% rename from java/src/game/init/RegistrySimple.java rename to common/src/main/java/common/util/RegistrySimple.java index 5b41625..8e75927 100755 --- a/java/src/game/init/RegistrySimple.java +++ b/common/src/main/java/common/util/RegistrySimple.java @@ -1,11 +1,11 @@ -package game.init; +package common.util; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; -import game.collect.Maps; +import common.collect.Maps; public class RegistrySimple implements IRegistry { diff --git a/common/src/main/java/common/util/ReleaseType.java b/common/src/main/java/common/util/ReleaseType.java new file mode 100644 index 0000000..be367f8 --- /dev/null +++ b/common/src/main/java/common/util/ReleaseType.java @@ -0,0 +1,24 @@ +package common.util; + +public enum ReleaseType { + DEV("dev", 3), + ALPHA("alpha", 2), + BETA("beta", 1), + STABLE(null, 0); + + private final String suffix; + private final int id; + + private ReleaseType(String suffix, int id) { + this.suffix = suffix == null ? "" : "-" + suffix; + this.id = id; + } + + public String toString() { + return this.suffix; + } + + public int getId() { + return this.id; + } +} diff --git a/common/src/main/java/common/util/Triplet.java b/common/src/main/java/common/util/Triplet.java new file mode 100644 index 0000000..ded6065 --- /dev/null +++ b/common/src/main/java/common/util/Triplet.java @@ -0,0 +1,4 @@ +package common.util; + +public record Triplet(A first, B second, C third) { +} diff --git a/common/src/main/java/common/util/Util.java b/common/src/main/java/common/util/Util.java new file mode 100644 index 0000000..2fc2605 --- /dev/null +++ b/common/src/main/java/common/util/Util.java @@ -0,0 +1,535 @@ +package common.util; + +import java.awt.Desktop; +import java.awt.GraphicsEnvironment; +import java.io.File; +import java.io.FileOutputStream; +import java.io.PrintStream; +import java.lang.Thread.UncaughtExceptionHandler; +import java.lang.management.ManagementFactory; +import java.lang.management.ThreadInfo; +import java.lang.management.ThreadMXBean; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.function.Function; + +import javax.imageio.ImageIO; +import javax.swing.JOptionPane; + +import common.Version; +import common.collect.Lists; +import common.collect.Maps; +import common.log.Log; +import common.rng.Random; + +public abstract class Util { + private static final long START = getTime(); + private static final int MIN_JAVA_FEATURE = 21; + public static final boolean WINDOWS = System.getProperty("os.name").toLowerCase(Locale.US).contains("win"); + public static final boolean DEVMODE = System.getProperty("runtime.devmode") != null; + public static final int PROTOCOL = Version.MAJOR << 16 | Version.MINOR << 8 | Version.PATCH; + public static final String VERSION = "v" + Version.MAJOR + "." + Version.MINOR + "." + Version.PATCH + Version.RELEASE; + + private static boolean crashed; + + public static String strip(String str, int offset, int len, char newl, char tab, char unk) { + StringBuilder sb = new StringBuilder(); + for(int pos = offset; pos < offset + len; pos++) { + char c = str.charAt(pos); + if(c == '\n') { + if(newl == 0) + return sb.toString(); + sb.append(newl); + } + else if((c == '\t') && tab != 0) { + for(int z = 0; z < 4; z++) + sb.append(tab); + } + else if(c == Log.CHR_UNK) { + if(unk != 0) + sb.append(unk); + } + else if(c >= Log.CHR_SPC && c <= 0xff) { + sb.append(c); + } + } + return sb.toString(); + } + + public static int compareLower(String str1, String str2) { + if(str2.length() > str1.length()) + return 0; + for(int z = 0; z < str2.length(); z++) { + if(Character.toLowerCase(str1.charAt(z)) != Character.toLowerCase(str2.charAt(z))) + return 0; + } + return str2.length() == str1.length() ? 0x7fffffff : str2.length(); + } + + public static Integer parseInt(String str, int base) { + char c; + boolean tbase = false; + int digits = 0; + long v = 0; + long nbase = base != 0 ? (base < 0 ? -base : base) : 10; + long nsign = 1; + for(int pos = 0; pos < str.length(); pos++) { + c = Character.toLowerCase(str.charAt(pos)); + if(pos == 0 && ((c == '+') || ((c == '-') && (base >= 0)))) + nsign = (c == '+') ? 1 : -1; + else if(pos == 0 && c == '0') { + tbase = true; + digits++; + } + else if(tbase && pos == 1 && c == 'x') { + nbase = 16; + digits--; + } + else if(((nbase == 16) && (c >= 'a' && c <= 'f')) || (c >= '0' && c <= '9')) { + v *= nbase; + v += ((long)((c >= '0' && c <= '9') ? (c - '0') : (10 + (c - 'a')))); + digits++; + } + else + return null; + } + if(digits == 0) + return null; + v *= nsign; + if((base < 0) ? (v < 0L || v > 0xffffffffL) : (v < -0x80000000L || v > 0x7fffffffL)) { + return null; + } + return (int)((base < 0) ? (v & 0xffffffff) : (((v >> 32) & 0x80000000) | (v & 0x7fffffff))); + } + + public static T parseEnum(Class clazz, String str) { + boolean name = Identifyable.class.isAssignableFrom(clazz); + T[] values = clazz.getEnumConstants(); + Integer value; + if((value = parseInt(str, 0)) != null && (value >= 0) && (value < values.length)) { + return values[value]; + } + int comp; + int max = 0; + T best = null; + for(int z = 0; z < values.length; z++) { + if((comp = compareLower(name ? ((Identifyable)values[z]).getName() : values[z].toString(), str)) > max) { + max = comp; + best = values[z]; + } + } + return best; + } + + public static T parseEnum(Class base, String str, Class ... enums) { + int comp; + int max = 0; + T best = null; + for(Class clazz : enums) { + if(!base.isAssignableFrom(clazz)) + throw new IllegalArgumentException("Klasse " + clazz.getSimpleName() + " ist nicht " + base.getSimpleName() + " untergeordnet"); + boolean name = Identifyable.class.isAssignableFrom(clazz); + Enum[] values = clazz.getEnumConstants(); + for(int z = 0; z < values.length; z++) { + if((comp = compareLower(name ? ((Identifyable)values[z]).getName() : values[z].toString(), str)) > max) { + max = comp; + best = (T)values[z]; + } + } + } + return best; + } + + public static int indexOf(T[] array, T elem) { + for(int z = 0; z < array.length; z++) { + if(array[z] == elem) + return z; + } + return -1; + } + + public static int indexOfChecked(T[] array, T elem) { + for(int z = 0; z < array.length; z++) { + if(array[z] == elem) + return z; + } + throw new IllegalArgumentException("Objekt ist nicht in Array"); + } + + public static Boolean parseBoolean(String str) { + if("1".equals(str) || "true".equalsIgnoreCase(str) || "on".equalsIgnoreCase(str) || "yes".equalsIgnoreCase(str) || "y".equalsIgnoreCase(str)) + return true; + else if("0".equals(str) || "false".equalsIgnoreCase(str) || "off".equalsIgnoreCase(str) || "no".equalsIgnoreCase(str) || "n".equalsIgnoreCase(str)) + return false; + return null; + } + + public static String buildLines(String separator, Function func, Iterable elems) { + StringBuilder sb = new StringBuilder(); + for(T elem : elems) { + if(sb.length() > 0) + sb.append(separator); + sb.append(func.apply(elem)); + } + return sb.toString(); + } + + public static String buildLines(Function func, Iterable elems) { + return buildLines("\n", func, elems); + } + + public static String buildLines(String separator, Iterable elems) { + return buildLines(separator, new Function() { + public String apply(T t) { + return String.valueOf(t); + } + }, elems); + } + + public static String buildLines(Iterable elems) { + return buildLines("\n", elems); + } + + public static String buildLines(String separator, Function func, T ... elems) { + StringBuilder sb = new StringBuilder(); + for(T elem : elems) { + if(sb.length() > 0) + sb.append(separator); + sb.append(func.apply(elem)); + } + return sb.toString(); + } + + public static String buildLines(Function func, T ... elems) { + return buildLines("\n", func, elems); + } + + public static String buildLines(String separator, T ... elems) { + return buildLines(separator, new Function() { + public String apply(T t) { + return String.valueOf(t); + } + }, elems); + } + + public static String buildLines(T ... elems) { + return buildLines("\n", elems); + } + + public static int mixColor(int c1, int c2) { + return ((((c1 >> 24 & 255) + (c2 >> 24 & 255)) / 2) << 24) | ((((c1 >> 16 & 255) + (c2 >> 16 & 255)) / 2) << 16) | ((((c1 >> 8 & 255) + (c2 >> 8 & 255)) / 2) << 8) | + (((c1 & 255) + (c2 & 255)) / 2); + } + + public static int mulColor(int color, float brightness) { + int mul = ExtMath.clampi((int)(brightness * 255.0f), 0, 255); + return (color & 0xff000000) | ((((color >> 16 & 255) * mul) / 255) << 16) | ((((color >> 8 & 255) * mul) / 255) << 8) | + (((color & 255) * mul) / 255); + } + + public static void checkPlatform() { + int feature; + try { + feature = Runtime.version().feature(); + } + catch(Throwable t) { + feature = 0; + } + String info = null; + String msg = null; + if(System.getProperty("os.name").startsWith("Mac")) { + info = "Inkompatibles Betriebssystem"; + msg = "Linux, *BSD oder Windows ist erforderlich, um dieses Programm\n" + + "auszuführen. Alle Versionen von Mac OS (X) sind nicht kompatibel."; + } + else if(feature < MIN_JAVA_FEATURE) { + info = "Inkompatible Java-Version"; + msg = "Java " + MIN_JAVA_FEATURE + " oder höher ist erforderlich, um dieses Programm auszuführen."; + } + if(info != null) { + System.err.println("#################################################################"); + System.err.println("*** " + info + " ***"); + System.err.println(msg); + System.err.println("#################################################################"); + if(!GraphicsEnvironment.isHeadless()) + JOptionPane.showMessageDialog(null, msg, info, JOptionPane.ERROR_MESSAGE); + System.exit(1); + } + } + + public static void setupHandlers() { + Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { + public void uncaughtException(Thread thread, Throwable e) { + System.err.println("Fehler in Thread '" + thread.getName() + "'"); + e.printStackTrace(System.err); + if(crashed) + System.exit(1); + if(e instanceof OutOfMemoryError) { + System.gc(); + System.gc(); + } + if(!thread.getName().startsWith("Thread-") || e instanceof OutOfMemoryError) { + System.err.println("Beende!"); + crashed = true; + if(!DEVMODE) { + PrintStream ps = null; + File report = null; + try { + Date date = new Date(); + File file = new File("crash-" + new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(date) + ".txt"); + FileOutputStream out = new FileOutputStream(file); + ps = new PrintStream(out); + ThreadMXBean bean = ManagementFactory.getThreadMXBean(); + ThreadInfo[] info = bean.dumpAllThreads(true, true); + StringBuilder sb = new StringBuilder(); + Error error = new Error(); + for(ThreadInfo threadinfo : info) { + if(threadinfo.getThreadId() == thread.threadId()) + error.setStackTrace(threadinfo.getStackTrace()); + sb.append(threadinfo); + } + ps.println("************************************************ " + new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date) + " ************************************************"); + ps.println(); + ps.println("\"Wie haste das denn nu wieder geschafft, Bursche?\""); + ps.println("Unerwarteter Fehler in Thread '" + thread.getName() + "':"); + e.printStackTrace(ps); + ps.println(); + ps.println("---------------------------------------------- Thread-Dump (" + info.length + " Threads) ---------------------------------------------"); + ps.println(); + ps.print(sb.toString()); + ps.println("*********************************************************************************************************************"); + report = file; + } + catch(Throwable t) { + System.err.println("Konnte Absturzbericht nicht speichern:"); + t.printStackTrace(System.err); + } + finally { + if(ps != null) + ps.close(); + } + if(report != null) { + System.err.println("Absturzbericht gespeichert unter " + report.getPath()); + try { + Desktop.getDesktop().browse(report.toURI()); + } + catch(Throwable e1) { + System.err.println("Konnte " + report + " nicht öffnen: " + e1); + } + } + } + System.exit(1); + } + } + }); + ImageIO.setUseCache(false); + Thread timer = new Thread("Timer Hack Thread") { + public void run() { + while(true) { + try { + Thread.sleep(2147483647L); + } + catch(InterruptedException e) { + ; + } + } + } + }; + timer.setDaemon(true); + timer.start(); + System.setProperty("java.net.preferIPv4Stack", "true"); + } + + public static void addShutdownHook(final Runnable hook) { + Runtime.getRuntime().addShutdownHook(new Thread("Game Shutdown Thread") { + public void run() { + if(!crashed) { + try { + hook.run(); + } + catch(Throwable e) { + e.printStackTrace(); + } + } + } + }); + } + + // plr_play("/home/sen/Musik/midi50k/Video_Games/ff/ff2cecil.mid", 0); + public static void meltdown() { + Random rand = new Random(); + Log.SYSTEM.error("CORE_MELTDOWN: Nuclear processor core meltdown imminent\n\n" + + " ************************ CAUTION ************************\n" + + " KCTL: Processor core #%02d has reached a critical\n" + + " temperature, system explosion is imminent! \n" + + " According to the general core density \n" + + " calculation routine defined by the SKC \n" + + " (Hard) Warfare Testing Facility (SKC-WTF) \n" + + " your processor will cause a detonation with \n" + + " a radius of (roughly) %d.%d kilometers. \n" + + " In addition, it will release appoximately \n" + + " %d megajoules of ionizing radiation. \n" + + " You have an estimate time of %d minutes and \n" + + " %d seconds left to clear the detonation area. \n" + + " ************************ CAUTION ************************\n" + , rand.range(1, 64), rand.range(1, 9), rand.range(0, 9), rand.range(10000, 39999), rand.range(3, 9), rand.range(2, 59)); + } + + public static Pair getKeyValue(String text, char separator) { + int index = text.indexOf(separator); + if(index == -1) + return new Pair(text, null); + return new Pair(text.substring(0, index), text.substring(index + 1)); + } + + public static Pair getKeyValue(String text) { + return getKeyValue(text, ' '); + } + + private static Object parseObject(String arg) { + try { + return Float.parseFloat(arg); + } + catch(NumberFormatException e) { + } + try { + return Integer.parseInt(arg); + } + catch(NumberFormatException e) { + } + return arg; + } + + public static Map parseArgsSimple(String[] args) { + Map map = Maps.newHashMap(); + List list = Lists.newArrayList(); + String option = null; + boolean parse = true; + for(int z = 0; z < args.length; z++) { + String arg = args[z]; + if(arg.startsWith("--")) { + if(arg.length() == 2) { + parse = false; + continue; + } + if(option != null) + map.put(option, null); + option = arg.substring(2); + } + else if(arg.startsWith("-") && arg.length() == 2) { + if(option != null) + map.put(option, null); + option = arg.substring(1); + } + else if(option != null) { + map.put(option, parseObject(arg)); + option = null; + } + else { + list.add(parseObject(arg)); + } + } + if(option != null) + map.put(option, null); + map.put("__pos", list); + return map; + } + + public static long getTime() { + return System.nanoTime() / 1000L; // glfwGetTimerValue() / (glfwGetTimerFrequency() / 1000000L); + } + + public static long rtime() { + return Util.getTime() - START; + } + + public static double ftime() { + return ((double)rtime()) / 1000000.0; + } + + public static String getRegionFolder(int x, int z) { + return String.format("%c%03X%c%03X", x < 0 ? 'n' : 'p', ((x < 0) ? -x : x) >> 9, z < 0 ? 'n' : 'p', ((z < 0) ? -z : z) >> 9); + } + + public static String getRegionName(int x, int z) { + return String.format("r.%c%X%c%X.rgn", x < 0 ? 'n' : 'p', ((x < 0) ? -x : x) >> 3, z < 0 ? 'n' : 'p', ((z < 0) ? -z : z) >> 3); + } + + public static String repeatString(Object obj, int count) { + StringBuilder sb = new StringBuilder(); + for(int z = 0; z < count; z++) { + sb.append(obj); + } + return sb.toString(); + } + + public static String getHexString(byte[] bytes) { + StringBuilder sb = new StringBuilder(); + for(int z = 0; z < bytes.length; z++) { + sb.append(String.format("%02x", bytes[z])); + } + return sb.toString(); + } + + public static byte[] fromHexString(String str) { + if((str.length() & 1) == 1) + str = "0" + str; + byte[] bytes = new byte[str.length() / 2]; + try { + for(int z = 0; z < bytes.length; z++) { + bytes[z] = (byte)Integer.parseUnsignedInt(str.substring(z * 2, (z + 1) * 2), 16); + } + } + catch(NumberFormatException e) { + return null; + } + return bytes; + } + + public static String breakString(String str, int width) { + StringBuilder sb = new StringBuilder(); + for(int z = 0; z < str.length() / width; z++) { + sb.append(str.substring(z * width, (z + 1) * width)).append('\n'); + } + return sb.append(str.substring(str.length() - (str.length() % width), str.length())).toString(); + } + + public static String sanitizeCommonName(String str) { + str = str.trim(); + StringBuilder sb = new StringBuilder(); + boolean hyphen = true; + for(int z = 0; z < str.length(); z++) { + char ch = Character.toLowerCase(str.charAt(z)); + if((ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9')) { + sb.append(ch); + hyphen = false; + } + else if(ch == '-' || ch == ' ') { + if(!hyphen) + sb.append('-'); + hyphen = true; + } + } + return sb.length() > 0 && sb.charAt(sb.length() - 1) == '-' ? sb.substring(0, sb.length() - 1) : sb.toString(); + } + + public static boolean isValidCommonName(String str) { + boolean hyphen = true; + for(int z = 0; z < str.length(); z++) { + char ch = Character.toLowerCase(str.charAt(z)); + if((ch < 'a' || ch > 'z') && (ch < '0' || ch > '9') && ch != '-') + return false; + if(ch == '-' && hyphen) + return false; + hyphen = ch == '-'; + } + return !hyphen; + } + + public static void throwUnchecked(Throwable t) { + throw t instanceof RuntimeException ? (RuntimeException)t : new RuntimeException(t); + } +} diff --git a/common/src/main/java/common/util/Var.java b/common/src/main/java/common/util/Var.java new file mode 100644 index 0000000..3951c15 --- /dev/null +++ b/common/src/main/java/common/util/Var.java @@ -0,0 +1,16 @@ +package common.util; + +import static java.lang.annotation.ElementType.FIELD; + +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; +import java.lang.annotation.Target; + +@Target(FIELD) +@Retention(value = RetentionPolicy.RUNTIME) +public @interface Var { + String name(); + float min() default (float)Integer.MIN_VALUE; + float max() default (float)Integer.MAX_VALUE; + boolean nonDefault() default false; +} \ No newline at end of file diff --git a/java/src/game/world/Vec3.java b/common/src/main/java/common/util/Vec3.java similarity index 96% rename from java/src/game/world/Vec3.java rename to common/src/main/java/common/util/Vec3.java index 8392614..e183bf1 100755 --- a/java/src/game/world/Vec3.java +++ b/common/src/main/java/common/util/Vec3.java @@ -1,7 +1,4 @@ -package game.world; - -import game.renderer.model.PositionTextureVertex; -import game.util.ExtMath; +package common.util; public class Vec3 { @@ -211,9 +208,4 @@ public class Vec3 double d2 = this.zCoord * (double)f - this.xCoord * (double)f1; return new Vec3(d0, d1, d2); } - - public PositionTextureVertex toTextureVertex(float tx, float ty) - { - return new PositionTextureVertex(this, tx, ty); - } } diff --git a/java/src/game/world/Vec3i.java b/common/src/main/java/common/util/Vec3i.java similarity index 98% rename from java/src/game/world/Vec3i.java rename to common/src/main/java/common/util/Vec3i.java index 6c03512..87ad35e 100755 --- a/java/src/game/world/Vec3i.java +++ b/common/src/main/java/common/util/Vec3i.java @@ -1,6 +1,4 @@ -package game.world; - -import game.util.ExtMath; +package common.util; public class Vec3i implements Comparable { diff --git a/java/src/game/renderer/Vector.java b/common/src/main/java/common/util/Vector.java similarity index 99% rename from java/src/game/renderer/Vector.java rename to common/src/main/java/common/util/Vector.java index c877b86..2388ca6 100644 --- a/java/src/game/renderer/Vector.java +++ b/common/src/main/java/common/util/Vector.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package game.renderer; +package common.util; import java.io.Serializable; import java.nio.FloatBuffer; diff --git a/java/src/game/renderer/Vector3f.java b/common/src/main/java/common/util/Vector3f.java similarity index 98% rename from java/src/game/renderer/Vector3f.java rename to common/src/main/java/common/util/Vector3f.java index 777b6bc..5416ce5 100644 --- a/java/src/game/renderer/Vector3f.java +++ b/common/src/main/java/common/util/Vector3f.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package game.renderer; +package common.util; import java.io.Serializable; import java.nio.FloatBuffer; @@ -252,7 +252,7 @@ public class Vector3f extends Vector implements Serializable { /* (non-Javadoc) * @see org.lwjgl.vector.Vector#load(FloatBuffer) */ - public Vector load(FloatBuffer buf) { + public Vector3f load(FloatBuffer buf) { x = buf.get(); y = buf.get(); z = buf.get(); @@ -262,7 +262,7 @@ public class Vector3f extends Vector implements Serializable { /* (non-Javadoc) * @see org.lwjgl.vector.Vector#scale(float) */ - public Vector scale(float scale) { + public Vector3f scale(float scale) { x *= scale; y *= scale; @@ -275,7 +275,7 @@ public class Vector3f extends Vector implements Serializable { /* (non-Javadoc) * @see org.lwjgl.vector.Vector#store(FloatBuffer) */ - public Vector store(FloatBuffer buf) { + public Vector3f store(FloatBuffer buf) { buf.put(x); buf.put(y); diff --git a/java/src/game/renderer/Vector4f.java b/common/src/main/java/common/util/Vector4f.java similarity index 99% rename from java/src/game/renderer/Vector4f.java rename to common/src/main/java/common/util/Vector4f.java index 58b8831..ce15037 100644 --- a/java/src/game/renderer/Vector4f.java +++ b/common/src/main/java/common/util/Vector4f.java @@ -29,7 +29,7 @@ * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -package game.renderer; +package common.util; import java.io.Serializable; import java.nio.FloatBuffer; diff --git a/java/src/game/world/WorldPos.java b/common/src/main/java/common/util/WorldPos.java similarity index 97% rename from java/src/game/world/WorldPos.java rename to common/src/main/java/common/util/WorldPos.java index bf49eac..c23895c 100755 --- a/java/src/game/world/WorldPos.java +++ b/common/src/main/java/common/util/WorldPos.java @@ -1,4 +1,4 @@ -package game.world; +package common.util; public class WorldPos extends BlockPos { private final int dim; diff --git a/common/src/main/java/common/vars/Vars.java b/common/src/main/java/common/vars/Vars.java new file mode 100755 index 0000000..a704e68 --- /dev/null +++ b/common/src/main/java/common/vars/Vars.java @@ -0,0 +1,259 @@ +package common.vars; + +import common.util.Var; + +public abstract class Vars { + @Var(name = "fireTick") + public static boolean fire = true; + @Var(name = "mobGriefing") + public static boolean mobGrief = true; + @Var(name = "mobSpawning") + public static boolean mobs = true; + @Var(name = "spawners") + public static boolean spawners = true; + @Var(name = "spawnEggChickens") + public static boolean spawnEggChicken = true; + @Var(name = "spawnSplitSlimes") + public static boolean spawnSplitSlime = true; + @Var(name = "chargeHaunter") + public static boolean chargeHaunter = true; + @Var(name = "convertVillageZombie") + public static boolean convertZombie = true; + @Var(name = "dropLoot") + public static boolean dropLoot = true; + @Var(name = "dropBlockXP") + public static boolean blockXP = true; + @Var(name = "dropBreedingXP") + public static boolean breedingXP = true; + @Var(name = "dropSmeltingXP") + public static boolean smeltingXP = true; + @Var(name = "dropFishingXP") + public static boolean fishingXP = true; + @Var(name = "dropMobXP") + public static boolean mobXP = true; + @Var(name = "dropBlocks") + public static boolean blockDrop = true; + @Var(name = "dropObjects") + public static boolean objectDrop = true; + @Var(name = "naturalRegeneration") + public static boolean regeneration = true; + @Var(name = "seasonLeafUpdate") + public static boolean seasonLeaves = true; + @Var(name = "leavesDecay") + public static boolean leavesDecay = true; + @Var(name = "repairExperience") + public static boolean repairXP = true; + @Var(name = "mobTick") + public static boolean mobTick = true; + @Var(name = "mobAttacks") + public static boolean mobAttacks = true; + @Var(name = "portals") + public static boolean portals = true; + @Var(name = "portalVoid") + public static boolean voidPortal = true; + @Var(name = "dropPlayerItems") + public static boolean playerDrop = true; + @Var(name = "blockGravity") + public static boolean blockGravity = true; + @Var(name = "liquidPhysics") + public static boolean liquidPhysics = true; + @Var(name = "lavaFire") + public static boolean lavaFire = true; + @Var(name = "mergeWater") + public static boolean mergeWater = true; + @Var(name = "mergeInfinite") + public static boolean mergeInfinite = true; + @Var(name = "infighting") + public static boolean infight = true; + @Var(name = "damageFall") + public static boolean damageFall = true; + @Var(name = "damageFire") + public static boolean damageFire = true; + @Var(name = "damageLava") + public static boolean damageLava = true; + @Var(name = "damageMolten") + public static boolean damageMolten = true; + @Var(name = "damageLightning") + public static boolean damageLightning = true; + @Var(name = "damageSquish") + public static boolean damageSquish = true; + @Var(name = "damageAcme") + public static boolean damageAcme = true; + @Var(name = "damageRadiation") + public static boolean damageRadiation = true; + @Var(name = "damagePoison") + public static boolean damagePoison = true; + @Var(name = "damagePotion") + public static boolean damagePotion = true; + @Var(name = "damageFlyingBox") + public static boolean damageFlyingBox = true; + @Var(name = "damageVoid") + public static boolean damageVoid = true; + @Var(name = "damageThorns") + public static boolean damageThorns = true; + @Var(name = "damageFireball") + public static boolean damageFireball = true; + @Var(name = "damageArrow") + public static boolean damageArrow = true; + @Var(name = "damageBullet") + public static boolean damageBullet = true; + @Var(name = "damageMobs") + public static boolean damageMobs = true; + @Var(name = "damageExplosion") + public static boolean damageExplosion = true; + @Var(name = "damageWall") + public static boolean damageWall = true; + @Var(name = "radiation") + public static boolean radiation = true; + @Var(name = "anvilFallDecay") + public static boolean anvilFallDecay = true; + @Var(name = "anvilRepairDecay") + public static boolean anvilRepairDecay = true; + @Var(name = "attacking") + public static boolean attack = true; + @Var(name = "cactusPrickly") + public static boolean cactusDamage = true; + @Var(name = "waterMobDrying") + public static boolean waterMobDry = true; + @Var(name = "itemBurning") + public static boolean itemBurn = true; + @Var(name = "xpOrbBurning") + public static boolean xpOrbBurn = true; + @Var(name = "smackingOrb") + public static boolean knockOrb = true; + @Var(name = "smackingDynamite") + public static boolean knockDynamite = true; + @Var(name = "smackingEgg") + public static boolean knockEgg = true; + @Var(name = "smackingSnowball") + public static boolean knockSnowball = true; + @Var(name = "smackingFishHook") + public static boolean knockHook = true; + @Var(name = "entityFishing") + public static boolean hookEntity = true; + @Var(name = "hookingRequiresDamage") + public static boolean hookCheckDamage = true; + @Var(name = "grassSpread") + public static boolean grassSpread = true; + @Var(name = "blackenedSoilSpread") + public static boolean darkSoilSpread = true; + @Var(name = "blackenedDirtSpread") + public static boolean darkDirtSpread = true; + @Var(name = "grassDecay") + public static boolean grassDecay = true; + @Var(name = "blackenedSoilDecay") + public static boolean darkSoilDecay = true; + @Var(name = "grassDrying") + public static boolean grassDry = true; + @Var(name = "tallgrassDrying") + public static boolean tallgrassDry = true; + @Var(name = "flowerDrying") + public static boolean flowerDry = true; + @Var(name = "plantDrying") + public static boolean plantDry = true; + @Var(name = "leafDrying") + public static boolean leafDry = true; + @Var(name = "saplingDrying") + public static boolean saplingDry = true; + @Var(name = "reedDrying") + public static boolean reedDry = true; + @Var(name = "vineDrying") + public static boolean vineDry = true; + @Var(name = "myceliumSpread") + public static boolean mycelSpread = true; + @Var(name = "myceliumDecay") + public static boolean mycelDecay = true; + @Var(name = "farmlandDecay") + public static boolean cropDecay = true; + @Var(name = "farmlandDrying") + public static boolean cropDrying = true; + @Var(name = "farmlandSoaking") + public static boolean cropSoaking = true; + @Var(name = "farmlandTrampling") + public static boolean cropTrampling = true; + @Var(name = "iceMelting") + public static boolean iceMelt = true; + @Var(name = "snowMelting") + public static boolean snowMelt = true; + @Var(name = "snowBlockMelting") + public static boolean snowFullMelt = true; + @Var(name = "chestLocking") + public static boolean locking = true; + @Var(name = "teleFragging") + public static boolean telefrag = true; + @Var(name = "chunkLoaders") + public static boolean loaders = true; + @Var(name = "fragileItems") + public static boolean itemFallDamage = true; + @Var(name = "signEditing") + public static boolean editSigns = true; + + @Var(name = "keepInventory") + public static boolean keepInventory = false; + @Var(name = "cleanCut") + public static boolean cleanCut = false; + @Var(name = "mergeLava") + public static boolean mergeLava = false; + @Var(name = "mergeFinite") + public static boolean mergeFinite = false; + @Var(name = "veryHungryRabbits") + public static boolean rabidRabbits = false; + @Var(name = "evilFowl") + public static boolean aggressiveChickens = false; + + @Var(name = "hurtCooldown") + public static int hurtDelay = 20; + @Var(name = "attackCooldown") + public static int attackDelay = 0; + @Var(name = "pistonPushLimit") + public static int pistonLimit = 16; + @Var(name = "gravelFlintChance") + public static int flintChance = 10; + @Var(name = "rabbitMateChance") + public static int rabbitMateChance = 10; + @Var(name = "killerBunnyChance") + public static int killerBunnyChance = 1000; + @Var(name = "evilChickenChance") + public static int evilChickenChance = 700; + @Var(name = "fallPortalHeight") + public static int portalHeight = 256; + @Var(name = "damageOrb") + public static int orbDamageSelf = 5; + @Var(name = "vineGrowthChance") + public static int vineGrowth = 4; + @Var(name = "blueShroomChance") + public static int blueShroomGrowth = 25; + @Var(name = "mushroomChance") + public static int shroomGrowth = 25; + @Var(name = "cropGrowthChance") + public static int cropGrowth = 26; + @Var(name = "stemGrowthChance") + public static int stemGrowth = 26; + @Var(name = "treeGrowthChance") + public static int treeGrowth = 7; + @Var(name = "wartGrowthChance") + public static int wartGrowth = 10; + @Var(name = "cocoaGrowthChance") + public static int cocoaGrowth = 5; + @Var(name = "reedGrowthHeight") + public static int reedHeight = 3; + @Var(name = "cactusGrowthHeight") + public static int cactusHeight = 3; + @Var(name = "orbThorns") + public static int orbDamageOther = 0; + @Var(name = "healChance") + public static int healChance = 5; + @Var(name = "hopperCooldown", min = 0, max = 160) + public static int hopperDelay = 2; + @Var(name = "hopperCartCooldown", min = 0, max = 160) + public static int hopperCartDelay = 1; + @Var(name = "xpCooldown", min = 0, max = 10) + public static int xpDelay = 0; // 2 + @Var(name = "eggLayTime") + public static int eggTimer = 6000; + @Var(name = "spawnMoreZombies") + public static int spawnMoreZombie = 25; + + @Var(name = "knockback") + public static float knockback = 1.0f; +} diff --git a/common/src/main/java/common/village/MerchantRecipe.java b/common/src/main/java/common/village/MerchantRecipe.java new file mode 100755 index 0000000..f21db8e --- /dev/null +++ b/common/src/main/java/common/village/MerchantRecipe.java @@ -0,0 +1,32 @@ +package common.village; + +import common.item.Item; +import common.item.ItemStack; +import common.tags.TagObject; + +public record MerchantRecipe(ItemStack first, ItemStack second, ItemStack result) { + public MerchantRecipe(TagObject tag) { + this(ItemStack.readFromTag(tag.getObject("buy")), tag.hasObject("buyB") ? ItemStack.readFromTag(tag.getObject("buyB")) : null, ItemStack.readFromTag(tag.getObject("sell"))); + } + + public MerchantRecipe(ItemStack buy, ItemStack sell) { + this(buy, null, sell); + } + + public MerchantRecipe(ItemStack buy, Item sell) { + this(buy, new ItemStack(sell)); + } + + public boolean both() { + return this.second != null; + } + + public TagObject toTags() { + TagObject tag = new TagObject(); + tag.setObject("buy", this.first.writeTags(new TagObject())); + tag.setObject("sell", this.result.writeTags(new TagObject())); + if(this.second != null) + tag.setObject("buyB", this.second.writeTags(new TagObject())); + return tag; + } +} diff --git a/common/src/main/java/common/village/MerchantRecipeList.java b/common/src/main/java/common/village/MerchantRecipeList.java new file mode 100755 index 0000000..f430552 --- /dev/null +++ b/common/src/main/java/common/village/MerchantRecipeList.java @@ -0,0 +1,53 @@ +package common.village; + +import java.util.ArrayList; + +import common.collect.Lists; +import common.item.ItemStack; +import common.tags.TagObject; +import java.util.List; + +public class MerchantRecipeList extends ArrayList { + public MerchantRecipe canUse(ItemStack stack1, ItemStack stack2, int index) { + if(index > 0 && index < this.size()) { + MerchantRecipe recipe = this.get(index); + return !areItemsSimilar(stack1, recipe.first()) + || (stack2 != null || recipe.both()) + && (!recipe.both() || !areItemsSimilar(stack2, recipe.second())) + || stack1.size < recipe.first().size + || recipe.both() && stack2.size < recipe.second().size ? null : recipe; + } + else { + for(int z = 0; z < this.size(); z++) { + MerchantRecipe recipe = this.get(z); + if(areItemsSimilar(stack1, recipe.first()) && stack1.size >= recipe.first().size + && (!recipe.both() && stack2 == null + || recipe.both() && areItemsSimilar(stack2, recipe.second()) + && stack2.size >= recipe.second().size)) { + return recipe; + } + } + return null; + } + } + + private static boolean areItemsSimilar(ItemStack stack1, ItemStack stack2) { + return ItemStack.areItemsEqual(stack1, stack2) + && (!stack2.hasTagCompound() || stack1.hasTagCompound() && TagObject.compare(stack2.getTagCompound(), stack1.getTagCompound())); + } + + public void fromTags(List list) { + this.clear(); + for(int z = 0; z < list.size(); z++) { + this.add(new MerchantRecipe(list.get(z))); + } + } + + public List toTags() { + List list = Lists.newArrayList(); + for(int z = 0; z < this.size(); z++) { + list.add(this.get(z).toTags()); + } + return list; + } +} diff --git a/java/src/game/village/Village.java b/common/src/main/java/common/village/Village.java similarity index 61% rename from java/src/game/village/Village.java rename to common/src/main/java/common/village/Village.java index 7cde6fe..0e6f693 100755 --- a/java/src/game/village/Village.java +++ b/common/src/main/java/common/village/Village.java @@ -1,17 +1,15 @@ -package game.village; +package common.village; import java.util.Iterator; import java.util.List; -import game.collect.Lists; - -import game.block.Block; -import game.block.BlockDoor; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.world.BlockPos; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.artificial.BlockDoor; +import common.collect.Lists; +import common.tags.TagObject; +import common.util.BlockPos; +import common.world.AWorldServer; public class Village { @@ -25,17 +23,17 @@ public class Village // { // } // -// public Village(WorldServer worldIn) +// public Village(IWorldServer worldIn) // { // this.worldObj = worldIn; // } // -// public void setWorld(WorldServer worldIn) +// public void setWorld(IWorldServer worldIn) // { // this.worldObj = worldIn; // } - public void tick(WorldServer world, int counter) + public void tick(AWorldServer world, int counter) { // this.tickCounter = counter; boolean mod = false; @@ -181,10 +179,10 @@ public class Village return this.doors.isEmpty(); } - private boolean isWoodDoor(WorldServer world, BlockPos pos) + private boolean isWoodDoor(AWorldServer world, BlockPos pos) { Block block = world.getState(pos).getBlock(); - return block instanceof BlockDoor ? block.getMaterial() == Material.wood : false; + return block instanceof BlockDoor ? block.getMaterial() == Material.WOOD : false; } private void updatePosition() @@ -210,52 +208,44 @@ public class Village } } - public void readVillageDataFromNBT(NBTTagCompound compound) + public void readTags(TagObject tag) { -// this.numVillagers = compound.getInteger("PopSize"); - this.radius = compound.getInteger("Radius"); -// this.lastDoor = compound.getInteger("Stable"); -// this.tickCounter = compound.getInteger("Tick"); -// this.noBreedTicks = compound.getInteger("MTick"); - this.center = new BlockPos(compound.getInteger("CX"), compound.getInteger("CY"), compound.getInteger("CZ")); - this.doorRange = new BlockPos(compound.getInteger("ACX"), compound.getInteger("ACY"), compound.getInteger("ACZ")); - NBTTagList nbttaglist = compound.getTagList("Doors", 10); + this.radius = tag.getInt("Radius"); + this.center = new BlockPos(tag.getInt("CX"), tag.getInt("CY"), tag.getInt("CZ")); + this.doorRange = new BlockPos(tag.getInt("ACX"), tag.getInt("ACY"), tag.getInt("ACZ")); + List doors = tag.getList("Doors"); - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < doors.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); - VillageDoorInfo villagedoorinfo = new VillageDoorInfo(new BlockPos(nbttagcompound.getInteger("X"), nbttagcompound.getInteger("Y"), nbttagcompound.getInteger("Z")), nbttagcompound.getInteger("IDX"), nbttagcompound.getInteger("IDZ"), nbttagcompound.getInteger("TS")); - this.doors.add(villagedoorinfo); + TagObject door = doors.get(i); + VillageDoorInfo info = new VillageDoorInfo(new BlockPos(door.getInt("X"), door.getInt("Y"), door.getInt("Z")), door.getInt("IDX"), door.getInt("IDZ"), door.getInt("TS")); + this.doors.add(info); } } - public void writeVillageDataToNBT(NBTTagCompound compound) + public void writeTags(TagObject tag) { -// compound.setInteger("PopSize", this.numVillagers); - compound.setInteger("Radius", this.radius); -// compound.setInteger("Stable", this.lastDoor); -// compound.setInteger("Tick", this.tickCounter); -// compound.setInteger("MTick", this.noBreedTicks); - compound.setInteger("CX", this.center.getX()); - compound.setInteger("CY", this.center.getY()); - compound.setInteger("CZ", this.center.getZ()); - compound.setInteger("ACX", this.doorRange.getX()); - compound.setInteger("ACY", this.doorRange.getY()); - compound.setInteger("ACZ", this.doorRange.getZ()); - NBTTagList nbttaglist = new NBTTagList(); + tag.setInt("Radius", this.radius); + tag.setInt("CX", this.center.getX()); + tag.setInt("CY", this.center.getY()); + tag.setInt("CZ", this.center.getZ()); + tag.setInt("ACX", this.doorRange.getX()); + tag.setInt("ACY", this.doorRange.getY()); + tag.setInt("ACZ", this.doorRange.getZ()); + List doors = Lists.newArrayList(); - for (VillageDoorInfo villagedoorinfo : this.doors) + for (VillageDoorInfo info : this.doors) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setInteger("X", villagedoorinfo.getDoorBlockPos().getX()); - nbttagcompound.setInteger("Y", villagedoorinfo.getDoorBlockPos().getY()); - nbttagcompound.setInteger("Z", villagedoorinfo.getDoorBlockPos().getZ()); - nbttagcompound.setInteger("IDX", villagedoorinfo.getInsideOffsetX()); - nbttagcompound.setInteger("IDZ", villagedoorinfo.getInsideOffsetZ()); - nbttagcompound.setInteger("TS", villagedoorinfo.getInsidePosY()); - nbttaglist.appendTag(nbttagcompound); + TagObject door = new TagObject(); + door.setInt("X", info.getDoorBlockPos().getX()); + door.setInt("Y", info.getDoorBlockPos().getY()); + door.setInt("Z", info.getDoorBlockPos().getZ()); + door.setInt("IDX", info.getInsideOffsetX()); + door.setInt("IDZ", info.getInsideOffsetZ()); + door.setInt("TS", info.getInsidePosY()); + doors.add(door); } - compound.setTag("Doors", nbttaglist); + tag.setList("Doors", doors); } } diff --git a/java/src/game/village/VillageDoorInfo.java b/common/src/main/java/common/village/VillageDoorInfo.java similarity index 97% rename from java/src/game/village/VillageDoorInfo.java rename to common/src/main/java/common/village/VillageDoorInfo.java index 4a27a2d..530d309 100755 --- a/java/src/game/village/VillageDoorInfo.java +++ b/common/src/main/java/common/village/VillageDoorInfo.java @@ -1,7 +1,7 @@ -package game.village; +package common.village; -import game.world.BlockPos; -import game.world.Facing; +import common.util.BlockPos; +import common.util.Facing; public class VillageDoorInfo { diff --git a/common/src/main/java/common/world/AWorldClient.java b/common/src/main/java/common/world/AWorldClient.java new file mode 100644 index 0000000..3b12d01 --- /dev/null +++ b/common/src/main/java/common/world/AWorldClient.java @@ -0,0 +1,15 @@ +package common.world; + +import common.dimension.Dimension; +import common.init.SoundEvent; +import common.tags.TagObject; + +public abstract class AWorldClient extends World { + protected AWorldClient(Dimension dim) { + super(dim, true); + } + + public abstract void playSound(double x, double y, double z, SoundEvent sound, float volume); + public abstract void makeFireworks(double x, double y, double z, double motionX, double motionY, double motionZ, TagObject compund); + public abstract void setLastLightning(int last, int color); +} diff --git a/common/src/main/java/common/world/AWorldServer.java b/common/src/main/java/common/world/AWorldServer.java new file mode 100644 index 0000000..e91f4ec --- /dev/null +++ b/common/src/main/java/common/world/AWorldServer.java @@ -0,0 +1,50 @@ +package common.world; + +import java.util.List; + +import common.biome.Biome; +import common.block.Block; +import common.dimension.Dimension; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.model.ParticleType; +import common.network.IPlayer; +import common.network.Packet; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.PortalType; +import common.village.Village; + +public abstract class AWorldServer extends World { + protected AWorldServer(Dimension dim) { + super(dim, false); + } + + public abstract List getAllPlayers(); + public abstract AWorldServer getOtherWorld(int dimension); + public abstract void placeInDimension(Entity entity, AWorldServer oldWorld, AWorldServer world, BlockPos pos, PortalType portal); + public abstract boolean addLoader(BlockPos pos); + public abstract boolean removeLoader(BlockPos pos); + public abstract boolean isBlockTickPending(BlockPos pos, Block blockType); + public abstract void updateBlockTick(BlockPos pos, Block blockIn, int delay, int priority); + public abstract void resetUpdateEntityTick(); + public abstract void strikeLightning(double x, double y, double z, int color, int damage, boolean fire, EntityLiving summoner); + public abstract void resetWeather(); + public abstract void spawnParticle(ParticleType particleType, double xCoord, double yCoord, double zCoord, int numberOfParticles, double xOffset, double yOffset, + double zOffset, double particleSpeed, int... particleArguments); + public abstract long getSeed(); + public abstract boolean isExterminated(); + public abstract boolean exterminate(); + public abstract Village getNearestVillage(BlockPos doorBlock, int radius); + public abstract void addToVillagerPositionList(BlockPos blockpos); + public abstract boolean isPlayerWatchingChunk(EntityNPC player, int chunkX, int chunkZ); + public abstract void sendToAllTrackingEntity(Entity entityIn, Packet packet); + public abstract boolean isDaytime(); + public abstract int getSkylightSubtracted(); + public abstract boolean isBlockinHighHumidity(BlockPos pos); + public abstract T findNearestEntityWithinAABB(Class entityType, BoundingBox aabb, T closestTo); + public abstract long getTime(); + public abstract void setBiome(BlockPos pos, Biome biome); + public abstract void markChunkDirty(BlockPos pos); +} diff --git a/java/src/game/world/BlockArray.java b/common/src/main/java/common/world/BlockArray.java similarity index 79% rename from java/src/game/world/BlockArray.java rename to common/src/main/java/common/world/BlockArray.java index e838cb8..12dd515 100755 --- a/java/src/game/world/BlockArray.java +++ b/common/src/main/java/common/world/BlockArray.java @@ -1,8 +1,11 @@ -package game.world; +package common.world; -import game.block.Block; -import game.init.BlockRegistry; -import game.init.Blocks; +import java.util.Arrays; + +import common.block.Block; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.util.NibbleArray; public class BlockArray { private int yBase; @@ -12,12 +15,17 @@ public class BlockArray { private NibbleArray blocklight; private NibbleArray skylight; - public BlockArray(int y, boolean sky) { + public BlockArray(int y, boolean sky, State filler) { this.yBase = y; this.data = new char[4096]; this.blocklight = new NibbleArray(); if(sky) this.skylight = new NibbleArray(); + if(filler != null && filler.getBlock() != Blocks.air) { + Arrays.fill(this.data, (char)BlockRegistry.STATEMAP.get(filler)); + this.blocks = this.data.length; + this.ticked = filler.getBlock().getTickRandomly() ? this.data.length : 0; + } } public State get(int x, int y, int z) { @@ -119,4 +127,12 @@ public class BlockArray { public void setSkylight(NibbleArray data) { this.skylight = data; } + + public int hashCode() { + return this.yBase >> 4; + } + + public boolean equals(Object other) { + return other instanceof BlockArray && ((BlockArray)other).yBase == this.yBase; + } } diff --git a/java/src/game/world/Chunk.java b/common/src/main/java/common/world/Chunk.java similarity index 56% rename from java/src/game/world/Chunk.java rename to common/src/main/java/common/world/Chunk.java index 51791fb..d86700b 100755 --- a/java/src/game/world/Chunk.java +++ b/common/src/main/java/common/world/Chunk.java @@ -1,174 +1,96 @@ -package game.world; +package common.world; import java.util.Arrays; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.ConcurrentLinkedQueue; - import java.util.function.Predicate; -import game.collect.Maps; -import game.biome.Biome; -import game.block.Block; -import game.block.ITileEntityProvider; -import game.entity.Entity; -import game.init.Blocks; -import game.log.Log; -import game.material.Material; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.util.ExtMath; -import game.worldgen.BiomeGenerator; -import game.worldgen.ChunkPrimer; -import game.worldgen.GeneratorDebug; +import common.block.Block; +import common.block.ITileEntityProvider; +import common.block.Material; +import common.collect.Maps; +import common.collect.Sets; +import common.entity.Entity; +import common.init.Blocks; +import common.log.Log; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.InheritanceMultiMap; +import common.util.ExtMath; +import common.util.Facing; +import common.util.IntHashMap; -public class Chunk { +public abstract class Chunk { public final int xPos; public final int zPos; - private final World world; - private final BlockArray[] blocks = new BlockArray[32]; - private final byte[] biomes = new byte[256]; - private final int[] precHeight = new int[256]; - private final boolean[] updateSky = new boolean[256]; - private final int[] height = new int[256]; - private final Map tiles = Maps.newHashMap(); - private final ClassInheritanceMultiMap[] entities = new ClassInheritanceMultiMap[32]; - private final ConcurrentLinkedQueue tileQueue = new ConcurrentLinkedQueue(); + protected final World world; + protected final State filler; + protected final Block fillerBlock; + protected final IntHashMap blocks = new IntHashMap(); + protected final Set blockList = Sets.newHashSet(); + protected final byte[] biomes = new byte[256]; + protected final int[] precHeight = new int[256]; + protected final boolean[] updateSky = new boolean[256]; + protected final int[] height = new int[256]; + protected final Map tiles = Maps.newHashMap(); + protected final InheritanceMultiMap[] entities = new InheritanceMultiMap[32]; + protected final ConcurrentLinkedQueue tileQueue = new ConcurrentLinkedQueue(); - private boolean loaded; - private boolean gapUpdate; - private boolean populated; - private boolean lightInit; - private boolean updated; - private boolean modified; - private boolean hasEntity; - private int minHeight; - private int lightChecks = 8192; - private long lastSave; - private long inhabited; + protected boolean loaded; + protected boolean gapUpdate; + protected boolean populated; + protected boolean lightInit; + protected boolean updated; + protected boolean modified; + protected boolean hasEntity; + protected int minHeight; + protected int lightChecks = Integer.MAX_VALUE; + protected int bottom = Integer.MAX_VALUE; + protected int top = Integer.MIN_VALUE; public Chunk(World world, int x, int z) { this.world = world; this.xPos = x; this.zPos = z; + this.filler = world.dimension.getFiller(); + this.fillerBlock = this.filler.getBlock(); for(int y = 0; y < this.entities.length; ++y) { - this.entities[y] = new ClassInheritanceMultiMap(Entity.class); + this.entities[y] = new InheritanceMultiMap(Entity.class); } - Arrays.fill(this.precHeight, -999); + Arrays.fill(this.precHeight, -99999999); Arrays.fill(this.biomes, (byte)-1); } - - public Chunk(World world, ChunkPrimer primer, State base, State ceil, Random rand, Biome[] biomes, int x, int z) { - this(world, x, z); - boolean sky = !world.dimension.hasNoLight(); - for(int bx = 0; bx < 16; ++bx) { - for(int bz = 0; bz < 16; ++bz) { - for(int by = 0; by < primer.height; ++by) { - State state = primer.get(bx, by, bz); - if(state.getBlock().getMaterial() != Material.air) { - int y = by >> 4; - if(this.blocks[y] == null) - this.blocks[y] = new BlockArray(y << 4, sky); - this.blocks[y].set(bx, by & 15, bz, state); - } - } - } - } - if(base != null) { - if(this.blocks[0] == null) - this.blocks[0] = new BlockArray(0, sky); - for(int bx = 0; bx < 16; ++bx) { - for(int bz = 0; bz < 16; ++bz) { - for(int by = 0; by < 5; ++by) { - if(by <= rand.zrange(5)) - this.blocks[0].set(bx, by, bz, base); - } - } - } - } - if(ceil != null) { - int y = (primer.height - 1) >> 4; - if(this.blocks[y] == null) - this.blocks[y] = new BlockArray(y << 4, sky); - y = (primer.height - 5) >> 4; - if(this.blocks[y] == null) - this.blocks[y] = new BlockArray(y << 4, sky); - for(int bx = 0; bx < 16; ++bx) { - for(int bz = 0; bz < 16; ++bz) { - for(int by = primer.height - 1; by >= primer.height - 5; --by) { - if(by >= (primer.height - 1) - rand.zrange(5)) - this.blocks[by >> 4].set(bx, by & 15, bz, ceil); - } - } - } - } - for(int n = 0; n < this.biomes.length; ++n) { - this.biomes[n] = (byte)biomes[n].id; - } - if(ceil == null) - this.genSkyLight(); - else - this.resetRelight(); - } - - public int getHeight(BlockPos pos) { - return this.getHeight(pos.getX() & 15, pos.getZ() & 15); - } - + public int getHeight(int x, int z) { return this.height[z << 4 | x]; } - - public int getTopSegment() { - for(int y = this.blocks.length - 1; y >= 0; --y) { - if(this.blocks[y] != null) { - return this.blocks[y].getY(); - } - } - - return 0; + + public BlockArray getArray(int y) { + return this.blocks.lookup(y); } - - public BlockArray[] getStorage() { - return this.blocks; + + protected void setArray(BlockArray array) { + int y = array.getY() >> 4; + this.blocks.addKey(y, array); + this.blockList.add(array); + y <<= 4; + this.bottom = y < this.bottom ? y : this.bottom; + this.top = y > this.top ? y : this.top; } - - protected void genHeights() { - int h = this.getTopSegment(); - this.minHeight = Integer.MAX_VALUE; - - for(int x = 0; x < 16; ++x) { - for(int z = 0; z < 16; ++z) { - this.precHeight[x + (z << 4)] = -999; - - for(int y = h + 16; y > 0; --y) { - Block block = this.getBlock0(x, y - 1, z); - - if(block.getLightOpacity() != 0) { - this.height[z << 4 | x] = y; - - if(y < this.minHeight) { - this.minHeight = y; - } - - break; - } - } - } - } - - this.modified = true; - } - + public void genSkyLight() { - int h = this.getTopSegment(); + int top = this.top; + int bottom = this.bottom; this.minHeight = Integer.MAX_VALUE; for(int x = 0; x < 16; ++x) { for(int z = 0; z < 16; ++z) { - this.precHeight[x + (z << 4)] = -999; + this.precHeight[x + (z << 4)] = -99999999; - for(int y = h + 16; y > 0; --y) { + for(int y = top + 16; y > bottom; --y) { if(this.getOpacity(x, y - 1, z) != 0) { this.height[z << 4 | x] = y; @@ -180,9 +102,9 @@ public class Chunk { } } - if(!this.world.dimension.hasNoLight()) { + if(!this.world.dimension.hasNoLight() && top != Integer.MIN_VALUE) { int l = 15; - int y = h + 16 - 1; + int y = top + 16 - 1; while(true) { int b = this.getOpacity(x, y, z); @@ -194,7 +116,7 @@ public class Chunk { l -= b; if(l > 0) { - BlockArray stor = this.blocks[y >> 4]; + BlockArray stor = this.getArray(y >> 4); if(stor != null) { stor.setSky(x, y & 15, z, l); @@ -204,7 +126,7 @@ public class Chunk { --y; - if(y <= 0 || l <= 0) { + if(y <= bottom || l <= 0) { break; } } @@ -221,8 +143,6 @@ public class Chunk { } private void recheckGaps(boolean single) { -// this.world.profiler.start("recheckGaps"); - if(this.world.isAreaLoaded(new BlockPos(this.xPos * 16 + 8, 0, this.zPos * 16 + 8), 16)) { for(int x = 0; x < 16; ++x) { for(int z = 0; z < 16; ++z) { @@ -245,7 +165,6 @@ public class Chunk { } if(single) { -// this.world.profiler.end(); return; } } @@ -254,8 +173,6 @@ public class Chunk { this.gapUpdate = false; } - -// this.world.profiler.end(); } private void checkNeighbor(int x, int z, int max) { @@ -280,14 +197,15 @@ public class Chunk { } private void relightBlock(int x, int y, int z) { - int h = this.height[z << 4 | x] & 511; + int h = this.height[z << 4 | x]; + int min = this.bottom; int cy = h; if(y > h) { cy = y; } - while(cy > 0 && this.getOpacity(x, cy - 1, z) == 0) { + while(cy > min && this.getOpacity(x, cy - 1, z) == 0) { --cy; } @@ -300,7 +218,7 @@ public class Chunk { if(!this.world.dimension.hasNoLight()) { if(cy < h) { for(int n = cy; n < h; ++n) { - BlockArray stor = this.blocks[n >> 4]; + BlockArray stor = this.getArray(n >> 4); if(stor != null) { stor.setSky(x, n & 15, z, 15); @@ -310,7 +228,7 @@ public class Chunk { } else { for(int n = h; n < cy; ++n) { - BlockArray stor = this.blocks[n >> 4]; + BlockArray stor = this.getArray(n >> 4); if(stor != null) { stor.setSky(x, n & 15, z, 0); @@ -321,7 +239,7 @@ public class Chunk { int l = 15; - while(cy > 0 && l > 0) { + while(cy > min && l > 0) { --cy; int b = this.getOpacity(x, cy, z); @@ -335,7 +253,7 @@ public class Chunk { l = 0; } - BlockArray stor = this.blocks[cy >> 4]; + BlockArray stor = this.getArray(cy >> 4); if(stor != null) { stor.setSky(x, cy & 15, z, l); @@ -368,80 +286,28 @@ public class Chunk { } } - public int getOpacity(BlockPos pos) { + private int getOpacity(BlockPos pos) { return this.getBlock(pos).getLightOpacity(); } private int getOpacity(int x, int y, int z) { return this.getBlock0(x, y, z).getLightOpacity(); } - - private Block getBlock0(int x, int y, int z) { - Block block = Blocks.air; - - if(y >= 0 && y >> 4 < this.blocks.length) { - BlockArray stor = this.blocks[y >> 4]; - - if(stor != null) { - block = stor.getBlock(x, y & 15, z); - } - } - - return block; + + protected Block getBlock0(int x, int y, int z) { + BlockArray stor = this.getArray(y >> 4); + return stor != null ? stor.getBlock(x, y & 15, z) : (y < 0 ? this.fillerBlock : Blocks.air); } - - public Block getBlock(int x, int y, int z) { - return this.getBlock0(x & 15, y, z & 15); + + public State getState(BlockPos pos) { + BlockArray stor = this.getArray(pos.getY() >> 4); + return stor != null ? stor.get(pos.getX() & 15, pos.getY() & 15, pos.getZ() & 15) : (pos.getY() < 0 ? this.filler : Blocks.air.getState()); } public Block getBlock(BlockPos pos) { return this.getBlock0(pos.getX() & 15, pos.getY(), pos.getZ() & 15); } - - public State getState(BlockPos pos) { - if(this.world.debug) { - State state = null; - -// if(pos.getY() == 60) { -// state = Blocks.glass.getDefaultState(); -// } - - if(pos.getY() == 1) { - state = GeneratorDebug.getState(pos.getX(), pos.getZ()); - } - - return state == null ? Blocks.air.getState() : state; - } - else { - if(pos.getY() >= 0 && pos.getY() >> 4 < this.blocks.length) { - BlockArray stor = this.blocks[pos.getY() >> 4]; - - if(stor != null) { - int x = pos.getX() & 15; - int y = pos.getY() & 15; - int z = pos.getZ() & 15; - return stor.get(x, y, z); - } - } - - return Blocks.air.getState(); - } - } - - private int getMeta(int x, int y, int z) { - if(y >> 4 >= this.blocks.length) { - return 0; - } - else { - BlockArray stor = this.blocks[y >> 4]; - return stor != null ? stor.getMeta(x, y & 15, z) : 0; - } - } - - public int getMeta(BlockPos pos) { - return this.getMeta(pos.getX() & 15, pos.getY(), pos.getZ() & 15); - } - + public State setState(BlockPos pos, State state) { int x = pos.getX() & 15; int y = pos.getY(); @@ -449,7 +315,7 @@ public class Chunk { int o = z << 4 | x; if(y >= this.precHeight[o] - 1) { - this.precHeight[o] = -999; + this.precHeight[o] = -99999999; } int h = this.height[o]; @@ -461,15 +327,16 @@ public class Chunk { else { Block block = state.getBlock(); Block oldb = old.getBlock(); - BlockArray stor = this.blocks[y >> 4]; + BlockArray stor = this.getArray(y >> 4); boolean up = false; if(stor == null) { - if(block == Blocks.air) { + if(block == Blocks.air && (y >= 0 || this.fillerBlock == Blocks.air)) { return null; } - stor = this.blocks[y >> 4] = new BlockArray(y >> 4 << 4, !this.world.dimension.hasNoLight()); + stor = new BlockArray(y >> 4 << 4, !this.world.dimension.hasNoLight(), y < 0 ? this.filler : null); + this.setArray(stor); up = y >= h; } @@ -477,7 +344,7 @@ public class Chunk { if(oldb != block) { if(!this.world.client) { - oldb.onBlockRemoved((WorldServer)this.world, pos, old); + oldb.onBlockRemoved((AWorldServer)this.world, pos, old); } else if(oldb instanceof ITileEntityProvider) { this.world.removeTileEntity(pos); @@ -518,14 +385,14 @@ public class Chunk { } if(!this.world.client && oldb != block) { - block.onBlockAdded((WorldServer)this.world, pos, state); + block.onBlockAdded((AWorldServer)this.world, pos, state); } if(block instanceof ITileEntityProvider) { TileEntity tile = this.getTileEntity(pos, TileEntity.EnumCreateEntityType.CHECK); if(tile == null) { - tile = ((ITileEntityProvider)block).createNewTileEntity(this.world, block.getMetaFromState(state)); + tile = ((ITileEntityProvider)block).createNewTileEntity(this.world); this.world.setTileEntity(pos, tile); } @@ -544,7 +411,7 @@ public class Chunk { int x = pos.getX() & 15; int y = pos.getY(); int z = pos.getZ() & 15; - BlockArray stor = this.blocks[y >> 4]; + BlockArray stor = this.getArray(y >> 4); return stor == null ? (this.canSeeSky(pos) ? type.defValue : 0) : (type == LightType.SKY ? (this.world.dimension.hasNoLight() ? 0 : stor.getSky(x, y & 15, z)) : (type == LightType.BLOCK ? stor.getLight(x, y & 15, z) : type.defValue)); @@ -554,10 +421,11 @@ public class Chunk { int x = pos.getX() & 15; int y = pos.getY(); int z = pos.getZ() & 15; - BlockArray stor = this.blocks[y >> 4]; + BlockArray stor = this.getArray(y >> 4); if(stor == null) { - stor = this.blocks[y >> 4] = new BlockArray(y >> 4 << 4, !this.world.dimension.hasNoLight()); + stor = new BlockArray(y >> 4 << 4, !this.world.dimension.hasNoLight(), y < 0 ? this.filler : null); + this.setArray(stor); this.genSkyLight(); } @@ -577,7 +445,7 @@ public class Chunk { int x = pos.getX() & 15; int y = pos.getY(); int z = pos.getZ() & 15; - BlockArray stor = this.blocks[y >> 4]; + BlockArray stor = this.getArray(y >> 4); if(stor == null) { return !this.world.dimension.hasNoLight() && amount < LightType.SKY.defValue @@ -602,12 +470,17 @@ public class Chunk { int z = ExtMath.floord(entity.posZ / 16.0D); if(x != this.xPos || z != this.zPos) { - Log.JNI.warn("Falsche Position! (" + x + ", " + z + ") sollte (" + this.xPos + ", " + this.zPos + ") sein, " + entity); + Log.TICK.warn("Falsche Position! (" + x + ", " + z + ") sollte (" + this.xPos + ", " + this.zPos + ") sein, " + entity); entity.setDead(); } int y = ExtMath.floord(entity.posY / 16.0D); + entity.addedToChunk = true; + entity.chunkCoordX = this.xPos; + entity.chunkCoordY = y; + entity.chunkCoordZ = this.zPos; + if(y < 0) { y = 0; } @@ -615,11 +488,7 @@ public class Chunk { if(y >= this.entities.length) { y = this.entities.length - 1; } - - entity.addedToChunk = true; - entity.chunkCoordX = this.xPos; - entity.chunkCoordY = y; - entity.chunkCoordZ = this.zPos; + this.entities[y].add(entity); } @@ -646,7 +515,7 @@ public class Chunk { private TileEntity createNewTileEntity(BlockPos pos) { Block block = this.getBlock(pos); - return !block.hasTileEntity() ? null : ((ITileEntityProvider)block).createNewTileEntity(this.world, this.getMeta(pos)); + return !block.hasTileEntity() ? null : ((ITileEntityProvider)block).createNewTileEntity(this.world); } public TileEntity getTileEntity(BlockPos pos, TileEntity.EnumCreateEntityType type) { @@ -669,14 +538,6 @@ public class Chunk { return tile; } - public void addTileEntity(TileEntity tile) { - this.addTileEntity(tile.getPos(), tile); - - if(this.loaded) { - this.world.addTileEntity(tile); - } - } - public void addTileEntity(BlockPos pos, TileEntity tile) { tile.setWorldObj(this.world); tile.setPos(pos); @@ -687,7 +548,7 @@ public class Chunk { } if(tile.validate()) { - this.setModified(); + this.modified = true; } this.tiles.put(pos, tile); } @@ -703,19 +564,6 @@ public class Chunk { } } - public void onChunkLoad() { - this.loaded = true; - this.world.addTileEntities(this.tiles.values()); - - for(int n = 0; n < this.entities.length; ++n) { - for(Entity entity : this.entities[n]) { - entity.onChunkLoad(); - } - - this.world.loadEntities(this.entities[n]); - } - } - public void onChunkUnload() { this.loaded = false; @@ -728,10 +576,6 @@ public class Chunk { } } - public void setModified() { - this.modified = true; - } - public void getEntities(Entity exclude, BoundingBox bb, List list, Predicate pred) { int sy = ExtMath.floord((bb.minY - 2.0D) / 16.0D); int ey = ExtMath.floord((bb.maxY + 2.0D) / 16.0D); @@ -779,43 +623,25 @@ public class Chunk { } } - public boolean isDirty(long time) { -// if (all) -// { - if(this.hasEntity && time /* this.world.getTime() */ != this.lastSave || this.modified) { - return true; - } -// } -// else if (this.hasEntity && this.world.getTime() >= this.lastSave + 600L) -// { -// return true; -// } - - return this.modified; - } - - public boolean isEmpty() { - return false; - } - public BlockPos getPrecipitation(BlockPos pos) { int x = pos.getX() & 15; int z = pos.getZ() & 15; int o = x | z << 4; BlockPos loc = new BlockPos(pos.getX(), this.precHeight[o], pos.getZ()); - if(loc.getY() == -999) { - int y = this.getTopSegment() + 15; + if(loc.getY() == -99999999) { + int y = this.top + 15; + int min = this.bottom; loc = new BlockPos(pos.getX(), y, pos.getZ()); int h = -1; - while(loc.getY() > 0 && h == -1) { + while(loc.getY() > min && h == -1) { Block block = this.getBlock(loc); Material mat = block.getMaterial(); if((!mat.blocksMovement() && !mat.isLiquid()) - || (mat == Material.leaves && ((mat = this.getBlock(loc.up()).getMaterial()) == Material.snow) - || mat == Material.leaves)) { + || (mat == Material.LEAVES && ((mat = this.getBlock(loc.up()).getMaterial()) == Material.POWDER) + || mat == Material.LEAVES)) { loc = loc.down(); } else { @@ -855,132 +681,6 @@ public class Chunk { return this.updated && this.populated && this.lightInit; } - public ChunkPos getPos() { - return new ChunkPos(this.xPos, this.zPos); - } - - public boolean isEmpty(int bottom, int top) { - if(bottom < 0) { - bottom = 0; - } - - if(top >= 512) { - top = 511; - } - - for(int y = bottom; y <= top; y += 16) { - BlockArray stor = this.blocks[y >> 4]; - - if(stor != null && !stor.isEmpty()) { - return false; - } - } - - return true; - } - - public void setStorage(BlockArray[] arrays) { - if(this.blocks.length != arrays.length) { - Log.JNI.warn("Konnte Sektionen des Chunks nicht setzen, Länge des Arrays ist " + arrays.length + " statt " - + this.blocks.length); - } - else { - for(int n = 0; n < this.blocks.length; ++n) { - this.blocks[n] = arrays[n]; - } - } - } - - public void setData(byte[] data, int update, boolean biomes) { - int pos = 0; - boolean sky = !this.world.dimension.hasNoLight(); - - for(int n = 0; n < this.blocks.length; ++n) { - if((update & 1 << n) != 0) { - if(this.blocks[n] == null) { - this.blocks[n] = new BlockArray(n << 4, sky); - } - - char[] blocks = this.blocks[n].getData(); - - for(int k = 0; k < blocks.length; ++k) { - blocks[k] = (char)((data[pos + 1] & 255) << 8 | data[pos] & 255); - pos += 2; - } - } - else if(biomes && this.blocks[n] != null) { - this.blocks[n] = null; - } - } - - for(int n = 0; n < this.blocks.length; ++n) { - if((update & 1 << n) != 0 && this.blocks[n] != null) { - NibbleArray light = this.blocks[n].getBlocklight(); - System.arraycopy(data, pos, light.getData(), 0, light.getData().length); - pos += light.getData().length; - } - } - - if(sky) { - for(int n = 0; n < this.blocks.length; ++n) { - if((update & 1 << n) != 0 && this.blocks[n] != null) { - NibbleArray slight = this.blocks[n].getSkylight(); - System.arraycopy(data, pos, slight.getData(), 0, slight.getData().length); - pos += slight.getData().length; - } - } - } - - if(biomes) { - System.arraycopy(data, pos, this.biomes, 0, this.biomes.length); -// int unk = pos + this.biomes.length; - } - - for(int n = 0; n < this.blocks.length; ++n) { - if(this.blocks[n] != null && (update & 1 << n) != 0) { - this.blocks[n].update(); - } - } - - this.lightInit = true; - this.populated = true; - this.genHeights(); - - for(TileEntity tile : this.tiles.values()) { - tile.updateContainingBlockInfo(); - } - } - - public Biome getBiome(BlockPos pos, BiomeGenerator gen) { - int x = pos.getX() & 15; - int z = pos.getZ() & 15; - int o = this.biomes[z << 4 | x] & 255; - - if(o == 255) { - Biome biome = gen == null ? Biome.DEF_BIOME : gen.getBiomeGenerator(pos, Biome.DEF_BIOME); - o = biome.id; - this.biomes[z << 4 | x] = (byte)(o & 255); - } - - Biome biome = Biome.getBiome(o); - return biome == null ? Biome.DEF_BIOME : biome; - } - - public byte[] getBiomes() { - return this.biomes; - } - - public void setBiomes(byte[] biomes) { - if(this.biomes.length != biomes.length) { - Log.JNI.warn("Konnte Biome des Chunks nicht setzen, Länge des Arrays ist " + biomes.length + " statt " + this.biomes.length); - } - else { - for(int n = 0; n < this.biomes.length; ++n) { - this.biomes[n] = biomes[n]; - } - } - } - public void resetRelight() { this.lightChecks = 0; } @@ -996,11 +696,14 @@ public class Chunk { BlockPos pos = new BlockPos(this.xPos << 4, 0, this.zPos << 4); for(int n = 0; n < 8; ++n) { - if(this.lightChecks >= 8192) + if(this.top == Integer.MIN_VALUE) + return; + int h = 1 + (this.top >> 4) - (this.bottom >> 4); + if(this.lightChecks >= 256 * h) return; - int s = this.lightChecks % 31; - int x = this.lightChecks / 31 % 16; + int s = (this.lightChecks % h) + (this.bottom >> 4); + int x = this.lightChecks / h % 16; int z = this.lightChecks / 512; ++this.lightChecks; @@ -1008,8 +711,9 @@ public class Chunk { BlockPos block = pos.add(x, (s << 4) + y, z); boolean edge = y == 0 || y == 15 || x == 0 || x == 15 || z == 0 || z == 15; - if(this.blocks[s] == null && edge || this.blocks[s] != null - && this.blocks[s].getBlock(x, y, z).getMaterial() == Material.air) { + BlockArray arr = this.getArray(s); + if(arr == null && edge || arr != null + && arr.getBlock(x, y, z) == Blocks.air) { for(Facing face : Facing.values()) { BlockPos side = block.offset(face); @@ -1091,12 +795,13 @@ public class Chunk { } private boolean updateColumn(int x, int z) { - int top = this.getTopSegment(); + int top = this.top; + int bottom = this.bottom; boolean opaque = false; boolean below = false; BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos((this.xPos << 4) + x, 0, (this.zPos << 4) + z); - for(int y = top + 16 - 1; y > this.world.getSeaLevel() || y > 0 && !below; --y) { + for(int y = top + 16 - 1; y > this.world.getSeaLevel() || y > bottom && !below; --y) { pos.set(pos.getX(), y, pos.getZ()); int o = this.getOpacity(pos); @@ -1112,7 +817,7 @@ public class Chunk { } } - for(int y = pos.getY(); y > 0; --y) { + for(int y = pos.getY(); y > bottom; --y) { pos.set(pos.getX(), y, pos.getZ()); if(this.getBlock(pos).getLightValue() > 0) { @@ -1126,75 +831,12 @@ public class Chunk { public boolean isLoaded() { return this.loaded; } - - public void setLoaded(boolean loaded) { - this.loaded = loaded; - } - - public World getWorld() { - return this.world; - } - - public int[] getHeights() { - return this.height; - } - - public void setHeights(int[] map) { - if(this.height.length != map.length) { - Log.JNI.warn("Konnte Höhen des Chunks nicht setzen, Länge des Arrays ist " + map.length + " statt " + this.height.length); - } - else { - for(int n = 0; n < this.height.length; ++n) { - this.height[n] = map[n]; - } - } - } - - public Map getTiles() { - return this.tiles; - } - - public ClassInheritanceMultiMap[] getEntities() { + + public InheritanceMultiMap[] getEntities() { return this.entities; } - public boolean isTerrainPopulated() { - return this.populated; - } - - public void setTerrainPopulated(boolean populated) { - this.populated = populated; - } - - public boolean isLightPopulated() { - return this.lightInit; - } - - public void setLightPopulated(boolean populated) { - this.lightInit = populated; - } - - public void setModified(boolean modified) { - this.modified = modified; - } - - public void setHasEntities(boolean entities) { - this.hasEntity = entities; - } - - public void setSaved(long time) { - this.lastSave = time; - } - public int getLowest() { return this.minHeight; } - - public long getInhabited() { - return this.inhabited; - } - - public void setInhabited(long time) { - this.inhabited = time; - } } diff --git a/java/src/game/world/Explosion.java b/common/src/main/java/common/world/Explosion.java similarity index 90% rename from java/src/game/world/Explosion.java rename to common/src/main/java/common/world/Explosion.java index 9a111cd..c9d687e 100755 --- a/java/src/game/world/Explosion.java +++ b/common/src/main/java/common/world/Explosion.java @@ -1,27 +1,28 @@ -package game.world; +package common.world; import java.util.List; import java.util.Map; import java.util.Set; -import game.collect.Lists; -import game.collect.Maps; -import game.collect.Sets; - -import game.block.Block; -import game.enchantment.EnchantmentProtection; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.item.EntityTnt; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.init.SoundEvent; -import game.material.Material; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.util.ExtMath; +import common.block.Block; +import common.collect.Lists; +import common.collect.Maps; +import common.collect.Sets; +import common.enchantment.Enchantment; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.item.EntityTnt; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.SoundEvent; +import common.model.ParticleType; +import common.rng.Random; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ExtMath; +import common.util.Vec3; +import common.vars.Vars; public class Explosion { @@ -95,7 +96,7 @@ public class Explosion BlockPos blockpos = new BlockPos(d4, d6, d8); State iblockstate = this.worldObj.getState(blockpos); - if (iblockstate.getBlock().getMaterial() != Material.air) + if (iblockstate.getBlock() != Blocks.air) { float f2 = this.exploder != null ? this.exploder.getExplosionResistance(this, this.worldObj, blockpos, iblockstate) : iblockstate.getBlock().getExplosionResistance((Entity)null); f -= (f2 + 0.3F) * 0.3F; @@ -134,7 +135,7 @@ public class Explosion State iblockstate = this.worldObj.getState(blockpos); float f = this.explosionSize; // * (0.7F + this.worldObj.rand.nextFloat() * 0.6F); - if (iblockstate.getBlock().getMaterial() != Material.air) + if (iblockstate.getBlock() != Blocks.air) { float f2 = this.exploder != null ? this.exploder.getExplosionResistance(this, this.worldObj, blockpos, iblockstate) : iblockstate.getBlock().getExplosionResistance((Entity)null); f -= (f2 + 0.3F) * 0.3F; @@ -166,11 +167,11 @@ public class Explosion (dist < explosionSize && rand.doublev() + ((dist - (explosionSize - falloff)) / falloff) < 1.0d))) { BlockPos blockpos = new BlockPos(explosionX + x, explosionY + y, explosionZ + z); State iblockstate = worldObj.getState(blockpos); - if(iblockstate.getBlock().getMaterial() != Material.air && iblockstate.getBlock().getExplosionResistance(null) < 60000.0f) { + if(iblockstate.getBlock() != Blocks.air && iblockstate.getBlock().getExplosionResistance(null) < 60000.0f) { worldObj.setState(blockpos, Blocks.air.getState(), 3); if(rand.chance(1000)) { worldObj.playSound(SoundEvent.EXPLODE, explosionX + x, explosionY + y, explosionZ + z, 4.0F); - ((WorldServer)worldObj).spawnParticle(ParticleType.EXPLOSION_HUGE, explosionX + x, explosionY + y, explosionZ + z, 0, rand.gaussian() * 0.02D, rand.gaussian() * 0.02D, rand.gaussian() * 0.02D, 1.0); + ((AWorldServer)worldObj).spawnParticle(ParticleType.EXPLOSION_HUGE, explosionX + x, explosionY + y, explosionZ + z, 0, rand.gaussian() * 0.02D, rand.gaussian() * 0.02D, rand.gaussian() * 0.02D, 1.0); } } } @@ -178,7 +179,7 @@ public class Explosion } } - if(worldObj.client || Config.damageExplosion) { + if(worldObj.client || Vars.damageExplosion) { List list = worldObj.getEntitiesWithinAABB(Entity.class, new BoundingBox(explosionX - (5.0 + (double)d), explosionY - (5.0 + (double)d), explosionZ - (5.0 + (double)d), explosionX + 5.0 + (double)d, explosionY + 5.0 + (double)d, explosionZ + 5.0 + (double)d)); @@ -243,9 +244,9 @@ public class Explosion d9 = d9 / d13; double d14 = (double)this.worldObj.getBlockDensity(vec3, entity.getEntityBoundingBox()); double d10 = (1.0D - d12) * d14; - if(this.worldObj.client || Config.damageExplosion) + if(this.worldObj.client || Vars.damageExplosion) entity.attackEntityFrom(DamageSource.causeExplosionDamage(this), ((int)((d10 * d10 + d10) / 2.0D * 8.0D * (double)f3 + 1.0D))); - double d11 = EnchantmentProtection.getKnockbackFactor(entity, d10); + double d11 = Enchantment.getKnockbackFactor(entity, d10); entity.motionX += d5 * d11; entity.motionY += d7 * d11; entity.motionZ += d9 * d11; @@ -304,7 +305,7 @@ public class Explosion this.worldObj.spawnParticle(ParticleType.SMOKE_NORMAL, d0, d1, d2, d3, d4, d5); } - if (block.getMaterial() != Material.air) + if (block != Blocks.air) { if (block.canDropFromExplosion(this)) { @@ -321,7 +322,7 @@ public class Explosion { for (BlockPos blockpos1 : this.affectedBlockPositions) { - if (this.worldObj.getState(blockpos1).getBlock().getMaterial() == Material.air && this.worldObj.getState(blockpos1.down()).getBlock().isFullBlock() && this.explosionRNG.zrange(3) == 0) + if (this.worldObj.getState(blockpos1).getBlock() == Blocks.air && this.worldObj.getState(blockpos1.down()).getBlock().isFullBlock() && this.explosionRNG.zrange(3) == 0) { this.worldObj.setState(blockpos1, Blocks.fire.getState()); } diff --git a/java/src/game/world/IBlockAccess.java b/common/src/main/java/common/world/IBlockAccess.java similarity index 57% rename from java/src/game/world/IBlockAccess.java rename to common/src/main/java/common/world/IBlockAccess.java index 79cb6fd..11fa2ab 100755 --- a/java/src/game/world/IBlockAccess.java +++ b/common/src/main/java/common/world/IBlockAccess.java @@ -1,4 +1,6 @@ -package game.world; +package common.world; + +import common.util.BlockPos; public interface IBlockAccess { diff --git a/java/src/game/world/IWorldAccess.java b/common/src/main/java/common/world/IWorldAccess.java similarity index 63% rename from java/src/game/world/IWorldAccess.java rename to common/src/main/java/common/world/IWorldAccess.java index c829d7f..b798152 100755 --- a/java/src/game/world/IWorldAccess.java +++ b/common/src/main/java/common/world/IWorldAccess.java @@ -1,7 +1,8 @@ -package game.world; +package common.world; -import game.biome.Biome; -import game.tileentity.TileEntity; +import common.biome.Biome; +import common.tileentity.TileEntity; +import common.util.BlockPos; public interface IWorldAccess extends IBlockAccess { diff --git a/java/src/game/world/LightType.java b/common/src/main/java/common/world/LightType.java similarity index 85% rename from java/src/game/world/LightType.java rename to common/src/main/java/common/world/LightType.java index ce17dd2..e1bfdbb 100755 --- a/java/src/game/world/LightType.java +++ b/common/src/main/java/common/world/LightType.java @@ -1,4 +1,4 @@ -package game.world; +package common.world; public enum LightType { SKY(15), BLOCK(0); diff --git a/java/src/game/world/State.java b/common/src/main/java/common/world/State.java similarity index 89% rename from java/src/game/world/State.java rename to common/src/main/java/common/world/State.java index 53cbd2a..76772ff 100755 --- a/java/src/game/world/State.java +++ b/common/src/main/java/common/world/State.java @@ -1,22 +1,21 @@ -package game.world; +package common.world; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; - import java.util.function.Function; -import game.collect.ImmutableMap; -import game.collect.ImmutableTable; -import game.collect.Iterables; -import game.collect.Maps; -import game.collect.StandardTable; -import game.collect.Table; -import game.block.Block; -import game.init.BlockRegistry; -import game.properties.IProperty; +import common.block.Block; +import common.collect.ImmutableMap; +import common.collect.ImmutableTable; +import common.collect.Iterables; +import common.collect.Maps; +import common.collect.StandardTable; +import common.collect.Table; +import common.init.BlockRegistry; +import common.properties.IProperty; public class State { // private static final Joiner COMMA_JOINER = Joiner.on(','); @@ -75,7 +74,7 @@ public class State { } else if(!property.getAllowedValues().contains(value)) { throw new IllegalArgumentException("Cannot set property " + property + " to " + value + " on block " - + BlockRegistry.REGISTRY.getNameForObject(this.block) + ", it is not an allowed value"); + + BlockRegistry.getNameFromBlock(this.block) + ", it is not an allowed value"); } else { return (State)(this.properties.get(property) == value ? this : (State)this.map.get(property, value)); @@ -100,7 +99,7 @@ public class State { public String toString() { StringBuilder sb = new StringBuilder(); - sb.append(BlockRegistry.REGISTRY.getNameForObject(this.getBlock())); + sb.append(BlockRegistry.getNameFromBlock(this.getBlock())); if(!this.getProperties().isEmpty()) { sb.append("["); Iterable iter = Iterables.transform(this.getProperties().entrySet(), MAP_ENTRY_TO_STRING); diff --git a/java/src/game/world/Weather.java b/common/src/main/java/common/world/Weather.java similarity index 96% rename from java/src/game/world/Weather.java rename to common/src/main/java/common/world/Weather.java index 9df13f4..89a99c7 100755 --- a/java/src/game/world/Weather.java +++ b/common/src/main/java/common/world/Weather.java @@ -1,12 +1,11 @@ -package game.world; +package common.world; import java.util.Map; -import game.collect.Maps; - -import game.rng.Random; -import game.rng.RngItem; -import game.rng.WeightedList; +import common.collect.Maps; +import common.rng.Random; +import common.rng.RngItem; +import common.rng.WeightedList; public enum Weather { CLEAR("clear", "Schön", 0.0f, 0.0f, 12, 30, 9, 7), diff --git a/java/src/game/world/World.java b/common/src/main/java/common/world/World.java similarity index 95% rename from java/src/game/world/World.java rename to common/src/main/java/common/world/World.java index 5c0e471..c2c668b 100755 --- a/java/src/game/world/World.java +++ b/common/src/main/java/common/world/World.java @@ -1,36 +1,42 @@ -package game.world; +package common.world; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Set; - import java.util.function.Predicate; -import game.collect.Lists; -import game.collect.Sets; -import game.biome.Biome; -import game.block.Block; -import game.block.BlockHopper; -import game.block.BlockLiquid; -import game.block.BlockSlab; -import game.block.BlockSnow; -import game.block.BlockStairs; -import game.block.LeavesType; -import game.dimension.Dimension; -import game.entity.Entity; -import game.entity.item.EntityExplosion; -import game.entity.npc.EntityNPC; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.SoundEvent; -import game.item.ItemStack; -import game.material.Material; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.tileentity.ITickable; -import game.tileentity.TileEntity; -import game.util.ExtMath; +import common.biome.Biome; +import common.block.Block; +import common.block.Material; +import common.block.artificial.BlockSlab; +import common.block.artificial.BlockStairs; +import common.block.foliage.LeavesType; +import common.block.liquid.BlockLiquid; +import common.block.natural.BlockSnow; +import common.block.tech.BlockHopper; +import common.collect.Lists; +import common.collect.Sets; +import common.dimension.Dimension; +import common.entity.Entity; +import common.entity.item.EntityExplosion; +import common.entity.npc.EntityNPC; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.SoundEvent; +import common.item.ItemStack; +import common.model.ParticleType; +import common.rng.Random; +import common.tileentity.ITickable; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ChunkPos; +import common.util.ExtMath; +import common.util.Facing; +import common.util.HitPosition; +import common.util.IntHashMap; +import common.util.Vec3; public abstract class World implements IWorldAccess { public static final float[][] BRIGHTNESS = new float[16][16]; @@ -45,14 +51,13 @@ public abstract class World implements IWorldAccess { } public static final float[] MOON_PHASES = new float[] {1.0F, 0.75F, 0.5F, 0.25F, 0.0F, 0.25F, 0.5F, 0.75F}; public static final int MAX_SIZE = 67108864; - public static final int HEIGHT = 512; + public static final int MAX_SIZE_Y = 4096; public static final long START_TIME = 4385238000L; public static final float ABSOLUTE_ZERO = -273.15f; // private static final Calendar calendar = Calendar.getInstance(); // private static long lastUpdate; public final boolean client; - public final boolean debug; public double gravity = 1.0; protected long timeFactor = 1L; public final Random rand = new Random(); @@ -103,21 +108,20 @@ public abstract class World implements IWorldAccess { public static boolean isValid(BlockPos pos) { return pos.getX() >= -MAX_SIZE && pos.getZ() >= -MAX_SIZE && pos.getX() < MAX_SIZE && pos.getZ() < MAX_SIZE && - pos.getY() >= 0 && pos.getY() < 512; + pos.getY() >= -MAX_SIZE_Y && pos.getY() < MAX_SIZE_Y; } public static boolean isValidXZ(BlockPos pos) { return pos.getX() >= -MAX_SIZE && pos.getZ() >= -MAX_SIZE && pos.getX() < MAX_SIZE && pos.getZ() < MAX_SIZE; } - protected World(Dimension dim, boolean client, boolean debug) { + protected World(Dimension dim, boolean client) { // this.profiler = profiler; // this.info = info; // this.dimInfo = info.getDimension(dim.getDimensionId()); this.dimension = dim; // this.storage = storage; this.client = client; - this.debug = debug; this.weather = dim.getWeather(); } @@ -127,15 +131,10 @@ public abstract class World implements IWorldAccess { this.gravity = Math.signum(this.gravity) * 0.075; } - public Biome getBiomeGenForCoords(final BlockPos pos) { - if(this.isBlockLoaded(pos)) - return this.getChunk(pos).getBiome(pos, null); - else - return Biome.DEF_BIOME; - } + public abstract Biome getBiomeGenForCoords(BlockPos pos); public boolean isAirBlock(BlockPos pos) { - return this.getState(pos).getBlock().getMaterial() == Material.air; + return this.getState(pos).getBlock() == Blocks.air; } public boolean isBlockLoaded(BlockPos pos) { @@ -164,7 +163,7 @@ public abstract class World implements IWorldAccess { } private boolean isAreaLoaded(int xStart, int yStart, int zStart, int xEnd, int yEnd, int zEnd, boolean allowEmpty) { - if(yEnd >= 0 && yStart < 512) { + if(yEnd >= -MAX_SIZE_Y && yStart < MAX_SIZE_Y) { xStart = xStart >> 4; zStart = zStart >> 4; xEnd = xEnd >> 4; @@ -185,9 +184,7 @@ public abstract class World implements IWorldAccess { } } - protected boolean isLoaded(int x, int z, boolean allowEmpty) { - return allowEmpty || !this.getChunk(x, z).isEmpty(); - } + protected abstract boolean isLoaded(int x, int z, boolean allowEmpty); public Chunk getChunk(BlockPos pos) { return this.getChunk(pos.getX() >> 4, pos.getZ() >> 4); @@ -201,9 +198,6 @@ public abstract class World implements IWorldAccess { if(!isValid(pos)) { return false; } - else if(!this.client && this.debug) { - return false; - } else { Chunk chunk = this.getChunk(pos); Block block = newState.getBlock(); @@ -226,7 +220,7 @@ public abstract class World implements IWorldAccess { } if(!this.client && (flags & 1) != 0) { - this.notifyNeighborsRespectDebug(pos, iblockstate.getBlock()); + this.notifyNeighborsOfStateChange(pos, iblockstate.getBlock()); if(block.hasComparatorInputOverride()) { this.updateComparatorOutputLevel(pos, block); @@ -250,7 +244,7 @@ public abstract class World implements IWorldAccess { State iblockstate = this.getState(pos); Block block = iblockstate.getBlock(); - if(block.getMaterial() == Material.air) { + if(block == Blocks.air) { return false; } else { @@ -264,12 +258,6 @@ public abstract class World implements IWorldAccess { } } - public void notifyNeighborsRespectDebug(BlockPos pos, Block blockType) { - if(!this.debug) { - this.notifyNeighborsOfStateChange(pos, blockType); - } - } - public void markBlocksDirtyVertical(int x1, int z1, int x2, int z2) { if(x2 > z2) { int i = z2; @@ -338,12 +326,12 @@ public abstract class World implements IWorldAccess { } public int getLight(BlockPos pos) { - if(pos.getY() < 0) { + if(pos.getY() < -MAX_SIZE_Y) { return 0; } else { - if(pos.getY() >= 512) { - pos = new BlockPos(pos.getX(), 511, pos.getZ()); + if(pos.getY() >= MAX_SIZE_Y) { + pos = new BlockPos(pos.getX(), MAX_SIZE_Y - 1, pos.getZ()); } return this.getChunk(pos).getLightSub(pos, 0); @@ -381,12 +369,12 @@ public abstract class World implements IWorldAccess { return i1; } - else if(pos.getY() < 0) { + else if(pos.getY() < -MAX_SIZE_Y) { return 0; } else { - if(pos.getY() >= 512) { - pos = new BlockPos(pos.getX(), 511, pos.getZ()); + if(pos.getY() >= MAX_SIZE_Y) { + pos = new BlockPos(pos.getX(), MAX_SIZE_Y - 1, pos.getZ()); } Chunk chunk = this.getChunk(pos); @@ -436,8 +424,8 @@ public abstract class World implements IWorldAccess { return 0; } else { - if(pos.getY() < 0) { - pos = new BlockPos(pos.getX(), 0, pos.getZ()); + if(pos.getY() < -MAX_SIZE_Y) { + pos = new BlockPos(pos.getX(), -MAX_SIZE_Y, pos.getZ()); } if(!isValid(pos)) { @@ -479,8 +467,8 @@ public abstract class World implements IWorldAccess { } public int getLightFor(LightType type, BlockPos pos) { - if(pos.getY() < 0) { - pos = new BlockPos(pos.getX(), 0, pos.getZ()); + if(pos.getY() < -MAX_SIZE_Y) { + pos = new BlockPos(pos.getX(), -MAX_SIZE_Y, pos.getZ()); } if(!isValid(pos)) { @@ -1227,7 +1215,7 @@ public abstract class World implements IWorldAccess { for(int i2 = i1; i2 < j1; ++i2) { Block block = this.getState(blockpos$mutableblockpos.set(k1, l1, i2)).getBlock(); - if(block == Blocks.fire || block == Blocks.flowing_lava || block == Blocks.lava) { + if(block == Blocks.fire || block == Blocks.soul_fire || block == Blocks.flowing_lava || block == Blocks.lava || block.getMaterial().isHotLiquid()) { return true; } } @@ -1400,7 +1388,7 @@ public abstract class World implements IWorldAccess { public boolean extinguishFire(EntityNPC player, BlockPos pos, Facing side) { pos = pos.offset(side); - if(this.getState(pos).getBlock() == Blocks.fire) { + if(this.getState(pos).getBlock().canExtinguish()) { this.playAuxSFX(player, 1004, pos, 0); this.setBlockToAir(pos); return true; @@ -1556,7 +1544,7 @@ public abstract class World implements IWorldAccess { } public float getTemperatureK(BlockPos pos) { - return this.temp + this.getBiomeGenForCoords(pos).getTemperature(pos); + return Math.max(this.temp + this.getBiomeGenForCoords(pos).getTemperature(pos), 0.0f); } public float getTemperatureC(BlockPos pos) { @@ -1587,10 +1575,10 @@ public abstract class World implements IWorldAccess { return true; } else { - if(pos.getY() >= 0 && pos.getY() < 512 && this.getLightFor(LightType.BLOCK, pos) < 10) { + if(pos.getY() >= -MAX_SIZE_Y && pos.getY() < MAX_SIZE_Y && this.getLightFor(LightType.BLOCK, pos) < 10) { Block block = this.getState(pos).getBlock(); - if((block.getMaterial() == Material.air || (allowLayers && block == Blocks.snow_layer)) + if((block == Blocks.air || (allowLayers && block == Blocks.snow_layer)) && Blocks.snow_layer.canPlaceBlockAt(this, pos)) { return true; } @@ -1816,12 +1804,6 @@ public abstract class World implements IWorldAccess { return (Entity)this.entityIds.lookup(id); } - public void markChunkDirty(BlockPos pos, TileEntity unusedTileEntity) { - if(this.isBlockLoaded(pos)) { - this.getChunk(pos).setModified(); - } - } - public void loadEntities(Collection entityCollection) { this.entities.addAll(entityCollection); @@ -1838,7 +1820,7 @@ public abstract class World implements IWorldAccess { Block block = this.getState(pos).getBlock(); BoundingBox axisalignedbb = p_175716_3_ ? null : blockIn.getCollisionBoundingBox(this, pos, blockIn.getState()); return axisalignedbb != null && !this.checkNoEntityCollision(axisalignedbb, entityIn) ? false - : (block.getMaterial() == Material.circuits && blockIn == Blocks.anvil ? true + : (block.getMaterial() == Material.SMALL && blockIn == Blocks.anvil ? true : block.getMaterial().isReplaceable() && blockIn.canReplace(this, pos, side, itemStackIn)); } diff --git a/glfw_license.txt b/glfw_license.txt deleted file mode 100644 index 8a60e1d..0000000 --- a/glfw_license.txt +++ /dev/null @@ -1,21 +0,0 @@ -Copyright (c) 2002-2006 Marcus Geelnard -Copyright (c) 2006-2010 Camilla Berglund - -This software is provided 'as-is', without any express or implied -warranty. In no event will the authors be held liable for any damages -arising from the use of this software. - -Permission is granted to anyone to use this software for any purpose, -including commercial applications, and to alter it and redistribute it -freely, subject to the following restrictions: - -1. The origin of this software must not be misrepresented; you must not - claim that you wrote the original software. If you use this software - in a product, an acknowledgment in the product documentation would - be appreciated but is not required. - -2. Altered source versions must be plainly marked as such, and must not - be misrepresented as being the original software. - -3. This notice may not be removed or altered from any source - distribution. diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..91ec0d3 --- /dev/null +++ b/gradle.properties @@ -0,0 +1,4 @@ + +org.gradle.configuration-cache=false +org.gradle.parallel=true +org.gradle.caching=true diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..7908d7b --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,8 @@ +# This file was generated by the Gradle 'init' task. +# https://docs.gradle.org/current/userguide/platforms.html#sub::toml-dependencies-format + +[versions] +guava = "33.4.5-jre" + +[libraries] +guava = { module = "com.google.guava:guava", version.ref = "guava" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..1b33c55 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..002b867 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.14.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..23d15a9 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH="\\\"\\\"" + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..db3a6ac --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@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 + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@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="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH= + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 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! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/java/src/game/biome/Biome.java b/java/src/game/biome/Biome.java deleted file mode 100755 index b5269e3..0000000 --- a/java/src/game/biome/Biome.java +++ /dev/null @@ -1,771 +0,0 @@ -package game.biome; - -import java.util.List; -import java.util.Map; - -import game.collect.Lists; -import game.collect.Maps; - -import game.block.Block; -import game.block.BlockColored; -import game.block.BlockFlower; -import game.block.BlockSand; -import game.block.BlockTallGrass; -import game.color.Colorizer; -import game.color.DyeColor; -import game.entity.animal.EntityBat; -import game.entity.animal.EntityChicken; -import game.entity.animal.EntityCow; -import game.entity.animal.EntityMouse; -import game.entity.animal.EntityPig; -import game.entity.animal.EntityRabbit; -import game.entity.animal.EntitySheep; -import game.entity.animal.EntitySquid; -import game.entity.npc.EntityArachnoid; -import game.entity.npc.EntityHaunter; -import game.entity.npc.EntityMage; -import game.entity.npc.EntitySlime; -import game.entity.npc.EntityUndead; -import game.entity.npc.EntityZombie; -import game.init.Blocks; -import game.log.Log; -import game.material.Material; -import game.rng.PerlinGen; -import game.rng.Random; -import game.rng.WeightedList; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.World; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; -import game.worldgen.FeatureGenerator; -import game.worldgen.feature.WorldGenClay; -import game.worldgen.feature.WorldGenClayExt; -import game.worldgen.feature.WorldGenSand; -import game.worldgen.foliage.FeatureDoublePlant; -import game.worldgen.foliage.WorldGenBigMushroom; -import game.worldgen.foliage.WorldGenCactus; -import game.worldgen.foliage.WorldGenDeadBush; -import game.worldgen.foliage.WorldGenFlowers; -import game.worldgen.foliage.WorldGenMushroom; -import game.worldgen.foliage.WorldGenPumpkin; -import game.worldgen.foliage.WorldGenReed; -import game.worldgen.foliage.WorldGenTallGrass; -import game.worldgen.foliage.WorldGenWaterlily; -import game.worldgen.tree.WorldGenBaseTree; -import game.worldgen.tree.WorldGenBigTree; -import game.worldgen.tree.WorldGenSwamp; -import game.worldgen.tree.WorldGenTree; - -public abstract class Biome { - private static final Biome[] BIOMES = new Biome[256]; - - public static final Biome none = (new BiomeNone(0)).setBiomeName("none", ""); - - public static final Biome plains = (new BiomePlains(1)).setColor(9286496).setBiomeName("plains", "Ebene"); - public static final Biome desert = (new BiomeDesert(2)).setColor(16421912).setBiomeName("desert", "Wüste").setTemperature(60.0f).setHumidity(0.0f).setScaling(Scaling.PLAINS_LOW); - public static final Biome extremeHills = (new BiomeHills(3, false)).setColor(6316128).setBiomeName("extremeHills", "Extremes Bergland").setScaling(Scaling.HILLS_LARGE).setTemperature(-12.0f).setHumidity(30.0f); - public static final Biome forest = (new BiomeForest(4, 0)).setColor(353825).setBiomeName("forest", "Wald"); - public static final Biome taiga = (new BiomeTaiga(5, 0)).setColor(747097).setBiomeName("taiga", "Taiga").setTemperature(-10.0f).setHumidity(80.0f).setScaling(Scaling.PLAINS_MEDIUM); - public static final Biome swampland = (new BiomeSwamp(6)).setColor(522674).setBiomeName("swampland", "Sumpf").setScaling(Scaling.SEA_POND).setTemperature(12.0f).setHumidity(90.0f); - public static final Biome river = (new BiomeWater(7, true)).setColor(255).setBiomeName("river", "Fluss").setScaling(Scaling.SEA_SHALLOW); - - public static final Biome exterminated = (new BiomeExterminated(8)).setColor(0x000000).setBiomeName("exterminated", "Ausgelöscht").setHumidity(0.0f).setTemperature(150.0f); - public static final Biome space = (new BiomeSpace(9)).setColor(0x000000).setBiomeName("space", "Leere des Weltraums").setHumidity(0.0f); - - public static final Biome frozenSea = (new BiomeWater(10, false)).setColor(9474208).setBiomeName("frozenSea", "Vereister See").enableColdBeach().setScaling(Scaling.SEA_MEDIUM).setTemperature(-20.0f).setHumidity(50.0f); - public static final Biome frozenRiver = (new BiomeWater(11, true)).setColor(10526975).setBiomeName("frozenRiver", "Vereister Fluss").enableColdBeach().setScaling(Scaling.SEA_SHALLOW).setTemperature(-20.0f).setHumidity(50.0f); - public static final Biome icePlains = (new BiomeSnow(12, false)).setColor(16777215).setBiomeName("icePlains", "Eisebene").enableColdBeach().setTemperature(-20.0f).setHumidity(50.0f).setScaling(Scaling.PLAINS_LOW); - public static final Biome iceMountains = (new BiomeSnow(13, false)).setColor(10526880).setBiomeName("iceMountains", "Vereistes Bergland").enableColdBeach().setScaling(Scaling.HILLS_LOW).setTemperature(-20.0f).setHumidity(50.0f); - public static final Biome mushroomPlains = (new BiomeMushroom(14)).setColor(16711935).setBiomeName("mushroomPlains", "Pilzland").setTemperature(16.0f).setHumidity(100.0f).setScaling(Scaling.PLAINS_VARYING); - public static final Biome blackened = (new BiomeBlackened(15)).setColor(0x000000).setBiomeName("blackened", "Schwarz").setHumidity(0.0f); - public static final Biome beach = (new BiomeBeach(16)).setColor(16440917).setBiomeName("beach", "Strand").setTemperature(12.0f).setHumidity(40.0f).setScaling(Scaling.SEA_SHORE); - public static final Biome desertHills = (new BiomeDesert(17)).setColor(13786898).setBiomeName("desertHills", "Wüsten-Bergland").setTemperature(60.0f).setHumidity(0.0f).setScaling(Scaling.HILLS_LOW); - public static final Biome forestHills = (new BiomeForest(18, 0)).setColor(2250012).setBiomeName("forestHills", "Wald-Bergland").setScaling(Scaling.HILLS_LOW); - public static final Biome taigaHills = (new BiomeTaiga(19, 0)).setColor(1456435).setBiomeName("taigaHills", "Taiga-Bergland").setTemperature(-10.0f).setHumidity(80.0f).setScaling(Scaling.HILLS_LOW); - public static final Biome extremeHillsEdge = (new BiomeHills(20, true)).setColor(7501978).setBiomeName("extremeHillsEdge", "Extremes Bergland Gr.").setScaling(Scaling.HILLS_MEDIUM).setTemperature(-12.0f).setHumidity(30.0f); - public static final Biome jungle = (new BiomeJungle(21, false)).setColor(5470985).setBiomeName("jungle", "Urwald").setTemperature(18.0f).setHumidity(90.0f); - public static final Biome jungleHills = (new BiomeJungle(22, false)).setColor(2900485).setBiomeName("jungleHills", "Urwald-Bergland").setTemperature(18.0f).setHumidity(90.0f).setScaling(Scaling.HILLS_LOW); - public static final Biome jungleEdge = (new BiomeJungle(23, true)).setColor(6458135).setBiomeName("jungleEdge", "Urwald Gr.").setTemperature(18.0f).setHumidity(80.0f); - public static final Biome sea = (new BiomeWater(24, false)).setColor(112).setBiomeName("sea", "See").setScaling(Scaling.SEA_MEDIUM); - public static final Biome stoneBeach = (new BiomeStoneBeach(25)).setColor(10658436).setBiomeName("stoneBeach", "Steinstrand").setTemperature(-12.0f).setHumidity(30.0f).setScaling(Scaling.SEA_VARYING); - public static final Biome coldBeach = (new BiomeBeach(26)).setColor(16445632).setBiomeName("coldBeach", "Vereister Strand").setTemperature(-18.0f).setHumidity(30.0f).setScaling(Scaling.SEA_SHORE).enableColdBeach(); - public static final Biome birchForest = (new BiomeForest(27, 2)).setBiomeName("birchForest", "Birkenwald").setColor(3175492); - public static final Biome birchForestHills = (new BiomeForest(28, 2)).setBiomeName("birchForestHills", "Birkenwald-Bergland").setColor(2055986).setScaling(Scaling.HILLS_LOW); - public static final Biome roofedForest = (new BiomeForest(29, 3)).setColor(4215066).setBiomeName("roofedForest", "Dichter Wald"); - public static final Biome coldTaiga = (new BiomeTaiga(30, 0)).setColor(3233098).setBiomeName("coldTaiga", "Vereiste Taiga").enableColdBeach().setTemperature(-40.0f).setHumidity(40.0f).setScaling(Scaling.PLAINS_MEDIUM); - public static final Biome coldTaigaHills = (new BiomeTaiga(31, 0)).setColor(2375478).setBiomeName("coldTaigaHills", "Vereistes Taiga-Bergland").enableColdBeach().setTemperature(-40.0f).setHumidity(40.0f).setScaling(Scaling.HILLS_LOW); - public static final Biome megaTaiga = (new BiomeTaiga(32, 1)).setColor(5858897).setBiomeName("megaTaiga", "Hohe Taiga").setTemperature(-8.0f).setHumidity(80.0f).setScaling(Scaling.PLAINS_MEDIUM); - public static final Biome megaTaigaHills = (new BiomeTaiga(33, 1)).setColor(4542270).setBiomeName("megaTaigaHills", "Hohes Taiga-Bergland").setTemperature(-8.0f).setHumidity(80.0f).setScaling(Scaling.HILLS_LOW); - public static final Biome extremeHillsPlus = (new BiomeHills(34, true)).setColor(5271632).setBiomeName("extremeHillsPlus", "Extremes Bergland +").setScaling(Scaling.HILLS_LARGE).setTemperature(-12.0f).setHumidity(30.0f); - public static final Biome savanna = (new BiomeSavanna(35)).setColor(12431967).setBiomeName("savanna", "Savanne").setTemperature(28.0F).setHumidity(0.0f).setScaling(Scaling.PLAINS_LOW); - public static final Biome savannaPlateau = (new BiomeSavanna(36)).setColor(10984804).setBiomeName("savannaPlateau", "Savannen-Plateau").setTemperature(20.0F).setHumidity(0.0f).setScaling(Scaling.HILLS_PLATEAU); - - public static final Biome mesa = (new BiomeMesa(37, false, false)).setColor(14238997).setBiomeName("mesa", "Mesa"); - public static final Biome mesaPlateau_F = (new BiomeMesa(38, false, true)).setColor(11573093).setBiomeName("mesaPlateauF", "Mesa-Waldplateau").setScaling(Scaling.HILLS_PLATEAU); - public static final Biome mesaPlateau = (new BiomeMesa(39, false, false)).setColor(13274213).setBiomeName("mesaPlateau", "Mesa-Plateau").setScaling(Scaling.HILLS_PLATEAU); - - public static final Biome snowLand = (new BiomeSnowLand(40)).setColor(0xffffff).setBiomeName("snowLand", "Eisland").enableColdBeach().setHumidity(100.0f); - public static final Biome tian = (new BiomeTian(41)).setColor(0x808080).setBiomeName("tian", "Tian").setHumidity(80.0f).setScaling(Scaling.VARYING_MEDIUM); - public static final Biome elvenForest = (new BiomeForest(42, 4)).setColor(0x059821).setBiomeName("elvenForest", "Elbenwald").setHumidity(90.0f); - public static final Biome upperHell = (new BiomeHell(43, 0)).setColor(16711680).setBiomeName("upperHell", "Übergang in die Hölle").setHumidity(0.0f); - public static final Biome lowerHell = (new BiomeHell(44, 1)).setColor(16711680).setBiomeName("lowerHell", "Abgrund der Hölle").setHumidity(0.0f); - public static final Biome hellHills = (new BiomeHell(45, 1)).setColor(16711680).setBiomeName("hellHills", "Bergland der Hölle").setHumidity(0.0f).setScaling(Scaling.HILLS_LARGE); - public static final Biome soulPlains = (new BiomeHell(46, 1)).setColor(16711680).setBiomeName("soulPlains", "Seelenland").setHumidity(0.0f).setScaling(Scaling.SEA_POND); - public static final Biome ashLand = (new BiomeHell(47, 2)).setColor(16711680).setBiomeName("ashLand", "Verbrannt").setHumidity(0.0f).setScaling(Scaling.PLAINS_LOW); - public static final Biome moon = (new BiomeMoon(48)).setColor(0xa0a0a0).setBiomeName("moon", "Mondoberfläche").setHumidity(0.0f).setScaling(Scaling.PLAINS_LOW); - public static final Biome chaos = (new BiomeChaos(49)).setColor(0xff00ff).setBiomeName("chaos", "Chaos").setHumidity(50.0f).setScaling(Scaling.VARYING_CHAOTIC); - - public static final Biome DEF_BIOME = forest; - protected static final PerlinGen TEMP_NOISE; - protected static final PerlinGen TREE_NOISE; - protected static final PerlinGen GRASS_NOISE; - protected static final FeatureDoublePlant DOUBLE_PLANT_GEN; - private static final Map LOOKUP = Maps.newTreeMap(); - private static final List LIST = Lists.newArrayList(); - - public final int id; - - protected final WeightedList mobs = new WeightedList(); - protected final WorldGenBaseTree worldGeneratorTrees = new WorldGenBaseTree(false); - protected final WorldGenBigTree worldGeneratorBigTree = new WorldGenBigTree(false); - protected final WorldGenSwamp worldGeneratorSwamp = new WorldGenSwamp(); - private final FeatureGenerator clayGen = new WorldGenClay(4); - private final FeatureGenerator sandGen = new WorldGenSand(Blocks.sand, 7); - private final FeatureGenerator gravelAsSandGen = new WorldGenSand(Blocks.gravel, 6); - private final WorldGenFlowers yellowFlowerGen = new WorldGenFlowers(Blocks.flower, BlockFlower.EnumFlowerType.DANDELION); - private final FeatureGenerator mushroomBrownGen = new WorldGenMushroom(Blocks.brown_mushroom); - private final FeatureGenerator mushroomRedGen = new WorldGenMushroom(Blocks.red_mushroom); - private final FeatureGenerator bigMushroomGen = new WorldGenBigMushroom(); - private final FeatureGenerator reedGen = new WorldGenReed(); - private final FeatureGenerator cactusGen = new WorldGenCactus(); - private final FeatureGenerator waterlilyGen = new WorldGenWaterlily(); - private final FeatureGenerator clayGenExt = new WorldGenClayExt(32); - - public String name = null; - public String display = ""; - public int color = 0x000000; - public State topBlock = Blocks.grass.getState(); - public State fillerBlock = Blocks.dirt.getState(); - public float depth = Scaling.VARYING_LOW.depth; - public float scale = Scaling.VARYING_LOW.scale; - protected float temperature = 0.0f; - protected float humidity = 50.0f; - public int waterColor = 0xffffff; - public boolean generateLakes = true; - public boolean generateLiquids = true; - public boolean allowColdBeach = false; - public boolean disallowBeach = false; - - protected int waterlilyPerChunk = 0; - protected int treesPerChunk = 0; - protected int flowersPerChunk = 2; - protected int grassPerChunk = 1; - protected int deadBushPerChunk = 0; - protected int mushroomsPerChunk = 0; - protected int reedsPerChunk = 0; - protected int cactiPerChunk = 0; - protected int sandPerChunk = 1; - protected int sandPerChunk2 = 3; - protected int clayPerChunk = 1; - protected int clayExtPerChunk = 0; // 10 - protected int bigMushroomsPerChunk = 0; - - protected Biome(int id) { - this.id = id; - BIOMES[id] = this; - this.addMobs(this.mobs); - } - - protected void addMobs(WeightedList mobs) { - mobs.add(new RngSpawn(EntitySheep.class, 12, 4, 4)); - mobs.add(new RngSpawn(EntityRabbit.class, 10, 3, 10)); - mobs.add(new RngSpawn(EntityPig.class, 10, 4, 4)); - mobs.add(new RngSpawn(EntityChicken.class, 10, 4, 4)); - mobs.add(new RngSpawn(EntityCow.class, 8, 4, 4)); - mobs.add(new RngSpawn(EntityArachnoid.class, 100, 4, 4)); - mobs.add(new RngSpawn(EntityZombie.class, 100, 4, 4)); - mobs.add(new RngSpawn(EntityUndead.class, 100, 4, 4)); - mobs.add(new RngSpawn(EntityHaunter.class, 100, 4, 4)); - mobs.add(new RngSpawn(EntitySlime.class, 100, 4, 4)); -// mobs.add(new Biome.RngSpawn(EntityEnder....class, 10, 1, 4)); - mobs.add(new RngSpawn(EntityMage.class, 5, 1, 1)); - mobs.add(new RngSpawn(EntitySquid.class, 10, 4, 4)); - mobs.add(new RngSpawn(EntityBat.class, 10, 8, 8)); - mobs.add(new RngSpawn(EntityMouse.class, 10, 8, 8)); - } - - public int getSkyColor() { - return 0xffffffff; - } - - public int getFogColor() { - return 0xffffffff; - } - - public int getCloudColor() { - return 0xffffffff; - } - - public float getFactor() { - float f = this.humidity * 0.01f * ((this.temperature + 14.0f) / 40.0f + 0.15f); - return f > 1.0f ? 1.0f : f; - } - - // skycolor = ((temp + 14) / 40 + 0.15) / 3 - protected Biome setTemperature(float temp) - { - this.temperature = temp; - return this; - } - - protected Biome setHumidity(float humidity) - { - this.humidity = humidity; - return this; - } - - protected final Biome setScaling(Scaling scaling) - { - return this.setScaling(scaling.depth, scaling.scale); - } - - protected final Biome setScaling(float depth, float scale) - { - this.depth = depth; - this.scale = scale; - return this; - } - - public WorldGenTree genBigTreeChance(Random rand) - { - return rand.chance(10) ? this.worldGeneratorBigTree : this.worldGeneratorTrees; - } - - public WorldGenTree genBigTreeLegacy(Random rand, BlockPos pos) - { - int noise = (int)((TREE_NOISE.generate((double)pos.getX() * 0.5D, (double)pos.getZ() * 0.5D) / 8D + rand.doublev() * 4D + 4D) / 3D); - return (noise > 0 && rand.chance(noise)) || (this.isHighHumidity() && rand.chance(3)) ? this.worldGeneratorBigTree : - this.worldGeneratorTrees; - } - - /** - * Gets a WorldGen appropriate for this biome. - */ - public FeatureGenerator getRandomWorldGenForGrass(Random rand) - { - return new WorldGenTallGrass(BlockTallGrass.EnumType.GRASS); - } - - public BlockFlower.EnumFlowerType pickRandomFlower(Random rand, BlockPos pos) - { - return rand.rarity(3) ? BlockFlower.EnumFlowerType.DANDELION : BlockFlower.EnumFlowerType.ROSE; - } - - protected Biome enableColdBeach() - { - this.allowColdBeach = true; - return this; - } - - protected Biome disableBeach() - { - this.disallowBeach = true; - return this; - } - - protected Biome setBiomeName(String name, String display) - { - this.name = name; - this.display = display; - return this; - } - - protected Biome setColor(int colorIn) - { - this.color = colorIn; - return this; - } - - public WeightedList getMobs() - { - return this.mobs; - } - - public boolean isHighHumidity() - { - return this.humidity > 85.0f; - } - - public float getMobGenChance() - { - return 0.1F; - } - - public final float getTemperature(BlockPos pos) - { - if (pos.getY() > 64) - { - float f = (float)(TEMP_NOISE.generate((double)pos.getX() * 1.0D / 8.0D, (double)pos.getZ() * 1.0D / 8.0D) * 4.0D); - return this.temperature - (f + (float)pos.getY() - 64.0F) / 15.0f; - } - else - { - return this.temperature; - } - } - - public void decorate(WorldServer world, Random rand, BlockPos pos) - { - for (int i = 0; i < this.sandPerChunk2; ++i) - { - int j = rand.chOffset(); - int k = rand.chOffset(); - this.sandGen.generate(world, rand, world.getTopSolidOrLiquidBlock(pos.add(j, 0, k))); - } - - for (int i1 = 0; i1 < this.clayPerChunk; ++i1) - { - int l1 = rand.chOffset(); - int i6 = rand.chOffset(); - this.clayGen.generate(world, rand, world.getTopSolidOrLiquidBlock(pos.add(l1, 0, i6))); - } - - for (int j1 = 0; j1 < this.sandPerChunk; ++j1) - { - int i2 = rand.chOffset(); - int j6 = rand.chOffset(); - this.gravelAsSandGen.generate(world, rand, world.getTopSolidOrLiquidBlock(pos.add(i2, 0, j6))); - } - - for (int i1 = 0; i1 < this.clayExtPerChunk; ++i1) - { - int l1 = rand.chOffset(); - int i6 = rand.chOffset(); - this.clayGenExt.generate(world, rand, world.getTopSolidOrLiquidBlock(pos.add(l1, 0, i6))); - } - - int k1 = this.treesPerChunk; - - if (rand.chance(10)) - { - ++k1; - } - - for (int j2 = 0; j2 < k1; ++j2) - { - int k6 = rand.chOffset(); - int l = rand.chOffset(); - WorldGenTree treeGen = this.genBigTreeChance(rand); - treeGen.prepare(); - BlockPos blockpos = world.getHeight(pos.add(k6, 0, l)); - - if (treeGen.generate(world, rand, blockpos)) - { - treeGen.finish(world, rand, blockpos); - } - } - - for (int k2 = 0; k2 < this.bigMushroomsPerChunk; ++k2) - { - int l6 = rand.chOffset(); - int k10 = rand.chOffset(); - this.bigMushroomGen.generate(world, rand, world.getHeight(pos.add(l6, 0, k10))); - } - - for (int l2 = 0; l2 < this.flowersPerChunk; ++l2) - { - int i7 = rand.chOffset(); - int l10 = rand.chOffset(); - int j14 = world.getHeight(pos.add(i7, 0, l10)).getY() + 32; - - if (j14 > 0) - { - int k17 = rand.zrange(j14); - BlockPos blockpos1 = pos.add(i7, k17, l10); - BlockFlower.EnumFlowerType blockflower$enumflowertype = this.pickRandomFlower(rand, blockpos1); - BlockFlower blockflower = blockflower$enumflowertype.getBlockType().getBlock(); - - if (blockflower.getMaterial() != Material.air) - { - this.yellowFlowerGen.setGeneratedBlock(blockflower, blockflower$enumflowertype); - this.yellowFlowerGen.generate(world, rand, blockpos1); - } - } - } - - for (int i3 = 0; i3 < this.grassPerChunk; ++i3) - { - int j7 = rand.chOffset(); - int i11 = rand.chOffset(); - int k14 = world.getHeight(pos.add(j7, 0, i11)).getY() * 2; - - if (k14 > 0) - { - int l17 = rand.zrange(k14); - this.getRandomWorldGenForGrass(rand).generate(world, rand, pos.add(j7, l17, i11)); - } - } - - for (int j3 = 0; j3 < this.deadBushPerChunk; ++j3) - { - int k7 = rand.chOffset(); - int j11 = rand.chOffset(); - int l14 = world.getHeight(pos.add(k7, 0, j11)).getY() * 2; - - if (l14 > 0) - { - int i18 = rand.zrange(l14); - (new WorldGenDeadBush()).generate(world, rand, pos.add(k7, i18, j11)); - } - } - - for (int k3 = 0; k3 < this.waterlilyPerChunk; ++k3) - { - int l7 = rand.chOffset(); - int k11 = rand.chOffset(); - int i15 = world.getHeight(pos.add(l7, 0, k11)).getY() * 2; - - if (i15 > 0) - { - int j18 = rand.zrange(i15); - BlockPos blockpos4; - BlockPos blockpos7; - - for (blockpos4 = pos.add(l7, j18, k11); blockpos4.getY() > 0; blockpos4 = blockpos7) - { - blockpos7 = blockpos4.down(); - - if (!world.isAirBlock(blockpos7)) - { - break; - } - } - - this.waterlilyGen.generate(world, rand, blockpos4); - } - } - - for (int l3 = 0; l3 < this.mushroomsPerChunk; ++l3) - { - if (rand.chance(4)) - { - int i8 = rand.chOffset(); - int l11 = rand.chOffset(); - BlockPos blockpos2 = world.getHeight(pos.add(i8, 0, l11)); - this.mushroomBrownGen.generate(world, rand, blockpos2); - } - - if (rand.chance(8)) - { - int j8 = rand.chOffset(); - int i12 = rand.chOffset(); - int j15 = world.getHeight(pos.add(j8, 0, i12)).getY() * 2; - - if (j15 > 0) - { - int k18 = rand.zrange(j15); - BlockPos blockpos5 = pos.add(j8, k18, i12); - this.mushroomRedGen.generate(world, rand, blockpos5); - } - } - } - - if (this.mushroomsPerChunk != -1 && rand.chance(4)) - { - int i4 = rand.chOffset(); - int k8 = rand.chOffset(); - int j12 = world.getHeight(pos.add(i4, 0, k8)).getY() * 2; - - if (j12 > 0) - { - int k15 = rand.zrange(j12); - this.mushroomBrownGen.generate(world, rand, pos.add(i4, k15, k8)); - } - } - - if (this.mushroomsPerChunk != -1 && rand.chance(8)) - { - int j4 = rand.chOffset(); - int l8 = rand.chOffset(); - int k12 = world.getHeight(pos.add(j4, 0, l8)).getY() * 2; - - if (k12 > 0) - { - int l15 = rand.zrange(k12); - this.mushroomRedGen.generate(world, rand, pos.add(j4, l15, l8)); - } - } - - for (int k4 = 0; k4 < this.reedsPerChunk; ++k4) - { - int i9 = rand.chOffset(); - int l12 = rand.chOffset(); - int i16 = world.getHeight(pos.add(i9, 0, l12)).getY() * 2; - - if (i16 > 0) - { - int l18 = rand.zrange(i16); - this.reedGen.generate(world, rand, pos.add(i9, l18, l12)); - } - } - - for (int l4 = 0; l4 < 10; ++l4) - { - int j9 = rand.chOffset(); - int i13 = rand.chOffset(); - int j16 = world.getHeight(pos.add(j9, 0, i13)).getY() * 2; - - if (j16 > 0) - { - int i19 = rand.zrange(j16); - this.reedGen.generate(world, rand, pos.add(j9, i19, i13)); - } - } - - if (rand.chance(32)) - { - int i5 = rand.chOffset(); - int k9 = rand.chOffset(); - int j13 = world.getHeight(pos.add(i5, 0, k9)).getY() * 2; - - if (j13 > 0) - { - int k16 = rand.zrange(j13); - (new WorldGenPumpkin()).generate(world, rand, pos.add(i5, k16, k9)); - } - } - - for (int j5 = 0; j5 < this.cactiPerChunk; ++j5) - { - int l9 = rand.chOffset(); - int k13 = rand.chOffset(); - int l16 = world.getHeight(pos.add(l9, 0, k13)).getY() * 2; - - if (l16 > 0) - { - int j19 = rand.zrange(l16); - this.cactusGen.generate(world, rand, pos.add(l9, j19, k13)); - } - } - } - - public int getGrassColorAtPos(BlockPos pos) - { - double d0 = (double)ExtMath.clampf((this.getTemperature(pos) + 14.0f) / 40.0f + 0.15f, 0.0F, 1.0F); - double d1 = (double)ExtMath.clampf(this.humidity * 0.01f, 0.0F, 1.0F); - return Colorizer.getGrassColor(d0, d1); - } - - public int getFoliageColorAtPos(BlockPos pos) - { - double d0 = (double)ExtMath.clampf((this.getTemperature(pos) + 14.0f) / 40.0f + 0.15f, 0.0F, 1.0F); - double d1 = (double)ExtMath.clampf(this.humidity * 0.01f, 0.0F, 1.0F); - return Colorizer.getFoliageColor(d0, d1); - } - - public void genTerrainBlocks(WorldServer worldIn, Random rand, ChunkPrimer chunkPrimerIn, int x, int z, double noiseVal) - { - this.generateBiomeTerrain(worldIn, rand, chunkPrimerIn, x, z, noiseVal); - } - - /** - * Given x, z coordinates, we count down all the y positions starting at height - 1 and working our way down. When we hit a - * non-air block, we replace it with this.topBlock (default grass, descendants may set otherwise), and then a - * relatively shallow layer of blocks of type this.fillerBlock (default dirt). A random set of blocks below y == 5 - * (but always including y == 0) is replaced with bedrock in Chunk(...). - * - * If we don't hit non-air until somewhat below sea level, we top with gravel and fill down with stone. - * - * If this.fillerBlock is red sand, we replace some of that with red sandstone. - */ - public final void generateBiomeTerrain(WorldServer worldIn, Random rand, ChunkPrimer chunkPrimerIn, int x, int z, double noiseVal) - { - int i = worldIn.getSeaLevel(); - State worldState = worldIn.dimension.getFiller(); - Block worldBlock = worldState.getBlock(); - State worldAlt = worldIn.dimension.getAltFiller1(); - State liquid = worldIn.getSurfaceLiquid(); - boolean freeze = liquid.getBlock().getMaterial() == Material.water; - State iblockstate = this.topBlock; - State iblockstate1 = this.fillerBlock; - int j = -1; - int k = (int)(noiseVal / 3.0D + 3.0D + rand.doublev() * 0.25D); - int l = x & 15; - int i1 = z & 15; - BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); - - for (int j1 = chunkPrimerIn.height - 1; j1 >= 0; --j1) - { - State iblockstate2 = chunkPrimerIn.get(i1, j1, l); - - if (iblockstate2.getBlock().getMaterial() == Material.air) - { - j = -1; - } - else if (iblockstate2.getBlock() == worldBlock) - { - if (j == -1) - { - if (k <= 0) - { - iblockstate = null; - iblockstate1 = worldState; - } - else if (j1 >= i - 4 && j1 <= i + 1) - { - iblockstate = this.topBlock; - iblockstate1 = this.fillerBlock; - } - - if (j1 < i && (iblockstate == null || iblockstate.getBlock().getMaterial() == Material.air)) - { - if (freeze && World.ABSOLUTE_ZERO + worldIn.getTempOffset() + this.getTemperature(blockpos$mutableblockpos.set(x, j1, z)) <= 0.0F) - { - iblockstate = Blocks.ice.getState(); - } - else - { - iblockstate = liquid; - } - } - - j = k; - - if (j1 >= i - 1) - { - chunkPrimerIn.set(i1, j1, l, iblockstate); - } - else if (j1 < i - 7 - k) - { - iblockstate = null; - iblockstate1 = worldState; - chunkPrimerIn.set(i1, j1, l, worldAlt); - } - else - { - chunkPrimerIn.set(i1, j1, l, iblockstate1); - } - } - else if (j > 0) - { - --j; - chunkPrimerIn.set(i1, j1, l, iblockstate1); - - if (j == 0 && iblockstate1.getBlock() == Blocks.sand) - { - j = rand.zrange(4) + Math.max(0, j1 - 63); - iblockstate1 = iblockstate1.getValue(BlockSand.VARIANT) == BlockSand.EnumType.RED_SAND ? Blocks.stained_hardened_clay.getState().withProperty(BlockColored.COLOR, DyeColor.ORANGE) : Blocks.sandstone.getState(); //TODO: check! - } - } - } - } - } - - protected Biome createMutation() - { - return this.createMutatedBiome(this.id + 128); - } - - protected Biome createMutatedBiome(int p_180277_1_) - { - return new BiomeMutated(p_180277_1_, this); - } - - public Class getBiomeClass() - { - return this.getClass(); - } - - public boolean isEqualTo(Biome biome) - { - return biome == this ? true : (biome == null ? false : this.getBiomeClass() == biome.getBiomeClass()); - } - - public Temperature getTempCategory() - { - return this.temperature < -12.0f ? Temperature.COLD : (this.temperature < 20.0f ? Temperature.MEDIUM : Temperature.WARM); - } - - public static Biome getBiome(int id) - { - return getBiome(id, null); - } - - public static Biome getBiome(int id, Biome def) - { - if (id >= 0 && id < BIOMES.length) - { - Biome biome = BIOMES[id]; - return biome == null ? def : biome; - } - else - { - Log.JNI.warn("Biom-ID ist nicht im Bereich: " + id + ", verwende " + DEF_BIOME.id + " (" + DEF_BIOME.name + ")"); - return DEF_BIOME; - } - } - - public static List getBiomes() { - return LIST; - } - - public static List getBiomeNames() { - return Lists.newArrayList(LOOKUP.keySet()); - } - - public static Biome findByName(String name) { - Biome biome = LOOKUP.get(name.toLowerCase().replace(" ", "").replace("_", "")); - if(biome == null) { - int z; - try { - z = Integer.parseInt(name); - } - catch(NumberFormatException e) { - return null; - } - return z < 0 || z >= BIOMES.length ? null : BIOMES[z]; - } - return biome; - } - - static - { -// plains.createMutation(); - desert.createMutation(); - forest.createMutation(); - taiga.createMutation(); - swampland.createMutation(); - icePlains.createMutation(); - jungle.createMutation(); - jungleEdge.createMutation(); - coldTaiga.createMutation(); - savanna.createMutation(); - savannaPlateau.createMutation(); - mesa.createMutation(); - mesaPlateau_F.createMutation(); - mesaPlateau.createMutation(); - birchForest.createMutation(); - birchForestHills.createMutation(); - roofedForest.createMutation(); - megaTaiga.createMutation(); - extremeHills.createMutation(); - extremeHillsPlus.createMutation(); - megaTaiga.createMutatedBiome(megaTaigaHills.id + 128).setBiomeName("redwoodTaigaHillsM", "Mammutbaumtaiga"); - - TEMP_NOISE = new PerlinGen(new Random(1234L), 1); - TREE_NOISE = new PerlinGen(new Random(667L), 8); - GRASS_NOISE = new PerlinGen(new Random(2345L), 1); - DOUBLE_PLANT_GEN = new FeatureDoublePlant(); - - for(Biome biome : BIOMES) { - if(biome == null) - continue; - if(LOOKUP.containsKey(biome.name.toLowerCase())) - throw new IllegalStateException("Biom \"" + biome.name + "\" ist als ID " + LOOKUP.get(biome.name.toLowerCase()).id + " und " + biome.id + " definiert"); - LOOKUP.put(biome.name.toLowerCase(), biome); - LIST.add(biome); - } - } -} diff --git a/java/src/game/biome/BiomeExterminated.java b/java/src/game/biome/BiomeExterminated.java deleted file mode 100755 index 076c215..0000000 --- a/java/src/game/biome/BiomeExterminated.java +++ /dev/null @@ -1,33 +0,0 @@ -package game.biome; - -import game.init.Blocks; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.world.WorldServer; - -public class BiomeExterminated extends Biome { - public BiomeExterminated(int id) { - super(id); - this.topBlock = Blocks.air.getState(); - this.fillerBlock = Blocks.air.getState(); - } - - protected void addMobs(WeightedList mobs) { - } - - public void decorate(WorldServer worldIn, Random rand, BlockPos pos) { - } - - public int getSkyColor() { - return 0x101010; - } - - public int getFogColor() { - return 0x303030; - } - - public int getCloudColor() { - return 0x000000; - } -} diff --git a/java/src/game/block/Block.java b/java/src/game/block/Block.java deleted file mode 100755 index 78aab88..0000000 --- a/java/src/game/block/Block.java +++ /dev/null @@ -1,1447 +0,0 @@ -package game.block; - -import java.lang.reflect.Array; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.NoSuchElementException; - -import java.util.function.Function; -import game.collect.ImmutableList; -import game.collect.ImmutableMap; -import game.collect.Iterables; -import game.collect.Lists; -import game.collect.Maps; -import game.collect.UnmodifiableIterator; - -import game.audio.SoundType; -import game.enchantment.EnchantmentHelper; -import game.entity.Entity; -import game.entity.item.EntityItem; -import game.entity.item.EntityXp; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Config; -import game.init.ItemRegistry; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Explosion; -import game.world.Facing; -import game.world.HitPosition; -import game.world.HitPosition.ObjectType; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.Vec3; -import game.world.World; -import game.world.WorldClient; -import game.world.WorldServer; - -public class Block -{ - private static class Product implements Iterable - { - private final Class clazz; - private final Iterable [] iterables; - - private Product(Class clazz, Iterable [] iterables) - { - this.clazz = clazz; - this.iterables = iterables; - } - - public Iterator iterator() - { - return (Iterator)(this.iterables.length <= 0 ? Collections.singletonList((Object[])createArray(this.clazz, 0)).iterator() : new Product.ProductIterator(this.clazz, this.iterables)); - } - - static class ProductIterator extends UnmodifiableIterator - { - private int index; - private final Iterable [] iterables; - private final Iterator [] iterators; - private final T[] results; - - private ProductIterator(Class clazz, Iterable [] iterables) - { - this.index = -2; - this.iterables = iterables; - this.iterators = (Iterator[])createArray(Iterator.class, this.iterables.length); - - for (int i = 0; i < this.iterables.length; ++i) - { - this.iterators[i] = iterables[i].iterator(); - } - - this.results = createArray(clazz, this.iterators.length); - } - - private void endOfData() - { - this.index = -1; - Arrays.fill(this.iterators, (Object)null); - Arrays.fill(this.results, (Object)null); - } - - public boolean hasNext() - { - if (this.index == -2) - { - this.index = 0; - - for (Iterator iterator1 : this.iterators) - { - if (!iterator1.hasNext()) - { - this.endOfData(); - break; - } - } - - return true; - } - else - { - if (this.index >= this.iterators.length) - { - for (this.index = this.iterators.length - 1; this.index >= 0; --this.index) - { - Iterator iterator = this.iterators[this.index]; - - if (iterator.hasNext()) - { - break; - } - - if (this.index == 0) - { - this.endOfData(); - break; - } - - iterator = this.iterables[this.index].iterator(); - this.iterators[this.index] = iterator; - - if (!iterator.hasNext()) - { - this.endOfData(); - break; - } - } - } - - return this.index >= 0; - } - } - - public T[] next() - { - if (!this.hasNext()) - { - throw new NoSuchElementException(); - } - else - { - while (this.index < this.iterators.length) - { - this.results[this.index] = this.iterators[this.index].next(); - ++this.index; - } - - return (T[])((Object[])this.results.clone()); - } - } - } - } - - private static class GetList implements Function> - { - private GetList() - { - } - - public List apply(Object[] p_apply_1_) - { - return Arrays.asList((T[])p_apply_1_); - } - } - - private final ImmutableList properties; - private final ImmutableList states; - protected final Material material; - - protected boolean fullBlock; - protected boolean translucent; - protected boolean sumBrightness; - protected boolean axeHarvest; - protected boolean shovelHarvest; -// protected boolean enableStats; - protected boolean ticked; - protected boolean hasTile; - protected int lightOpacity; - protected int lightValue; - protected int miningLevel; - protected int shearsEfficiency; - protected float blockHardness; - protected float blockResistance; - protected float radiation; - public float slipperiness; - protected double minX; - protected double minY; - protected double minZ; - protected double maxX; - protected double maxY; - protected double maxZ; - private State defaultState; - private String display; - private CheatTab tab; - public SoundType sound; - - private static Iterable> cartesianProduct(Iterable > sets) - { - return arraysAsLists(cartesianProduct(Object.class, sets)); - } - - private static Iterable cartesianProduct(Class clazz, Iterable > sets) - { - return new Product(clazz, (Iterable[])toArray(Iterable.class, sets)); - } - - private static Iterable> arraysAsLists(Iterable arrays) - { - return Iterables.transform(arrays, new GetList()); - } - - private static T[] toArray(Class clazz, Iterable it) - { - List list = Lists.newArrayList(); - - for (T t : it) - { - list.add(t); - } - - return (T[])((Object[])list.toArray(createArray(clazz, list.size()))); - } - - private static T[] createArray(Class p_179319_0_, int p_179319_1_) - { - return (T[])((Object[])((Object[])Array.newInstance(p_179319_0_, p_179319_1_))); - } - - private static Map createMap(Iterable keys, Iterable values) - { - return populateMap(keys, values, Maps.newLinkedHashMap()); - } - - private static Map populateMap(Iterable keys, Iterable values, Map map) - { - Iterator iterator = values.iterator(); - - for (IProperty k : keys) - { - map.put(k, iterator.next()); - } - - if (iterator.hasNext()) - { - throw new NoSuchElementException(); - } - else - { - return map; - } - } - - public Block(Material material) - { - this.miningLevel = (material == Material.rock || material == Material.iron || material == Material.anvil) ? 0 : -1; - this.axeHarvest = material == Material.wood || material == Material.plants || material == Material.vine || - material == Material.gourd; - this.shearsEfficiency = (material == Material.leaves || material == Material.web) ? 3 : -1; -// this.enableStats = true; - this.sound = SoundType.STONE; - this.slipperiness = 0.6F; - this.material = material; -// this.blockMapColor = blockMapColorIn; - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - this.fullBlock = this.isOpaqueCube(); - this.lightOpacity = this.isOpaqueCube() ? 255 : 0; - this.translucent = !material.blocksLight(); -// this.smap = new StateList(this, this.getProperties()); - IProperty[] properties = this.getProperties(); - Arrays.sort(properties, new Comparator() { - public int compare(IProperty p1, IProperty p2) { - return p1.getName().compareTo(p2.getName()); - } - }); - this.properties = ImmutableList.copyOf(properties); - Map, State> map = Maps., State>newLinkedHashMap(); - List list = Lists.newArrayList(); - for(List allowed : cartesianProduct(this.getAllowedValues())) { - Map props = createMap(this.properties, allowed); - State state = new State(this, ImmutableMap.copyOf(props)); - map.put(props, state); - list.add(state); - } - for(State state : list) { - state.buildTable(map); - } - this.states = ImmutableList.copyOf(list); - this.setDefaultState(this.getBaseState()); - } - - /** - * Sets the footstep sound for the block. Returns the object for convenience in constructing. - */ - public Block setStepSound(SoundType sound) - { - this.sound = sound; - return this; - } - - /** - * Sets how much light is blocked going through this block. Returns the object for convenience in constructing. - */ - public Block setLightOpacity(int opacity) - { - this.lightOpacity = opacity; - return this; - } - - /** - * Sets the light value that the block emits. Returns resulting block instance for constructing convenience. Args: - * level - */ - public Block setLightLevel(float value) - { - this.lightValue = (int)(15.0F * value); - return this; - } - - /** - * Sets the the blocks resistance to explosions. Returns the object for convenience in constructing. - */ - public Block setResistance(float resistance) - { - this.blockResistance = resistance * 3.0F; - return this; - } - - /** - * Sets how many hits it takes to break a block. - */ - public Block setHardness(float hardness) - { - this.blockHardness = hardness; - - if (this.blockResistance < hardness * 5.0F) - { - this.blockResistance = hardness * 5.0F; - } - - return this; - } - -// public Block setBlockUnbreakable() -// { -// this.setHardness(-1.0F); -// this.setResistance(6000000.0F); -// return this; -// } - - /** - * Sets whether this block type will receive random update ticks - */ - protected Block setTickRandomly() - { - this.ticked = true; - return this; - } - - public Block setDisplay(String name) - { - this.display = name; - return this; - } - -// public Block disableStats() -// { -// this.enableStats = false; -// return this; -// } - - public Block setTab(CheatTab tab) - { - this.tab = tab; - return this; - } - - public Block setSumBrightness() - { - this.sumBrightness = true; - return this; - } - - public Block setMiningLevel(int level) - { - this.miningLevel = level; - return this; - } - - public Block setAxeHarvestable() - { - this.axeHarvest = true; - return this; - } - - public Block setShovelHarvestable() - { - this.shovelHarvest = true; - return this; - } - - public Block setShearsEfficiency(int efficiency) - { - this.shearsEfficiency = efficiency; - return this; - } - - public Block setRadiation(float value) - { - this.radiation = value; - if(value > 0.0f) - this.ticked = true; - return this; - } - - - - public boolean isFullBlock() - { - return this.fullBlock; - } - - public int getLightOpacity() - { - return this.lightOpacity; - } - - /** - * Used in the renderer to apply ambient occlusion - */ - public boolean isTranslucent() - { - return this.translucent; - } - - public int getLightValue() - { - return this.lightValue; - } - - /** - * Should block use the brightest neighbor light value as its own - */ - public boolean getSumBrightness() - { - return this.sumBrightness; - } - - /** - * Get a material of block - */ - public Material getMaterial() - { - return this.material; - } - - public ImmutableList getValidStates() { - return this.states; - } - - private List> getAllowedValues() { - List> list = Lists.>newArrayList(); - for(int z = 0; z < this.properties.size(); z++) { - list.add((this.properties.get(z)).getAllowedValues()); - } - return list; - } - - public final State getBaseState() { - return this.states.get(0); - } - -// public Block getBlock() { -// return this; -// } - - public Collection getPropertyMap() { - return this.properties; - } - -// public String toString() { -// return Objects.toStringHelper(this).add("block", BlockRegistry.REGISTRY.getNameForObject(this)) -// .add("properties", Iterables.transform(this.properties, GET_NAME_FUNC)).toString(); -// } - -// /** -// * Get the MapColor for this Block and the given BlockState -// */ -// public final MapColor getMapColor(IBlockState state) -// { -// return this.blockMapColor; -// } - - /** - * Convert the given metadata into a BlockState for this Block - */ - public State getStateFromMeta(int meta) - { - return this.getState(); - } - - /** - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(State state) - { - if (state != null && !state.getPropertyNames().isEmpty()) - { - throw new IllegalArgumentException("Don\'t know how to convert " + state + " back into data..."); - } - else - { - return 0; - } - } - - /** - * Get the actual Block state of this Block at the given position. This applies properties not visible in the - * metadata, such as fence connections. - */ - public State getActualState(State state, IWorldAccess worldIn, BlockPos pos) - { - return state; - } - - /** - * Indicate if a material is a normal solid opaque cube - */ - public boolean isBlockNormalCube() - { - return this.material.blocksMovement() && this.isFullCube(); - } - - /** - * Used for nearly all game logic (non-rendering) purposes. Use Forge-provided isNormalCube(IBlockAccess, BlockPos) - * instead. - */ - public boolean isNormalCube() - { - return this.material.isOpaque() && this.isFullCube() && !this.canProvidePower(); - } - - public boolean isVisuallyOpaque() - { - return this.material.blocksMovement() && this.isFullCube(); - } - - public boolean isFullCube() - { - return true; - } - - public boolean isPassable(IBlockAccess worldIn, BlockPos pos) - { - return !this.material.blocksMovement(); - } - - /** - * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() - { - return 3; - } - - public boolean isXrayVisible() - { - return false; - } - - /** - * Whether this Block can be replaced directly by other blocks (true for e.g. tall grass) - */ - public boolean isReplaceable(World worldIn, BlockPos pos) - { - return false; - } - - public float getBlockHardness(World worldIn, BlockPos pos) - { - return this.blockHardness; - } - - /** - * Returns whether or not this block is of a type that needs random ticking. Called for ref-counting purposes by - * ExtendedBlockStorage in order to broadly cull a chunk from the random chunk update list for efficiency's sake. - */ - public boolean getTickRandomly() - { - return this.ticked; - } - - public boolean hasTileEntity() - { - return this.hasTile; - } - - protected final void setBlockBounds(float minX, float minY, float minZ, float maxX, float maxY, float maxZ) - { - this.minX = (double)minX; - this.minY = (double)minY; - this.minZ = (double)minZ; - this.maxX = (double)maxX; - this.maxY = (double)maxY; - this.maxZ = (double)maxZ; - } - - public int getMixedBrightnessForBlock(IWorldAccess worldIn, BlockPos pos) - { - Block block = worldIn.getState(pos).getBlock(); - int i = worldIn.getCombinedLight(pos, block.getLightValue()); - - if (i == 0 && block instanceof BlockSlab) - { - pos = pos.down(); - block = worldIn.getState(pos).getBlock(); - return worldIn.getCombinedLight(pos, block.getLightValue()); - } - else - { - return i; - } - } - - public boolean shouldSideBeRendered(IWorldAccess worldIn, BlockPos pos, Facing side) - { - return side == Facing.DOWN && this.minY > 0.0D ? true : (side == Facing.UP && this.maxY < 1.0D ? true : (side == Facing.NORTH && this.minZ > 0.0D ? true : (side == Facing.SOUTH && this.maxZ < 1.0D ? true : (side == Facing.WEST && this.minX > 0.0D ? true : (side == Facing.EAST && this.maxX < 1.0D ? true : !worldIn.getState(pos).getBlock().isOpaqueCube()))))); - } - - /** - * Whether this Block is solid on the given Side - */ - public boolean isBlockSolid(IBlockAccess worldIn, BlockPos pos, Facing side) - { - return worldIn.getState(pos).getBlock().getMaterial().isSolid(); - } - - public BoundingBox getSelectedBoundingBox(World worldIn, BlockPos pos) - { - return new BoundingBox((double)pos.getX() + this.minX, (double)pos.getY() + this.minY, (double)pos.getZ() + this.minZ, (double)pos.getX() + this.maxX, (double)pos.getY() + this.maxY, (double)pos.getZ() + this.maxZ); - } - - /** - * Add all collision boxes of this Block to the list that intersect with the given mask. - */ - public void addCollisionBoxesToList(World worldIn, BlockPos pos, State state, BoundingBox mask, List list, Entity collidingEntity) - { - BoundingBox axisalignedbb = this.getCollisionBoundingBox(worldIn, pos, state); - - if (axisalignedbb != null && mask.intersectsWith(axisalignedbb)) - { - list.add(axisalignedbb); - } - } - - public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) - { - return new BoundingBox((double)pos.getX() + this.minX, (double)pos.getY() + this.minY, (double)pos.getZ() + this.minZ, (double)pos.getX() + this.maxX, (double)pos.getY() + this.maxY, (double)pos.getZ() + this.maxZ); - } - - /** - * Used to determine ambient occlusion and culling when rebuilding chunks for render - */ - public boolean isOpaqueCube() - { - return true; - } - - public boolean canCollideCheck(State state, boolean hitIfLiquid) - { - return this.isCollidable(); - } - - /** - * Returns if this block is collidable (only used by Fire). Args: x, y, z - */ - public boolean isCollidable() - { - return true; - } - - /** - * Called randomly when setTickRandomly is set to true (used by e.g. crops to grow, etc.) - */ - public void randomTick(WorldServer worldIn, BlockPos pos, State state, Random random) - { - this.updateTick(worldIn, pos, state, random); - if(this.radiation > 0.0f && /* worldIn.getTime() % 5L == 0L && */ random.chance(Config.randomTick / 3)) - this.affectEntities(worldIn, pos, state, this.radiation * 8.0f * 0.25f); - } - - private void affectEntities(WorldServer worldIn, BlockPos pos, State state, float rad) - { - float r = ExtMath.clampf(rad * 2.0f, 0.0f, 25.0f); - BoundingBox box = this.getCollisionBoundingBox(worldIn, pos, state); - if(box == null) - box = new BoundingBox(pos, pos.add(1, 1, 1)); - for (EntityLiving entity : worldIn.getEntitiesWithinAABB(EntityLiving.class, box.expand(r, r, r))) - { - float effect = rad * 2.0f * (r - ExtMath.sqrtf((float)entity.getDistanceSq(pos))) / r; - if(effect > 0.0f) - entity.addRadiation(effect); - } - } - - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) - { - } - - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) - { - } - - /** - * Called when a player destroys this Block - */ - public void onBlockDestroyedByPlayer(World worldIn, BlockPos pos, State state) - { - } - - /** - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) - { - } - - /** - * How many world ticks before ticking - */ - public int tickRate(World worldIn, BlockPos pos) - { - return 10; - } - - public void onBlockAdded(WorldServer world, BlockPos pos, State state) - { - } - - public void onBlockRemoved(WorldServer world, BlockPos pos, State state) - { - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(Random random) - { - return 1; - } - - /** - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(State state, Random rand, int fortune) - { - return ItemRegistry.getItemFromBlock(this); - } - - /** - * Get the hardness of this Block relative to the ability of the given player - */ - public float getPlayerRelativeBlockHardness(EntityNPC playerIn, World worldIn, BlockPos pos) - { - float f = this.getBlockHardness(worldIn, pos); - return f < 0.0F ? 0.0F : (!playerIn.canHarvestBlock(this) ? playerIn.getToolDigEfficiency(this) / f / 100.0F : playerIn.getToolDigEfficiency(this) / f / 30.0F); - } - - /** - * Spawn this Block's drops into the World as EntityItems - */ - public final void dropBlockAsItem(World worldIn, BlockPos pos, State state, int forture) - { - this.dropBlockAsItemWithChance(worldIn, pos, state, 1.0F, forture); - } - - /** - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) - { - if (!worldIn.client) - { - int i = this.quantityDroppedWithBonus(fortune, worldIn.rand); - - for (int j = 0; j < i; ++j) - { - if (worldIn.rand.floatv() <= chance) - { - Item item = this.getItemDropped(state, worldIn.rand, fortune); - - if (item != null) - { - spawnAsEntity(worldIn, pos, new ItemStack(item, 1, this.damageDropped(state))); - } - } - } - } - } - - /** - * Spawns the given ItemStack as an EntityItem into the World at the given position - */ - public static void spawnAsEntity(World worldIn, BlockPos pos, ItemStack stack) - { - if (!worldIn.client && Config.blockDrop) - { - float f = 0.5F; - double d0 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; - double d1 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; - double d2 = (double)(worldIn.rand.floatv() * f) + (double)(1.0F - f) * 0.5D; - EntityItem entityitem = new EntityItem(worldIn, (double)pos.getX() + d0, (double)pos.getY() + d1, (double)pos.getZ() + d2, stack); - entityitem.setDefaultPickupDelay(); - worldIn.spawnEntityInWorld(entityitem); - } - } - - /** - * Spawns the given amount of experience into the World as XP orb entities - */ - protected void dropXpOnBlockBreak(World worldIn, BlockPos pos, int amount) - { - if (!worldIn.client && Config.blockXP) - { - while (amount > 0) - { - int i = EntityXp.getXPSplit(amount); - amount -= i; - worldIn.spawnEntityInWorld(new EntityXp(worldIn, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, i)); - } - } - } - - /** - * Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It - * returns the metadata of the dropped item based on the old metadata of the block. - */ - public int damageDropped(State state) - { - return 0; - } - - /** - * Returns how much this block can resist explosions from the passed in entity. - */ - public float getExplosionResistance(Entity exploder) - { - return this.blockResistance / 5.0F; - } - - /** - * Ray traces through the blocks collision from start vector to end vector returning a ray trace hit. - */ - public HitPosition collisionRayTrace(World worldIn, BlockPos pos, Vec3 start, Vec3 end) - { - this.setBlockBoundsBasedOnState(worldIn, pos); - start = start.addVector((double)(-pos.getX()), (double)(-pos.getY()), (double)(-pos.getZ())); - end = end.addVector((double)(-pos.getX()), (double)(-pos.getY()), (double)(-pos.getZ())); - Vec3 vec3 = start.getIntermediateWithXValue(end, this.minX); - Vec3 vec31 = start.getIntermediateWithXValue(end, this.maxX); - Vec3 vec32 = start.getIntermediateWithYValue(end, this.minY); - Vec3 vec33 = start.getIntermediateWithYValue(end, this.maxY); - Vec3 vec34 = start.getIntermediateWithZValue(end, this.minZ); - Vec3 vec35 = start.getIntermediateWithZValue(end, this.maxZ); - - if (!this.isVecInsideYZBounds(vec3)) - { - vec3 = null; - } - - if (!this.isVecInsideYZBounds(vec31)) - { - vec31 = null; - } - - if (!this.isVecInsideXZBounds(vec32)) - { - vec32 = null; - } - - if (!this.isVecInsideXZBounds(vec33)) - { - vec33 = null; - } - - if (!this.isVecInsideXYBounds(vec34)) - { - vec34 = null; - } - - if (!this.isVecInsideXYBounds(vec35)) - { - vec35 = null; - } - - Vec3 vec36 = null; - - if (vec3 != null && (vec36 == null || start.squareDistanceTo(vec3) < start.squareDistanceTo(vec36))) - { - vec36 = vec3; - } - - if (vec31 != null && (vec36 == null || start.squareDistanceTo(vec31) < start.squareDistanceTo(vec36))) - { - vec36 = vec31; - } - - if (vec32 != null && (vec36 == null || start.squareDistanceTo(vec32) < start.squareDistanceTo(vec36))) - { - vec36 = vec32; - } - - if (vec33 != null && (vec36 == null || start.squareDistanceTo(vec33) < start.squareDistanceTo(vec36))) - { - vec36 = vec33; - } - - if (vec34 != null && (vec36 == null || start.squareDistanceTo(vec34) < start.squareDistanceTo(vec36))) - { - vec36 = vec34; - } - - if (vec35 != null && (vec36 == null || start.squareDistanceTo(vec35) < start.squareDistanceTo(vec36))) - { - vec36 = vec35; - } - - if (vec36 == null) - { - return null; - } - else - { - Facing enumfacing = null; - - if (vec36 == vec3) - { - enumfacing = Facing.WEST; - } - - if (vec36 == vec31) - { - enumfacing = Facing.EAST; - } - - if (vec36 == vec32) - { - enumfacing = Facing.DOWN; - } - - if (vec36 == vec33) - { - enumfacing = Facing.UP; - } - - if (vec36 == vec34) - { - enumfacing = Facing.NORTH; - } - - if (vec36 == vec35) - { - enumfacing = Facing.SOUTH; - } - - return new HitPosition(ObjectType.BLOCK, vec36.addVector((double)pos.getX(), (double)pos.getY(), (double)pos.getZ()), enumfacing, pos); - } - } - - /** - * Checks if a vector is within the Y and Z bounds of the block. - */ - private boolean isVecInsideYZBounds(Vec3 point) - { - return point == null ? false : point.yCoord >= this.minY && point.yCoord <= this.maxY && point.zCoord >= this.minZ && point.zCoord <= this.maxZ; - } - - /** - * Checks if a vector is within the X and Z bounds of the block. - */ - private boolean isVecInsideXZBounds(Vec3 point) - { - return point == null ? false : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.zCoord >= this.minZ && point.zCoord <= this.maxZ; - } - - /** - * Checks if a vector is within the X and Y bounds of the block. - */ - private boolean isVecInsideXYBounds(Vec3 point) - { - return point == null ? false : point.xCoord >= this.minX && point.xCoord <= this.maxX && point.yCoord >= this.minY && point.yCoord <= this.maxY; - } - - /** - * Called when this Block is destroyed by an Explosion - */ - public void onBlockDestroyedByExplosion(World worldIn, BlockPos pos, Explosion explosionIn, State prevState) - { - } - - public BlockLayer getBlockLayer() - { - return BlockLayer.SOLID; - } - - public boolean canReplace(World worldIn, BlockPos pos, Facing side, ItemStack stack) - { - return this.canPlaceBlockOnSide(worldIn, pos, side); - } - - /** - * Check whether this Block can be placed on the given side - */ - public boolean canPlaceBlockOnSide(World worldIn, BlockPos pos, Facing side) - { - return this.canPlaceBlockAt(worldIn, pos); - } - - public boolean canPlaceBlockAt(World worldIn, BlockPos pos) - { - return worldIn.getState(pos).getBlock().material.isReplaceable(); - } - - public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) - { - return false; - } - - /** - * Triggered whenever an entity collides with this block (enters into the block) - */ - public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, Entity entityIn) - { - } - - /** - * Called by ItemBlocks just before a block is actually set in the world, to allow for adjustments to the - * IBlockstate - */ - public State onBlockPlaced(World worldIn, BlockPos pos, Facing facing, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) - { - return this.getStateFromMeta(meta); - } - - public void onBlockClicked(World worldIn, BlockPos pos, EntityNPC playerIn) - { - } - - public Vec3 modifyAcceleration(World worldIn, BlockPos pos, Entity entityIn, Vec3 motion) - { - return motion; - } - - public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos) - { - } - - /** - * returns the block bounderies minX value - */ - public final double getBlockBoundsMinX() - { - return this.minX; - } - - /** - * returns the block bounderies maxX value - */ - public final double getBlockBoundsMaxX() - { - return this.maxX; - } - - /** - * returns the block bounderies minY value - */ - public final double getBlockBoundsMinY() - { - return this.minY; - } - - /** - * returns the block bounderies maxY value - */ - public final double getBlockBoundsMaxY() - { - return this.maxY; - } - - /** - * returns the block bounderies minZ value - */ - public final double getBlockBoundsMinZ() - { - return this.minZ; - } - - /** - * returns the block bounderies maxZ value - */ - public final double getBlockBoundsMaxZ() - { - return this.maxZ; - } - -// public int getBlockColor() -// { -// return 16777215; -// } - - public int getRenderColor(State state) - { - return 16777215; - } - - public int colorMultiplier(IWorldAccess worldIn, BlockPos pos, int renderPass) - { - return 16777215; - } - - public final int colorMultiplier(IWorldAccess worldIn, BlockPos pos) - { - return this.colorMultiplier(worldIn, pos, 0); - } - - public int getWeakPower(IWorldAccess worldIn, BlockPos pos, State state, Facing side) - { - return 0; - } - - /** - * Can this block provide power. Only wire currently seems to have this change based on its state. - */ - public boolean canProvidePower() - { - return false; - } - - /** - * Called When an Entity Collided with the Block - */ - public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, State state, Entity entityIn) - { - } - - public int getStrongPower(IWorldAccess worldIn, BlockPos pos, State state, Facing side) - { - return 0; - } - - /** - * Sets the block's bounds for rendering it as an item - */ - public void setBlockBoundsForItemRender() - { - } - - public void harvestBlock(World worldIn, EntityNPC player, BlockPos pos, State state, TileEntity te) - { -// player.triggerAchievement(StatRegistry.mineBlockStatArray[BlockRegistry.getIdFromBlock(this)]); - - if (this.canSilkHarvest() && EnchantmentHelper.getSilkTouchModifier(player)) - { - ItemStack itemstack = this.createStackedBlock(state); - - if (itemstack != null) - { - spawnAsEntity(worldIn, pos, itemstack); - } - } - else - { - int i = EnchantmentHelper.getFortuneModifier(player); - this.dropBlockAsItem(worldIn, pos, state, i); - } - } - - public boolean canSilkHarvest() - { - return this.isFullCube() && !this.hasTile; - } - - public ItemStack createStackedBlock(State state) - { - int i = 0; - Item item = ItemRegistry.getItemFromBlock(this); - - if (item != null && item.getHasSubtypes()) - { - i = this.getMetaFromState(state); - } - - return new ItemStack(item, 1, i); - } - - /** - * Get the quantity dropped based on the given fortune level - */ - public int quantityDroppedWithBonus(int fortune, Random random) - { - return this.quantityDropped(random); - } - - /** - * Called by ItemBlocks after a block is set in the world, to allow post-place logic - */ - public void onBlockPlacedBy(World worldIn, BlockPos pos, State state, EntityLiving placer, ItemStack stack) - { - } - - /** - * Return true if an entity can be spawned inside the block (used to get the player's bed spawn location) - */ - public boolean canSpawnInBlock() - { - return !this.material.isSolid() && !this.material.isLiquid(); - } - -// /** -// * Gets the localized name of this block. Used for the statistics page. -// */ -// public String getLocalizedName() -// { -// return Strs.get(this.getUnlocalizedName() + ".name"); -// } - - public final String getDisplay() - { - return this.display; - } - - /** - * Called on both Client and Server when World#addBlockEvent is called - */ - public boolean onBlockEventReceived(World worldIn, BlockPos pos, State state, int eventID, int eventParam) - { - return false; - } - -// /** -// * Return the state of blocks statistics flags - if the block is counted for mined and placed. -// */ -// public boolean getEnableStats() -// { -// return this.enableStats; -// } - - public int getMobilityFlag() - { - return this.material.getMaterialMobility(); - } - - /** - * Returns the default ambient occlusion value based on block opacity - */ - public float getAmbientOcclusionLightValue() - { - return this.isBlockNormalCube() ? 0.2F : 1.0F; - } - - /** - * Block's chance to react to a living entity falling on it. - */ - public void onFallenUpon(World worldIn, BlockPos pos, Entity entityIn, float fallDistance) - { - entityIn.fall(fallDistance, 1.0F); - } - - /** - * Called when an Entity lands on this Block. This method *must* update motionY because the entity will not do that - * on its own - */ - public void onLanded(World worldIn, Entity entityIn) - { - entityIn.motionY = 0.0D; - } - - public Item getItem(World worldIn, BlockPos pos) - { - return ItemRegistry.getItemFromBlock(this); - } - - /** - * Gets the meta to use for the Pick Block ItemStack result - */ - public int getDamageValue(World worldIn, BlockPos pos) - { - return this.damageDropped(worldIn.getState(pos)); - } - - /** - * returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item itemIn, CheatTab tab, List list) - { - list.add(new ItemStack(itemIn, 1, 0)); - } - - /** - * Returns the tab to display the given block on. - */ - public CheatTab getTab() - { - return this.tab; - } - - public void onBlockHarvested(World worldIn, BlockPos pos, State state, EntityNPC player) - { - } - - /** - * Called similar to random ticks, but only when it is raining. - */ - public void fillWithRain(World worldIn, BlockPos pos) - { - } - - public boolean isPickStrict() - { - return false; - } - - public boolean requiresUpdates() - { - return true; - } - - /** - * Return whether this block can drop from an explosion. - */ - public boolean canDropFromExplosion(Explosion explosionIn) - { - return true; - } - - public boolean isAssociatedBlock(Block other) - { - return this == other; - } - - public static boolean isEqualTo(Block blockIn, Block other) - { - return blockIn != null && other != null ? (blockIn == other ? true : blockIn.isAssociatedBlock(other)) : false; - } - - public boolean hasComparatorInputOverride() - { - return false; - } - - public int getComparatorInputOverride(World worldIn, BlockPos pos) - { - return 0; - } - - /** - * Possibly modify the given BlockState before rendering it on an Entity (Minecarts, Endermen, ...) - */ - public State getStateForEntityRender(State state) - { - return state; - } - - protected IProperty[] getProperties() - { - return new IProperty[0]; - } - - protected final void setDefaultState(State state) - { - this.defaultState = state; - } - - public final State getState() - { - return this.defaultState; - } - -// public EnumOffsetType getOffsetType() -// { -// return EnumOffsetType.NONE; -// } - -// public String toString() -// { -// return "Block{" + BlockRegistry.REGISTRY.getNameForObject(this) + "}"; -// } - - public int getMiningLevel() { - return this.miningLevel; - } - - public boolean canAxeHarvest() { - return this.axeHarvest; - } - - public boolean canShovelHarvest() { - return this.shovelHarvest; - } - - public int getShearsEfficiency() { - return this.shearsEfficiency; - } - - public boolean isMagnetic() { - return false; - } - - public Transforms getTransform() { - return Transforms.BLOCK; - } - - public ModelBlock getModel(String name, State state) { - return new ModelBlock(name).add().all(); - } - - public IProperty[] getIgnoredProperties() { - return null; - } - - public void getAnimatedTextures(Map map) { - } - - public boolean canKeepFire() { - return false; - } - - public void onDestroyedByFire(World world, BlockPos pos, State state) { - } -} diff --git a/java/src/game/block/BlockAir.java b/java/src/game/block/BlockAir.java deleted file mode 100755 index 55fdb2b..0000000 --- a/java/src/game/block/BlockAir.java +++ /dev/null @@ -1,56 +0,0 @@ -package game.block; - -import game.material.Material; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.State; -import game.world.World; - -public class BlockAir extends Block -{ - public BlockAir() - { - super(Material.air); - } - - /** - * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() - { - return -1; - } - - public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) - { - return null; - } - - /** - * Used to determine ambient occlusion and culling when rebuilding chunks for render - */ - public boolean isOpaqueCube() - { - return false; - } - - public boolean canCollideCheck(State state, boolean hitIfLiquid) - { - return false; - } - - /** - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) - { - } - - /** - * Whether this Block can be replaced directly by other blocks (true for e.g. tall grass) - */ - public boolean isReplaceable(World worldIn, BlockPos pos) - { - return true; - } -} diff --git a/java/src/game/block/BlockBanner.java b/java/src/game/block/BlockBanner.java deleted file mode 100755 index 4136f50..0000000 --- a/java/src/game/block/BlockBanner.java +++ /dev/null @@ -1,273 +0,0 @@ -package game.block; - -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.Transforms; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityBanner; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IBlockAccess; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; - -public class BlockBanner extends BlockContainer -{ - public static final PropertyDirection FACING = PropertyDirection.create("facing", Facing.Plane.HORIZONTAL); - public static final PropertyInteger ROTATION = PropertyInteger.create("rotation", 0, 15); - - public BlockBanner() - { - super(Material.wood); - float f = 0.25F; - float f1 = 1.0F; - this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f1, 0.5F + f); - } - -// /** -// * Gets the localized name of this block. Used for the statistics page. -// */ -// public String getLocalizedName() -// { -// return "Banner"; -// } - - public boolean isPickStrict() - { - return true; - } - - public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) - { - return null; - } - - public BoundingBox getSelectedBoundingBox(World worldIn, BlockPos pos) - { - this.setBlockBoundsBasedOnState(worldIn, pos); - return super.getSelectedBoundingBox(worldIn, pos); - } - - public boolean isFullCube() - { - return false; - } - - public boolean isPassable(IBlockAccess worldIn, BlockPos pos) - { - return true; - } - - /** - * Used to determine ambient occlusion and culling when rebuilding chunks for render - */ - public boolean isOpaqueCube() - { - return false; - } - - /** - * Return true if an entity can be spawned inside the block (used to get the player's bed spawn location) - */ - public boolean canSpawnInBlock() - { - return true; - } - - /** - * Returns a new instance of a block's tile entity class. Called on placing the block. - */ - public TileEntity createNewTileEntity(World worldIn, int meta) - { - return new TileEntityBanner(); - } - - /** - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(State state, Random rand, int fortune) - { - return Items.banner; - } - - public Item getItem(World worldIn, BlockPos pos) - { - return Items.banner; - } - - public int getDamageValue(World worldIn, BlockPos pos) - { - TileEntity te = worldIn.getTileEntity(pos); - if(te instanceof TileEntityBanner) - return ((TileEntityBanner)te).getBaseColor(); - return super.getDamageValue(worldIn, pos); - } - - /** - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) - { - TileEntity tileentity = worldIn.getTileEntity(pos); - - if (tileentity instanceof TileEntityBanner) - { - ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner)tileentity).getBaseColor()); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - tileentity.writeToNBT(nbttagcompound); - nbttagcompound.removeTag("x"); - nbttagcompound.removeTag("y"); - nbttagcompound.removeTag("z"); - nbttagcompound.removeTag("id"); - itemstack.setTagInfo("BlockEntityTag", nbttagcompound); - spawnAsEntity(worldIn, pos, itemstack); - } - else - { - super.dropBlockAsItemWithChance(worldIn, pos, state, chance, fortune); - } - } - - public boolean canPlaceBlockAt(World worldIn, BlockPos pos) - { - return !this.hasInvalidNeighbor(worldIn, pos) && super.canPlaceBlockAt(worldIn, pos); - } - - public void harvestBlock(World worldIn, EntityNPC player, BlockPos pos, State state, TileEntity te) - { - if (te instanceof TileEntityBanner) - { - TileEntityBanner tileentitybanner = (TileEntityBanner)te; - ItemStack itemstack = new ItemStack(Items.banner, 1, ((TileEntityBanner)te).getBaseColor()); - NBTTagCompound nbttagcompound = new NBTTagCompound(); - TileEntityBanner.setBaseColorAndPatterns(nbttagcompound, tileentitybanner.getBaseColor(), tileentitybanner.getPatterns()); - itemstack.setTagInfo("BlockEntityTag", nbttagcompound); - spawnAsEntity(worldIn, pos, itemstack); - } - else - { - super.harvestBlock(worldIn, player, pos, state, (TileEntity)null); - } - } - - public Transforms getTransform() { - return Transforms.BANNER; - } - - public static class BlockBannerHanging extends BlockBanner - { - public BlockBannerHanging() - { - this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); - } - - public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos) - { - Facing enumfacing = (Facing)worldIn.getState(pos).getValue(FACING); - float f = 0.0F; - float f1 = 0.78125F; - float f2 = 0.0F; - float f3 = 1.0F; - float f4 = 0.125F; - this.setBlockBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F); - - switch (enumfacing) - { - case NORTH: - default: - this.setBlockBounds(f2, f, 1.0F - f4, f3, f1, 1.0F); - break; - - case SOUTH: - this.setBlockBounds(f2, f, 0.0F, f3, f1, f4); - break; - - case WEST: - this.setBlockBounds(1.0F - f4, f, f2, 1.0F, f1, f3); - break; - - case EAST: - this.setBlockBounds(0.0F, f, f2, f4, f1, f3); - } - } - - public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) - { - Facing enumfacing = (Facing)state.getValue(FACING); - - if (!worldIn.getState(pos.offset(enumfacing.getOpposite())).getBlock().getMaterial().isSolid()) - { - this.dropBlockAsItem(worldIn, pos, state, 0); - worldIn.setBlockToAir(pos); - } - - super.onNeighborBlockChange(worldIn, pos, state, neighborBlock); - } - - public State getStateFromMeta(int meta) - { - Facing enumfacing = Facing.getFront(meta); - - if (enumfacing.getAxis() == Facing.Axis.Y) - { - enumfacing = Facing.NORTH; - } - - return this.getState().withProperty(FACING, enumfacing); - } - - public int getMetaFromState(State state) - { - return ((Facing)state.getValue(FACING)).getIndex(); - } - - protected IProperty[] getProperties() - { - return new IProperty[] {FACING}; - } - } - - public static class BlockBannerStanding extends BlockBanner - { - public BlockBannerStanding() - { - this.setDefaultState(this.getBaseState().withProperty(ROTATION, Integer.valueOf(0))); - } - - public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) - { - if (!worldIn.getState(pos.down()).getBlock().getMaterial().isSolid()) - { - this.dropBlockAsItem(worldIn, pos, state, 0); - worldIn.setBlockToAir(pos); - } - - super.onNeighborBlockChange(worldIn, pos, state, neighborBlock); - } - - public State getStateFromMeta(int meta) - { - return this.getState().withProperty(ROTATION, Integer.valueOf(meta)); - } - - public int getMetaFromState(State state) - { - return ((Integer)state.getValue(ROTATION)).intValue(); - } - - protected IProperty[] getProperties() - { - return new IProperty[] {ROTATION}; - } - } -} diff --git a/java/src/game/block/BlockBedrock.java b/java/src/game/block/BlockBedrock.java deleted file mode 100755 index c5abe11..0000000 --- a/java/src/game/block/BlockBedrock.java +++ /dev/null @@ -1,22 +0,0 @@ -package game.block; - -import game.material.Material; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldClient; - -public class BlockBedrock extends Block { - public BlockBedrock() { - super(Material.rock); - } - - public void randomDisplayTick(WorldClient worldIn, BlockPos pos, State state, Random rand) - { - if(/* worldIn.canShowVoidParticles() && */ pos.getY() <= 5 && rand.chance(8)) { - worldIn.spawnParticle(ParticleType.SUSPENDED_DEPTH, (double)pos.getX() + rand.floatv(), (double)(pos.getY()+1) + (rand.floatv() * 0.5f), - (double)pos.getZ() + rand.floatv(), 0.0D, 0.0D, 0.0D); - } - } -} diff --git a/java/src/game/block/BlockBlackenedStone.java b/java/src/game/block/BlockBlackenedStone.java deleted file mode 100644 index 7454eae..0000000 --- a/java/src/game/block/BlockBlackenedStone.java +++ /dev/null @@ -1,20 +0,0 @@ -package game.block; - -import game.init.Blocks; -import game.init.ItemRegistry; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.rng.Random; -import game.world.State; - -public class BlockBlackenedStone extends Block { - public BlockBlackenedStone() { - super(Material.rock); - this.setTab(CheatTab.tabNature); - } - - public Item getItemDropped(State state, Random rand, int fortune) { - return ItemRegistry.getItemFromBlock(Blocks.blackened_cobble); - } -} diff --git a/java/src/game/block/BlockBookshelf.java b/java/src/game/block/BlockBookshelf.java deleted file mode 100755 index bd4761a..0000000 --- a/java/src/game/block/BlockBookshelf.java +++ /dev/null @@ -1,38 +0,0 @@ -package game.block; - -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.State; - -public class BlockBookshelf extends Block -{ - public BlockBookshelf() - { - super(Material.wood); - this.setTab(CheatTab.tabDeco); - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(Random random) - { - return 3; - } - - /** - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(State state, Random rand, int fortune) - { - return Items.book; - } - - public ModelBlock getModel(String name, State state) { - return new ModelBlock("bookshelf").add().nswe().du("oak_planks"); - } -} diff --git a/java/src/game/block/BlockBreakable.java b/java/src/game/block/BlockBreakable.java deleted file mode 100755 index f99b134..0000000 --- a/java/src/game/block/BlockBreakable.java +++ /dev/null @@ -1,48 +0,0 @@ -package game.block; - -import game.init.Blocks; -import game.material.Material; -import game.world.BlockPos; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; - -public class BlockBreakable extends Block -{ - private boolean ignoreSimilarity; - - public BlockBreakable(Material p_i46393_1_, boolean p_i46393_2_) - { - super(p_i46393_1_); - this.ignoreSimilarity = p_i46393_2_; - } - - /** - * Used to determine ambient occlusion and culling when rebuilding chunks for render - */ - public boolean isOpaqueCube() - { - return false; - } - - public boolean shouldSideBeRendered(IWorldAccess worldIn, BlockPos pos, Facing side) - { - State iblockstate = worldIn.getState(pos); - Block block = iblockstate.getBlock(); - - if (this == Blocks.glass || this == Blocks.stained_glass) - { - if (worldIn.getState(pos.offset(side.getOpposite())) != iblockstate) - { - return true; - } - - if (block == this) - { - return false; - } - } - - return !this.ignoreSimilarity && block == this ? false : super.shouldSideBeRendered(worldIn, pos, side); - } -} diff --git a/java/src/game/block/BlockCarrot.java b/java/src/game/block/BlockCarrot.java deleted file mode 100755 index 0339480..0000000 --- a/java/src/game/block/BlockCarrot.java +++ /dev/null @@ -1,24 +0,0 @@ -package game.block; - -import game.init.Items; -import game.item.Item; -import game.renderer.blockmodel.ModelBlock; -import game.world.State; - -public class BlockCarrot extends BlockCrops -{ - protected Item getSeed() - { - return Items.carrot; - } - - protected Item getCrop() - { - return Items.carrot; - } - - public ModelBlock getModel(String name, State state) { - int age = state.getValue(AGE); - return crop(name + "_" + (age == 6 ? 2 : (age / 2))); - } -} diff --git a/java/src/game/block/BlockColored.java b/java/src/game/block/BlockColored.java deleted file mode 100755 index 3b3aafc..0000000 --- a/java/src/game/block/BlockColored.java +++ /dev/null @@ -1,78 +0,0 @@ -package game.block; - -import java.util.List; - -import game.color.DyeColor; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.world.State; - -public class BlockColored extends Block -{ - public static final PropertyEnum COLOR = PropertyEnum.create("color", DyeColor.class); - - public BlockColored(Material materialIn) - { - super(materialIn); - this.setDefaultState(this.getBaseState().withProperty(COLOR, DyeColor.WHITE)); - this.setTab(CheatTab.tabBlocks); - } - - /** - * Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It - * returns the metadata of the dropped item based on the old metadata of the block. - */ - public int damageDropped(State state) - { - return ((DyeColor)state.getValue(COLOR)).getMetadata(); - } - - /** - * returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item itemIn, CheatTab tab, List list) - { - for (DyeColor enumdyecolor : DyeColor.values()) - { - list.add(new ItemStack(itemIn, 1, enumdyecolor.getMetadata())); - } - } - -// /** -// * Get the MapColor for this Block and the given BlockState -// */ -// public MapColor getMapColor(IBlockState state) -// { -// return ((EnumDyeColor)state.getValue(COLOR)).getMapColor(); -// } - - /** - * Convert the given metadata into a BlockState for this Block - */ - public State getStateFromMeta(int meta) - { - return this.getState().withProperty(COLOR, DyeColor.byMetadata(meta)); - } - - /** - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(State state) - { - return ((DyeColor)state.getValue(COLOR)).getMetadata(); - } - - protected IProperty[] getProperties() - { - return new IProperty[] {COLOR}; - } - - public ModelBlock getModel(String name, State state) { - return new ModelBlock(state.getValue(COLOR).getName() + "_" + name).add().all(); - } -} diff --git a/java/src/game/block/BlockContainer.java b/java/src/game/block/BlockContainer.java deleted file mode 100755 index 909b5d6..0000000 --- a/java/src/game/block/BlockContainer.java +++ /dev/null @@ -1,52 +0,0 @@ -package game.block; - -import game.material.Material; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; -import game.world.WorldServer; - -public abstract class BlockContainer extends Block implements ITileEntityProvider -{ - public BlockContainer(Material p_i46402_1_) - { - super(p_i46402_1_); - this.hasTile = true; - } - - protected boolean isInvalidNeighbor(World p_181086_1_, BlockPos p_181086_2_, Facing p_181086_3_) - { - return p_181086_1_.getState(p_181086_2_.offset(p_181086_3_)).getBlock().getMaterial() == Material.cactus; - } - - protected boolean hasInvalidNeighbor(World p_181087_1_, BlockPos p_181087_2_) - { - return this.isInvalidNeighbor(p_181087_1_, p_181087_2_, Facing.NORTH) || this.isInvalidNeighbor(p_181087_1_, p_181087_2_, Facing.SOUTH) || this.isInvalidNeighbor(p_181087_1_, p_181087_2_, Facing.WEST) || this.isInvalidNeighbor(p_181087_1_, p_181087_2_, Facing.EAST); - } - - /** - * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() - { - return -1; - } - - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) - { - super.onBlockRemoved(worldIn, pos, state); - worldIn.removeTileEntity(pos); - } - - /** - * Called on both Client and Server when World#addBlockEvent is called - */ - public boolean onBlockEventReceived(World worldIn, BlockPos pos, State state, int eventID, int eventParam) - { - super.onBlockEventReceived(worldIn, pos, state, eventID, eventParam); - TileEntity tileentity = worldIn.getTileEntity(pos); - return tileentity == null ? false : tileentity.receiveClientEvent(eventID, eventParam); - } -} diff --git a/java/src/game/block/BlockCore.java b/java/src/game/block/BlockCore.java deleted file mode 100755 index 03ac7e9..0000000 --- a/java/src/game/block/BlockCore.java +++ /dev/null @@ -1,27 +0,0 @@ -package game.block; - -import game.init.Config; -import game.item.CheatTab; -import game.material.Material; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; - -public class BlockCore extends Block { - public BlockCore() { - super(Material.iron); - this.setTab(CheatTab.tabTech); - } - - public void onBlockRemoved(WorldServer world, BlockPos pos, State state) - { - if(Config.loaders) - world.removeLoader(pos); - } - - public void onBlockAdded(WorldServer world, BlockPos pos, State state) - { - if(Config.loaders) - world.addLoader(pos); - } -} diff --git a/java/src/game/block/BlockDirectional.java b/java/src/game/block/BlockDirectional.java deleted file mode 100755 index 5c2c881..0000000 --- a/java/src/game/block/BlockDirectional.java +++ /dev/null @@ -1,15 +0,0 @@ -package game.block; - -import game.material.Material; -import game.properties.PropertyDirection; -import game.world.Facing; - -public abstract class BlockDirectional extends Block -{ - public static final PropertyDirection FACING = PropertyDirection.create("facing", Facing.Plane.HORIZONTAL); - - public BlockDirectional(Material materialIn) - { - super(materialIn); - } -} diff --git a/java/src/game/block/BlockEventData.java b/java/src/game/block/BlockEventData.java deleted file mode 100755 index b595cbb..0000000 --- a/java/src/game/block/BlockEventData.java +++ /dev/null @@ -1,62 +0,0 @@ -package game.block; - -import game.world.BlockPos; - -public class BlockEventData -{ - private BlockPos position; - private Block blockType; - - /** Different for each blockID */ - private int eventID; - private int eventParameter; - - public BlockEventData(BlockPos pos, Block blockType, int eventId, int p_i45756_4_) - { - this.position = pos; - this.eventID = eventId; - this.eventParameter = p_i45756_4_; - this.blockType = blockType; - } - - public BlockPos getPosition() - { - return this.position; - } - - /** - * Get the Event ID (different for each BlockID) - */ - public int getEventID() - { - return this.eventID; - } - - public int getEventParameter() - { - return this.eventParameter; - } - - public Block getBlock() - { - return this.blockType; - } - - public boolean equals(Object p_equals_1_) - { - if (!(p_equals_1_ instanceof BlockEventData)) - { - return false; - } - else - { - BlockEventData blockeventdata = (BlockEventData)p_equals_1_; - return this.position.equals(blockeventdata.position) && this.eventID == blockeventdata.eventID && this.eventParameter == blockeventdata.eventParameter && this.blockType == blockeventdata.blockType; - } - } - - public String toString() - { - return "TE(" + this.position + ")," + this.eventID + "," + this.eventParameter + "," + this.blockType; - } -} diff --git a/java/src/game/block/BlockFalling.java b/java/src/game/block/BlockFalling.java deleted file mode 100755 index 9546e4d..0000000 --- a/java/src/game/block/BlockFalling.java +++ /dev/null @@ -1,103 +0,0 @@ -package game.block; - -import game.entity.item.EntityFalling; -import game.init.Blocks; -import game.init.Config; -import game.item.CheatTab; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.World; -import game.world.WorldServer; - -public class BlockFalling extends Block -{ - public static boolean fallInstantly; - - public BlockFalling() - { - super(Material.sand); - this.setTab(CheatTab.tabNature); - } - - public BlockFalling(Material materialIn) - { - super(materialIn); - } - - public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) - { - worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn, pos)); - } - - /** - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) - { - worldIn.scheduleUpdate(pos, this, this.tickRate(worldIn, pos)); - } - - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) - { - if(/* !worldIn.client && */ Config.blockGravity) - this.checkFallable(worldIn, pos); - } - - private void checkFallable(World worldIn, BlockPos pos) - { - if (canFallInto(worldIn, pos.down()) && pos.getY() >= 0) - { - int i = 32; - - if (!fallInstantly && worldIn.isAreaLoaded(pos.add(-i, -i, -i), pos.add(i, i, i))) - { - if (!worldIn.client) - { - EntityFalling entityfallingblock = new EntityFalling(worldIn, (double)pos.getX() + 0.5D, (double)pos.getY(), (double)pos.getZ() + 0.5D, worldIn.getState(pos)); - this.onStartFalling(entityfallingblock); - worldIn.spawnEntityInWorld(entityfallingblock); - } - } - else - { - worldIn.setBlockToAir(pos); - BlockPos blockpos; - - for (blockpos = pos.down(); canFallInto(worldIn, blockpos) && blockpos.getY() > 0; blockpos = blockpos.down()) - { - ; - } - - if (blockpos.getY() > 0) - { - worldIn.setState(blockpos.up(), this.getState()); - } - } - } - } - - protected void onStartFalling(EntityFalling fallingEntity) - { - } - - /** - * How many world ticks before ticking - */ - public int tickRate(World worldIn, BlockPos pos) - { - return 2; - } - - public static boolean canFallInto(World worldIn, BlockPos pos) - { - Block block = worldIn.getState(pos).getBlock(); - Material material = block.material; - return block == Blocks.fire || material == Material.air || material.isLiquid(); - } - - public void onEndFalling(World worldIn, BlockPos pos) - { - } -} diff --git a/java/src/game/block/BlockGlass.java b/java/src/game/block/BlockGlass.java deleted file mode 100755 index 2d0a22a..0000000 --- a/java/src/game/block/BlockGlass.java +++ /dev/null @@ -1,38 +0,0 @@ -package game.block; - -import game.item.CheatTab; -import game.material.Material; -import game.renderer.BlockLayer; -import game.rng.Random; - -public class BlockGlass extends BlockBreakable -{ - public BlockGlass(Material materialIn, boolean ignoreSimilarity) - { - super(materialIn, ignoreSimilarity); - this.setTab(CheatTab.tabBlocks); - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(Random random) - { - return 0; - } - - public BlockLayer getBlockLayer() - { - return BlockLayer.CUTOUT; - } - - public boolean isFullCube() - { - return false; - } - - public boolean canSilkHarvest() - { - return true; - } -} diff --git a/java/src/game/block/BlockIce.java b/java/src/game/block/BlockIce.java deleted file mode 100755 index 805124d..0000000 --- a/java/src/game/block/BlockIce.java +++ /dev/null @@ -1,94 +0,0 @@ -package game.block; - -import game.enchantment.EnchantmentHelper; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Config; -import game.item.CheatTab; -import game.item.ItemStack; -import game.material.Material; -import game.renderer.BlockLayer; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.LightType; -import game.world.State; -import game.world.World; -import game.world.WorldServer; - -public class BlockIce extends BlockBreakable -{ - public BlockIce() - { - super(Material.ice, false); - this.slipperiness = 0.98F; - this.setTickRandomly(); - this.setTab(CheatTab.tabNature); - } - - public BlockLayer getBlockLayer() - { - return BlockLayer.TRANSLUCENT; - } - - public void harvestBlock(World worldIn, EntityNPC player, BlockPos pos, State state, TileEntity te) - { -// player.triggerAchievement(StatRegistry.mineBlockStatArray[BlockRegistry.getIdFromBlock(this)]); - - if (this.canSilkHarvest() && EnchantmentHelper.getSilkTouchModifier(player)) - { - ItemStack itemstack = this.createStackedBlock(state); - - if (itemstack != null) - { - spawnAsEntity(worldIn, pos, itemstack); - } - } - else - { - if (worldIn.doesWaterVaporize(pos)) - { - worldIn.setBlockToAir(pos); - return; - } - - int i = EnchantmentHelper.getFortuneModifier(player); - this.dropBlockAsItem(worldIn, pos, state, i); - Material material = worldIn.getState(pos.down()).getBlock().getMaterial(); - - if (material.blocksMovement() || material.isLiquid()) - { - worldIn.setState(pos, Blocks.flowing_water.getState()); - } - } - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(Random random) - { - return 0; - } - - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) - { - if (Config.iceMelt && ((worldIn.getLightFor(LightType.BLOCK, pos) > 11 - this.getLightOpacity()) || !worldIn.canFreezeAt(pos))) - { - if (worldIn.doesWaterVaporize(pos)) - { - worldIn.setBlockToAir(pos); - } - else - { - this.dropBlockAsItem(worldIn, pos, worldIn.getState(pos), 0); - worldIn.setState(pos, Blocks.water.getState()); - } - } - } - - public int getMobilityFlag() - { - return 0; - } -} diff --git a/java/src/game/block/BlockJukebox.java b/java/src/game/block/BlockJukebox.java deleted file mode 100755 index ae45af8..0000000 --- a/java/src/game/block/BlockJukebox.java +++ /dev/null @@ -1,28 +0,0 @@ -package game.block; - -import game.entity.npc.EntityNPC; -import game.init.SoundEvent; -import game.item.CheatTab; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; - -public class BlockJukebox extends Block { - public BlockJukebox() { - super(Material.wood); - this.setTab(CheatTab.tabTech); - } - - public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) { - if(!worldIn.client) - worldIn.playSound(worldIn.rand.pick(SoundEvent.values()), pos.getX() + 0.5, pos.getY() + 0.5, pos.getZ() + 0.5, 1.0f); - return true; - } - - public ModelBlock getModel(String name, State state) { - return new ModelBlock("jukebox_side").add().dnswe().u("jukebox_top"); - } -} diff --git a/java/src/game/block/BlockMobSpawner.java b/java/src/game/block/BlockMobSpawner.java deleted file mode 100755 index 6559c80..0000000 --- a/java/src/game/block/BlockMobSpawner.java +++ /dev/null @@ -1,90 +0,0 @@ -package game.block; - -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.renderer.BlockLayer; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityMobSpawner; -import game.world.BlockPos; -import game.world.State; -import game.world.World; - -public class BlockMobSpawner extends BlockContainer -{ - public BlockMobSpawner() - { - super(Material.rock); - this.setTab(CheatTab.tabTech); - } - - /** - * Returns a new instance of a block's tile entity class. Called on placing the block. - */ - public TileEntity createNewTileEntity(World worldIn, int meta) - { - return new TileEntityMobSpawner(); - } - - /** - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(State state, Random rand, int fortune) - { - return null; - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(Random random) - { - return 0; - } - - /** - * Spawns this Block's drops into the World as EntityItems. - */ - public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) - { - super.dropBlockAsItemWithChance(worldIn, pos, state, chance, fortune); - int i = worldIn.rand.rangeBonus(15, 29, 14); - this.dropXpOnBlockBreak(worldIn, pos, i); - } - - /** - * Used to determine ambient occlusion and culling when rebuilding chunks for render - */ - public boolean isOpaqueCube() - { - return false; - } - - /** - * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() - { - return 3; - } - - public BlockLayer getBlockLayer() - { - return BlockLayer.CUTOUT; - } - - public Item getItem(World worldIn, BlockPos pos) - { - return null; - } - - public boolean isXrayVisible() - { - return true; - } - - public boolean isMagnetic() { - return true; - } -} diff --git a/java/src/game/block/BlockNote.java b/java/src/game/block/BlockNote.java deleted file mode 100755 index 5e01ddb..0000000 --- a/java/src/game/block/BlockNote.java +++ /dev/null @@ -1,125 +0,0 @@ -package game.block; - -import game.entity.npc.EntityNPC; -import game.init.SoundEvent; -import game.item.CheatTab; -import game.material.Material; -import game.renderer.particle.ParticleType; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityNote; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; - -public class BlockNote extends BlockContainer -{ -// private static final List INSTRUMENTS = Lists.newArrayList("harp", "bd", "snare", "hat", "bassattack"); - - public BlockNote() - { - super(Material.wood); - this.setTab(CheatTab.tabTech); - } - - /** - * Called when a neighboring block changes. - */ - public void onNeighborBlockChange(World worldIn, BlockPos pos, State state, Block neighborBlock) - { - boolean flag = worldIn.isBlockPowered(pos); - TileEntity tileentity = worldIn.getTileEntity(pos); - - if (tileentity instanceof TileEntityNote) - { - TileEntityNote tileentitynote = (TileEntityNote)tileentity; - - if (tileentitynote.previousRedstoneState != flag) - { - if (flag) - { - tileentitynote.triggerNote(worldIn, pos); - } - - tileentitynote.previousRedstoneState = flag; - } - } - } - - public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) - { - if (worldIn.client) - { - return true; - } - else - { - TileEntity tileentity = worldIn.getTileEntity(pos); - - if (tileentity instanceof TileEntityNote) - { - TileEntityNote tileentitynote = (TileEntityNote)tileentity; - tileentitynote.changePitch(); - tileentitynote.triggerNote(worldIn, pos); -// playerIn.triggerAchievement(StatRegistry.noteblockTuneStat); - } - - return true; - } - } - - public void onBlockClicked(World worldIn, BlockPos pos, EntityNPC playerIn) - { - if (!worldIn.client) - { - TileEntity tileentity = worldIn.getTileEntity(pos); - - if (tileentity instanceof TileEntityNote) - { - ((TileEntityNote)tileentity).triggerNote(worldIn, pos); -// playerIn.triggerAchievement(StatRegistry.noteblockPlayStat); - } - } - } - - /** - * Returns a new instance of a block's tile entity class. Called on placing the block. - */ - public TileEntity createNewTileEntity(World worldIn, int meta) - { - return new TileEntityNote(); - } - -// private String getInstrument(int id) -// { -// if (id < 0 || id >= INSTRUMENTS.size()) -// { -// id = 0; -// } -// -// return (String)INSTRUMENTS.get(id); -// } - - /** - * Called on both Client and Server when World#addBlockEvent is called - */ - public boolean onBlockEventReceived(World worldIn, BlockPos pos, State state, int eventID, int eventParam) - { - float f = (float)Math.pow(2.0D, (double)(eventParam - 12) / 12.0D); - worldIn.playSound(SoundEvent.NOTE, (double)pos.getX() + 0.5D, (double)pos.getY() + 0.5D, (double)pos.getZ() + 0.5D, 3.0F); - worldIn.spawnParticle(ParticleType.NOTE, (double)pos.getX() + 0.5D, (double)pos.getY() + 1.2D, (double)pos.getZ() + 0.5D, (double)eventParam / 24.0D, 0.0D, 0.0D); - return true; - } - - /** - * The type of render function called. 3 for standard block models, 2 for TESR's, 1 for liquids, -1 is no render - */ - public int getRenderType() - { - return 3; - } - - public boolean isMagnetic() { - return true; - } -} diff --git a/java/src/game/block/BlockPumpkin.java b/java/src/game/block/BlockPumpkin.java deleted file mode 100755 index c955c33..0000000 --- a/java/src/game/block/BlockPumpkin.java +++ /dev/null @@ -1,190 +0,0 @@ -package game.block; - -import game.entity.types.EntityLiving; -import game.item.CheatTab; -import game.material.Material; -import game.model.ModelRotation; -import game.properties.IProperty; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; - -public class BlockPumpkin extends BlockDirectional -{ -// private BlockPattern snowmanBasePattern; -// private BlockPattern snowmanPattern; -// private BlockPattern golemBasePattern; -// private BlockPattern golemPattern; -// private static final Predicate field_181085_Q = new Predicate() -// { -// public boolean test(IBlockState p_apply_1_) -// { -// return p_apply_1_ != null && (p_apply_1_.getBlock() == Blocks.pumpkin || p_apply_1_.getBlock() == Blocks.lit_pumpkin); -// } -// }; - - public BlockPumpkin() - { - super(Material.gourd); - this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); -// this.setTickRandomly(true); - this.setTab(CheatTab.tabPlants); - } - -// public void onBlockAdded(WorldServer worldIn, BlockPos pos, IBlockState state) -// { -// super.onBlockAdded(worldIn, pos, state); -// this.trySpawnGolem(worldIn, pos); -// } - -// public boolean canDispenserPlace(World worldIn, BlockPos pos) -// { -// return this.getSnowmanBasePattern().match(worldIn, pos) != null; // || this.getGolemBasePattern().match(worldIn, pos) != null; -// } - -// private void trySpawnGolem(World worldIn, BlockPos pos) -// { -// if(!Config.createSnowman) { -// return; -// } -// -// BlockPattern.PatternHelper blockpattern$patternhelper; -// -// if ((blockpattern$patternhelper = this.getSnowmanPattern().match(worldIn, pos)) != null) -// { -// for (int i = 0; i < this.getSnowmanPattern().getThumbLength(); ++i) -// { -// BlockWorldState blockworldstate = blockpattern$patternhelper.translateOffset(0, i, 0); -// worldIn.setBlockState(blockworldstate.getPos(), Blocks.air.getDefaultState(), 2); -// } -// -// EntitySnowman entitysnowman = new EntitySnowman(worldIn); -// BlockPos blockpos1 = blockpattern$patternhelper.translateOffset(0, 2, 0).getPos(); -// entitysnowman.setLocationAndAngles((double)blockpos1.getX() + 0.5D, (double)blockpos1.getY() + 0.05D, (double)blockpos1.getZ() + 0.5D, 0.0F, 0.0F); -// worldIn.spawnEntityInWorld(entitysnowman); -// -// for (int j = 0; j < 120; ++j) -// { -// worldIn.spawnParticle(EnumParticleTypes.SNOW_SHOVEL, (double)blockpos1.getX() + worldIn.rand.doublev(), (double)blockpos1.getY() + worldIn.rand.doublev() * 2.5D, (double)blockpos1.getZ() + worldIn.rand.doublev(), 0.0D, 0.0D, 0.0D); -// } -// -// for (int i1 = 0; i1 < this.getSnowmanPattern().getThumbLength(); ++i1) -// { -// BlockWorldState blockworldstate1 = blockpattern$patternhelper.translateOffset(0, i1, 0); -// worldIn.notifyNeighborsRespectDebug(blockworldstate1.getPos(), Blocks.air); -// } -// } -//// else if ((blockpattern$patternhelper = this.getGolemPattern().match(worldIn, pos)) != null) -//// { -//// for (int k = 0; k < this.getGolemPattern().getPalmLength(); ++k) -//// { -//// for (int l = 0; l < this.getGolemPattern().getThumbLength(); ++l) -//// { -//// worldIn.setBlockState(blockpattern$patternhelper.translateOffset(k, l, 0).getPos(), Blocks.air.getDefaultState(), 2); -//// } -//// } -//// -//// BlockPos blockpos = blockpattern$patternhelper.translateOffset(1, 2, 0).getPos(); -//// EntityIronGolem entityirongolem = new EntityIronGolem(worldIn); -////// entityirongolem.setPlayerCreated(true); -//// entityirongolem.setLocationAndAngles((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.05D, (double)blockpos.getZ() + 0.5D, 0.0F, 0.0F); -//// worldIn.spawnEntityInWorld(entityirongolem); -//// -//// for (int j1 = 0; j1 < 120; ++j1) -//// { -//// worldIn.spawnParticle(EnumParticleTypes.SNOWBALL, (double)blockpos.getX() + worldIn.rand.doublev(), (double)blockpos.getY() + worldIn.rand.doublev() * 3.9D, (double)blockpos.getZ() + worldIn.rand.doublev(), 0.0D, 0.0D, 0.0D); -//// } -//// -//// for (int k1 = 0; k1 < this.getGolemPattern().getPalmLength(); ++k1) -//// { -//// for (int l1 = 0; l1 < this.getGolemPattern().getThumbLength(); ++l1) -//// { -//// BlockWorldState blockworldstate2 = blockpattern$patternhelper.translateOffset(k1, l1, 0); -//// worldIn.notifyNeighborsRespectDebug(blockworldstate2.getPos(), Blocks.air); -//// } -//// } -//// } -// } - - public boolean canPlaceBlockAt(World worldIn, BlockPos pos) - { - return worldIn.getState(pos).getBlock().material.isReplaceable() && worldIn.isBlockSolid(pos.down()); - } - - /** - * Called by ItemBlocks just before a block is actually set in the world, to allow for adjustments to the - * IBlockstate - */ - public State onBlockPlaced(World worldIn, BlockPos pos, Facing facing, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) - { - return this.getState().withProperty(FACING, placer.getHorizontalFacing().getOpposite()); - } - - /** - * Convert the given metadata into a BlockState for this Block - */ - public State getStateFromMeta(int meta) - { - return this.getState().withProperty(FACING, Facing.getHorizontal(meta)); - } - - /** - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(State state) - { - return ((Facing)state.getValue(FACING)).getHorizontalIndex(); - } - - protected IProperty[] getProperties() - { - return new IProperty[] {FACING}; - } - -// protected BlockPattern getSnowmanBasePattern() -// { -// if (this.snowmanBasePattern == null) -// { -// this.snowmanBasePattern = FactoryBlockPattern.start().aisle(" ", "#", "#").where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.snow))).build(); -// } -// -// return this.snowmanBasePattern; -// } -// -// protected BlockPattern getSnowmanPattern() -// { -// if (this.snowmanPattern == null) -// { -// this.snowmanPattern = FactoryBlockPattern.start().aisle("^", "#", "#").where('^', BlockWorldState.hasState(field_181085_Q)).where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.snow))).build(); -// } -// -// return this.snowmanPattern; -// } - -// protected BlockPattern getGolemBasePattern() -// { -// if (this.golemBasePattern == null) -// { -// this.golemBasePattern = FactoryBlockPattern.start().aisle("~ ~", "###", "~#~").where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.iron_block))).where('~', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.air))).build(); -// } -// -// return this.golemBasePattern; -// } - -// protected BlockPattern getGolemPattern() -// { -// if (this.golemPattern == null) -// { -// this.golemPattern = FactoryBlockPattern.start().aisle("~^~", "###", "~#~").where('^', BlockWorldState.hasState(field_181085_Q)).where('#', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.iron_block))).where('~', BlockWorldState.hasState(BlockStateHelper.forBlock(Blocks.air))).build(); -// } -// -// return this.golemPattern; -// } - - public ModelBlock getModel(String name, State state) { - return new ModelBlock("pumpkin_side").add().du("pumpkin_top").n("pumpkin_face_" + (this.getLightValue() == 0 ? "off" : "on")) - .s().we().rotate(ModelRotation.getNorthRot(state.getValue(FACING))); - } -} diff --git a/java/src/game/block/BlockRotatedPillar.java b/java/src/game/block/BlockRotatedPillar.java deleted file mode 100755 index a1c42ba..0000000 --- a/java/src/game/block/BlockRotatedPillar.java +++ /dev/null @@ -1,34 +0,0 @@ -package game.block; - -import game.material.Material; -import game.model.ModelRotation; -import game.properties.PropertyEnum; -import game.renderer.blockmodel.ModelBlock; -import game.world.Facing; -import game.world.State; - -public abstract class BlockRotatedPillar extends Block -{ - public static final PropertyEnum AXIS = PropertyEnum.create("axis", Facing.Axis.class); - - public BlockRotatedPillar(Material materialIn) - { - super(materialIn); - } - - public ModelBlock getModel(String name, State state) { - switch(state.getValue(AXIS)) { - case X: - return new ModelBlock(name + "_side").add().d().rot(180).u() - .n(name + "_top").rot(180).s(name + "_top").w().rot(270) - .e().rot(90).rotate(ModelRotation.X0_Y90); - case Y: - default: - return new ModelBlock(name + "_side").add().nswe().du(name + "_top"); - case Z: - return new ModelBlock(name + "_side").add().d().rot(180).u() - .n(name + "_top").rot(180).s(name + "_top").w().rot(270) - .e().rot(90); - } - } -} diff --git a/java/src/game/block/BlockSapling.java b/java/src/game/block/BlockSapling.java deleted file mode 100755 index e829bc7..0000000 --- a/java/src/game/block/BlockSapling.java +++ /dev/null @@ -1,299 +0,0 @@ -package game.block; - -import java.util.List; - -import game.collect.Lists; - -import game.init.Blocks; -import game.init.Config; -import game.init.WoodType; -import game.item.CheatTab; -import game.properties.IProperty; -import game.properties.PropertyInteger; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.World; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; -import game.worldgen.tree.WorldGenBaseTree; -import game.worldgen.tree.WorldGenBigTree; -import game.worldgen.tree.WorldGenBirch; -import game.worldgen.tree.WorldGenDarkOak; -import game.worldgen.tree.WorldGenJungle; -import game.worldgen.tree.WorldGenPine; -import game.worldgen.tree.WorldGenSavanna; -import game.worldgen.tree.WorldGenTaiga2; - -public class BlockSapling extends BlockBush implements IGrowable -{ -// public static final PropertyEnum TYPE = PropertyEnum.create("type", BlockPlanks.EnumType.class); - public static final PropertyInteger STAGE = PropertyInteger.create("stage", 0, 1); - public static final List SAPLINGS = Lists.newArrayList(); - - private final WoodType type; - - public BlockSapling(WoodType type) - { - this.setDefaultState(this.getBaseState() /* .withProperty(TYPE, BlockPlanks.EnumType.OAK) */ .withProperty(STAGE, Integer.valueOf(0))); - float f = 0.4F; - this.setBlockBounds(0.5F - f, 0.0F, 0.5F - f, 0.5F + f, f * 2.0F, 0.5F + f); - this.setTab(CheatTab.tabPlants); - this.type = type; - SAPLINGS.add(this); - } - -// /** -// * Gets the localized name of this block. Used for the statistics page. -// */ -// public String getLocalizedName() -// { -// return I18n.translate(this.getUnlocalizedName() + "." + BlockPlanks.EnumType.OAK.getUnlocalizedName() + ".name"); -// } - - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) - { - if(Config.saplingDry && worldIn.getTemperatureC(pos) >= 50.0f) - { - worldIn.setState(pos, worldIn.rand.chance(25) ? Blocks.air.getState() : - Blocks.tallgrass.getState().withProperty(BlockTallGrass.TYPE, BlockTallGrass.EnumType.DEAD_BUSH)); - return; - } -// if (!worldIn.client) -// { - super.updateTick(worldIn, pos, state, rand); - - if (Config.treeGrowth > 0 && worldIn.getLightFromNeighbors(pos.up()) >= 9 && rand.chance(Config.treeGrowth)) - { - this.grow(worldIn, pos, state, rand); - } -// } - } - - public void grow(WorldServer worldIn, BlockPos pos, State state, Random rand) - { - if (((Integer)state.getValue(STAGE)).intValue() == 0) - { - worldIn.setState(pos, state.cycleProperty(STAGE), 4); - } - else - { - this.generateTree(worldIn, pos, state, rand); - } - } - - public void generateTree(WorldServer worldIn, BlockPos pos, State state, Random rand) - { - WoodType type = state.getBlock() instanceof BlockSapling ? ((BlockSapling)state.getBlock()).type : WoodType.OAK; - State log = type == WoodType.CHERRY ? Blocks.cherry_log.getState() : // .withProperty(BlockNewLog.VARIANT, BlockPlanks.EnumType.CHERRY) : - (type == WoodType.MAPLE ? Blocks.maple_log.getState() /* .withProperty(BlockNewLog.VARIANT, BlockPlanks.EnumType.MAPLE) */ : Blocks.oak_log.getState()); - State leaves = type == WoodType.CHERRY ? Blocks.cherry_leaves.getState() : - (type == WoodType.MAPLE ? Blocks.maple_leaves.getState() : Blocks.oak_leaves.getState()); - FeatureGenerator worldgenerator = (FeatureGenerator)(rand.chance(10) ? new WorldGenBigTree(true, log, leaves) : new WorldGenBaseTree(true, log, leaves)); - int i = 0; - int j = 0; - boolean flag = false; -// leaves = leaves.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen()); - - switch (type) - { - case SPRUCE: - label114: - for (i = 0; i >= -1; --i) - { - for (j = 0; j >= -1; --j) - { - if (this.isSameSaplingTypeIn(worldIn, pos, i, j, WoodType.SPRUCE)) - { - worldgenerator = new WorldGenPine(false, rand.chance()); - flag = true; - break label114; - } - } - } - - if (!flag) - { - j = 0; - i = 0; - worldgenerator = new WorldGenTaiga2(true); - } - - break; - - case BIRCH: - worldgenerator = new WorldGenBirch(true, false); - break; - - case TIAN: - worldgenerator = new WorldGenBigTree(true, Blocks.tian_log.getState(), Blocks.tian_leaves.getState()) - .setHeightLimit(6, 20); - break; - - case JUNGLE: - State iblockstate = Blocks.jungle_log.getState(); // .withProperty(BlockOldLog.VARIANT, BlockPlanks.EnumType.JUNGLE); - State iblockstate1 = Blocks.jungle_leaves.getState(); // .withProperty(BlockOldLeaf.VARIANT, BlockPlanks.EnumType.JUNGLE); // .withProperty(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false)); - label269: - - for (i = 0; i >= -1; --i) - { - for (j = 0; j >= -1; --j) - { - if (this.isSameSaplingTypeIn(worldIn, pos, i, j, WoodType.JUNGLE)) - { - worldgenerator = new WorldGenJungle(true, 10, 20, iblockstate, iblockstate1); - flag = true; - break label269; - } - } - } - - if (!flag) - { - j = 0; - i = 0; - worldgenerator = new WorldGenBaseTree(true, rand.range(4, 10), iblockstate, iblockstate1, false); - } - - break; - - case ACACIA: - worldgenerator = new WorldGenSavanna(true); - break; - - case DARK_OAK: - label390: - for (i = 0; i >= -1; --i) - { - for (j = 0; j >= -1; --j) - { - if (this.isSameSaplingTypeIn(worldIn, pos, i, j, WoodType.DARK_OAK)) - { - worldgenerator = new WorldGenDarkOak(true); - flag = true; - break label390; - } - } - } - - if (!flag) - { - return; - } - - case OAK: - case CHERRY: - case MAPLE: - } - - State iblockstate2 = Blocks.air.getState(); - - if (flag) - { - worldIn.setState(pos.add(i, 0, j), iblockstate2, 4); - worldIn.setState(pos.add(i + 1, 0, j), iblockstate2, 4); - worldIn.setState(pos.add(i, 0, j + 1), iblockstate2, 4); - worldIn.setState(pos.add(i + 1, 0, j + 1), iblockstate2, 4); - } - else - { - worldIn.setState(pos, iblockstate2, 4); - } - - if (!worldgenerator.generate(worldIn, rand, pos.add(i, 0, j))) - { - if (flag) - { - worldIn.setState(pos.add(i, 0, j), state, 4); - worldIn.setState(pos.add(i + 1, 0, j), state, 4); - worldIn.setState(pos.add(i, 0, j + 1), state, 4); - worldIn.setState(pos.add(i + 1, 0, j + 1), state, 4); - } - else - { - worldIn.setState(pos, state, 4); - } - } - } - - private boolean isSameSaplingTypeIn(World worldIn, BlockPos pos, int xOff, int yOff, WoodType type) - { - return this.isTypeAt(worldIn, pos.add(xOff, 0, yOff), type) && this.isTypeAt(worldIn, pos.add(xOff + 1, 0, yOff), type) && this.isTypeAt(worldIn, pos.add(xOff, 0, yOff + 1), type) && this.isTypeAt(worldIn, pos.add(xOff + 1, 0, yOff + 1), type); - } - - /** - * Check whether the given BlockPos has a Sapling of the given type - */ - public boolean isTypeAt(World worldIn, BlockPos pos, WoodType type) - { - State iblockstate = worldIn.getState(pos); - return iblockstate.getBlock() instanceof BlockSapling && ((BlockSapling)iblockstate.getBlock()).type == type; - } - -// /** -// * Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It -// * returns the metadata of the dropped item based on the old metadata of the block. -// */ -// public int damageDropped(IBlockState state) -// { -// return ((BlockPlanks.EnumType)state.getValue(TYPE)).getMetadata(); -// } - -// /** -// * returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks) -// */ -// public void getSubBlocks(Item itemIn, CreativeTab tab, List list) -// { -// for (BlockPlanks.EnumType blockplanks$enumtype : BlockPlanks.EnumType.values()) -// { -// list.add(new ItemStack(itemIn, 1, blockplanks$enumtype.getMetadata())); -// } -// } - - /** - * Whether this IGrowable can grow - */ - public boolean canGrow(World worldIn, BlockPos pos, State state, boolean isClient) - { - return true; - } - - public boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, State state) - { - return (double)worldIn.rand.floatv() < 0.45D; - } - - public void grow(WorldServer worldIn, Random rand, BlockPos pos, State state) - { - this.grow(worldIn, pos, state, rand); - } - - /** - * Convert the given metadata into a BlockState for this Block - */ - public State getStateFromMeta(int meta) - { - return this.getState() /* .withProperty(TYPE, BlockPlanks.EnumType.byMetadata(meta & 7)) */ .withProperty(STAGE, meta & 1); - } - - /** - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(State state) - { -// int i = 0; -// i = i | ((BlockPlanks.EnumType)state.getValue(TYPE)).getMetadata(); -// i = i | ((Integer)state.getValue(STAGE)).intValue() << 3; - return state.getValue(STAGE); - } - - protected IProperty[] getProperties() - { - return new IProperty[] {STAGE}; - } - - public ModelBlock getModel(String name, State state) { - return new ModelBlock(name).cross(); - } -} diff --git a/java/src/game/block/BlockSkull.java b/java/src/game/block/BlockSkull.java deleted file mode 100755 index 5c88d17..0000000 --- a/java/src/game/block/BlockSkull.java +++ /dev/null @@ -1,153 +0,0 @@ -package game.block; - -import game.entity.types.EntityLiving; -import game.init.Items; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.renderer.blockmodel.Transforms; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntitySkull; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Facing; -import game.world.IWorldAccess; -import game.world.State; -import game.world.World; -import game.world.WorldServer; - -public class BlockSkull extends BlockContainer -{ - public static final PropertyDirection FACING = PropertyDirection.create("facing"); - - public BlockSkull() - { - super(Material.circuits); - this.setDefaultState(this.getBaseState().withProperty(FACING, Facing.NORTH)); - this.setBlockBounds(0.25F, 0.0F, 0.25F, 0.75F, 0.5F, 0.75F); - } - - public boolean isOpaqueCube() - { - return false; - } - - public boolean isFullCube() - { - return false; - } - - public void setBlockBoundsBasedOnState(IWorldAccess worldIn, BlockPos pos) - { - switch ((Facing)worldIn.getState(pos).getValue(FACING)) - { - case UP: - default: - this.setBlockBounds(0.25F, 0.0F, 0.25F, 0.75F, 0.5F, 0.75F); - break; - - case NORTH: - this.setBlockBounds(0.25F, 0.25F, 0.5F, 0.75F, 0.75F, 1.0F); - break; - - case SOUTH: - this.setBlockBounds(0.25F, 0.25F, 0.0F, 0.75F, 0.75F, 0.5F); - break; - - case WEST: - this.setBlockBounds(0.5F, 0.25F, 0.25F, 1.0F, 0.75F, 0.75F); - break; - - case EAST: - this.setBlockBounds(0.0F, 0.25F, 0.25F, 0.5F, 0.75F, 0.75F); - } - } - - public BoundingBox getCollisionBoundingBox(World worldIn, BlockPos pos, State state) - { - this.setBlockBoundsBasedOnState(worldIn, pos); - return super.getCollisionBoundingBox(worldIn, pos, state); - } - - public State onBlockPlaced(World worldIn, BlockPos pos, Facing facing, float hitX, float hitY, float hitZ, int meta, EntityLiving placer) - { - return this.getState().withProperty(FACING, placer.getHorizontalFacing()); - } - - public TileEntity createNewTileEntity(World worldIn, int meta) - { - return new TileEntitySkull(); - } - - public Item getItem(World worldIn, BlockPos pos) - { - return Items.skull; - } - - public void dropBlockAsItemWithChance(World worldIn, BlockPos pos, State state, float chance, int fortune) - { - } - -// public void onBlockHarvested(World worldIn, BlockPos pos, State state, EntityNPC player) -// { -// if (player.creative) -// { -// if(!worldIn.client) -// worldIn.removeTileEntity(pos); -// } -// -// super.onBlockHarvested(worldIn, pos, state, player); -// } - - public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) - { - if (!worldIn.client) - { - TileEntity tileentity = worldIn.getTileEntity(pos); - if (tileentity instanceof TileEntitySkull) - { -// TileEntitySkull tileentityskull = (TileEntitySkull)tileentity; - ItemStack itemstack = new ItemStack(Items.skull, 1, 0); -// if (tileentityskull.getUser() != null) -// { -// itemstack.setTagCompound(new NBTTagCompound()); -// itemstack.getTagCompound().setString("SkullOwner", tileentityskull.getUser()); -// } - spawnAsEntity(worldIn, pos, itemstack); - } - super.onBlockRemoved(worldIn, pos, state); - } - } - - public Item getItemDropped(State state, Random rand, int fortune) - { - return Items.skull; - } - - public State getStateFromMeta(int meta) - { - return this.getState().withProperty(FACING, Facing.getFront(meta)); - } - - public int getMetaFromState(State state) - { - return ((Facing)state.getValue(FACING)).getIndex(); - } - - protected IProperty[] getProperties() - { - return new IProperty[] {FACING}; - } - - public boolean isXrayVisible() - { - return true; - } - - public Transforms getTransform() { - return Transforms.SKULL; - } -} diff --git a/java/src/game/block/BlockSlime.java b/java/src/game/block/BlockSlime.java deleted file mode 100755 index 27bdee5..0000000 --- a/java/src/game/block/BlockSlime.java +++ /dev/null @@ -1,92 +0,0 @@ -package game.block; - -import game.entity.Entity; -import game.item.CheatTab; -import game.material.Material; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.world.BlockPos; -import game.world.State; -import game.world.World; - -public class BlockSlime extends BlockBreakable -{ - private static final ModelBlock slime = new ModelBlock("slime") - .add(0, 0, 0, 16, 16, 16) - .d().uv(0, 0, 16, 16).noCull() - .u().uv(0, 0, 16, 16).noCull() - .n().uv(0, 0, 16, 16).noCull() - .s().uv(0, 0, 16, 16).noCull() - .w().uv(0, 0, 16, 16).noCull() - .e().uv(0, 0, 16, 16).noCull() - .add(3, 3, 3, 13, 13, 13) - .d().uv(3, 3, 13, 13).noCull() - .u().uv(3, 3, 13, 13).noCull() - .n().uv(3, 3, 13, 13).noCull() - .s().uv(3, 3, 13, 13).noCull() - .w().uv(3, 3, 13, 13).noCull() - .e().uv(3, 3, 13, 13).noCull() - ; - - public BlockSlime() - { - super(Material.clay, false); - this.setTab(CheatTab.tabTech); - this.slipperiness = 0.8F; - } - - public BlockLayer getBlockLayer() - { - return BlockLayer.TRANSLUCENT; - } - - /** - * Block's chance to react to a living entity falling on it. - */ - public void onFallenUpon(World worldIn, BlockPos pos, Entity entityIn, float fallDistance) - { - if (entityIn.isSneaking()) - { - super.onFallenUpon(worldIn, pos, entityIn, fallDistance); - } - else - { - entityIn.fall(fallDistance, 0.0F); - } - } - - /** - * Called when an Entity lands on this Block. This method *must* update motionY because the entity will not do that - * on its own - */ - public void onLanded(World worldIn, Entity entityIn) - { - if (entityIn.isSneaking()) - { - super.onLanded(worldIn, entityIn); - } - else if (entityIn.motionY < 0.0D) - { - entityIn.motionY = -entityIn.motionY; - } - } - - /** - * Triggered whenever an entity collides with this block (enters into the block) - */ - public void onEntityCollidedWithBlock(World worldIn, BlockPos pos, Entity entityIn) - { - if (Math.abs(entityIn.motionY) < 0.1D && !entityIn.isSneaking()) - { - double d0 = 0.4D + Math.abs(entityIn.motionY) * 0.2D; - entityIn.motionX *= d0; - entityIn.motionZ *= d0; - } - - super.onEntityCollidedWithBlock(worldIn, pos, entityIn); - } - - public ModelBlock getModel(String name, State state) { - return slime; - } -} diff --git a/java/src/game/block/BlockSnowBlock.java b/java/src/game/block/BlockSnowBlock.java deleted file mode 100755 index 9eb13c3..0000000 --- a/java/src/game/block/BlockSnowBlock.java +++ /dev/null @@ -1,47 +0,0 @@ -package game.block; - -import game.init.Config; -import game.init.Items; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.LightType; -import game.world.State; -import game.world.WorldServer; - -public class BlockSnowBlock extends Block -{ - public BlockSnowBlock() - { - super(Material.craftedSnow); - this.setTickRandomly(); - this.setTab(CheatTab.tabNature); - } - - /** - * Get the Item that this Block should drop when harvested. - */ - public Item getItemDropped(State state, Random rand, int fortune) - { - return Items.snowball; - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(Random random) - { - return 4; - } - - public void updateTick(WorldServer worldIn, BlockPos pos, State state, Random rand) - { - if (Config.snowFullMelt && worldIn.getLightFor(LightType.BLOCK, pos) > 11) - { - this.dropBlockAsItem(worldIn, pos, worldIn.getState(pos), 0); - worldIn.setBlockToAir(pos); - } - } -} diff --git a/java/src/game/block/BlockSourceImpl.java b/java/src/game/block/BlockSourceImpl.java deleted file mode 100755 index 6243f42..0000000 --- a/java/src/game/block/BlockSourceImpl.java +++ /dev/null @@ -1,55 +0,0 @@ -package game.block; - -import game.dispenser.IBlockSource; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.State; -import game.world.World; - -public class BlockSourceImpl implements IBlockSource -{ - private final World worldObj; - private final BlockPos pos; - - public BlockSourceImpl(World worldIn, BlockPos posIn) - { - this.worldObj = worldIn; - this.pos = posIn; - } - - public World getWorld() - { - return this.worldObj; - } - - public double getX() - { - return (double)this.pos.getX() + 0.5D; - } - - public double getY() - { - return (double)this.pos.getY() + 0.5D; - } - - public double getZ() - { - return (double)this.pos.getZ() + 0.5D; - } - - public BlockPos getBlockPos() - { - return this.pos; - } - - public int getBlockMetadata() - { - State iblockstate = this.worldObj.getState(this.pos); - return iblockstate.getBlock().getMetaFromState(iblockstate); - } - - public T getBlockTileEntity() - { - return (T)this.worldObj.getTileEntity(this.pos); - } -} diff --git a/java/src/game/block/BlockStainedGlass.java b/java/src/game/block/BlockStainedGlass.java deleted file mode 100755 index 6277a9a..0000000 --- a/java/src/game/block/BlockStainedGlass.java +++ /dev/null @@ -1,119 +0,0 @@ -package game.block; - -import java.util.List; - -import game.color.DyeColor; -import game.item.CheatTab; -import game.item.Item; -import game.item.ItemStack; -import game.material.Material; -import game.properties.IProperty; -import game.properties.PropertyEnum; -import game.renderer.BlockLayer; -import game.renderer.blockmodel.ModelBlock; -import game.rng.Random; -import game.world.State; - -public class BlockStainedGlass extends BlockBreakable -{ - public static final PropertyEnum COLOR = PropertyEnum.create("color", DyeColor.class); - - public BlockStainedGlass(Material materialIn) - { - super(materialIn, false); - this.setDefaultState(this.getBaseState().withProperty(COLOR, DyeColor.WHITE)); - this.setTab(CheatTab.tabBlocks); - } - - /** - * Gets the metadata of the item this Block can drop. This method is called when the block gets destroyed. It - * returns the metadata of the dropped item based on the old metadata of the block. - */ - public int damageDropped(State state) - { - return ((DyeColor)state.getValue(COLOR)).getMetadata(); - } - - /** - * returns a list of blocks with the same ID, but different meta (eg: wood returns 4 blocks) - */ - public void getSubBlocks(Item itemIn, CheatTab tab, List list) - { - for (DyeColor enumdyecolor : DyeColor.values()) - { - list.add(new ItemStack(itemIn, 1, enumdyecolor.getMetadata())); - } - } - -// /** -// * Get the MapColor for this Block and the given BlockState -// */ -// public MapColor getMapColor(IBlockState state) -// { -// return ((EnumDyeColor)state.getValue(COLOR)).getMapColor(); -// } - - public BlockLayer getBlockLayer() - { - return BlockLayer.TRANSLUCENT; - } - - /** - * Returns the quantity of items to drop on block destruction. - */ - public int quantityDropped(Random random) - { - return 0; - } - - public boolean canSilkHarvest() - { - return true; - } - - public boolean isFullCube() - { - return false; - } - - /** - * Convert the given metadata into a BlockState for this Block - */ - public State getStateFromMeta(int meta) - { - return this.getState().withProperty(COLOR, DyeColor.byMetadata(meta)); - } - -// public void onBlockAdded(WorldServer worldIn, BlockPos pos, State state) -// { -// if (!worldIn.client) -// { -// BlockBeacon.updateColorAsync(worldIn, pos); -// } -// } -// -// public void onBlockRemoved(WorldServer worldIn, BlockPos pos, State state) -// { -// if (!worldIn.client) -// { -// BlockBeacon.updateColorAsync(worldIn, pos); -// } -// } - - /** - * Convert the BlockState into the correct metadata value - */ - public int getMetaFromState(State state) - { - return ((DyeColor)state.getValue(COLOR)).getMetadata(); - } - - protected IProperty[] getProperties() - { - return new IProperty[] {COLOR}; - } - - public ModelBlock getModel(String name, State state) { - return new ModelBlock(state.getValue(COLOR).getName() + "_glass").add().all(); - } -} diff --git a/java/src/game/block/BlockStone.java b/java/src/game/block/BlockStone.java deleted file mode 100755 index 89d99a6..0000000 --- a/java/src/game/block/BlockStone.java +++ /dev/null @@ -1,20 +0,0 @@ -package game.block; - -import game.init.Blocks; -import game.init.ItemRegistry; -import game.item.CheatTab; -import game.item.Item; -import game.material.Material; -import game.rng.Random; -import game.world.State; - -public class BlockStone extends Block { - public BlockStone() { - super(Material.rock); - this.setTab(CheatTab.tabNature); - } - - public Item getItemDropped(State state, Random rand, int fortune) { - return ItemRegistry.getItemFromBlock(Blocks.cobblestone); - } -} diff --git a/java/src/game/block/BlockTianReactor.java b/java/src/game/block/BlockTianReactor.java deleted file mode 100755 index f480c46..0000000 --- a/java/src/game/block/BlockTianReactor.java +++ /dev/null @@ -1,25 +0,0 @@ -package game.block; - -import java.util.Map; - -import game.model.ModelRotation; -import game.renderer.blockmodel.ModelBlock; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityTianReactor; -import game.world.State; -import game.world.World; - -public class BlockTianReactor extends BlockMachine { - public TileEntity createNewTileEntity(World worldIn, int meta) { - return new TileEntityTianReactor(); - } - - public ModelBlock getModel(String name, State state) { - return new ModelBlock("tian_reactor_front").add().d("tian_reactor_bottom").u("tian_reactor_top").n().s("tian_reactor_side") - .we("tian_reactor_side").rotate(ModelRotation.getNorthRot(state.getValue(FACING))); - } - - public void getAnimatedTextures(Map map) { - map.put("blocks/tian_reactor_front", 5); - } -} diff --git a/java/src/game/block/BlockTreasure.java b/java/src/game/block/BlockTreasure.java deleted file mode 100755 index fd5c5f7..0000000 --- a/java/src/game/block/BlockTreasure.java +++ /dev/null @@ -1,13 +0,0 @@ -package game.block; - -import game.material.Material; - -public class BlockTreasure extends Block { - public BlockTreasure(Material materialIn) { - super(materialIn); - } - - public boolean isXrayVisible() { - return true; - } -} diff --git a/java/src/game/block/BlockWorkbench.java b/java/src/game/block/BlockWorkbench.java deleted file mode 100755 index 453d852..0000000 --- a/java/src/game/block/BlockWorkbench.java +++ /dev/null @@ -1,79 +0,0 @@ -package game.block; - -import game.entity.npc.EntityNPC; -import game.inventory.Container; -import game.inventory.ContainerWorkbench; -import game.inventory.InventoryPlayer; -import game.item.CheatTab; -import game.material.Material; -import game.renderer.blockmodel.ModelBlock; -import game.tileentity.IInteractionObject; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; - -public class BlockWorkbench extends Block -{ - public BlockWorkbench() - { - super(Material.wood); - this.setTab(CheatTab.tabTech); - } - - public boolean onBlockActivated(World worldIn, BlockPos pos, State state, EntityNPC playerIn, Facing side, float hitX, float hitY, float hitZ) - { - if (worldIn.client) - { - return true; - } - else - { - playerIn.displayGui(new BlockWorkbench.InterfaceCraftingTable(worldIn, pos)); -// playerIn.triggerAchievement(StatRegistry.craftingTableStat); - return true; - } - } - - public ModelBlock getModel(String name, State state) { - return new ModelBlock("crafting_table_front").add().d("oak_planks").u("crafting_table_top").n().s("crafting_table_side") - .w().e("crafting_table_side"); - } - - public static class InterfaceCraftingTable implements IInteractionObject - { - private final World world; - private final BlockPos position; - - public InterfaceCraftingTable(World worldIn, BlockPos pos) - { - this.world = worldIn; - this.position = pos; - } - - public String getName() - { - return null; - } - - public boolean hasCustomName() - { - return false; - } - - public String getCommandName() - { - return "Werkbank"; - } - - public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) - { - return new ContainerWorkbench(playerInventory, this.world, this.position); - } - - public String getGuiID() - { - return "crafting_table"; - } - } -} diff --git a/java/src/game/block/IGrowable.java b/java/src/game/block/IGrowable.java deleted file mode 100755 index 6c9561d..0000000 --- a/java/src/game/block/IGrowable.java +++ /dev/null @@ -1,16 +0,0 @@ -package game.block; - -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.World; -import game.world.WorldServer; - -public interface IGrowable -{ - boolean canGrow(World worldIn, BlockPos pos, State state, boolean isClient); - - boolean canUseBonemeal(World worldIn, Random rand, BlockPos pos, State state); - - void grow(WorldServer worldIn, Random rand, BlockPos pos, State state); -} diff --git a/java/src/game/block/ITileEntityProvider.java b/java/src/game/block/ITileEntityProvider.java deleted file mode 100755 index af5e3cd..0000000 --- a/java/src/game/block/ITileEntityProvider.java +++ /dev/null @@ -1,12 +0,0 @@ -package game.block; - -import game.tileentity.TileEntity; -import game.world.World; - -public interface ITileEntityProvider -{ - /** - * Returns a new instance of a block's tile entity class. Called on placing the block. - */ - TileEntity createNewTileEntity(World worldIn, int meta); -} diff --git a/java/src/game/command/Argument.java b/java/src/game/command/Argument.java deleted file mode 100644 index fb1307e..0000000 --- a/java/src/game/command/Argument.java +++ /dev/null @@ -1,33 +0,0 @@ -package game.command; - -import java.util.Map; - -public class Argument { - private final Parameter parameter; - private final int position; - private final String[] inputs; - private final Map values; - - public Argument(Parameter parameter, int position, String[] inputs, Map values) { - this.parameter = parameter; - this.position = position; - this.inputs = inputs; - this.values = values; - } - - public Parameter getParameter() { - return this.parameter; - } - - public int getPosition() { - return this.position; - } - - public String[] getInputs() { - return this.inputs; - } - - public Map getValues() { - return this.values; - } -} diff --git a/java/src/game/command/ArgumentSplitter.java b/java/src/game/command/ArgumentSplitter.java deleted file mode 100644 index 6d229e5..0000000 --- a/java/src/game/command/ArgumentSplitter.java +++ /dev/null @@ -1,411 +0,0 @@ -package game.command; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import game.collect.Lists; -import game.collect.Maps; -import game.collect.Sets; - -public class ArgumentSplitter { - private final String command; - private final Map arguments; - private final CommandEnvironment env; - - protected ArgumentSplitter(Map arguments, String command, CommandEnvironment env) { - this.arguments = arguments; - this.command = command; - this.env = env; - } - - private static String joinArgs(Iterable iter) { - StringBuilder sb = new StringBuilder("'"); - for(T obj : iter) { - if(sb.length() > 1) - sb.append("', '"); - sb.append(String.valueOf(obj)); - } - return sb.append("'").toString(); - } - - public static ArgumentSplitter parseArgs(CommandEnvironment env, String str, String[] argv, CachedExecutable cached) { - Map parameters = cached.getParameters(); - List positionals = Lists.newArrayList(cached.getPositionals()); - // String[] argv = ArgumentParser.splitString(str); - Map args = Maps.newHashMap(); - int ppos = 0; - boolean parse = true; - for(int z = 1; z < argv.length; z++) { - String arg = argv[z]; - Parameter param = null; - boolean pos = false; - if(parse && arg.equals("--")) { - parse = false; - continue; - } - else if(parse && (arg.startsWith("--") || (arg.startsWith("-") && arg.length() == 2))) { - param = parameters.get(arg.substring(arg.startsWith("--") ? 2 : 1)); - if(param != null && param.isPositional() && !args.containsKey(param.getName())) { - for(int n = 0; n < positionals.size(); n++) { - if(param == positionals.get(n)) { - positionals.remove(n); - break; - } - } - } - } - else if(ppos < positionals.size()) { - param = positionals.get(ppos++); - pos = true; - } - else { - throw new RunException("Position %d: Parameter '%s' ist überflüssig", z, arg); - } - if(param == null) - throw new RunException("Position %d: Argument '%s' ist unbekannt", z, arg); - if(args.containsKey(param.getName())) - throw new RunException("Position %d: Parameter '%s' mehrfach angegeben", z, param.getName()); - int nargs = param.getParsers().size(); -// if(!pos) -// z += 1; - if(z + (pos ? 0 : 1) + nargs > argv.length) - if(nargs == 1 && param.getName().equals(param.getParsers().get(0).getName())) - throw new RunException("Position %d: Argument '%s' benötigt einen Parameter", z, param.getName()); - else - throw new RunException("Position %d: Argument '%s' benötigt %d Parameter (%s)", z, param.getName(), nargs, - joinArgs(param.getParsers())); - Map params = Maps.newHashMapWithExpectedSize(nargs); - String[] inputs = new String[nargs + (pos ? 0 : 1)]; - int apos = 0; - for(int n = pos ? 0 : 1; n < nargs + (pos ? 0 : 1); n++) { - String par = inputs[n] = argv[z + n]; - ArgumentParser parser = param.getParsers().get(apos); - if(parse && (par.startsWith("--") || (par.startsWith("-") && par.length() == 2))) - if(nargs == 1 && param.getName().equals(parser.getName())) - throw new RunException("Position %d: Argument '%s': '%s' als Parameter verwendet", z + n, param.getName(), par); - else - throw new RunException("Position %d: Argument '%s': '%s' als Parameter '%s' (#%d) verwendet", z + n, - param.getName(), par, parser.getName(), apos + 1); - try { - params.put(parser.getName(), parser.parse(env, par)); - } - catch(Throwable e) { - if(nargs == 1 && param.getName().equals(parser.getName())) - throw new RunException(e, "Position %d: Argument '%s': Parameter konnte nicht interpretiert werden", z + n, - param.getName()); - else - throw new RunException(e, "Position %d: Argument '%s': Parameter '%s' (#%d) konnte nicht interpretiert werden", z + n, - param.getName(), parser.getName(), apos + 1); - } - apos += 1; - } - if(!pos) - inputs[0] = arg; - args.put(param.getName(), new Argument(param, z, inputs, params)); - z += nargs - (pos ? 1 : 0); - } - for(Parameter param : parameters.values()) { - if(!args.containsKey(param.getName())) { - if(param.isRequired()) { - for(ArgumentParser parser : param.getParsers()) { - if(parser.getDefault(env) == null) - throw new RunException("Argument '%s' muss angegeben werden", param.getName()); - } - } - else if(param.getParsers().isEmpty()) { - continue; - } - Map params = Maps.newHashMapWithExpectedSize(param.getParsers().size()); - for(ArgumentParser parser : param.getParsers()) { - params.put(parser.getName(), parser.getDefault(env)); - } - args.put(param.getName(), new Argument(param, -1, null, params)); - } - } - return new ArgumentSplitter(args, str, env); - } - - private static Iterable getParam(CommandEnvironment env, String[] argv, CachedExecutable cached) { - Map parameters = cached.getParameters(); - List positionals = Lists.newArrayList(cached.getPositionals()); - Set args = Sets.newHashSet(); - int ppos = 0; - boolean parse = true; - for(int z = 1; z < argv.length; z++) { - String arg = argv[z]; - Parameter param = null; - boolean pos = false; - if(z == argv.length - 1) { - if(ppos < positionals.size()) { - param = positionals.get(ppos); - if(param.getParsers().isEmpty()) // np - return null; - return param.getParsers().get(0).getCompletions(env); - } - else { - return null; - } - } - else if(parse && arg.equals("--")) { - parse = false; - continue; - } - else if(parse && (arg.startsWith("--") || (arg.startsWith("-") && arg.length() == 2))) { - param = parameters.get(arg.substring(arg.startsWith("--") ? 2 : 1)); - if(param != null && param.isPositional() && !args.contains(param.getName())) { - for(int n = 0; n < positionals.size(); n++) { - if(param == positionals.get(n)) { - positionals.remove(n); - break; - } - } - } - } - else if(ppos < positionals.size()) { - param = positionals.get(ppos++); - pos = true; - } - else { - return null; - } - if(param == null || args.contains(param.getName())) - return null; - int nargs = param.getParsers().size(); -// if(z + (pos ? 0 : 1) + nargs > argv.length - 1) { -// return param.getParsers().get(argv.length - z).getCompletions(env); -// } - int apos = 0; - for(int n = pos ? 0 : 1; n < nargs + (pos ? 0 : 1); n++) { - if(z + n == argv.length - 1) - return param.getParsers().get(apos).getCompletions(env); - String par = argv[z + n]; - if(parse && (par.startsWith("--") || (par.startsWith("-") && par.length() == 2))) - return null; - apos += 1; - } - args.add(param.getName()); - z += nargs - (pos ? 1 : 0); - } - return null; - } - - public static Iterable parseComplete(CommandEnvironment env, String[] argv, CachedExecutable cached, String last) { - Iterable comp = getParam(env, argv, cached); - if(comp == null /* || comp.length == 0 */ ) { - Set params = Sets.newTreeSet(); - boolean all = last.startsWith("--"); - for(String param : cached.getParameters().keySet()) { - if(all || param.length() == 1) - params.add(param.length() == 1 ? "-" + param : ("--" + param)); - } - return params; - } - return comp; - } - -// public ScriptArg getArg(String name) { -// return this.arguments.get(name); -// } - - public boolean hasArg(String name) { - return this.arguments.containsKey(name); - } - -// public boolean has(String name, String par) { -// return this.arguments.containsKey(name) && this.arguments.get(name).getValues().containsKey(par); -// } - -// public boolean has(String name) { -// return this.has(name, name); -// } - -// public T getDefault(String name, String par, T def) { -// ScriptArg arg = this.arguments.get(name); -// if(arg == null) -// return def; -// Object value = arg.getValues().get(par); -// return value == null ? def : (T)value; -// } -// -// public T getDefault(String name, T def) { -// return this.getDefault(name, name, def); -// } -// -// public T getUnchecked(String name, String par) { -// return this.getDefault(name, par, null); -// } - - public T getUnchecked(String name, String par) { - Argument arg = this.arguments.get(name); - if(arg == null) - return null; - Object value = arg.getValues().get(par); - return value == null ? null : (T)value; - } - -// public T getUnchecked(String name) { -// return this.getDefault(name, null); -// } -// -// public boolean getBool(String name, boolean def) { -// return this.getDefault(name, def); -// } -// -// public boolean getBool(String name) { -// return this.getUnchecked(name); -// } -// -// public > T getEnum(String name, T def) { -// return this.getDefault(name, def); -// } -// -// public > T getEnum(String name) { -// return this.getUnchecked(name); -// } -// -// public int getInt(String name, int def) { -// return this.getDefault(name, def); -// } -// -// public int getInt(String name) { -// return this.getUnchecked(name); -// } -// -// public long getLong(String name, long def) { -// return this.getDefault(name, def); -// } -// -// public long getLong(String name) { -// return this.getUnchecked(name); -// } -// -// public double getDouble(String name, double def) { -// return this.getDefault(name, def); -// } -// -// public double getDouble(String name) { -// return this.getUnchecked(name); -// } -// -// public String getString(String name, String def) { -// return this.getDefault(name, def); -// } -// -// public String getString(String name) { -// return this.getUnchecked(name); -// } -// -// public String[] getStrings(String name, String[] def) { -// return this.getDefault(name, def); -// } -// -// public String[] getStrings(String name) { -// return this.getUnchecked(name); -// } -// -// public Entity getEntity(String name, Entity def) { -// return this.getDefault(name, def); -// } -// -// public Entity getEntity(String name) { -// return this.getUnchecked(name); -// } -// -// public EntityLiving getLiving(String name, EntityLiving def) { -// return this.getDefault(name, def); -// } -// -// public EntityLiving getLiving(String name) { -// return this.getUnchecked(name); -// } -// -// public EntityNPC getNpc(String name, EntityNPC def) { -// return this.getDefault(name, def); -// } -// -// public EntityNPC getNpc(String name) { -// return this.getUnchecked(name); -// } -// -// public Block getBlock(String name, Block def) { -// return this.getDefault(name, def); -// } -// -// public Block getBlock(String name) { -// return this.getUnchecked(name); -// } -// -// public State getState(String name, State def) { -// return this.getDefault(name, def); -// } -// -// public State getState(String name) { -// return this.getUnchecked(name); -// } -// -// public Item getItem(String name, Item def) { -// return this.getDefault(name, def); -// } -// -// public Item getItem(String name) { -// return this.getUnchecked(name); -// } -// -// public ItemStack getStack(String name, ItemStack def) { -// return this.getDefault(name, def); -// } -// -// public ItemStack getStack(String name) { -// return this.getUnchecked(name); -// } -// -// public BlockPos getColumnPos(String name, BlockPos def) { -// return this.hasArg(name) ? this.getColumnPos(name) : def; -// } -// -// public BlockPos getColumnPos(String name) { -// return new BlockPos(this.getUnchecked(name, "x"), 0, this.getUnchecked(name, "z")); -// } -// -// public BlockPos getBlockPos(String name, BlockPos def) { -// return this.hasArg(name) ? this.getBlockPos(name) : def; -// } -// -// public BlockPos getBlockPos(String name) { -// return new BlockPos(this.getUnchecked(name, "x"), this.getUnchecked(name, "y"), this.getUnchecked(name, "z")); -// } -// -// public WorldPos getWorldPos(String name, WorldPos def) { -// return this.hasArg(name) ? this.getWorldPos(name) : def; -// } -// -// public WorldPos getWorldPos(String name) { -// return new WorldPos(this.getUnchecked(name, "x"), this.getUnchecked(name, "y"), this.getUnchecked(name, "z"), -// this.getUnchecked(name, "dim")); -// } -// -// public Vec3 getVector2D(String name, Vec3 def) { -// return this.hasArg(name) ? this.getVector2D(name) : def; -// } -// -// public Vec3 getVector2D(String name) { -// return new Vec3(this.getUnchecked(name, "x"), 0.0, this.getUnchecked(name, "z")); -// } -// -// public Vec3 getVector(String name, Vec3 def) { -// return this.hasArg(name) ? this.getVector(name) : def; -// } -// -// public Vec3 getVector(String name) { -// return new Vec3(this.getUnchecked(name, "x"), this.getUnchecked(name, "y"), this.getUnchecked(name, "z")); -// } -// -// public WorldServer getWorld(String name) { -// return this.getUnchecked(name); -// } -// -// public NBTTagCompound getTag(String name) { -// return this.getUnchecked(name); -// } -} diff --git a/java/src/game/command/CachedExecutable.java b/java/src/game/command/CachedExecutable.java deleted file mode 100644 index af728d2..0000000 --- a/java/src/game/command/CachedExecutable.java +++ /dev/null @@ -1,93 +0,0 @@ -package game.command; - -import java.lang.reflect.Method; -import java.util.List; -import java.util.Map; - -import game.collect.Lists; -import game.collect.Maps; - -public class CachedExecutable { - private final Executable executable; - private final String name; - private final Map parameters; - private final List positionals; - private final Method method; - - protected CachedExecutable(Executable executable, Map parameters, List positionals, Method method) { - this.executable = executable; - this.parameters = parameters; - this.positionals = positionals; - this.name = executable.getName(); - this.method = method; - } - - public static CachedExecutable cacheExecutable(Executable executable) { - Map parameters = Maps.newTreeMap(); - Map params = executable.getParameters(); - parameters.putAll(params); - Parameter[] positions = new Parameter[parameters.size()]; - int pos = -1; - for(Parameter param : params.values()) { - if(param.isPositional()) { - positions[param.getPosition()] = param; - pos = param.getPosition() > pos ? param.getPosition() : pos; - } - if(param.hasShortName()) - parameters.put("" + param.getShortName(), param); - } - List positionals = Lists.newArrayList(); - for(int z = 0; z <= pos; z++) { - if(positions[z] == null) - throw new NullPointerException("positions[" + z + "]"); - positionals.add(positions[z]); - } - List> classes = Lists.newArrayList(CommandEnvironment.class, Executor.class); - for(Parameter param : executable.getParamList()) { - ArgCombiner combiner = param.getCombiner(); - if(combiner != null) { - classes.add(combiner.getTypeClass()); - continue; - } - if(param.getParsers().isEmpty()) { - classes.add(boolean.class); - continue; - } - for(ArgumentParser parser : param.getParsers()) { - classes.add(parser.getTypeClass()); - } - } - Method method; - try { - method = executable.getClass().getDeclaredMethod("exec", classes.toArray(new Class[classes.size()])); - } - catch(NoSuchMethodException e) { - throw new RuntimeException(e); - } - return new CachedExecutable(executable, parameters, positionals, method); - } - - public Executable getExecutable() { - return this.executable; - } - - public Method getMethod() { - return this.method; - } - - public Map getParameters() { - return this.parameters; - } - - public List getPositionals() { - return this.positionals; - } - - public String getName() { - return this.name; - } - - public String toString() { - return this.name; - } -} diff --git a/java/src/game/command/Executable.java b/java/src/game/command/Executable.java deleted file mode 100644 index 8761873..0000000 --- a/java/src/game/command/Executable.java +++ /dev/null @@ -1,11 +0,0 @@ -package game.command; - -import java.util.List; -import java.util.Map; - -public interface Executable { -// Object exec(ScriptEnvironment env, ScriptArgs args); - Map getParameters(); - List getParamList(); - String getName(); -} diff --git a/java/src/game/command/Executor.java b/java/src/game/command/Executor.java deleted file mode 100644 index 85f7b93..0000000 --- a/java/src/game/command/Executor.java +++ /dev/null @@ -1,18 +0,0 @@ -package game.command; - -import game.entity.Entity; -import game.world.BlockPos; -import game.world.Position; - -public interface Executor { - void logConsole(String msg); - String getExecId(); - String getExecName(); - Position getExecPos(); - Entity getPointedEntity(); - BlockPos getPointedPosition(); - - default void logConsole(String fmt, Object ... args) { - this.logConsole(String.format(fmt, args)); - } -} diff --git a/java/src/game/command/FixedExecutor.java b/java/src/game/command/FixedExecutor.java deleted file mode 100644 index 04b5d43..0000000 --- a/java/src/game/command/FixedExecutor.java +++ /dev/null @@ -1,53 +0,0 @@ -package game.command; - -import game.Server; -import game.entity.Entity; -import game.world.BlockPos; -import game.world.Position; - -public class FixedExecutor implements Executor { - private final Server server; - private final String id; - - private String name; - private Position position; - - public FixedExecutor(Server server, String id, String name, Position pos) { - this.server = server; - this.id = id; - this.name = name; - this.position = pos; - } - - public void setName(String name) { - this.name = name; - } - - public void setPosition(Position pos) { - this.position = pos; - } - - public void logConsole(String msg) { - this.server.logConsole(msg); - } - - public String getExecId() { - return this.id; - } - - public String getExecName() { - return this.name; - } - - public Position getExecPos() { - return this.position; - } - - public Entity getPointedEntity() { - return null; - } - - public BlockPos getPointedPosition() { - return null; - } -} diff --git a/java/src/game/command/IntParser.java b/java/src/game/command/IntParser.java deleted file mode 100644 index 56dc52d..0000000 --- a/java/src/game/command/IntParser.java +++ /dev/null @@ -1,39 +0,0 @@ -package game.command; - -public class IntParser extends DefaultingParser { - private final Integer min; - private final Integer max; - private final boolean hex; - - public IntParser(String name, boolean hex, Integer def, Integer min, Integer max, Object ... completions) { - super(name, def, completions); - this.min = min; - this.max = max; - this.hex = hex; - } - - public Integer parse(CommandEnvironment env, String input) { - int value; - try { - value = Integer.parseInt(input, this.hex ? 16 : 10); - } - catch(NumberFormatException e) { - throw new RunException("Ungültige " + (this.hex ? "Hexadezimalzahl" : "Ganzzahl") + " '%s'", input); - } - if(this.min != null && value < this.min) - if(this.max != null) - throw new RunException("Die Zahl muss im Bereich %d .. %d liegen, habe %d", this.min, this.max, value); - else - throw new RunException("Die Zahl muss mindestens %d betragen, habe %d", this.min, value); - if(this.max != null && value > this.max) - if(this.min != null) - throw new RunException("Die Zahl muss im Bereich %d .. %d liegen, habe %d", this.min, this.max, value); - else - throw new RunException("Die Zahl darf höchstens %d betragen, habe %d", this.max, value); - return value; - } - - public Class getTypeClass() { - return this.hasDefault() ? int.class : Integer.class; - } -} diff --git a/java/src/game/command/Parameter.java b/java/src/game/command/Parameter.java deleted file mode 100644 index 8aef298..0000000 --- a/java/src/game/command/Parameter.java +++ /dev/null @@ -1,53 +0,0 @@ -package game.command; - -import java.util.List; - -public class Parameter { - private final String name; - private final char shortName; - private final boolean required; - private final int position; - private final List parsers; - private final ArgCombiner combiner; - - public Parameter(String name, char shortName, int position, boolean required, List parsers, ArgCombiner combiner) { - this.name = name; - this.shortName = shortName; - this.position = position; - this.required = required; - this.parsers = parsers; - this.combiner = combiner; - } - - public boolean isPositional() { - return this.position >= 0; - } - - public int getPosition() { - return this.position; - } - - public List getParsers() { - return this.parsers; - } - - public ArgCombiner getCombiner() { - return this.combiner; - } - - public boolean isRequired() { - return this.required; - } - - public String getName() { - return this.name; - } - - public boolean hasShortName() { - return this.shortName != 0; - } - - public char getShortName() { - return this.shortName; - } -} diff --git a/java/src/game/command/PatternReplacer.java b/java/src/game/command/PatternReplacer.java deleted file mode 100644 index 0f064b8..0000000 --- a/java/src/game/command/PatternReplacer.java +++ /dev/null @@ -1,49 +0,0 @@ -package game.command; - -import java.util.function.Function; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -public class PatternReplacer { - private final String variable; - private final boolean matchAll; - private final Pattern pattern; - private final Function function; - - public PatternReplacer(String variable, boolean matchAll, Function function) { - this.variable = variable; - this.matchAll = matchAll; - this.pattern = Pattern.compile("\\$\\((" + Pattern.quote(variable) + (matchAll ? "[^\\)]*" : "") + ")\\)"); - this.function = function; - } - - public void replaceVar(StringBuffer sb) { - String str = sb.toString(); - sb.delete(0, sb.length()); - Matcher matcher = this.pattern.matcher(str); - while(matcher.find()) { - String orig = matcher.group(1); - String rep = this.function.apply(orig); - if(rep == null) - throw new RunException("Variable '%s' konnte in diesem Kontext nicht ersetzt werden", orig); - matcher.appendReplacement(sb, rep); - } - matcher.appendTail(sb); - } - - public String getVariable() { - return this.variable; - } - - public boolean matchesAll() { - return this.matchAll; - } - - public Pattern getPattern() { - return this.pattern; - } - - public Function getFunction() { - return this.function; - } -} diff --git a/java/src/game/command/PlayerParser.java b/java/src/game/command/PlayerParser.java deleted file mode 100644 index 0c5d7c8..0000000 --- a/java/src/game/command/PlayerParser.java +++ /dev/null @@ -1,32 +0,0 @@ -package game.command; - -import java.util.Collection; -import game.network.Player; - -public class PlayerParser extends CompletingParser { - protected final boolean useSender; - - public PlayerParser(String name, boolean useSender) { - super(name); - this.useSender = useSender; - } - - public Object parse(CommandEnvironment env, String input) { - Player net = env.getServer().getPlayer(input); - if(net == null) - throw new RunException("Spieler '%s' wurde nicht gefunden", input); - return net; - } - - public Object getDefault(CommandEnvironment env) { - return this.useSender && env.getExecutor() instanceof Player ? (Player)env.getExecutor() : null; - } - - public Collection getCompletions(CommandEnvironment env) { - return env.getServer().getAllUsernames(); - } - - public Class getTypeClass() { - return Player.class; - } -} diff --git a/java/src/game/command/TagParser.java b/java/src/game/command/TagParser.java deleted file mode 100644 index 44327ff..0000000 --- a/java/src/game/command/TagParser.java +++ /dev/null @@ -1,26 +0,0 @@ -package game.command; - -import game.nbt.NBTException; -import game.nbt.NBTParser; -import game.nbt.NBTTagCompound; - -public class TagParser extends DefaultingParser { - public TagParser(String name, NBTTagCompound def, Object ... completions) { - super(name, def, completions); - } - - public NBTTagCompound parse(CommandEnvironment env, String input) { - NBTTagCompound value; - try { - value = NBTParser.parseTag(input); - } - catch(NBTException e) { - throw new RunException(e, "Ungültiger NBT-Tag '%s'", input); - } - return value; - } - - public Class getTypeClass() { - return NBTTagCompound.class; - } -} diff --git a/java/src/game/command/commands/CommandAdmin.java b/java/src/game/command/commands/CommandAdmin.java deleted file mode 100644 index eb58a51..0000000 --- a/java/src/game/command/commands/CommandAdmin.java +++ /dev/null @@ -1,25 +0,0 @@ -package game.command.commands; - -import game.command.CommandEnvironment; -import game.command.RunException; -import game.command.Command; -import game.command.Executor; -import game.network.Player; - -public class CommandAdmin extends Command { - public CommandAdmin() { - super("admin"); - - this.addPlayer("player", false); - } - - public void exec(CommandEnvironment env, Executor exec, Player player) { - if(player == exec) - throw new RunException("Du kannst nicht deinen eigenen Admin-Status erneut setzen"); - else if(player.getAdmin()) - throw new RunException("%s ist bereits ein Admin", player.getUser()); - player.setAdmin(true); - player.logConsole("Du hast Administatorrechte von %s bekommen", exec.getExecId()); - exec.logConsole("%s ist jetzt ein Admin", player.getUser()); - } -} diff --git a/java/src/game/command/commands/CommandHelp.java b/java/src/game/command/commands/CommandHelp.java deleted file mode 100644 index 3d2b988..0000000 --- a/java/src/game/command/commands/CommandHelp.java +++ /dev/null @@ -1,56 +0,0 @@ -package game.command.commands; - -import java.util.List; -import java.util.Map.Entry; -import java.util.function.Function; - -import game.collect.Lists; - -import game.command.ArgumentParser; -import game.command.CachedExecutable; -import game.command.Parameter; -import game.command.CommandEnvironment; -import game.command.Command; -import game.command.Executor; -import game.util.Util; - -public class CommandHelp extends Command { - public CommandHelp(CommandEnvironment env) { - super("help"); - - this.setParamsOptional(); - this.addEnum("command", CachedExecutable.class, env.getExecutables().values()); - } - - public void exec(CommandEnvironment env, Executor exec, CachedExecutable command) { - if(command == null) { - for(CachedExecutable cmd : env.getExecutables().values()) { - this.exec(env, exec, cmd); - } - return; - } - List list = Lists.newArrayList(); - for(Entry entry : command.getParameters().entrySet()) { - Parameter param = entry.getValue(); - if(entry.getKey().length() == 1 && !param.isPositional() && param.hasShortName()) { - list.add("-" + param.getShortName() + (param.getParsers().isEmpty() ? " (" + param.getName() + ")" : (param.getParsers().size() == 1 && - param.getParsers().get(0).getName().equals(param.getName()) ? " <" + param.getName() + ">" : - " (" + param.getName() + ")" + Util.buildLines(" ", new Function() { - public String apply(ArgumentParser parser) { - return "<" + parser.getName() + ">"; - } - }, param.getParsers())))); - } - } - for(Parameter param : command.getPositionals()) { - list.add((param.isRequired() ? "<" : "[") + (param.getParsers().size() == 1 && - param.getParsers().get(0).getName().equals(param.getName()) ? param.getName() : - "(" + param.getName() + ") " + Util.buildLines(" ", new Function() { - public String apply(ArgumentParser parser) { - return "<" + parser.getName() + ">"; - } - }, param.getParsers())) + (param.isRequired() ? ">" : "]")); - } - exec.logConsole("%s %s", command.getName(), Util.buildLines(" ", list)); - } -} diff --git a/java/src/game/command/commands/CommandKick.java b/java/src/game/command/commands/CommandKick.java deleted file mode 100644 index 5f93b33..0000000 --- a/java/src/game/command/commands/CommandKick.java +++ /dev/null @@ -1,26 +0,0 @@ -package game.command.commands; - -import game.command.CommandEnvironment; -import game.command.RunException; -import game.command.Command; -import game.command.Executor; -import game.network.Player; - -public class CommandKick extends Command { - public CommandKick() { - super("kick"); - - this.addPlayer("player", false); - } - - public void exec(CommandEnvironment env, Executor exec, Player player) { - if(!(exec instanceof Player)) - throw new RunException("Dieser Befehl kann nur von Spielern ausgeführt werden"); - else if(player == exec) - throw new RunException("Du kannst nicht dich nicht selbst vom Server werfen"); - else if(player.getAdmin()) - throw new RunException("%s ist ein Admin", player.getUser()); - player.disconnect(); - exec.logConsole("%s wurde vom Server geworfen", player.getUser()); - } -} diff --git a/java/src/game/command/commands/CommandRevoke.java b/java/src/game/command/commands/CommandRevoke.java deleted file mode 100644 index 25ceb93..0000000 --- a/java/src/game/command/commands/CommandRevoke.java +++ /dev/null @@ -1,27 +0,0 @@ -package game.command.commands; - -import game.command.CommandEnvironment; -import game.command.RunException; -import game.command.Command; -import game.command.Executor; -import game.network.Player; - -public class CommandRevoke extends Command { - public CommandRevoke() { - super("revoke"); - - this.addPlayer("player", false); - } - - public void exec(CommandEnvironment env, Executor exec, Player player) { - if(exec instanceof Player) - throw new RunException("Dieser Befehl kann nur der Konsole ausgeführt werden"); -// else if(player == exec) -// throw new RunException("Du kannst nicht deinen eigenen Admin-Status entfernen"); - else if(!player.getAdmin()) - throw new RunException("%s ist kein Admin", player.getUser()); - player.setAdmin(false); - player.logConsole("Der Host hat deine Administatorrechte entfernt"); - exec.logConsole("%s ist jetzt kein Admin mehr", player.getUser()); - } -} diff --git a/java/src/game/command/commands/CommandTp.java b/java/src/game/command/commands/CommandTp.java deleted file mode 100644 index 56a1443..0000000 --- a/java/src/game/command/commands/CommandTp.java +++ /dev/null @@ -1,28 +0,0 @@ -package game.command.commands; - -import java.util.List; -import game.command.CommandEnvironment; -import game.command.Command; -import game.command.Executor; -import game.entity.Entity; -import game.init.UniverseRegistry; -import game.world.Position; - -public class CommandTp extends Command { - public CommandTp() { - super("tp"); - - this.addEntity("target", false); - - this.addEntityList("entities", 'e', true); - } - - public Object exec(CommandEnvironment env, Executor exec, Entity target, List entities) { - Position pos = target.getPos(); - for(Entity entity : entities) { - entity.teleport(pos); - exec.logConsole("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x, (int)pos.y, (int)pos.z, UniverseRegistry.getDimension(pos.dim).getFormattedName(false)); - } - return entities.size(); - } -} diff --git a/java/src/game/dispenser/IBlockSource.java b/java/src/game/dispenser/IBlockSource.java deleted file mode 100755 index 8e6359e..0000000 --- a/java/src/game/dispenser/IBlockSource.java +++ /dev/null @@ -1,19 +0,0 @@ -package game.dispenser; - -import game.tileentity.TileEntity; -import game.world.BlockPos; - -public interface IBlockSource extends ILocatableSource -{ - double getX(); - - double getY(); - - double getZ(); - - BlockPos getBlockPos(); - - int getBlockMetadata(); - - T getBlockTileEntity(); -} diff --git a/java/src/game/dispenser/ILocatableSource.java b/java/src/game/dispenser/ILocatableSource.java deleted file mode 100755 index ea67a66..0000000 --- a/java/src/game/dispenser/ILocatableSource.java +++ /dev/null @@ -1,5 +0,0 @@ -package game.dispenser; - -public interface ILocatableSource extends ILocation -{ -} diff --git a/java/src/game/dispenser/ILocation.java b/java/src/game/dispenser/ILocation.java deleted file mode 100755 index c4a4142..0000000 --- a/java/src/game/dispenser/ILocation.java +++ /dev/null @@ -1,8 +0,0 @@ -package game.dispenser; - -import game.world.World; - -public interface ILocation extends IPosition -{ - World getWorld(); -} diff --git a/java/src/game/dispenser/PositionImpl.java b/java/src/game/dispenser/PositionImpl.java deleted file mode 100755 index a268ee3..0000000 --- a/java/src/game/dispenser/PositionImpl.java +++ /dev/null @@ -1,30 +0,0 @@ -package game.dispenser; - -public class PositionImpl implements IPosition -{ - protected final double x; - protected final double y; - protected final double z; - - public PositionImpl(double xCoord, double yCoord, double zCoord) - { - this.x = xCoord; - this.y = yCoord; - this.z = zCoord; - } - - public double getX() - { - return this.x; - } - - public double getY() - { - return this.y; - } - - public double getZ() - { - return this.z; - } -} diff --git a/java/src/game/enchantment/Enchantment.java b/java/src/game/enchantment/Enchantment.java deleted file mode 100755 index b212fd0..0000000 --- a/java/src/game/enchantment/Enchantment.java +++ /dev/null @@ -1,222 +0,0 @@ -package game.enchantment; - -import java.util.List; -import java.util.Map; -import java.util.Set; - -import game.collect.Lists; -import game.collect.Maps; - -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.item.ItemStack; - -public abstract class Enchantment -{ - private static final String[] LEVELS = new String[] {"I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X"}; - private static final Enchantment[] enchantmentsList = new Enchantment[256]; - public static final Enchantment[] enchantmentsBookList; - private static final Map locationEnchantments = Maps.newHashMap(); - - public static final Enchantment protection = new EnchantmentProtection(0, "protection", 10, 0); - public static final Enchantment fireProtection = new EnchantmentProtection(1, "fire_protection", 5, 1); - public static final Enchantment featherFalling = new EnchantmentProtection(2, "feather_falling", 5, 2); - public static final Enchantment blastProtection = new EnchantmentProtection(3, "blast_protection", 2, 3); - public static final Enchantment projectileProtection = new EnchantmentProtection(4, "projectile_protection", 5, 4); -// public static final Enchantment respiration = new EnchantmentOxygen(5, "respiration", 2); -// public static final Enchantment aquaAffinity = new EnchantmentWaterWorker(6, "aqua_affinity", 2); - public static final Enchantment thorns = new EnchantmentThorns(7, "thorns", 1); -// public static final Enchantment depthStrider = new EnchantmentWaterWalker(8, "depth_strider", 2); - public static final Enchantment sharpness = new EnchantmentDamage(16, "sharpness", 10); -// public static final Enchantment smite = new EnchantmentDamage(17, "smite", 5, 1); -// public static final Enchantment baneOfArthropods = new EnchantmentDamage(18, "bane_of_arthropods", 5, 2); - public static final Enchantment knockback = new EnchantmentKnockback(19, "knockback", 5); - public static final Enchantment fireAspect = new EnchantmentFireAspect(20, "fire_aspect", 2); - public static final Enchantment looting = new EnchantmentLootBonus(21, "looting", 2, EnumEnchantmentType.WEAPON); - public static final Enchantment efficiency = new EnchantmentDigging(32, "efficiency", 10); - public static final Enchantment silkTouch = new EnchantmentUntouching(33, "silk_touch", 1); - public static final Enchantment unbreaking = new EnchantmentDurability(34, "unbreaking", 5); - public static final Enchantment fortune = new EnchantmentLootBonus(35, "fortune", 2, EnumEnchantmentType.DIGGER); - public static final Enchantment power = new EnchantmentArrowDamage(48, "power", 10); - public static final Enchantment punch = new EnchantmentArrowKnockback(49, "punch", 2); - public static final Enchantment flame = new EnchantmentArrowFire(50, "flame", 2); - public static final Enchantment infinity = new EnchantmentArrowInfinite(51, "infinity", 1); - public static final Enchantment luckOfTheSea = new EnchantmentLootBonus(61, "luck_of_the_sea", 2, EnumEnchantmentType.FISHING_ROD); - public static final Enchantment lure = new EnchantmentFishingSpeed(62, "lure", 2, EnumEnchantmentType.FISHING_ROD); - - public static final Enchantment draining = new EnchantmentDraining(64, "draining", 1); - - public final int effectId; - private final int weight; - - /** The EnumEnchantmentType given to this Enchantment. */ - public EnumEnchantmentType type; - - /** Used in localisation and stats. */ - protected String name; - - /** - * Retrieves an Enchantment from the enchantmentsList - */ - public static Enchantment getEnchantmentById(int enchID) - { - return enchID >= 0 && enchID < enchantmentsList.length ? enchantmentsList[enchID] : null; - } - - protected Enchantment(int enchID, String enchName, int enchWeight, EnumEnchantmentType enchType) - { - this.effectId = enchID; - this.weight = enchWeight; - this.type = enchType; - - if (enchantmentsList[enchID] != null) - { - throw new IllegalArgumentException("Duplicate enchantment id!"); - } - else - { - enchantmentsList[enchID] = this; - locationEnchantments.put(enchName, this); - } - } - - /** - * Retrieves an enchantment by using its location name. - */ - public static Enchantment getEnchantmentByLocation(String location) - { - return locationEnchantments.get(location); - } - - public static Set getNames() - { - return locationEnchantments.keySet(); - } - - /** - * Retrieves the weight value of an Enchantment. This weight value is used within vanilla to determine how rare an - * enchantment is. - */ - public int getWeight() - { - return this.weight; - } - - /** - * Returns the minimum level that the enchantment can have. - */ - public int getMinLevel() - { - return 1; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 1; - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 1 + enchantmentLevel * 10; - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 5; - } - - /** - * Calculates the damage protection of the enchantment based on level and damage source passed. - */ - public int calcDamageReduction(int level, DamageSource source) - { - return 0; - } - - /** - * Calculates the additional damage that will be dealt by an item with this enchantment. This alternative to - * calcModifierDamage is sensitive to the targets EnumCreatureAttribute. - */ - public int calcAdditionalDamage(int level) - { - return 0; - } - - /** - * Determines if the enchantment passed can be applyied together with this enchantment. - */ - public boolean canApplyTogether(Enchantment ench) - { - return this != ench; - } - - /** - * Sets the enchantment name - */ - public Enchantment setName(String enchName) - { - this.name = enchName; - return this; - } - - /** - * Return the name of key of this enchantment. - */ - public String getName() - { - return this.name; - } - - public String getFormattedName(int level) - { - return this.getName() + " " + ((level >= 1 && level <= 10) ? LEVELS[level - 1] : "" + level); - } - - /** - * Determines if this enchantment can be applied to a specific ItemStack. - */ - public boolean canApply(ItemStack stack) - { - return this.type.canEnchantItem(stack.getItem()); - } - - /** - * Called whenever a mob is damaged with an item that has this enchantment on it. - */ - public void onEntityDamaged(EntityLiving user, Entity target, int level) - { - } - - /** - * Whenever an entity that has this enchantment on one of its associated items is damaged this method will be - * called. - */ - public void onUserHurt(EntityLiving user, Entity attacker, int level) - { - } - - static - { - List list = Lists.newArrayList(); - - for (Enchantment enchantment : enchantmentsList) - { - if (enchantment != null) - { - list.add(enchantment); - } - } - - enchantmentsBookList = (Enchantment[])list.toArray(new Enchantment[list.size()]); - } -} diff --git a/java/src/game/enchantment/EnchantmentArrowDamage.java b/java/src/game/enchantment/EnchantmentArrowDamage.java deleted file mode 100755 index 7d6b93e..0000000 --- a/java/src/game/enchantment/EnchantmentArrowDamage.java +++ /dev/null @@ -1,36 +0,0 @@ -package game.enchantment; - - - -public class EnchantmentArrowDamage extends Enchantment -{ - public EnchantmentArrowDamage(int enchID, String enchName, int enchWeight) - { - super(enchID, enchName, enchWeight, EnumEnchantmentType.BOW); - this.setName("Stärke"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 1 + (enchantmentLevel - 1) * 10; - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 15; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 5; - } -} diff --git a/java/src/game/enchantment/EnchantmentArrowFire.java b/java/src/game/enchantment/EnchantmentArrowFire.java deleted file mode 100755 index 4e0121e..0000000 --- a/java/src/game/enchantment/EnchantmentArrowFire.java +++ /dev/null @@ -1,36 +0,0 @@ -package game.enchantment; - - - -public class EnchantmentArrowFire extends Enchantment -{ - public EnchantmentArrowFire(int enchID, String enchName, int enchWeight) - { - super(enchID, enchName, enchWeight, EnumEnchantmentType.BOW); - this.setName("Flamme"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 20; - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return 50; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 1; - } -} diff --git a/java/src/game/enchantment/EnchantmentArrowInfinite.java b/java/src/game/enchantment/EnchantmentArrowInfinite.java deleted file mode 100755 index 7845109..0000000 --- a/java/src/game/enchantment/EnchantmentArrowInfinite.java +++ /dev/null @@ -1,36 +0,0 @@ -package game.enchantment; - - - -public class EnchantmentArrowInfinite extends Enchantment -{ - public EnchantmentArrowInfinite(int enchID, String enchName, int enchWeight) - { - super(enchID, enchName, enchWeight, EnumEnchantmentType.BOW); - this.setName("Unendlich"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 20; - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return 50; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 1; - } -} diff --git a/java/src/game/enchantment/EnchantmentArrowKnockback.java b/java/src/game/enchantment/EnchantmentArrowKnockback.java deleted file mode 100755 index 3619294..0000000 --- a/java/src/game/enchantment/EnchantmentArrowKnockback.java +++ /dev/null @@ -1,36 +0,0 @@ -package game.enchantment; - - - -public class EnchantmentArrowKnockback extends Enchantment -{ - public EnchantmentArrowKnockback(int enchID, String enchName, int enchWeight) - { - super(enchID, enchName, enchWeight, EnumEnchantmentType.BOW); - this.setName("Schlag"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 12 + (enchantmentLevel - 1) * 20; - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 25; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 2; - } -} diff --git a/java/src/game/enchantment/EnchantmentDamage.java b/java/src/game/enchantment/EnchantmentDamage.java deleted file mode 100755 index ffe689f..0000000 --- a/java/src/game/enchantment/EnchantmentDamage.java +++ /dev/null @@ -1,80 +0,0 @@ -package game.enchantment; - -import game.item.ItemAxe; -import game.item.ItemStack; - - -public class EnchantmentDamage extends Enchantment -{ - public EnchantmentDamage(int enchID, String enchName, int enchWeight) - { - super(enchID, enchName, enchWeight, EnumEnchantmentType.WEAPON); - this.setName("Schärfe"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 1 + (enchantmentLevel - 1) * 11; - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + 20; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 5; - } - - /** - * Calculates the additional damage that will be dealt by an item with this enchantment. This alternative to - * calcModifierDamage is sensitive to the targets EnumCreatureAttribute. - */ - public int calcAdditionalDamage(int level) - { - return (int)(/*this.damageType == 0 ? */ (float)level * 1.25F); // : (this.damageType == 1 && creatureType == CreatureType.UNDEAD ? (float)level * 2.5F : (this.damageType == 2 && creatureType == CreatureType.ARTHROPOD ? (float)level * 2.5F : 0.0F))); - } - - /** - * Determines if the enchantment passed can be applyied together with this enchantment. - */ - public boolean canApplyTogether(Enchantment ench) - { - return !(ench instanceof EnchantmentDamage); - } - - /** - * Determines if this enchantment can be applied to a specific ItemStack. - */ - public boolean canApply(ItemStack stack) - { - return stack.getItem() instanceof ItemAxe ? true : super.canApply(stack); - } - -// /** -// * Called whenever a mob is damaged with an item that has this enchantment on it. -// */ -// public void onEntityDamaged(EntityLivingBase user, Entity target, int level) -// { -// if (target instanceof EntityLivingBase) -// { -// EntityLivingBase entitylivingbase = (EntityLivingBase)target; -// -// if (this.damageType == 2 && entitylivingbase.getCreatureType() == CreatureType.ARTHROPOD) -// { -// int i = 20 + user.getRNG().zrange(10 * level); -// entitylivingbase.addEffect(new PotionEffect(Potion.moveSlowdown.id, i, 3)); -// } -// } -// } -} diff --git a/java/src/game/enchantment/EnchantmentDigging.java b/java/src/game/enchantment/EnchantmentDigging.java deleted file mode 100755 index 32b3031..0000000 --- a/java/src/game/enchantment/EnchantmentDigging.java +++ /dev/null @@ -1,46 +0,0 @@ -package game.enchantment; - -import game.item.ItemShears; -import game.item.ItemStack; - - -public class EnchantmentDigging extends Enchantment -{ - protected EnchantmentDigging(int enchID, String enchName, int enchWeight) - { - super(enchID, enchName, enchWeight, EnumEnchantmentType.DIGGER); - this.setName("Effizienz"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 1 + 10 * (enchantmentLevel - 1); - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 5; - } - - /** - * Determines if this enchantment can be applied to a specific ItemStack. - */ - public boolean canApply(ItemStack stack) - { - return stack.getItem() instanceof ItemShears ? true : super.canApply(stack); - } -} diff --git a/java/src/game/enchantment/EnchantmentDraining.java b/java/src/game/enchantment/EnchantmentDraining.java deleted file mode 100755 index ed9f589..0000000 --- a/java/src/game/enchantment/EnchantmentDraining.java +++ /dev/null @@ -1,44 +0,0 @@ -package game.enchantment; - -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.item.ItemAxe; -import game.item.ItemStack; - - -public class EnchantmentDraining extends Enchantment { - public EnchantmentDraining(int enchID, String enchName, int enchWeight) { - super(enchID, enchName, enchWeight, EnumEnchantmentType.WEAPON); - this.setName("Seelenentzug"); - } - - public int getMinEnchantability(int enchantmentLevel) { - return 2 + (enchantmentLevel - 1) * 11; - } - - public int getMaxEnchantability(int enchantmentLevel) { - return this.getMinEnchantability(enchantmentLevel) + 20; - } - - public int getMaxLevel() { - return 16; - } - -// public boolean canApplyTogether(Enchantment ench) -// { -// return !(ench instanceof EnchantmentDraining); -// } - - public boolean canApply(ItemStack stack) { - return stack.getItem() instanceof ItemAxe ? true : super.canApply(stack); - } - - public void onEntityDamaged(EntityLiving user, Entity target, int level) { - if(target instanceof EntityLiving) { - EntityLiving entity = (EntityLiving)target; - entity.attackEntityFrom(DamageSource.causeIndirectMagicDamage(user, user), (int)((float)level * 1.25F)); - user.heal((int)((entity.arePotionsInverted() ? 0.2f : 1.0f) * (float)level)); - } - } -} diff --git a/java/src/game/enchantment/EnchantmentDurability.java b/java/src/game/enchantment/EnchantmentDurability.java deleted file mode 100755 index a8854bb..0000000 --- a/java/src/game/enchantment/EnchantmentDurability.java +++ /dev/null @@ -1,57 +0,0 @@ -package game.enchantment; - -import game.item.ItemArmor; -import game.item.ItemStack; -import game.rng.Random; - - -public class EnchantmentDurability extends Enchantment -{ - protected EnchantmentDurability(int enchID, String enchName, int enchWeight) - { - super(enchID, enchName, enchWeight, EnumEnchantmentType.BREAKABLE); - this.setName("Haltbarkeit"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 5 + (enchantmentLevel - 1) * 8; - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 3; - } - - /** - * Determines if this enchantment can be applied to a specific ItemStack. - */ - public boolean canApply(ItemStack stack) - { - return stack.isItemStackDamageable() ? true : super.canApply(stack); - } - - /** - * Used by ItemStack.attemptDamageItem. Randomly determines if a point of damage should be negated using the - * enchantment level (par1). If the ItemStack is Armor then there is a flat 60% chance for damage to be negated no - * matter the enchantment level, otherwise there is a 1-(par/1) chance for damage to be negated. - */ - public static boolean negateDamage(ItemStack stack, int level, Random rand) - { - return stack.getItem() instanceof ItemArmor && rand.floatv() < 0.6F ? false : rand.rarity(level + 1); - } -} diff --git a/java/src/game/enchantment/EnchantmentFireAspect.java b/java/src/game/enchantment/EnchantmentFireAspect.java deleted file mode 100755 index 956374f..0000000 --- a/java/src/game/enchantment/EnchantmentFireAspect.java +++ /dev/null @@ -1,36 +0,0 @@ -package game.enchantment; - - - -public class EnchantmentFireAspect extends Enchantment -{ - protected EnchantmentFireAspect(int enchID, String enchName, int enchWeight) - { - super(enchID, enchName, enchWeight, EnumEnchantmentType.WEAPON); - this.setName("Verbrennung"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 10 + 20 * (enchantmentLevel - 1); - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 2; - } -} diff --git a/java/src/game/enchantment/EnchantmentFishingSpeed.java b/java/src/game/enchantment/EnchantmentFishingSpeed.java deleted file mode 100755 index a1e4cc7..0000000 --- a/java/src/game/enchantment/EnchantmentFishingSpeed.java +++ /dev/null @@ -1,36 +0,0 @@ -package game.enchantment; - - - -public class EnchantmentFishingSpeed extends Enchantment -{ - protected EnchantmentFishingSpeed(int enchID, String enchName, int enchWeight, EnumEnchantmentType enchType) - { - super(enchID, enchName, enchWeight, enchType); - this.setName("Köder"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 15 + (enchantmentLevel - 1) * 9; - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 3; - } -} diff --git a/java/src/game/enchantment/EnchantmentKnockback.java b/java/src/game/enchantment/EnchantmentKnockback.java deleted file mode 100755 index 295f00a..0000000 --- a/java/src/game/enchantment/EnchantmentKnockback.java +++ /dev/null @@ -1,36 +0,0 @@ -package game.enchantment; - - - -public class EnchantmentKnockback extends Enchantment -{ - protected EnchantmentKnockback(int p_i45768_1_, String p_i45768_2_, int p_i45768_3_) - { - super(p_i45768_1_, p_i45768_2_, p_i45768_3_, EnumEnchantmentType.WEAPON); - this.setName("Rückstoß"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 5 + 20 * (enchantmentLevel - 1); - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 2; - } -} diff --git a/java/src/game/enchantment/EnchantmentLootBonus.java b/java/src/game/enchantment/EnchantmentLootBonus.java deleted file mode 100755 index 63b683a..0000000 --- a/java/src/game/enchantment/EnchantmentLootBonus.java +++ /dev/null @@ -1,56 +0,0 @@ -package game.enchantment; - - - -public class EnchantmentLootBonus extends Enchantment -{ - protected EnchantmentLootBonus(int p_i45767_1_, String p_i45767_2_, int p_i45767_3_, EnumEnchantmentType p_i45767_4_) - { - super(p_i45767_1_, p_i45767_2_, p_i45767_3_, p_i45767_4_); - - if (p_i45767_4_ == EnumEnchantmentType.DIGGER) - { - this.setName("Glück"); - } - else if (p_i45767_4_ == EnumEnchantmentType.FISHING_ROD) - { - this.setName("Glück des Meeres"); - } - else - { - this.setName("Plünderung"); - } - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 15 + (enchantmentLevel - 1) * 9; - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 3; - } - - /** - * Determines if the enchantment passed can be applyied together with this enchantment. - */ - public boolean canApplyTogether(Enchantment ench) - { - return super.canApplyTogether(ench) && ench.effectId != silkTouch.effectId; - } -} diff --git a/java/src/game/enchantment/EnchantmentProtection.java b/java/src/game/enchantment/EnchantmentProtection.java deleted file mode 100755 index 9c4d0fb..0000000 --- a/java/src/game/enchantment/EnchantmentProtection.java +++ /dev/null @@ -1,132 +0,0 @@ -package game.enchantment; - -import game.entity.DamageSource; -import game.entity.Entity; -import game.util.ExtMath; - - -public class EnchantmentProtection extends Enchantment -{ - private static final String[] NAMES = new String[] {"Schutz", "Feuerschutz", "Federfall", "Explosionsschutz", "Schusssicher"}; - - /** - * Holds the base factor of enchantability needed to be able to use the enchant. - */ - private static final int[] baseEnchantability = new int[] {1, 10, 5, 5, 3}; - - /** - * Holds how much each level increased the enchantability factor to be able to use this enchant. - */ - private static final int[] levelEnchantability = new int[] {11, 8, 6, 8, 6}; - - /** - * Used on the formula of base enchantability, this is the 'window' factor of values to be able to use thing - * enchant. - */ - private static final int[] thresholdEnchantability = new int[] {20, 12, 10, 12, 15}; - - /** - * Defines the type of protection of the enchantment, 0 = all, 1 = fire, 2 = fall (feather fall), 3 = explosion and - * 4 = projectile. - */ - public final int protectionType; - - public EnchantmentProtection(int id, String name, int weight, int type) - { - super(id, name, weight, EnumEnchantmentType.ARMOR); - this.protectionType = type; - - if (type == 2) - { - this.type = EnumEnchantmentType.ARMOR_FEET; - } - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return baseEnchantability[this.protectionType] + (enchantmentLevel - 1) * levelEnchantability[this.protectionType]; - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return this.getMinEnchantability(enchantmentLevel) + thresholdEnchantability[this.protectionType]; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 4; - } - - /** - * Calculates the damage protection of the enchantment based on level and damage source passed. - */ - public int calcDamageReduction(int level, DamageSource source) - { - if (source == DamageSource.outOfWorld) - { - return 0; - } - else - { - float f = (float)(6 + level * level) / 3.0F; - return this.protectionType == 0 ? ExtMath.floorf(f * 0.75F) : (this.protectionType == 1 && source.isFireDamage() ? ExtMath.floorf(f * 1.25F) : (this.protectionType == 2 && source == DamageSource.fall ? ExtMath.floorf(f * 2.5F) : (this.protectionType == 3 && source.isExplosion() ? ExtMath.floorf(f * 1.5F) : (this.protectionType == 4 && source.isProjectile() ? ExtMath.floorf(f * 1.5F) : 0)))); - } - } - - public String getName() - { - return NAMES[this.protectionType]; - } - - /** - * Determines if the enchantment passed can be applyied together with this enchantment. - */ - public boolean canApplyTogether(Enchantment ench) - { - if (ench instanceof EnchantmentProtection) - { - EnchantmentProtection enchantmentprotection = (EnchantmentProtection)ench; - return enchantmentprotection.protectionType == this.protectionType ? false : this.protectionType == 2 || enchantmentprotection.protectionType == 2; - } - else - { - return super.canApplyTogether(ench); - } - } - - /** - * Gets the amount of ticks an entity should be set fire, adjusted for fire protection. - */ - public static int getFireTimeForEntity(Entity entity, int duration) - { - int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.fireProtection.effectId, entity.getInventory()); - - if (i > 0) - { - duration -= ExtMath.floorf((float)duration * (float)i * 0.15F); - } - - return duration; - } - - public static double getKnockbackFactor(Entity entity, double strength) - { - int i = EnchantmentHelper.getMaxEnchantmentLevel(Enchantment.blastProtection.effectId, entity.getInventory()); - - if (i > 0) - { - strength -= (double)ExtMath.floord(strength * (double)((float)i * 0.15F)); - } - - return strength; - } -} diff --git a/java/src/game/enchantment/EnchantmentThorns.java b/java/src/game/enchantment/EnchantmentThorns.java deleted file mode 100755 index 67844c4..0000000 --- a/java/src/game/enchantment/EnchantmentThorns.java +++ /dev/null @@ -1,88 +0,0 @@ -package game.enchantment; - -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.init.Config; -import game.item.ItemArmor; -import game.item.ItemStack; -import game.rng.Random; - -public class EnchantmentThorns extends Enchantment -{ - public EnchantmentThorns(int p_i45764_1_, String p_i45764_2_, int p_i45764_3_) - { - super(p_i45764_1_, p_i45764_2_, p_i45764_3_, EnumEnchantmentType.ARMOR_TORSO); - this.setName("Dornen"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 10 + 20 * (enchantmentLevel - 1); - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 3; - } - - /** - * Determines if this enchantment can be applied to a specific ItemStack. - */ - public boolean canApply(ItemStack stack) - { - return stack.getItem() instanceof ItemArmor ? true : super.canApply(stack); - } - - /** - * Whenever an entity that has this enchantment on one of its associated items is damaged this method will be - * called. - */ - public void onUserHurt(EntityLiving user, Entity attacker, int level) - { - Random random = user.getRNG(); - ItemStack itemstack = EnchantmentHelper.getEnchantedItem(Enchantment.thorns, user); - - if ((user.worldObj.client || Config.damageThorns) && isHurting(level, random)) - { - if (attacker != null) - { - attacker.attackEntityFrom(DamageSource.causeThornsDamage(user), getDamage(level, random)); -// attacker.playSound("damage.thorns", 0.5F, 1.0F); - } - - if (itemstack != null) - { - itemstack.damageItem(3, user); - } - } - else if (itemstack != null) - { - itemstack.damageItem(1, user); - } - } - - public static boolean isHurting(int level, Random rand) - { - return level <= 0 ? false : rand.floatv() < 0.15F * (float)level; - } - - public static int getDamage(int level, Random rand) - { - return level > 10 ? level - 10 : rand.roll(4); - } -} diff --git a/java/src/game/enchantment/EnchantmentUntouching.java b/java/src/game/enchantment/EnchantmentUntouching.java deleted file mode 100755 index 090d142..0000000 --- a/java/src/game/enchantment/EnchantmentUntouching.java +++ /dev/null @@ -1,54 +0,0 @@ -package game.enchantment; - -import game.item.ItemShears; -import game.item.ItemStack; - - -public class EnchantmentUntouching extends Enchantment -{ - protected EnchantmentUntouching(int p_i45763_1_, String p_i45763_2_, int p_i45763_3_) - { - super(p_i45763_1_, p_i45763_2_, p_i45763_3_, EnumEnchantmentType.DIGGER); - this.setName("Behutsamkeit"); - } - - /** - * Returns the minimal value of enchantability needed on the enchantment level passed. - */ - public int getMinEnchantability(int enchantmentLevel) - { - return 15; - } - - /** - * Returns the maximum value of enchantability nedded on the enchantment level passed. - */ - public int getMaxEnchantability(int enchantmentLevel) - { - return super.getMinEnchantability(enchantmentLevel) + 50; - } - - /** - * Returns the maximum level that the enchantment can have. - */ - public int getMaxLevel() - { - return 1; - } - - /** - * Determines if the enchantment passed can be applyied together with this enchantment. - */ - public boolean canApplyTogether(Enchantment ench) - { - return super.canApplyTogether(ench) && ench.effectId != fortune.effectId; - } - - /** - * Determines if this enchantment can be applied to a specific ItemStack. - */ - public boolean canApply(ItemStack stack) - { - return stack.getItem() instanceof ItemShears ? true : super.canApply(stack); - } -} diff --git a/java/src/game/enchantment/EnumEnchantmentType.java b/java/src/game/enchantment/EnumEnchantmentType.java deleted file mode 100755 index adc56dc..0000000 --- a/java/src/game/enchantment/EnumEnchantmentType.java +++ /dev/null @@ -1,54 +0,0 @@ -package game.enchantment; - -import game.item.Item; -import game.item.ItemArmor; -import game.item.ItemBow; -import game.item.ItemFishingRod; -import game.item.ItemSword; -import game.item.ItemTool; - -public enum EnumEnchantmentType -{ - ALL, - ARMOR, - ARMOR_FEET, - ARMOR_LEGS, - ARMOR_TORSO, - ARMOR_HEAD, - WEAPON, - DIGGER, - FISHING_ROD, - BREAKABLE, - BOW; - - /** - * Return true if the item passed can be enchanted by a enchantment of this type. - */ - public boolean canEnchantItem(Item p_77557_1_) - { - if (this == ALL) - { - return true; - } - else if (this == BREAKABLE && p_77557_1_.isDamageable()) - { - return true; - } - else if (p_77557_1_ instanceof ItemArmor) - { - if (this == ARMOR) - { - return true; - } - else - { - ItemArmor itemarmor = (ItemArmor)p_77557_1_; - return itemarmor.armorType == 0 ? this == ARMOR_HEAD : (itemarmor.armorType == 2 ? this == ARMOR_LEGS : (itemarmor.armorType == 1 ? this == ARMOR_TORSO : (itemarmor.armorType == 3 ? this == ARMOR_FEET : false))); - } - } - else - { - return p_77557_1_ instanceof ItemSword ? this == WEAPON : (p_77557_1_ instanceof ItemTool ? this == DIGGER : (p_77557_1_ instanceof ItemBow ? this == BOW : (p_77557_1_ instanceof ItemFishingRod ? this == FISHING_ROD : false))); - } - } -} diff --git a/java/src/game/enchantment/RngEnchantment.java b/java/src/game/enchantment/RngEnchantment.java deleted file mode 100755 index b945bde..0000000 --- a/java/src/game/enchantment/RngEnchantment.java +++ /dev/null @@ -1,19 +0,0 @@ -package game.enchantment; - -import game.rng.RngItem; - -public class RngEnchantment extends RngItem -{ - /** Enchantment object associated with this EnchantmentData */ - public final Enchantment enchantmentobj; - - /** Enchantment level associated with this EnchantmentData */ - public final int enchantmentLevel; - - public RngEnchantment(Enchantment enchantmentObj, int enchLevel) - { - super(enchantmentObj.getWeight()); - this.enchantmentobj = enchantmentObj; - this.enchantmentLevel = enchLevel; - } -} diff --git a/java/src/game/entity/animal/EntityChicken.java b/java/src/game/entity/animal/EntityChicken.java deleted file mode 100755 index dd39420..0000000 --- a/java/src/game/entity/animal/EntityChicken.java +++ /dev/null @@ -1,249 +0,0 @@ -package game.entity.animal; - -import game.ai.EntityAIFollowParent; -import game.ai.EntityAILookIdle; -import game.ai.EntityAIMate; -import game.ai.EntityAIPanic; -import game.ai.EntityAISwimming; -import game.ai.EntityAITempt; -import game.ai.EntityAIWander; -import game.ai.EntityAIWatchClosest; -import game.entity.attributes.Attributes; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityAnimal; -import game.entity.types.EntityLiving; -import game.init.Config; -import game.init.Items; -import game.init.SoundEvent; -import game.item.Item; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.util.ExtMath; -import game.world.World; - -public class EntityChicken extends EntityAnimal -{ - public float wingRotation; - public float destPos; - public float field_70884_g; - public float field_70888_h; - public float wingRotDelta = 1.0F; - - /** The time until the next egg is spawned. */ - public int timeUntilNextEgg; - public boolean chickenJockey; - - public EntityChicken(World worldIn) - { - super(worldIn); - this.setSize(0.4F, 0.7F); - this.timeUntilNextEgg = worldIn.client || Config.eggTimer <= 0 ? 1000 : this.rand.excl(Config.eggTimer, Config.eggTimer * 2); - this.tasks.addTask(0, new EntityAISwimming(this)); - this.tasks.addTask(1, new EntityAIPanic(this, 1.4D)); - this.tasks.addTask(2, new EntityAIMate(this, 1.0D)); - this.tasks.addTask(3, new EntityAITempt(this, 1.0D, Items.wheat, false)); - this.tasks.addTask(4, new EntityAIFollowParent(this, 1.1D)); - this.tasks.addTask(5, new EntityAIWander(this, 1.0D)); - this.tasks.addTask(6, new EntityAIWatchClosest(this, null, 6.0F)); - this.tasks.addTask(7, new EntityAILookIdle(this)); - } - - public float getEyeHeight() - { - return this.height; - } - - protected void applyEntityAttributes() - { - super.applyEntityAttributes(); - this.setMaxHealth(4); - this.getEntityAttribute(Attributes.MOVEMENT_SPEED).setBaseValue(0.25D); - } - - /** - * Called frequently so the entity can update its state every tick as required. For example, zombies and skeletons - * use this to react to sunlight and start to burn. - */ - public void onLivingUpdate() - { - super.onLivingUpdate(); - this.field_70888_h = this.wingRotation; - this.field_70884_g = this.destPos; - this.destPos = (float)((double)this.destPos + (double)(this.onGround ? -1 : 4) * 0.3D); - this.destPos = ExtMath.clampf(this.destPos, 0.0F, 1.0F); - - if (!this.onGround && this.wingRotDelta < 1.0F) - { - this.wingRotDelta = 1.0F; - } - - this.wingRotDelta = (float)((double)this.wingRotDelta * 0.9D); - - if (!this.onGround && this.motionY < 0.0D) - { - this.motionY *= 0.6D; - } - - this.wingRotation += this.wingRotDelta * 2.0F; - - if (!this.worldObj.client && Config.eggTimer > 0 && !this.isChild() && !this.isChickenJockey() && --this.timeUntilNextEgg <= 0) - { - this.playSound(SoundEvent.PLOP, 1.0F); - this.dropItem(Items.egg, 1); - this.timeUntilNextEgg = this.rand.excl(Config.eggTimer, Config.eggTimer * 2); - } - } - - public void fall(float distance, float damageMultiplier) - { - } - - /** - * Returns the sound this mob makes while it's alive. - */ - protected SoundEvent getLivingSound() - { - return SoundEvent.CHICKEN_IDLE; - } - - /** - * Returns the sound this mob makes when it is hurt. - */ - protected SoundEvent getHurtSound() - { - return SoundEvent.CHICKEN_HIT; - } - - /** - * Returns the sound this mob makes on death. - */ - protected SoundEvent getDeathSound() - { - return SoundEvent.CHICKEN_HIT; - } - -// protected void playStepSound(BlockPos pos, Block blockIn) -// { -// this.playSound("mob.chicken.step", 0.15F, 1.0F); -// } - - protected Item getDropItem() - { - return Items.feather; - } - - /** - * Drop 0-2 items of this living's type - * - * @param wasRecentlyHit true if this this entity was recently hit by appropriate entity (generally only if player - * or tameable) - * @param lootingModifier level of enchanment to be applied to this drop - */ - protected void dropFewItems(boolean wasRecentlyHit, int lootingModifier) - { - int i = this.rand.zrange(3) + this.rand.zrange(1 + lootingModifier); - - for (int j = 0; j < i; ++j) - { - this.dropItem(Items.feather, 1); - } - - if (this.isBurning()) - { - this.dropItem(Items.cooked_chicken, 1); - } - else - { - this.dropItem(Items.chicken, 1); - } - } - - public EntityChicken createChild(EntityLiving ageable) - { - return new EntityChicken(this.worldObj); - } - - /** - * Checks if the parameter is an item which this animal can be fed to breed it (wheat, carrots or seeds depending on - * the animal type) - */ - public boolean isBreedingItem(ItemStack stack) - { - return stack != null && stack.getItem() == Items.wheat; - } - - /** - * (abstract) Protected helper method to read subclass entity data from NBT. - */ - public void readEntityFromNBT(NBTTagCompound tagCompund) - { - super.readEntityFromNBT(tagCompund); - this.chickenJockey = tagCompund.getBoolean("IsChickenJockey"); - - if (tagCompund.hasKey("EggLayTime")) - { - this.timeUntilNextEgg = tagCompund.getInteger("EggLayTime"); - } - } - - /** - * Get the experience points the entity currently has. - */ - protected int getExperiencePoints(EntityNPC player) - { - return this.isChickenJockey() ? 10 : super.getExperiencePoints(player); - } - - /** - * (abstract) Protected helper method to write subclass entity data to NBT. - */ - public void writeEntityToNBT(NBTTagCompound tagCompound) - { - super.writeEntityToNBT(tagCompound); - tagCompound.setBoolean("IsChickenJockey", this.chickenJockey); - tagCompound.setInteger("EggLayTime", this.timeUntilNextEgg); - } - -// /** -// * Determines if an entity can be despawned, used on idle far away entities -// */ -// protected boolean canDespawn() -// { -// return this.isChickenJockey() && this.passenger == null; -// } - - public void updateRiderPosition() - { - super.updateRiderPosition(); - float f = ExtMath.sin(this.yawOffset * (float)Math.PI / 180.0F); - float f1 = ExtMath.cos(this.yawOffset * (float)Math.PI / 180.0F); - float f2 = 0.1F; - float f3 = 0.0F; - this.passenger.setPosition(this.posX + (double)(f2 * f), this.posY + (double)(this.height * 0.5F) + this.passenger.getYOffset() + (double)f3, this.posZ - (double)(f2 * f1)); - - if (this.passenger instanceof EntityLiving) - { - ((EntityLiving)this.passenger).yawOffset = this.yawOffset; - } - } - - /** - * Determines if this chicken is a jokey with a zombie riding it. - */ - public boolean isChickenJockey() - { - return this.chickenJockey; - } - - /** - * Sets whether this chicken is a jockey or not. - */ - public void setChickenJockey(boolean jockey) - { - this.chickenJockey = jockey; - } - - public int getColor() { - return 0xdb5152; - } -} diff --git a/java/src/game/entity/attributes/Attribute.java b/java/src/game/entity/attributes/Attribute.java deleted file mode 100755 index 25804a4..0000000 --- a/java/src/game/entity/attributes/Attribute.java +++ /dev/null @@ -1,85 +0,0 @@ -package game.entity.attributes; - -import java.util.Map; - -import game.collect.Maps; - -import game.util.ExtMath; - -public class Attribute -{ - private static final Map ATTRIBUTES = Maps.newHashMap(); - - private final String name; - private final String display; - private final double defValue; - private final double minValue; - private final double maxValue; - private final boolean shouldWatch; - - public static Attribute getAttribute(String name) { - return ATTRIBUTES.get(name); - } - - public Attribute(String name, String display, double def, double min, double max, boolean watch) - { - this.name = name; - this.display = display; - this.defValue = def; - if(name == null) - throw new IllegalArgumentException("Name cannot be null!"); - this.minValue = min; - this.maxValue = max; - this.shouldWatch = watch; - - if (min > max) - { - throw new IllegalArgumentException("Minimum value cannot be bigger than maximum value!"); - } - else if (def < min) - { - throw new IllegalArgumentException("Default value cannot be lower than minimum value!"); - } - else if (def > max) - { - throw new IllegalArgumentException("Default value cannot be bigger than maximum value!"); - } - - ATTRIBUTES.put(name, this); - } - - public String getUnlocalizedName() - { - return this.name; - } - - public String getDisplayName() - { - return this.display; - } - - public double getDefaultValue() - { - return this.defValue; - } - - public boolean getShouldWatch() - { - return this.shouldWatch; - } - - public double clampValue(double value) - { - return ExtMath.clampd(value, this.minValue, this.maxValue); - } - - public int hashCode() - { - return this.name.hashCode(); - } - - public boolean equals(Object obj) - { - return obj instanceof Attribute && this.name.equals(((Attribute)obj).getUnlocalizedName()); - } -} diff --git a/java/src/game/entity/attributes/AttributeInstance.java b/java/src/game/entity/attributes/AttributeInstance.java deleted file mode 100755 index e2e2cb3..0000000 --- a/java/src/game/entity/attributes/AttributeInstance.java +++ /dev/null @@ -1,191 +0,0 @@ -package game.entity.attributes; - -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import game.collect.Lists; -import game.collect.Maps; -import game.collect.Sets; - -public class AttributeInstance -{ - private final AttributeMap attributeMap; - private final Attribute genericAttribute; - private final Set additions = Sets.newHashSet(); - private final Set multipliers = Sets.newHashSet(); - private final Map> mapByName = Maps.>newHashMap(); - private final Map mapByID = Maps.newHashMap(); - private double baseValue; - private boolean needsUpdate = true; - private double cachedValue; - - public AttributeInstance(AttributeMap attributeMapIn, Attribute genericAttributeIn) - { - this.attributeMap = attributeMapIn; - this.genericAttribute = genericAttributeIn; - this.baseValue = genericAttributeIn.getDefaultValue(); - } - - public Attribute getAttribute() - { - return this.genericAttribute; - } - - public double getBaseValue() - { - return this.baseValue; - } - - public void setBaseValue(double baseValue) - { - if (baseValue != this.getBaseValue()) - { - this.baseValue = baseValue; - this.flagForUpdate(); - } - } - -// public Collection getModifiersByOperation(AttributeOp operation) -// { -// return (Collection)this.mapByOperation.get(operation); -// } - - public Collection getModifiers() - { - Set set = Sets.newHashSet(); - -// for (AttributeOp op : AttributeOp.values()) -// { -// set.addAll(this.getModifiersByOperation(op)); -// } - set.addAll(this.additions); - set.addAll(this.multipliers); - - return set; - } - - public AttributeModifier getModifier(long id) - { - return (AttributeModifier)this.mapByID.get(id); - } - - public boolean hasModifier(AttributeModifier modifier) - { - return this.mapByID.get(modifier.getID()) != null; - } - - public void applyModifier(AttributeModifier modifier) - { - if (this.getModifier(modifier.getID()) != null) - { - throw new IllegalArgumentException("Modifier is already applied on this attribute!"); - } - else - { - Set set = (Set)this.mapByName.get(modifier.getName()); - - if (set == null) - { - set = Sets.newHashSet(); - this.mapByName.put(modifier.getName(), set); - } - - (modifier.isMultiplied() ? this.multipliers : this.additions).add(modifier); - set.add(modifier); - this.mapByID.put(modifier.getID(), modifier); - this.flagForUpdate(); - } - } - - protected void flagForUpdate() - { - this.needsUpdate = true; - this.attributeMap.flagDirty(this); - } - - public void removeModifier(AttributeModifier modifier) - { -// for (AttributeOp op : AttributeOp.values()) -// { -// Set set = (Set)this.mapByOperation.get(op); -// set.remove(modifier); -// } - this.additions.remove(modifier); - this.multipliers.remove(modifier); - - Set set1 = (Set)this.mapByName.get(modifier.getName()); - - if (set1 != null) - { - set1.remove(modifier); - - if (set1.isEmpty()) - { - this.mapByName.remove(modifier.getName()); - } - } - - this.mapByID.remove(modifier.getID()); - this.flagForUpdate(); - } - - public void removeAllModifiers() - { - Collection collection = this.getModifiers(); - - if (collection != null) - { - for (AttributeModifier attributemodifier : Lists.newArrayList(collection)) - { - this.removeModifier(attributemodifier); - } - } - } - - public double getAttributeValue() - { - if (this.needsUpdate) - { - this.cachedValue = this.computeValue(); - this.needsUpdate = false; - } - - return this.cachedValue; - } - - private double computeValue() - { - double base = this.getBaseValue(); - - for (AttributeModifier attributemodifier : this.additions) - { - base += attributemodifier.getAmount(); - } - - for (AttributeModifier attributemodifier2 : this.multipliers) - { - base *= 1.0D + attributemodifier2.getAmount(); - } - - return this.genericAttribute.clampValue(base); - } - -// private Collection getModifierList(AttributeOp operation) -// { -// // Set set = -// return Sets.newHashSet(this.getModifiersByOperation(operation)); -// -//// for (BaseAttribute iattribute = this.genericAttribute.func_180372_d(); iattribute != null; iattribute = iattribute.func_180372_d()) -//// { -//// ModifiableAttributeInstance iattributeinstance = this.attributeMap.getAttributeInstance(iattribute); -//// -//// if (iattributeinstance != null) -//// { -//// set.addAll(iattributeinstance.getModifiersByOperation(operation)); -//// } -//// } -// -// // return set; -// } -} diff --git a/java/src/game/entity/attributes/AttributeMap.java b/java/src/game/entity/attributes/AttributeMap.java deleted file mode 100755 index af5666e..0000000 --- a/java/src/game/entity/attributes/AttributeMap.java +++ /dev/null @@ -1,161 +0,0 @@ -package game.entity.attributes; - -import java.util.Collection; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import game.collect.Maps; -import game.collect.Sets; - -public class AttributeMap -{ - protected final Map attributes = Maps.newHashMap(); - protected final Map nameMap = new LowerStringMap(); - private final Set dirtyAttributes; - - public AttributeMap(boolean client) { - this.dirtyAttributes = client ? null : Sets.newHashSet(); - } - - public AttributeInstance getAttributeInstance(Attribute attribute) - { - return (AttributeInstance)this.attributes.get(attribute); - } - - public AttributeInstance getAttributeInstanceByName(String attributeName) - { -// AttributeInstance iattributeinstance = - return (AttributeInstance)this.nameMap.get(attributeName); - -// if (iattributeinstance == null) -// { -// iattributeinstance = (AttributeInstance)this.descMap.get(attributeName); -// } -// -// return (AttributeInstance)iattributeinstance; - } - - public AttributeInstance registerAttribute(Attribute attribute) - { - if(this.nameMap.containsKey(attribute.getUnlocalizedName())) - throw new IllegalArgumentException("Attribute is already registered!"); - AttributeInstance inst = new AttributeInstance(this, attribute); - this.nameMap.put(attribute.getUnlocalizedName(), inst); - this.attributes.put(attribute, inst); -// for (BaseAttribute iattribute = attribute.func_180372_d(); iattribute != null; iattribute = iattribute.func_180372_d()) -// { -// this.field_180377_c.put(iattribute, attribute); -// } -// if(attribute.getDescription() != null) -// this.descMap.put(attribute.getDescription(), inst); - return inst; - } - - public Collection getAllAttributes() - { - return this.nameMap.values(); - } - - public void flagDirty(AttributeInstance instance) - { - if (this.dirtyAttributes != null && instance.getAttribute().getShouldWatch()) - { - this.dirtyAttributes.add(instance); - } - -// for (BaseAttribute iattribute : this.field_180377_c.get(instance.getAttribute())) -// { -// ModifiableAttributeInstance modifiableattributeinstance = this.getAttributeInstance(iattribute); -// -// if (modifiableattributeinstance != null) -// { -// modifiableattributeinstance.flagForUpdate(); -// } -// } - } - - public Set getDirty() - { - return this.dirtyAttributes; - } - - public Collection getWatchedAttributes() - { - Set set = Sets.newHashSet(); - - for (AttributeInstance iattributeinstance : this.getAllAttributes()) - { - if (iattributeinstance.getAttribute().getShouldWatch()) - { - set.add(iattributeinstance); - } - } - - return set; - } - - public void removeAttributeModifiers(Map> modifiers) - { - for (Entry> entry : modifiers.entrySet()) - { - AttributeInstance iattributeinstance = this.getAttributeInstanceByName(entry.getKey().getUnlocalizedName()); - - if (iattributeinstance != null) - { - for(AttributeModifier mod : entry.getValue()) { - iattributeinstance.removeModifier(mod); - } - } - } - } - - public void applyAttributeModifiers(Map> modifiers) - { - for (Entry> entry : modifiers.entrySet()) - { - AttributeInstance iattributeinstance = this.getAttributeInstanceByName(entry.getKey().getUnlocalizedName()); - - if (iattributeinstance != null) - { - for(AttributeModifier mod : entry.getValue()) { - iattributeinstance.removeModifier(mod); - iattributeinstance.applyModifier(mod); - } - } - } - } - - public void removeAttributeModifiers(Map> modifiers, int slot, int amount) - { - for (Entry> entry : modifiers.entrySet()) - { - AttributeInstance iattributeinstance = this.getAttributeInstanceByName(entry.getKey().getUnlocalizedName()); - - if (iattributeinstance != null) - { - for(AttributeModifier mod : entry.getValue()) { - AttributeModifier nmod = new AttributeModifier(mod, slot+1, amount); - iattributeinstance.removeModifier(nmod); - } - } - } - } - - public void applyAttributeModifiers(Map> modifiers, int slot, int amount) - { - for (Entry> entry : modifiers.entrySet()) - { - AttributeInstance iattributeinstance = this.getAttributeInstanceByName(entry.getKey().getUnlocalizedName()); - - if (iattributeinstance != null) - { - for(AttributeModifier mod : entry.getValue()) { - AttributeModifier nmod = new AttributeModifier(mod, slot+1, amount); - iattributeinstance.removeModifier(nmod); - iattributeinstance.applyModifier(nmod); - } - } - } - } -} diff --git a/java/src/game/entity/attributes/AttributeModifier.java b/java/src/game/entity/attributes/AttributeModifier.java deleted file mode 100755 index 176417f..0000000 --- a/java/src/game/entity/attributes/AttributeModifier.java +++ /dev/null @@ -1,134 +0,0 @@ -package game.entity.attributes; - -import game.rng.Random; - -public class AttributeModifier -{ - private final double amount; - private final boolean multiply; - private final String name; - private final long id; - private final boolean isSaved; - private final boolean inventory; - - public static long getModifierId(String name) { - if(name.length() > 7) - throw new IllegalArgumentException("Name darf höchstens 7 Zeichen enthalten"); - long id = '@'; - for(int z = 0; z < name.length(); z++) { - id <<= 8; - char c = name.charAt(z); - if(c > 0xff) - throw new IllegalArgumentException("Name darf keine 16-Bit-Zeichen enthalten"); - id |= (long)c; - } -// Log.CONFIG.debug(String.format("Modifikator '%s' -> 0x%016x", name, id)); - return id; - } - - public AttributeModifier(String nameIn, double amountIn, boolean multiplyIn) - { - this(new Random().longv() | 0x8000000000000000L, nameIn, amountIn, multiplyIn, true, false); - } - - public AttributeModifier(long idIn, String nameIn, double amountIn, boolean multiplyIn) { - this(idIn, nameIn, amountIn, multiplyIn, true, false); - } - - public AttributeModifier(long idIn, String nameIn, double amountIn, boolean multiplyIn, boolean saved) { - this(idIn, nameIn, amountIn, multiplyIn, saved, false); - } - - public AttributeModifier(long idIn, String nameIn, double amountIn, boolean multiplyIn, boolean saved, boolean inv) - { - this.isSaved = saved; - this.inventory = inv; - this.id = idIn; - this.name = nameIn; - this.amount = amountIn; - this.multiply = multiplyIn; - if (nameIn == null) { - throw new NullPointerException("Modifier name cannot be empty"); - } - else if (nameIn.length() == 0) { - throw new IllegalArgumentException("Modifier name cannot be empty"); - } -// else if (operationIn == null) { -// throw new IllegalArgumentException("Invalid operation"); -// } - } - - public AttributeModifier(AttributeModifier attr, int slot, int amount) { - this(attr.id + (long)slot, attr.name, attr.amount * (double)amount, attr.multiply, attr.isSaved); - } - - public long getID() - { - return this.id; - } - - public String getName() - { - return this.name; - } - - public boolean isMultiplied() - { - return this.multiply; - } - - public double getAmount() - { - return this.amount; - } - - public boolean isSaved() - { - return this.isSaved; - } - - public boolean isInventory() - { - return this.inventory; - } - - public boolean equals(Object obj) - { - if (this == obj) - { - return true; - } - else if (obj != null && this.getClass() == obj.getClass()) - { - AttributeModifier attributemodifier = (AttributeModifier)obj; - - if (this.id != 0L) - { - if (this.id != attributemodifier.id) - { - return false; - } - } - else if (attributemodifier.id != 0L) - { - return false; - } - - return true; - } - else - { - return false; - } - } - - public int hashCode() - { - return this.id != 0L ? Long.hashCode(this.id) : 0; - } - - public String toString() - { - return "AttributeModifier{amount=" + this.amount + ", multiply=" + this.multiply + ", name=\'" + this.name + '\'' + ", id=" + this.id + ", serialize=" + this.isSaved + '}'; - } -} diff --git a/java/src/game/entity/attributes/Attributes.java b/java/src/game/entity/attributes/Attributes.java deleted file mode 100755 index cf4736b..0000000 --- a/java/src/game/entity/attributes/Attributes.java +++ /dev/null @@ -1,161 +0,0 @@ -package game.entity.attributes; - -import java.util.Collection; - -import game.log.Log; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; - -public class Attributes -{ - public static final Attribute MAX_HEALTH = (new Attribute("generic.maxHealth", "Maximale Gesundheit", 20.0D, 0.0D, 1024.0D, true)); - public static final Attribute FOLLOW_RANGE = (new Attribute("generic.followRange", "Kreaturen-Folgedistanz", 32.0D, 0.0D, 2048.0D, false)); - public static final Attribute KNOCKBACK_RESISTANCE = (new Attribute("generic.knockbackResistance", "Standfestigkeit", 0.0D, 0.0D, 1.0D, false)); - public static final Attribute MOVEMENT_SPEED = (new Attribute("generic.movementSpeed", "Geschwindigkeit", 0.699999988079071D, 0.0D, 1024.0D, true)); - public static final Attribute ATTACK_DAMAGE = new Attribute("generic.attackDamage", "Angriffsschaden", 2.0D, 0.0D, 2048.0D, false); - public static final Attribute RADIATION = new Attribute("generic.radiation", "Strahlung", 0.0D, 0.0D, 16384.0D, false); - public static final Attribute RADIATION_RESISTANCE = new Attribute("generic.radiationResistance", "Strahlungsresistenz", 10.0D, 0.0D, 16384.0D, false); - public static final Attribute MANA_CAPACITY = new Attribute("generic.manaCapacity", "Mana-Kapazität", 0.0D, 0.0D, 2048.0D, false); - public static final Attribute MAGIC_RESISTANCE = new Attribute("generic.magicResistance", "Magieresistenz", 0.0D, 0.0D, 4096.0D, false); - public static final Attribute REINFORCEMENT_CHANCE = (new Attribute("zombie.spawnReinforcements", "Zombie-Verstärkung", 0.0D, 0.0D, 1.0D, false)); - public static final Attribute HORSE_JUMP_STRENGTH = (new Attribute("horse.jumpStrength", "Pferdesprungstärke", 0.7D, 0.0D, 2.0D, true)); - -// public static final long ATTACK_SPEED_ID = AttributeModifier.getModifierId("EnderSp"); -// public static final AttributeModifier ATTACK_SPEED_MOD = (new AttributeModifier(ATTACK_SPEED_ID, "Attacking speed boost", 0.15000000596046448D, false, false)); - public static final long RUSHING_SPEED_ID = AttributeModifier.getModifierId("RushSpd"); - public static final AttributeModifier RUSHING_SPEED_MOD = (new AttributeModifier(RUSHING_SPEED_ID, "Attacking speed boost", 0.05D, false, false)); - public static final long MAGE_POTSPEED_ID = AttributeModifier.getModifierId("MagePot"); - public static final AttributeModifier MAGE_POTSPEED_MOD = (new AttributeModifier(MAGE_POTSPEED_ID, "Drinking speed penalty", -0.25D, false, false)); - public static final long ZOMBIE_BABY_ID = AttributeModifier.getModifierId("ZombSpd"); - public static final AttributeModifier ZOMBIE_BABY_MOD = new AttributeModifier(ZOMBIE_BABY_ID, "Baby speed boost", 0.5D, true); - public static final long FLEEING_SPEED_ID = AttributeModifier.getModifierId("FleeSpd"); - public static final AttributeModifier FLEEING_SPEED_MOD = (new AttributeModifier(FLEEING_SPEED_ID, "Fleeing speed bonus", 2.0D, true, false)); - public static final long SPRINT_SPEED_ID = AttributeModifier.getModifierId("Sprint"); - public static final AttributeModifier SPRINT_SPEED_MOD = (new AttributeModifier(SPRINT_SPEED_ID, "Sprinting speed boost", 0.30000001192092896D, true, false)); - public static final long ITEM_VAL_ID = AttributeModifier.getModifierId("ItemVal"); - public static final long RADIATION_BASE = AttributeModifier.getModifierId("NukeVal"); - public static final long MOUSE_SPEEDY_ID = AttributeModifier.getModifierId("SpeedyG"); - public static final AttributeModifier MOUSE_SPEEDY_MOD = new AttributeModifier(MOUSE_SPEEDY_ID, "Mouse speed boost", 1.0D, true); - - /** - * Creates an NBTTagList from a BaseAttributeMap, including all its AttributeInstances - */ - public static NBTTagList writeBaseAttributeMapToNBT(AttributeMap map) - { - NBTTagList nbttaglist = new NBTTagList(); - - for (AttributeInstance iattributeinstance : map.getAllAttributes()) - { - nbttaglist.appendTag(writeAttributeInstanceToNBT(iattributeinstance)); - } - - return nbttaglist; - } - - /** - * Creates an NBTTagCompound from an AttributeInstance, including its AttributeModifiers - */ - private static NBTTagCompound writeAttributeInstanceToNBT(AttributeInstance instance) - { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - Attribute iattribute = instance.getAttribute(); - nbttagcompound.setString("Name", iattribute.getUnlocalizedName()); - nbttagcompound.setDouble("Base", instance.getBaseValue()); - Collection collection = instance.getModifiers(); - - if (collection != null && !collection.isEmpty()) - { - NBTTagList nbttaglist = new NBTTagList(); - - for (AttributeModifier attributemodifier : collection) - { - if (attributemodifier.isSaved()) - { - nbttaglist.appendTag(writeAttributeModifierToNBT(attributemodifier)); - } - } - - nbttagcompound.setTag("Modifiers", nbttaglist); - } - - return nbttagcompound; - } - - /** - * Creates an NBTTagCompound from an AttributeModifier - */ - private static NBTTagCompound writeAttributeModifierToNBT(AttributeModifier modifier) - { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setString("Name", modifier.getName()); - nbttagcompound.setDouble("Amount", modifier.getAmount()); - nbttagcompound.setBoolean("Multiply", modifier.isMultiplied()); - nbttagcompound.setLong("AttrId", modifier.getID()); - return nbttagcompound; - } - - public static void setAttributeModifiers(AttributeMap map, NBTTagList list) - { - for (int i = 0; i < list.tagCount(); ++i) - { - NBTTagCompound nbttagcompound = list.getCompoundTagAt(i); - AttributeInstance iattributeinstance = map.getAttributeInstanceByName(nbttagcompound.getString("Name")); - - if (iattributeinstance != null) - { - applyModifiersToAttributeInstance(iattributeinstance, nbttagcompound); - } - else - { - Log.JNI.warn("Ignoriere unbekannte Attribute \'" + nbttagcompound.getString("Name") + "\'"); - } - } - } - - private static void applyModifiersToAttributeInstance(AttributeInstance instance, NBTTagCompound compound) - { - instance.setBaseValue(compound.getDouble("Base")); - - if (compound.hasKey("Modifiers", 9)) - { - NBTTagList nbttaglist = compound.getTagList("Modifiers", 10); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) - { - AttributeModifier attributemodifier = readAttributeModifierFromNBT(nbttaglist.getCompoundTagAt(i)); - - if (attributemodifier != null) - { - AttributeModifier attributemodifier1 = instance.getModifier(attributemodifier.getID()); - - if (attributemodifier1 != null) - { - instance.removeModifier(attributemodifier1); - } - - instance.applyModifier(attributemodifier); - } - } - } - } - - /** - * Creates an AttributeModifier from an NBTTagCompound - */ - public static AttributeModifier readAttributeModifierFromNBT(NBTTagCompound compound) - { - long id = compound.getLong("AttrId"); - if(id == 0L) - return null; - - try - { - return new AttributeModifier(id, compound.getString("Name"), compound.getDouble("Amount"), compound.getBoolean("Multiply")); - } - catch (Exception exception) - { - Log.JNI.warn("Konnte Attribute nicht erstellen: " + exception.getMessage()); - return null; - } - } -} diff --git a/java/src/game/entity/attributes/LowerStringMap.java b/java/src/game/entity/attributes/LowerStringMap.java deleted file mode 100755 index 11110bb..0000000 --- a/java/src/game/entity/attributes/LowerStringMap.java +++ /dev/null @@ -1,75 +0,0 @@ -package game.entity.attributes; - -import java.util.Collection; -import java.util.Map; -import java.util.Set; - -import game.collect.Maps; - -public class LowerStringMap implements Map -{ - private final Map internalMap = Maps.newLinkedHashMap(); - - public int size() - { - return this.internalMap.size(); - } - - public boolean isEmpty() - { - return this.internalMap.isEmpty(); - } - - public boolean containsKey(Object p_containsKey_1_) - { - return this.internalMap.containsKey(p_containsKey_1_.toString().toLowerCase()); - } - - public boolean containsValue(Object p_containsValue_1_) - { - return this.internalMap.containsKey(p_containsValue_1_); - } - - public V get(Object p_get_1_) - { - return this.internalMap.get(p_get_1_.toString().toLowerCase()); - } - - public V put(String p_put_1_, V p_put_2_) - { - return this.internalMap.put(p_put_1_.toLowerCase(), p_put_2_); - } - - public V remove(Object p_remove_1_) - { - return this.internalMap.remove(p_remove_1_.toString().toLowerCase()); - } - - public void putAll(Map p_putAll_1_) - { - for (Entry entry : p_putAll_1_.entrySet()) - { - this.put((String)entry.getKey(), entry.getValue()); - } - } - - public void clear() - { - this.internalMap.clear(); - } - - public Set keySet() - { - return this.internalMap.keySet(); - } - - public Collection values() - { - return this.internalMap.values(); - } - - public Set> entrySet() - { - return this.internalMap.entrySet(); - } -} diff --git a/java/src/game/entity/npc/ClassInfo.java b/java/src/game/entity/npc/ClassInfo.java deleted file mode 100755 index 7802003..0000000 --- a/java/src/game/entity/npc/ClassInfo.java +++ /dev/null @@ -1,9 +0,0 @@ -package game.entity.npc; - -public class ClassInfo { - public final Enum type; - - public ClassInfo(Enum type) { - this.type = type; - } -} diff --git a/java/src/game/entity/npc/PlayerCharacter.java b/java/src/game/entity/npc/PlayerCharacter.java deleted file mode 100644 index cc39e4e..0000000 --- a/java/src/game/entity/npc/PlayerCharacter.java +++ /dev/null @@ -1,23 +0,0 @@ -package game.entity.npc; - -import game.world.BlockPos; - -public class PlayerCharacter { - public final String name; - public final String info; - public final Alignment align; - public final String dim; - public final BlockPos pos; - public final String type; - public final int level; - - public PlayerCharacter(String name, String info, Alignment align, String dim, BlockPos pos, String type, int level) { - this.name = name; - this.info = info; - this.align = align; - this.dim = dim; - this.pos = pos; - this.type = type; - this.level = level; - } -} diff --git a/java/src/game/entity/projectile/EntityBullet.java b/java/src/game/entity/projectile/EntityBullet.java deleted file mode 100755 index 035e8a9..0000000 --- a/java/src/game/entity/projectile/EntityBullet.java +++ /dev/null @@ -1,411 +0,0 @@ -package game.entity.projectile; - -import java.util.List; - -import game.enchantment.EnchantmentHelper; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.types.EntityLiving; -import game.entity.types.IObjectData; -import game.entity.types.IProjectile; -import game.init.Config; -import game.init.SoundEvent; -import game.nbt.NBTTagCompound; -import game.util.ExtMath; -import game.world.BoundingBox; -import game.world.HitPosition; -import game.world.Vec3; -import game.world.World; - -public class EntityBullet extends Entity implements IProjectile, IObjectData -{ - public Entity shootingEntity; - private int ticksInAir; - private int age; - private int damage = 5; - - public EntityBullet(World worldIn) - { - super(worldIn); - this.renderDistWeight = 10.0D; - this.setSize(0.5F, 0.5F); - } - - public EntityBullet(World worldIn, double x, double y, double z) - { - super(worldIn); - this.renderDistWeight = 10.0D; - this.setSize(0.5F, 0.5F); - this.setPosition(x, y, z); - } - - public EntityBullet(World worldIn, double x, double y, double z, int data) - { - this(worldIn, x, y, z); - Entity entity2 = worldIn.getEntityByID(data); - if(entity2 instanceof EntityLiving) { - this.shootingEntity = entity2; - } - } - - public EntityBullet(World worldIn, EntityLiving shooter, EntityLiving target, float velocity, float innacuracy) - { - super(worldIn); - this.renderDistWeight = 10.0D; - this.shootingEntity = shooter; - - this.posY = shooter.posY + (double)shooter.getEyeHeight() - 0.10000000149011612D; - double d0 = target.posX - shooter.posX; - double d1 = target.getEntityBoundingBox().minY + (double)(target.height * 0.7f) - this.posY; - double d2 = target.posZ - shooter.posZ; - double d3 = (double)ExtMath.sqrtd(d0 * d0 + d2 * d2); - - if (d3 >= 1.0E-7D) - { - float f = (float)(ExtMath.atan2(d2, d0) * 180.0D / Math.PI) - 90.0F; - float f1 = (float)(-(ExtMath.atan2(d1, d3) * 180.0D / Math.PI)); - double d4 = d0 / d3; - double d5 = d2 / d3; - this.setLocationAndAngles(shooter.posX + d4, this.posY, shooter.posZ + d5, f, f1); -// float f2 = (float)(d3 * 0.20000000298023224D); - this.setThrowableHeading(d0, d1 /* + (double)f2 */ , d2, velocity, innacuracy); - } - } - - public EntityBullet(World worldIn, EntityLiving shooter, float velocity) - { - super(worldIn); - this.renderDistWeight = 10.0D; - this.shootingEntity = shooter; - - this.setSize(0.5F, 0.5F); - this.setLocationAndAngles(shooter.posX, shooter.posY + (double)shooter.getEyeHeight(), shooter.posZ, shooter.rotYaw, shooter.rotPitch); - this.posX -= (double)(ExtMath.cos(this.rotYaw / 180.0F * (float)Math.PI) * 0.16F); - this.posY -= 0.10000000149011612D; - this.posZ -= (double)(ExtMath.sin(this.rotYaw / 180.0F * (float)Math.PI) * 0.16F); - this.setPosition(this.posX, this.posY, this.posZ); - this.motionX = (double)(-ExtMath.sin(this.rotYaw / 180.0F * (float)Math.PI) * ExtMath.cos(this.rotPitch / 180.0F * (float)Math.PI)); - this.motionZ = (double)(ExtMath.cos(this.rotYaw / 180.0F * (float)Math.PI) * ExtMath.cos(this.rotPitch / 180.0F * (float)Math.PI)); - this.motionY = (double)(-ExtMath.sin(this.rotPitch / 180.0F * (float)Math.PI)); - this.setThrowableHeading(this.motionX, this.motionY, this.motionZ, velocity, 0.5F); - } - - protected void entityInit() - { - } - - /** - * Similar to setArrowHeading, it's point the throwable entity to a x, y, z direction. - */ - public void setThrowableHeading(double x, double y, double z, float velocity, float inaccuracy) - { - float f = ExtMath.sqrtd(x * x + y * y + z * z); - x = x / (double)f; - y = y / (double)f; - z = z / (double)f; - x = x + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; - y = y + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; - z = z + this.rand.gaussian() * (double)(this.rand.chance() ? -1 : 1) * 0.007499999832361937D * (double)inaccuracy; - x = x * (double)velocity; - y = y * (double)velocity; - z = z * (double)velocity; - this.motionX = x; - this.motionY = y; - this.motionZ = z; - float f1 = ExtMath.sqrtd(x * x + z * z); - this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(x, z) * 180.0D / Math.PI); - this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(y, (double)f1) * 180.0D / Math.PI); - } - - public void setPositionAndRotation2(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean p_180426_10_) - { - this.setPosition(x, y, z); - this.setRotation(yaw, pitch); - } - - /** - * Sets the velocity to the args. Args: x, y, z - */ - public void setVelocity(double x, double y, double z) - { - this.motionX = x; - this.motionY = y; - this.motionZ = z; - - if (this.prevPitch == 0.0F && this.prevYaw == 0.0F) - { - float f = ExtMath.sqrtd(x * x + z * z); - this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(x, z) * 180.0D / Math.PI); - this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(y, (double)f) * 180.0D / Math.PI); - this.prevPitch = this.rotPitch; - this.prevYaw = this.rotYaw; - this.setLocationAndAngles(this.posX, this.posY, this.posZ, this.rotYaw, this.rotPitch); - } - } - - /** - * Called to update the entity's position/logic. - */ - public void onUpdate() - { - super.onUpdate(); - - if (this.prevPitch == 0.0F && this.prevYaw == 0.0F) - { - float f = ExtMath.sqrtd(this.motionX * this.motionX + this.motionZ * this.motionZ); - this.prevYaw = this.rotYaw = (float)(ExtMath.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI); - this.prevPitch = this.rotPitch = (float)(ExtMath.atan2(this.motionY, (double)f) * 180.0D / Math.PI); - } - - if(!this.worldObj.client && ++this.age >= 200) { - this.setDead(); - return; - } - ++this.ticksInAir; - Vec3 vec31 = new Vec3(this.posX, this.posY, this.posZ); - Vec3 vec3 = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); - HitPosition movingobjectposition = this.worldObj.rayTraceBlocks(vec31, vec3, false, true, false); - vec31 = new Vec3(this.posX, this.posY, this.posZ); - vec3 = new Vec3(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ); - - if (movingobjectposition != null) - { - vec3 = new Vec3(movingobjectposition.vec.xCoord, movingobjectposition.vec.yCoord, movingobjectposition.vec.zCoord); - } - - Entity entity = null; - List list = this.worldObj.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox().addCoord(this.motionX, this.motionY, this.motionZ).expand(1.0D, 1.0D, 1.0D)); - double d0 = 0.0D; - - for (int i = 0; i < list.size(); ++i) - { - Entity entity1 = (Entity)list.get(i); - - if (entity1.canBeCollidedWith() && (entity1 != this.shootingEntity || this.ticksInAir >= 5)) - { - float f1 = 0.3F; - BoundingBox axisalignedbb1 = entity1.getEntityBoundingBox().expand((double)f1, (double)f1, (double)f1); - HitPosition movingobjectposition1 = axisalignedbb1.calculateIntercept(vec31, vec3); - - if (movingobjectposition1 != null) - { - double d1 = vec31.squareDistanceTo(movingobjectposition1.vec); - - if (d1 < d0 || d0 == 0.0D) - { - entity = entity1; - d0 = d1; - } - } - } - } - - if (entity != null) - { - movingobjectposition = new HitPosition(entity); - } - -// if (movingobjectposition != null && movingobjectposition.entity != null && movingobjectposition.entity.isPlayer()) -// { -// EntityNPC entityplayer = (EntityNPC)movingobjectposition.entity; -// -// if (entityplayer.creative || this.shootingEntity.isPlayer() && !((EntityNPC)this.shootingEntity).canAttackPlayer(entityplayer)) -// { -// movingobjectposition = null; -// } -// } - - if (movingobjectposition != null) - { - if (movingobjectposition.entity != null) - { - float f2 = ExtMath.sqrtd(this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ); - int l = ExtMath.ceild((double)f2 * (double)this.damage); - - DamageSource damagesource; - - if (this.shootingEntity == null) - { - damagesource = DamageSource.causeShotDamage(this, this); - } - else - { - damagesource = DamageSource.causeShotDamage(this, this.shootingEntity); - } - - if ((this.worldObj.client || Config.damageBullet) && movingobjectposition.entity.attackEntityFrom(damagesource, l)) - { - if (movingobjectposition.entity instanceof EntityLiving) - { - EntityLiving entitylivingbase = (EntityLiving)movingobjectposition.entity; - -// if (!this.worldObj.client) -// { -// entitylivingbase.setArrowCountInEntity(entitylivingbase.getArrowCountInEntity() + 1); -// } - -// if (this.knockbackStrength > 0) -// { -// float f7 = MathHelper.sqrt_double(this.motionX * this.motionX + this.motionZ * this.motionZ); -// -// if (f7 > 0.0F) -// { -// movingobjectposition.entityHit.addKnockback(this.motionX * (double)this.knockbackStrength * 0.6000000238418579D / (double)f7, 0.1D, this.motionZ * (double)this.knockbackStrength * 0.6000000238418579D / (double)f7); -// } -// } - - if (this.shootingEntity instanceof EntityLiving) - { - EnchantmentHelper.applyThornEnchantments(entitylivingbase, this.shootingEntity); - EnchantmentHelper.applyArthropodEnchantments((EntityLiving)this.shootingEntity, entitylivingbase); - } - -// if (this.shootingEntity != null && movingobjectposition.entityHit != this.shootingEntity && movingobjectposition.entityHit.isPlayer() && this.shootingEntity.isPlayer()) -// { -// ((EntityNPCMP)this.shootingEntity).netHandler.sendPacket(new S29PacketSoundEffect( -// "random.successful_hit", shootingEntity.posX, -// shootingEntity.posY + (double)shootingEntity.getEyeHeight(), shootingEntity.posZ, 0.18F, 0.45F)); -// } - } - - this.playSound(SoundEvent.METALHIT, 0.2F); - -// this.setDead(); - } -// else -// { - this.setDead(); -// this.motionX *= -0.10000000149011612D; -// this.motionY *= -0.10000000149011612D; -// this.motionZ *= -0.10000000149011612D; -// this.rotYaw += 180.0F; -// this.prevYaw += 180.0F; -// this.ticksInAir = 0; -// } - } - else - { - this.playSound(SoundEvent.METALHIT, 0.5F); - - this.setDead(); - } - } - - this.posX += this.motionX; - this.posY += this.motionY; - this.posZ += this.motionZ; - float f3 = ExtMath.sqrtd(this.motionX * this.motionX + this.motionZ * this.motionZ); - this.rotYaw = (float)(ExtMath.atan2(this.motionX, this.motionZ) * 180.0D / Math.PI); - - for (this.rotPitch = (float)(ExtMath.atan2(this.motionY, (double)f3) * 180.0D / Math.PI); this.rotPitch - this.prevPitch < -180.0F; this.prevPitch -= 360.0F) - { - ; - } - - while (this.rotPitch - this.prevPitch >= 180.0F) - { - this.prevPitch += 360.0F; - } - - while (this.rotYaw - this.prevYaw < -180.0F) - { - this.prevYaw -= 360.0F; - } - - while (this.rotYaw - this.prevYaw >= 180.0F) - { - this.prevYaw += 360.0F; - } - - this.rotPitch = this.prevPitch + (this.rotPitch - this.prevPitch) * 0.2F; - this.rotYaw = this.prevYaw + (this.rotYaw - this.prevYaw) * 0.2F; -// float f4 = 0.99F; -// float f6 = 0.001F; - -// if (this.isInLiquid()) -// { -// for (int i1 = 0; i1 < 4; ++i1) -// { -// float f8 = 0.25F; -// this.worldObj.spawnParticle(ParticleType.WATER_BUBBLE, this.posX - this.motionX * (double)f8, this.posY - this.motionY * (double)f8, this.posZ - this.motionZ * (double)f8, this.motionX, this.motionY, this.motionZ); -// } -// -// f4 = 0.85F; -// } - -// if (this.isWet()) -// { -// this.extinguish(); -// } - -// this.motionX *= (double)f4; -// this.motionY *= (double)f4; -// this.motionZ *= (double)f4; -// this.motionY -= (double)f6; - this.setPosition(this.posX, this.posY, this.posZ); -// this.doBlockCollisions(); - } - - public void writeEntityToNBT(NBTTagCompound tagCompound) - { - tagCompound.setInteger("damage", this.damage); - tagCompound.setInteger("age", this.age); - } - - public void readEntityFromNBT(NBTTagCompound tagCompund) - { - if(tagCompund.hasKey("damage", 99)) - this.damage = tagCompund.getInteger("damage"); - this.age = tagCompund.getInteger("age"); - } - - protected boolean canTriggerWalking() - { - return false; - } - - public void setDamage(int damageIn) - { - this.damage = damageIn; - } - - public int getDamage() - { - return this.damage; - } - - public boolean canAttackWithItem() - { - return false; - } - - public float getEyeHeight() - { - return 0.0F; - } - - public int getTrackingRange() { - return 96; - } - - public int getUpdateFrequency() { - return 1; - } - - public boolean isSendingVeloUpdates() { - return false; - } - - public int getPacketData() { - return this.shootingEntity != null ? this.shootingEntity.getId() : this.getId(); - } - - public boolean hasSpawnVelocity() { - return true; - } - - public EntityType getType() { - return EntityType.PROJECTILE; - } -} diff --git a/java/src/game/entity/types/CombatEntry.java b/java/src/game/entity/types/CombatEntry.java deleted file mode 100755 index 5239d4f..0000000 --- a/java/src/game/entity/types/CombatEntry.java +++ /dev/null @@ -1,33 +0,0 @@ -package game.entity.types; - -import game.entity.DamageSource; - -public class CombatEntry { - private final DamageSource source; - private final int damage; - private final String blockType; - private final float fallDistance; - - public CombatEntry(DamageSource source, int damage, String blockType, float fallDistance) { - this.source = source; - this.damage = damage; - this.blockType = blockType; - this.fallDistance = fallDistance; - } - - public DamageSource getSource() { - return this.source; - } - - public int getDamage() { - return this.damage; - } - - public String getBlockType() { - return this.blockType; - } - - public float getFallDistance() { - return this.source == DamageSource.outOfWorld ? Float.MAX_VALUE : this.fallDistance; - } -} diff --git a/java/src/game/gui/GuiConfirm.java b/java/src/game/gui/GuiConfirm.java deleted file mode 100755 index b272826..0000000 --- a/java/src/game/gui/GuiConfirm.java +++ /dev/null @@ -1,44 +0,0 @@ -package game.gui; - -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; -import game.gui.element.Label; -import game.gui.element.TransparentBox; - -public class GuiConfirm extends Gui implements ActButton.Callback { - public static interface Callback { - void confirm(boolean confirmed); - } - - protected Callback callback; - protected String messageLine1; - private String messageLine2; - protected String confirmButtonText; - protected String cancelButtonText; - private ActButton confirmBtn; - private ActButton cancelBtn; - - public GuiConfirm(Callback callback, String msg1, String msg2, String msgConfirm, String msgCancel) { - this.callback = callback; - this.messageLine1 = msg1; - this.messageLine2 = msg2; - this.confirmButtonText = msgConfirm; - this.cancelButtonText = msgCancel; - } - - public void init(int width, int height) { - this.add(new Label(0, 0, 500, 24, this.messageLine1, true)); - this.add(new TransparentBox(0, 80, 500, 300, this.messageLine2, this.gm.theWorld != null && !this.gm.charEditor)); - this.confirmBtn = this.add(new ActButton(48, 500, 200, 24, this, this.confirmButtonText)); - this.cancelBtn = this.add(new ActButton(252, 500, 200, 24, this, this.cancelButtonText)); - this.shift(); - } - - public String getTitle() { - return "Aktion bestätigen"; - } - - public void use(ActButton btn, Mode mode) { - this.callback.confirm(btn == this.confirmBtn); - } -} diff --git a/java/src/game/gui/GuiConnect.java b/java/src/game/gui/GuiConnect.java deleted file mode 100644 index b1dabd1..0000000 --- a/java/src/game/gui/GuiConnect.java +++ /dev/null @@ -1,267 +0,0 @@ -package game.gui; - -import java.io.File; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Date; -import game.color.TextColor; -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; -import game.gui.element.GuiList; -import game.gui.element.ListEntry; -import game.gui.element.NavButton; -import game.init.Config; -import game.log.Log; -import game.network.Player; -import game.renderer.Drawing; -import game.util.FileUtils; -import game.util.Tuple; -import game.util.Util; - -public class GuiConnect extends GuiList implements ActButton.Callback { - public class ServerInfo implements Comparable, ListEntry { - private String name; - private String address; - private int port; - private String user; - private String password; - private String access; - private long lastConnected; - - public ServerInfo(String name, String address, int port, String user, String password, String access, long lastConnected) { - this.name = name; - this.address = address; - this.port = port; - this.user = user; - this.password = password; - this.access = access; - this.lastConnected = lastConnected; - } - - public String getName() { - return this.name; - } - - public String getAddress() { - return this.address; - } - - public int getPort() { - return this.port; - } - - public String getUser() { - return this.user; - } - - public String getPassword() { - return this.password; - } - - public String getAccess() { - return this.access; - } - - public long getLastConnected() { - return this.lastConnected; - } - - public void setData(String name, String address, int port, String user, String password, String access) { - this.name = name; - this.address = address; - this.port = port; - this.user = user; - this.password = password; - this.access = access; - } - - public void setLastConnected() { - this.lastConnected = System.currentTimeMillis(); - } - - public int compareTo(ServerInfo comp) { - return this.lastConnected < comp.lastConnected ? 1 : (this.lastConnected > comp.lastConnected ? -1 : this.name.compareTo(comp.name)); - } - - public void select(boolean isDoubleClick, int mouseX, int mouseY) { - GuiConnect.this.selectButton.enabled = true; - GuiConnect.this.deleteButton.enabled = true; - GuiConnect.this.editButton.enabled = true; - GuiConnect.this.copyButton.enabled = true; - - if(isDoubleClick) { - GuiConnect.this.use(GuiConnect.this.selectButton, Mode.PRIMARY); - } - } - - public void draw(int x, int y, int mouseXIn, int mouseYIn, boolean hover) { - Drawing.drawText(this.name + TextColor.GRAY + " - " + TextColor.RESET + this.user, x + 2, y, 0xffffffff); - Drawing.drawText(this.address + TextColor.GRAY + " Port " + TextColor.RESET + this.port, x + 2, y + 18, 0xff808080); - Drawing.drawText("Zuletzt verbunden: " + (this.lastConnected == -1L ? "nie" : DATE_FORMAT.format(new Date(this.lastConnected))), x + 2, y + 18 + 16, 0xff808080); - } - } - - public static final GuiConnect INSTANCE = new GuiConnect(); - private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); - private static final File SERVERS_FILE = new File("servers.cfg"); - - private ActButton deleteButton; - private ActButton selectButton; - private ActButton copyButton; - private ActButton editButton; - private ActButton createButton; - - private GuiConnect() { - } - - public void init(int width, int height) { - super.init(width, height); - this.setDimensions(width, height, 32, height - 32); - this.elements.clear(); - if(SERVERS_FILE.exists()) { - try { - String[] lines = FileUtils.read(SERVERS_FILE).split("\n"); - String name = ""; - String address = ""; - int port = -1; - String user = ""; - String password = ""; - String access = ""; - long time = -1L; - for(int z = 0; z <= lines.length; z++) { - String line = z == lines.length ? null : lines[z]; - if(line == null || (line.startsWith("[") && line.endsWith("]"))) { - if(!name.isEmpty() && !address.isEmpty() && !user.isEmpty() && user.length() < Player.MAX_USER_LENGTH && Player.isValidUser(user) && password.length() < Player.MAX_PASS_LENGTH && access.length() < Player.MAX_PASS_LENGTH && address.length() < 128 && name.length() < 128 && port >= 0 && port < 65536) - this.elements.add(new ServerInfo(name, address, port, user, password, access, time)); - if(line != null) { - address = ""; - port = -1; - user = ""; - password = ""; - access = ""; - time = -1L; - name = line.substring(1, line.length() - 1); - } - } - else { - Tuple value = Util.getKeyValue(line); - if(value.first.equals("address")) - address = value.second; - else if(value.first.equals("port")) - try { - port = Integer.parseInt(value.second); - } - catch(NumberFormatException e) { - } - else if(value.first.equals("user")) - user = value.second; - else if(value.first.equals("password")) - password = value.second; - else if(value.first.equals("access")) - access = value.second; - else if(value.first.equals("connected")) - try { - time = Long.parseLong(value.second); - } - catch(NumberFormatException e) { - } - } - } - Collections.sort(this.elements); - } - catch(Exception e) { - Log.IO.error("Konnte Serverliste nicht laden", e); - this.elements.clear(); - } - } - - this.add(this.selectButton = new ActButton(width / 2 - 383, height - 28, 150, 24, this, "Verbinden")); - this.add(this.createButton = new ActButton(width - 204, 4, 200, 24, this, "Server hinzufügen ...")); - this.add(this.deleteButton = new ActButton(width / 2 - 75, height - 28, 150, 24, this, "Löschen")); - this.add(this.editButton = new ActButton(width / 2 + 79, height - 28, 150, 24, this, "Bearbeiten")); - this.add(this.copyButton = new ActButton(width / 2 - 229, height - 28, 150, 24, this, "Kopieren")); - this.add(new NavButton(4, 4, 200, 24, GuiServer.INSTANCE, "Schnellverbindung ...")); - this.add(new NavButton(width / 2 + 233, height - 28, 150, 24, GuiMenu.INSTANCE, "Abbrechen")); - - this.selectButton.enabled = false; - this.deleteButton.enabled = false; - this.editButton.enabled = false; - this.copyButton.enabled = false; - } - - public void onGuiClosed() { - this.save(); - } - - public void applyServer(ServerInfo server) { - if(this.selectedElement < 0) - this.elements.add(server); - this.save(); - this.gm.displayGuiScreen(this); - } - - private void save() { - try { - StringBuilder sb = new StringBuilder(); - for(ServerInfo server : this.elements) { - if(sb.length() > 0) - sb.append("\n"); - sb.append("[" + server.getName() + "]\n"); - sb.append("address " + server.getAddress() + "\n"); - sb.append("port " + server.getPort() + "\n"); - sb.append("user " + server.getUser() + "\n"); - sb.append("password " + server.getPassword() + "\n"); - sb.append("access " + server.getAccess() + "\n"); - sb.append("connected " + server.getLastConnected()); - } - FileUtils.write(SERVERS_FILE, sb.toString()); - } - catch(Exception e) { - Log.IO.error("Konnte Serverliste nicht speichern", e); - } - } - - public String getTitle() { - return "Server auswählen"; - } - - public int getListWidth() { - return 660; - } - - public int getSlotHeight() { - return 56; - } - - public void use(ActButton button, Mode mode) { - if(button == this.deleteButton) { - if(this.selectedElement >= 0) { - this.elements.remove(this.selectedElement); - this.gm.displayGuiScreen(this); - } - } - else if(button == this.selectButton) { - ServerInfo server = this.getSelected(); - if(server != null) { - server.setLastConnected(); - this.gm.connect(server.address, server.port, server.user, server.password, server.access); - } - } - else if(button == this.createButton) { - this.setSelected(-1); - this.gm.displayGuiScreen(new GuiServer(new ServerInfo("", "", Config.PORT, "", "", "", -1L))); - } - else if(button == this.editButton) { - ServerInfo server = this.getSelected(); - if(server != null) - this.gm.displayGuiScreen(new GuiServer(server)); - } - else if(button == this.copyButton) { - ServerInfo server = this.getSelected(); - if(server != null) { - this.setSelected(-1); - this.gm.displayGuiScreen(new GuiServer(new ServerInfo(server.name, server.address, server.port, server.user, server.address, server.access, -1L))); - } - } - } -} diff --git a/java/src/game/gui/GuiConvert.java b/java/src/game/gui/GuiConvert.java deleted file mode 100755 index 1d15ac6..0000000 --- a/java/src/game/gui/GuiConvert.java +++ /dev/null @@ -1,214 +0,0 @@ -package game.gui; - -import java.io.File; -import java.io.FileFilter; -import java.text.SimpleDateFormat; -import java.util.Collections; -import java.util.Date; -import game.Game.FileMode; -import game.color.TextColor; -import game.dimension.Space; -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; -import game.gui.element.GuiList; -import game.gui.element.ListEntry; -import game.gui.element.NavButton; -import game.log.Log; -import game.renderer.Drawing; -import game.util.FileCallback; -import game.world.Converter; -import game.world.Converter.SaveVersion; -import game.world.Region; -import game.world.Region.FolderInfo; -import game.world.World; - -public class GuiConvert extends GuiList implements ActButton.Callback -{ - protected class SaveInfo implements Comparable, ListEntry { - private final String file; - private final int dimensions; - private final int players; - private final long seed; - private final FolderInfo info; - - public SaveInfo(String file, int dimensions, int players, long seed, FolderInfo info) { - this.file = file; - this.dimensions = dimensions; - this.players = players; - this.seed = seed; - this.info = info; - } - - public String getFile() { - return this.file; - } - - public int getDimensions() { - return this.dimensions; - } - - public int getPlayers() { - return this.players; - } - - public boolean mustConvert() { - return this.info.legacy != null; - } - - public String getVersion() { - return this.info.legacy == null ? (this.info.version == null ? "" : this.info.version) : this.info.legacy.toString(); - } - - public boolean isIncompatible() { - return this.info.legacy == SaveVersion.RELEASE_1_13; - } - - public long getLastPlayed() { - return this.info.lastPlayed; - } - - public long getSeed() { - return this.seed; - } - - public int compareTo(SaveInfo comp) { - return this.info.lastPlayed < comp.info.lastPlayed ? 1 : (this.info.lastPlayed > comp.info.lastPlayed ? -1 : this.file.compareTo(comp.file)); - } - - public void select(boolean isDoubleClick, int mouseX, int mouseY) - { - boolean use = !this.isIncompatible() && this.mustConvert(); - GuiConvert.this.selectButton.enabled = use; - - if (isDoubleClick && use) - { - GuiConvert.this.use(GuiConvert.this.selectButton, Mode.PRIMARY); - } - } - - public void draw(int x, int y, int mouseXIn, int mouseYIn, boolean hover) - { - Drawing.drawText((this.isIncompatible() ? TextColor.DRED : "") + this.getFile() + (this.mustConvert() ? "" : - (TextColor.GRAY + " - " + TextColor.RESET + (this.getPlayers() > 0 ? this.getPlayers() + " Spieler" : "Keine Spieler"))), - x + 2, y, 0xffffffff); - Drawing.drawText((this.mustConvert() ? (this.isIncompatible() ? TextColor.CRIMSON : "") + this.getVersion() : (this.getDimensions() <= 0 ? "Keine Dimensionen" : this.getDimensions() + " Dimension" + (this.getDimensions() != 1 ? "en" : "") + " erschaffen")) - , x + 2, y + 18, 0xff808080); - Drawing.drawText(this.mustConvert() ? (this.isIncompatible() ? TextColor.CRIMSON + "Kann nicht konvertiert werden!" : - "Muss konvertiert werden!") : ( // "Kreativmodus: " + (info.isNoCreative() ? "Aus" : "An") + - "Zuletzt gespielt: " + DATE_FORMAT.format(new Date(this.getLastPlayed()))) + " " + TextColor.LGRAY + this.getVersion(), x + 2, y + 18 + 16, 0xff808080); - } - } - - public static final GuiConvert INSTANCE = new GuiConvert(); - private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss"); - - private ActButton selectButton; - private File dir = null; - - private GuiConvert() - { - } - - private void load() { - this.elements.clear(); - if(this.dir == null || !this.dir.exists() || !this.dir.isDirectory()) - return; - try - { - File[] files = dir.listFiles(); - if(files == null) - throw new RuntimeException("Kann den Speicherordner für Welten nicht lesen oder öffnen!"); - for(File file : files) { - if(!file.isDirectory()) - continue; - FolderInfo info = Region.loadWorldInfo(file); - if(info == null) - info = Converter.convertMapFormat(file, false); - if(info == null) { - this.elements.add(new SaveInfo(file.getName(), -1, -1, - 0L, new FolderInfo(World.START_TIME, file.lastModified(), null, null))); - continue; - } - int dims = -1; - int players = -1; - if(info.legacy == null) { - dims = 0; - File[] folders = new File(new File(dir, file.getName()), "chunk").listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.isDirectory() && !pathname.getName().equals(Space.INSTANCE.getDimensionName()); - } - }); - if(folders != null) { - for(File sub : folders) { - File[] dim = sub.listFiles(); - if(dim != null && dim.length > 0) - dims++; - } - } - File[] plrs = new File(new File(dir, file.getName()), "players").listFiles(new FileFilter() { - public boolean accept(File pathname) { - return pathname.getName().endsWith(".nbt"); - } - }); - players = plrs == null ? 0 : plrs.length; - } - this.elements.add(new SaveInfo(file.getName(), dims, players, - 0L, info)); - } - Collections.sort(this.elements); - } - catch (Exception e) - { - Log.IO.error("Konnte Weltliste nicht laden", e); - this.elements.clear(); - } - } - - public void init(int width, int height) - { - super.init(width, height); - this.setDimensions(width, height, 32, height - 32); - - this.load(); - - this.add(this.selectButton = new ActButton(width / 2 - 383, height - 28, 150, 24, this, "Konvertieren")); - this.add(new NavButton(width / 2 + 233, height - 28, 150, 24, GuiMenu.INSTANCE, "Abbrechen")); - - this.add(new ActButton(4, 4, 200, 24, new ActButton.Callback() { - public void use(ActButton elem, ActButton.Mode action) { - if(GuiConvert.this.gm.theWorld != null) - return; - GuiConvert.this.gm.showFileDialog(FileMode.DIRECTORY_LOAD, "Ordner wählen", GuiConvert.this.dir, new FileCallback() { - public void selected(File file) { - GuiConvert.this.dir = file; - GuiConvert.this.gm.displayGuiScreen(GuiConvert.this); - } - }); - } - }, "Ordner wählen ...")); - - this.selectButton.enabled = false; - } - - public String getTitle() { - return "Welt auswählen"; - } - - public int getListWidth() - { - return 660; - } - - public int getSlotHeight() - { - return 56; - } - - public void use(ActButton button, Mode mode) - { - String dir = this.getSelected().getFile(); - File folder = new File(this.dir, dir); - if(folder.isDirectory()) - Converter.convertMapFormat(folder, true); - } -} diff --git a/java/src/game/gui/GuiServer.java b/java/src/game/gui/GuiServer.java deleted file mode 100644 index e0ba390..0000000 --- a/java/src/game/gui/GuiServer.java +++ /dev/null @@ -1,146 +0,0 @@ -package game.gui; - -import game.color.TextColor; -import game.gui.GuiConnect.ServerInfo; -import game.gui.element.ActButton; -import game.gui.element.Label; -import game.gui.element.NavButton; -import game.gui.element.Textbox; -import game.gui.element.Textbox.Action; -import game.init.Config; -import game.network.Player; -import game.vars.CVarCategory; -import game.vars.Variable; - -public class GuiServer extends Gui implements Textbox.Callback { - public static final GuiServer INSTANCE = new GuiServer(null); - - private final ServerInfo server; - - private Textbox nameBox; - private Textbox addrBox; - private Textbox portBox; - private Textbox userBox; - private Textbox passBox; - private Textbox accBox; - private Label nameLabel; - private Label addrLabel; - private Label portLabel; - private Label userLabel; - private Label passLabel; - private Label accLabel; - - public GuiServer(ServerInfo server) { - this.server = server; - } - - @Variable(name = "srv_last_address", category = CVarCategory.SYSTEM, min = 1, max = 128, display = "Letzte Server-Adresse") - private String lastAddr = ""; - @Variable(name = "srv_last_port", category = CVarCategory.SYSTEM, min = 0, max = 65535, display = "Letzter Server-Port") - private int lastPort = Config.PORT; - @Variable(name = "srv_last_user", category = CVarCategory.SYSTEM, max = Player.MAX_USER_LENGTH, display = "Letzter Server-Nutzer", validator = Player.UserValidator.class) - private String lastUser = ""; - @Variable(name = "srv_last_password", category = CVarCategory.SYSTEM, max = Player.MAX_PASS_LENGTH, display = "Letztes Server-Passwort") - private String lastPass = ""; - @Variable(name = "srv_last_access", category = CVarCategory.SYSTEM, max = Player.MAX_PASS_LENGTH, display = "Letzter Server-Zugang") - private String lastAcc = ""; - - public void init(int width, int height) { - if(this.server != null) - this.nameBox = this.add(new Textbox(0, -50, 400, 24, 128, true, this, this.server.getName())); - this.addrBox = this.add(new Textbox(0, 20, 400, 24, 128, true, this, this.server == null ? this.lastAddr : this.server.getAddress())); - this.portBox = this.add(new Textbox(404, 20, 76, 24, 5, true, this, "" + (this.server == null ? this.lastPort : this.server.getPort()))); - this.userBox = this.add(new Textbox(0, 70, 220, 24, Player.MAX_USER_LENGTH, true, this, Player.VALID_USER, this.server == null ? this.lastUser : this.server.getUser())); - this.passBox = this.add(new Textbox(0, 120, 480, 24, Player.MAX_PASS_LENGTH, true, this, this.server == null ? this.lastPass : this.server.getPassword())); - this.accBox = this.add(new Textbox(0, 170, 480, 24, Player.MAX_PASS_LENGTH, true, this, this.server == null ? this.lastAcc : this.server.getAccess())); - this.add(new ActButton(0, 220, 480, 24, new ActButton.Callback() { - public void use(ActButton elem, ActButton.Mode action) { - GuiServer.this.connect(); - } - }, this.server == null ? "Verbinden" : (this.server.getName().isEmpty() ? "Hinzufügen" : "Übernehmen"))); - this.add(new NavButton(0, 250, 480, 24, GuiConnect.INSTANCE, "Zurück")); - if(this.server != null) - this.nameLabel = this.add(new Label(0, -70, 410, 20, "Name", true)); - this.addrLabel = this.add(new Label(0, 0, 410, 20, "Adresse", true)); - this.portLabel = this.add(new Label(414, 0, 66, 20, "Port", true)); - this.userLabel = this.add(new Label(0, 50, 220, 20, "Nutzer", true)); - this.passLabel = this.add(new Label(0, 100, 480, 20, "Passwort", true)); - this.accLabel = this.add(new Label(0, 150, 480, 20, "Zugang", true)); - this.shift(); - } - - public String getTitle() { - return this.server == null ? "Mit Server verbinden" : (this.server.getName().isEmpty() ? "Server hinzufügen" : "Server bearbeiten"); - } - - private void connect() { - if(this.gm.theWorld != null) - return; - String name = null; - if(this.server != null) { - name = this.nameBox.getText(); - if(name.isEmpty()) { - this.nameLabel.setText(TextColor.RED + "Name"); - return; - } - } - String addr = this.addrBox.getText(); - if(addr.isEmpty()) { - this.addrLabel.setText(TextColor.RED + "Adresse"); - return; - } - int port = -1; - if(this.portBox.getText().isEmpty()) { - this.portLabel.setText(TextColor.RED + "Port"); - return; - } - else { - try { - port = Integer.parseInt(this.portBox.getText()); - } - catch(NumberFormatException e) { - } - if(port < 0 || port > 65535) { - this.portLabel.setText(TextColor.RED + "Port"); - return; - } - } - String user = this.userBox.getText(); - if(user.isEmpty()) { - this.userLabel.setText(TextColor.RED + "Nutzer"); - return; - } - String pass = this.passBox.getText(); - String acc = this.accBox.getText(); - if(this.server == null) { - this.lastAddr = addr; - this.lastPort = port; - this.lastUser = user; - this.lastPass = pass; - this.lastAcc = acc; - this.gm.setDirty(); - this.gm.connect(addr, port, user, pass, acc); - } - else { - this.server.setData(name, addr, port, user, pass, acc); - GuiConnect.INSTANCE.applyServer(this.server); - } - } - - public void use(Textbox elem, Action value) { - if(value == Action.SEND) { - elem.setDeselected(); - this.connect(); - } - else if(value == Action.FOCUS) { - if(elem == this.addrBox) - this.addrLabel.setText("Adresse"); - else if(elem == this.portBox) - this.portLabel.setText("Port"); - else if(elem == this.userBox) - this.userLabel.setText("Nutzer"); - else if(this.server != null && elem == this.nameBox) - this.nameLabel.setText("Name"); - } - } -} diff --git a/java/src/game/gui/character/GuiCharacters.java b/java/src/game/gui/character/GuiCharacters.java deleted file mode 100644 index 04f800d..0000000 --- a/java/src/game/gui/character/GuiCharacters.java +++ /dev/null @@ -1,122 +0,0 @@ -package game.gui.character; - -import game.color.TextColor; -import game.entity.npc.PlayerCharacter; -import game.gui.GuiConfirm; -import game.gui.GuiMenu; -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; -import game.gui.element.GuiList; -import game.gui.element.ListEntry; -import game.gui.element.NavButton; -import game.gui.element.TransparentBox; -import game.packet.CPacketAction; -import game.renderer.Drawing; - -public class GuiCharacters extends GuiList implements ActButton.Callback -{ - protected class CharacterEntry implements ListEntry - { - private final PlayerCharacter character; - private final boolean initial; - - protected CharacterEntry(PlayerCharacter character, boolean initial) - { - this.character = character; - this.initial = initial; - } - - public void draw(int x, int y, int mouseX, int mouseY, boolean hovered) - { - if(this.initial) - Drawing.drawRect(x, y, 1, 36, 0xffaf0000); - String str = this.character == null ? TextColor.BLUE + "[" + TextColor.CYAN + "+" + TextColor.BLUE + "]" : - String.format(TextColor.GREEN + "Level " + TextColor.DGREEN + "%d " + TextColor.YELLOW + "%s " + TextColor.VIOLET + "%s" + TextColor.GRAY + " [%s%s" + TextColor.GRAY + "]", - character.level, character.type, character.name, character.align.color, character.align.display); - String pos = this.character == null ? TextColor.BROWN + "Neuen Charakter erstellen" : - String.format(TextColor.NEON + "%s " + TextColor.GRAY + "bei " + TextColor.ACID + "%d" + TextColor.GRAY + ", " + TextColor.ACID + "%d" + TextColor.GRAY + ", " + TextColor.ACID + "%d", - character.dim, character.pos.getX(), character.pos.getY(), character.pos.getZ()); - Drawing.drawText(str, x + 3, y, 0xffffffff); - Drawing.drawText(pos, x + 3, y + 16, 0xffffffff); - } - - public void select(boolean dclick, int mx, int my) - { - if(dclick) - GuiCharacters.this.use(GuiCharacters.this.actionButtom, Mode.PRIMARY); - GuiCharacters.this.updateButtons(); - } - } - - public static final GuiCharacters INSTANCE = new GuiCharacters(); - - private TransparentBox descField; - private ActButton actionButtom; - private ActButton deleteButtom; - - private GuiCharacters() { - } - - private void updateButtons() { - CharacterEntry entry = this.getSelected(); - this.descField.setText(entry == null ? "" : (entry.character == null ? "*neuer Charakter*" : (entry.character.info == null ? "*keine Beschreibung vorhanden*" : this.getSelected().character.info))); - this.actionButtom.setText(entry != null && entry.character == null ? "Charakter erstellen" : "Charakter spielen"); - this.actionButtom.enabled = entry != null && !entry.initial; - this.deleteButtom.enabled = entry != null && entry.character != null && !entry.initial; - } - - public void init(int width, int height) - { - super.init(width, height); - this.setDimensions(600, height, 32, height - 32); - this.elements.clear(); - if(this.gm.getNetHandler() != null) { - int initialSelection = this.gm.getNetHandler().getSelectedCharacter(); - for(PlayerCharacter character : this.gm.getNetHandler().getCharacterList()) { - this.elements.add(new CharacterEntry(initialSelection == this.elements.size() ? new PlayerCharacter(character.name, character.info, character.align, this.gm.thePlayer.worldObj.dimension.getFormattedName(false), this.gm.thePlayer.getPosition(), character.type, this.gm.thePlayer.experienceLevel) : character, initialSelection == this.elements.size())); - } - this.elements.add(new CharacterEntry(null, false)); - this.setSelected(initialSelection); - } - this.descField = this.add(new TransparentBox(width - 390, 62, 380, height - 124, "", false)); - this.deleteButtom = this.add(new ActButton(width / 2 - 304, height - 28, 200, 24, this, "Charakter löschen")); - this.actionButtom = this.add(new ActButton(width / 2 - 100, height - 28, 200, 24, this, "")); - this.add(new NavButton(width / 2 + 104, height - 28, 200, 24, GuiMenu.INSTANCE, "Abbrechen")); - this.updateButtons(); - } - - public String getTitle() { - return "Charakter anpassen"; - } - - public int getListWidth() - { - return 560; - } - - public int getSlotHeight() - { - return 36 + 4; - } - - public void use(ActButton elem, Mode action) { - CharacterEntry entry = GuiCharacters.this.getSelected(); - if(entry != null && GuiCharacters.this.gm.getNetHandler() != null) { - if(elem == this.actionButtom) { - if(entry.character == null) - this.gm.getNetHandler().addToSendQueue(new CPacketAction(CPacketAction.Action.OPEN_EDITOR)); - else - this.gm.getNetHandler().addToSendQueue(new CPacketAction(CPacketAction.Action.SELECT_CHARACTER, this.selectedElement)); - } - else if(elem == this.deleteButtom && entry.character != null) { - this.gm.displayGuiScreen(new GuiConfirm(new GuiConfirm.Callback() { - public void confirm(boolean confirmed) { - if(confirmed) - GuiCharacters.this.gm.getNetHandler().addToSendQueue(new CPacketAction(CPacketAction.Action.DELETE_CHARACTER, GuiCharacters.this.selectedElement)); - GuiCharacters.this.gm.displayGuiScreen(GuiCharacters.this); - } - }, "Möchtest du diesen Charakter wirklich löschen?", "Der Fortschritt, die Gegenstände und die Historie von \"" + entry.character.name + "\" werden für imer verloren sein!", "Löschen", "Abbrechen")); - } - } - } -} diff --git a/java/src/game/gui/character/GuiClass.java b/java/src/game/gui/character/GuiClass.java deleted file mode 100644 index d82db44..0000000 --- a/java/src/game/gui/character/GuiClass.java +++ /dev/null @@ -1,77 +0,0 @@ -package game.gui.character; - -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; -import game.gui.element.GuiList; -import game.gui.element.ListEntry; -import game.gui.element.NavButton; -import game.packet.CPacketAction; -import game.renderer.Drawing; - -public class GuiClass extends GuiList implements ActButton.Callback -{ - protected class ClassEntry implements ListEntry - { - private final Enum clazz; - - protected ClassEntry(Enum clazz) - { - this.clazz = clazz; - } - - public void draw(int x, int y, int mouseX, int mouseY, boolean hovered) - { - if(GuiClass.this.gm.thePlayer != null && this.clazz == GuiClass.this.gm.thePlayer.getNpcClass()) - Drawing.drawRect(x, y, 1, 44, 0xffaf0000); - Drawing.drawText(this.clazz.toString().isEmpty() ? "" : this.clazz.toString(), x + 3, y, 0xffffffff); - } - - public void select(boolean dclick, int mx, int my) - { - if((GuiClass.this.selectButton.enabled = GuiClass.this.gm.thePlayer == null || this.clazz != GuiClass.this.gm.thePlayer.getNpcClass()) && dclick) - GuiClass.this.use(GuiClass.this.selectButton, Mode.PRIMARY); - } - } - - public static final GuiClass INSTANCE = new GuiClass(); - - private ActButton selectButton; - - private GuiClass() { - } - - public void init(int width, int height) - { - super.init(width, height); - this.setDimensions(400, height, 32, height - 32); - this.elements.clear(); - if(this.gm.thePlayer != null && this.gm.thePlayer.getSpecies().classEnum != null) - for(Enum clazz : this.gm.thePlayer.getSpecies().classEnum.getEnumConstants()) { - this.elements.add(new ClassEntry(clazz)); - } - this.add(new NavButton(width - 198 * 2, height - 28, 194, 24, GuiChar.INSTANCE, "Zurück")); - this.selectButton = this.add(new ActButton(width - 198, height - 28, 194, 24, this, "Klasse ändern")); - } - - public String getTitle() { - return "Klasse wählen"; - } - - public int getListWidth() - { - return 400 - 20; - } - - public int getSlotHeight() - { - return 44 + 4; - } - - public void use(ActButton elem, Mode action) { - ClassEntry entry = this.getSelected(); - if(entry != null && GuiClass.this.gm.thePlayer != null) { - GuiClass.this.gm.thePlayer.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_CLASS, entry.clazz.ordinal())); - this.gm.displayGuiScreen(GuiChar.INSTANCE); - } - } -} diff --git a/java/src/game/gui/character/GuiSpecies.java b/java/src/game/gui/character/GuiSpecies.java deleted file mode 100644 index 33e03d6..0000000 --- a/java/src/game/gui/character/GuiSpecies.java +++ /dev/null @@ -1,79 +0,0 @@ -package game.gui.character; - -import game.entity.npc.SpeciesInfo; -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; -import game.gui.element.GuiList; -import game.gui.element.ListEntry; -import game.gui.element.NavButton; -import game.init.EntityRegistry; -import game.init.SpeciesRegistry; -import game.packet.CPacketAction; -import game.renderer.Drawing; - -public class GuiSpecies extends GuiList implements ActButton.Callback -{ - protected class SpeciesEntry implements ListEntry - { - private final SpeciesInfo species; - - protected SpeciesEntry(SpeciesInfo species) - { - this.species = species; - } - - public void draw(int x, int y, int mouseX, int mouseY, boolean hovered) - { - if(GuiSpecies.this.gm.thePlayer != null && this.species == GuiSpecies.this.gm.thePlayer.getSpecies()) - Drawing.drawRect(x, y, 1, 44, 0xffaf0000); - Drawing.drawText(this.species.name, x + 3, y, 0xff000000 | this.species.color1 | this.species.color2); - if(this.species.classEnum != null) - Drawing.drawText(this.species.classEnum.getEnumConstants().length + " Klassen", x + 3, y + 18, 0xffc0c0c0); - } - - public void select(boolean dclick, int mx, int my) - { - if((GuiSpecies.this.selectButton.enabled = GuiSpecies.this.gm.thePlayer == null || this.species != GuiSpecies.this.gm.thePlayer.getSpecies()) && dclick) - GuiSpecies.this.use(GuiSpecies.this.selectButton, Mode.PRIMARY); - } - } - - public static final GuiSpecies INSTANCE = new GuiSpecies(); - - private ActButton selectButton; - - private GuiSpecies() { - } - - public void init(int width, int height) - { - super.init(width, height); - this.setDimensions(400, height, 32, height - 32); - this.elements.clear(); - for(SpeciesInfo species : SpeciesRegistry.SPECIMEN) { - this.elements.add(new SpeciesEntry(species)); - } - this.add(new NavButton(width - 198 * 2, height - 28, 194, 24, GuiChar.INSTANCE, "Zurück")); - this.selectButton = this.add(new ActButton(width - 198, height - 28, 194, 24, this, "Spezies ändern")); - } - - public String getTitle() { - return "Spezies wählen"; - } - - public int getListWidth() - { - return 400 - 20; - } - - public int getSlotHeight() - { - return 44 + 4; - } - - public void use(ActButton elem, Mode action) { - SpeciesEntry entry = this.getSelected(); - if(entry != null && GuiSpecies.this.gm.thePlayer != null) - GuiSpecies.this.gm.thePlayer.sendQueue.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_SPECIES, EntityRegistry.getEntityID(entry.species.clazz))); - } -} diff --git a/java/src/game/gui/container/GuiCrafting.java b/java/src/game/gui/container/GuiCrafting.java deleted file mode 100755 index 0dbe12c..0000000 --- a/java/src/game/gui/container/GuiCrafting.java +++ /dev/null @@ -1,42 +0,0 @@ -package game.gui.container; - -import game.inventory.ContainerWorkbench; -import game.inventory.InventoryPlayer; -import game.world.BlockPos; -import game.world.World; - -public class GuiCrafting extends GuiContainer -{ -// private static final String craftingTableGuiTextures = "textures/gui/crafting_table.png"; - - public GuiCrafting(InventoryPlayer playerInv, World worldIn) - { - this(playerInv, worldIn, BlockPos.ORIGIN); - } - - public GuiCrafting(InventoryPlayer playerInv, World worldIn, BlockPos blockPosition) - { - super(new ContainerWorkbench(playerInv, worldIn, blockPosition)); - } - - /** - * Draw the foreground layer for the GuiContainer (everything in front of the items). Args : mouseX, mouseY - */ - public void drawGuiContainerForegroundLayer() - { - this.drawString("Handwerk", 28, 6); - this.drawString("Inventar", 8, this.ySize - 96 + 2); - } - -// /** -// * Args : renderPartialTicks, mouseX, mouseY -// */ -// protected void drawGuiContainerBackgroundLayer(int mouseX, int mouseY) -// { -// GlState.color(1.0F, 1.0F, 1.0F, 1.0F); -// this.gm.getTextureManager().bindTexture(craftingTableGuiTextures); -// int i = (this.width - this.xSize) / 2; -// int j = (this.height - this.ySize) / 2; -//// this.rect(i, j, 0, 0, this.xSize, this.ySize); -// } -} diff --git a/java/src/game/gui/container/GuiMachine.java b/java/src/game/gui/container/GuiMachine.java deleted file mode 100755 index cca3fda..0000000 --- a/java/src/game/gui/container/GuiMachine.java +++ /dev/null @@ -1,44 +0,0 @@ -package game.gui.container; - -import game.Game; -import game.inventory.ContainerMachine; -import game.inventory.IInventory; -import game.inventory.InventoryPlayer; -import game.tileentity.TileEntityMachine; - - -public class GuiMachine extends GuiContainer -{ -// private final String texture; - private final IInventory playerInv; - private final IInventory machineInv; - private final TileEntityMachine machine; - - public GuiMachine(InventoryPlayer player, IInventory inv, TileEntityMachine machine) - { - super(new ContainerMachine(player, machine, inv, Game.getGame().thePlayer)); - this.playerInv = player; - this.machineInv = machine; -// this.allowUserInput = false; - this.ySize = 153; -// this.texture = "textures/gui/" + texture + ".png"; - this.machine = machine; - } - - public void drawGuiContainerForegroundLayer() - { - this.drawString(this.machine.getStatus().color + this.machineInv.getCommandName() + " - " + this.machine.getStatus().name, 8, 6); - this.drawString(this.playerInv.getCommandName(), 8, this.ySize - 96 + 2); - this.drawString(String.format("Temperatur: %d °", this.machine.getTemperature()), 8, 18); - this.drawString(this.machine.formatDisplay(), 8, 28); - } - -// protected void drawGuiContainerBackgroundLayer(int mouseX, int mouseY) -// { -// GlState.color(1.0F, 1.0F, 1.0F, 1.0F); -// this.gm.getTextureManager().bindTexture(this.texture); -// int i = (this.width - this.xSize) / 2; -// int j = (this.height - this.ySize) / 2; -//// this.rect(i, j, 0, 0, this.xSize, this.ySize); -// } -} diff --git a/java/src/game/gui/element/ActButton.java b/java/src/game/gui/element/ActButton.java deleted file mode 100644 index 91eb00f..0000000 --- a/java/src/game/gui/element/ActButton.java +++ /dev/null @@ -1,34 +0,0 @@ -package game.gui.element; - -import game.util.Formatter; -import game.window.Button; - -public class ActButton extends Element { - public static enum Mode { - PRIMARY, SECONDARY, TERTIARY; - } - - public static interface Callback { - void use(ActButton elem, Mode action); - } - - private final Callback func; - - public ActButton(int x, int y, int w, int h, Callback callback, Formatter formatter) { - super(x, y, w, h, formatter); - this.func = callback; - this.formatText(); - } - - public ActButton(int x, int y, int w, int h, Callback callback, String text) { - super(x, y, w, h, null); - this.func = callback; - this.setText(text); - } - - public void mouse(Button btn, int x, int y, boolean ctrl, boolean shift) { - this.func.use(this, (ctrl || (btn == Button.MOUSE_MIDDLE)) ? Mode.TERTIARY : ((shift || (btn == Button.MOUSE_RIGHT)) ? Mode.SECONDARY : Mode.PRIMARY)); - this.formatText(); - this.playSound(); - } -} diff --git a/java/src/game/gui/element/GuiList.java b/java/src/game/gui/element/GuiList.java deleted file mode 100755 index 32326cd..0000000 --- a/java/src/game/gui/element/GuiList.java +++ /dev/null @@ -1,414 +0,0 @@ -package game.gui.element; - -import java.util.List; - -import org.lwjgl.opengl.GL11; - -import game.collect.Lists; - -import game.gui.Gui; -import game.renderer.DefaultVertexFormats; -import game.renderer.Drawing; -import game.renderer.GlState; -import game.renderer.RenderBuffer; -import game.renderer.Tessellator; -import game.util.ExtMath; -import game.window.Button; - -public abstract class GuiList extends Gui -{ - protected final List elements = Lists.newArrayList(); - - protected int width; - protected int height; - - protected int top; - protected int bottom; - protected int right; - protected int left; - protected int mouseX; - protected int mouseY; - protected int initialClickY = -2; - protected float scrollMultiplier; - protected float amountScrolled; - protected int selectedElement = -1; - protected long lastClicked; - - public abstract int getListWidth(); // 220 - - public abstract int getSlotHeight(); - - protected int getScrollBarX() - { - return 0; - } - - public void setDimensions(int widthIn, int heightIn, int topIn, int bottomIn) - { - this.width = widthIn; - this.height = heightIn; - this.top = topIn; - this.bottom = bottomIn; - this.left = 0; - this.right = widthIn; - } - - public void init(int width, int height) { - - this.selectedElement = -1; - } - - public void setSlotXBoundsFromLeft(int leftIn) - { - this.left = leftIn; - this.right = leftIn + this.width; - } - - public final T getListEntry(int index) { - return this.elements.get(index); - } - - public final T getSelected() { - return this.selectedElement < 0 ? null : this.elements.get(this.selectedElement); - } - - public final int getSize() { - return this.elements.size(); - } - - public final void setSelected(int index) { - this.selectedElement = index; - } - - protected int getContentHeight() - { - return this.getSize() * this.getSlotHeight(); - } - - public int getSlotIndexFromScreenCoords(int x, int y) - { - int i = this.left + this.width / 2 - this.getListWidth() / 2; - int j = this.left + this.width / 2 + this.getListWidth() / 2; - int k = y - this.top + (int)this.amountScrolled - 4; - int l = k / this.getSlotHeight(); - return this.isInList(x, y) && x >= i && x <= j && l >= 0 && k >= 0 && l < this.getSize() ? l : -1; - } - - protected boolean isInList(int x, int y) - { - return x >= this.getScrollBarX() + 6; // x < this.getScrollBarX(); - } - - protected final boolean isSelected(int slotIndex) - { - return slotIndex == this.selectedElement; - } - - protected void bindAmountScrolled() - { - this.amountScrolled = ExtMath.clampf(this.amountScrolled, 0.0F, (float)this.getMaxScroll()); - } - - public int getMaxScroll() - { - return Math.max(0, this.getContentHeight() - (this.bottom - this.top - 4)); - } - - public int getAmountScrolled() - { - return (int)this.amountScrolled; - } - - public boolean isMouseYWithinSlotBounds(int p_148141_1_) - { - return p_148141_1_ >= this.top && p_148141_1_ <= this.bottom && this.mouseX >= this.left && this.mouseX <= this.right; - } - - public void scrollBy(int amount) - { - this.amountScrolled += (float)amount; - this.bindAmountScrolled(); - this.initialClickY = -2; - } - -// public void actionPerformed(Button button) -// { -// if (button.enabled) -// { -// if (button.id == this.scrollUpButtonID) -// { -// this.amountScrolled -= (float)(this.slotHeight * 2 / 3); -// this.initialClickY = -2; -// this.bindAmountScrolled(); -// } -// else if (button.id == this.scrollDownButtonID) -// { -// this.amountScrolled += (float)(this.slotHeight * 2 / 3); -// this.initialClickY = -2; -// this.bindAmountScrolled(); -// } -// } -// } - - public void draw() - { - int mouseXIn = this.gm.mouse_x; - int mouseYIn = this.gm.mouse_y; - this.mouseX = mouseXIn; - this.mouseY = mouseYIn; - this.drawBackground(); - int i = this.getScrollBarX(); - int j = i + 6; - this.bindAmountScrolled(); - GlState.disableLighting(); - GlState.disableFog(); - GlState.enableTexture2D(); - RenderBuffer worldrenderer = Tessellator.getBuffer(); - this.gm.getTextureManager().bindTexture(Gui.DIRT_BACKGROUND); - GlState.color(1.0F, 1.0F, 1.0F, 1.0F); - - float f = 32.0F; - worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos((double)0, (double)this.bottom, 0.0D).tex((double)((float)0 / f), (double)((float)(this.bottom + (int)this.amountScrolled) / f)).color(32, 32, 32, 255).endVertex(); - worldrenderer.pos((double)this.gm.fb_x, (double)this.bottom, 0.0D).tex((double)((float)this.gm.fb_x / f), (double)((float)(this.bottom + (int)this.amountScrolled) / f)).color(32, 32, 32, 255).endVertex(); - worldrenderer.pos((double)this.gm.fb_x, (double)this.top, 0.0D).tex((double)((float)this.gm.fb_x / f), (double)((float)(this.top + (int)this.amountScrolled) / f)).color(32, 32, 32, 255).endVertex(); - worldrenderer.pos((double)0, (double)this.top, 0.0D).tex((double)((float)0 / f), (double)((float)(this.top + (int)this.amountScrolled) / f)).color(32, 32, 32, 255).endVertex(); - Tessellator.draw(); - - int x = this.left + this.width / 2 - this.getListWidth() / 2 + 2; - int y = this.top + 4 - (int)this.amountScrolled; - - this.drawSelectionBox(x, y, mouseXIn, mouseYIn); - GlState.disableDepth(); - - this.overlayBackground(0, this.top, 255, 255); - this.overlayBackground(this.bottom, this.height, 255, 255); - - GlState.enableBlend(); - GlState.tryBlendFuncSeparate(GL11.GL_SRC_ALPHA, GL11.GL_ONE_MINUS_SRC_ALPHA, GL11.GL_ZERO, GL11.GL_ONE); - GlState.disableAlpha(); - GlState.shadeModel(GL11.GL_SMOOTH); - GlState.disableTexture2D(); - - int i1 = 4; - worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos((double)0, (double)(this.top + i1), 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 0).endVertex(); - worldrenderer.pos((double)this.gm.fb_x, (double)(this.top + i1), 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 0).endVertex(); - worldrenderer.pos((double)this.gm.fb_x, (double)this.top, 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos((double)0, (double)this.top, 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); - Tessellator.draw(); - worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos((double)0, (double)this.bottom, 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos((double)this.gm.fb_x, (double)this.bottom, 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos((double)this.gm.fb_x, (double)(this.bottom - i1), 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 0).endVertex(); - worldrenderer.pos((double)0, (double)(this.bottom - i1), 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 0).endVertex(); - Tessellator.draw(); - - int j1 = this.getMaxScroll(); - - if (j1 > 0) - { - int k1 = (this.bottom - this.top) * (this.bottom - this.top) / this.getContentHeight(); - k1 = ExtMath.clampi(k1, 32, this.bottom - this.top - 8); - int l1 = (int)this.amountScrolled * (this.bottom - this.top - k1) / j1 + this.top; - - if (l1 < this.top) - { - l1 = this.top; - } - - worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos((double)i, (double)this.bottom, 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos((double)j, (double)this.bottom, 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos((double)j, (double)this.top, 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex(); - worldrenderer.pos((double)i, (double)this.top, 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); - Tessellator.draw(); - worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos((double)i, (double)(l1 + k1), 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255).endVertex(); - worldrenderer.pos((double)j, (double)(l1 + k1), 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255).endVertex(); - worldrenderer.pos((double)j, (double)l1, 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255).endVertex(); - worldrenderer.pos((double)i, (double)l1, 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255).endVertex(); - Tessellator.draw(); - worldrenderer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); - worldrenderer.pos((double)i, (double)(l1 + k1 - 1), 0.0D).tex(0.0D, 1.0D).color(192, 192, 192, 255).endVertex(); - worldrenderer.pos((double)(j - 1), (double)(l1 + k1 - 1), 0.0D).tex(1.0D, 1.0D).color(192, 192, 192, 255).endVertex(); - worldrenderer.pos((double)(j - 1), (double)l1, 0.0D).tex(1.0D, 0.0D).color(192, 192, 192, 255).endVertex(); - worldrenderer.pos((double)i, (double)l1, 0.0D).tex(0.0D, 0.0D).color(192, 192, 192, 255).endVertex(); - Tessellator.draw(); - } - - GlState.enableTexture2D(); - GlState.shadeModel(GL11.GL_FLAT); - GlState.enableAlpha(); - GlState.disableBlend(); - - super.draw(); - } - - public void handleMouseInput() - { - if (this.isMouseYWithinSlotBounds(this.mouseY)) - { -// if (Button.MOUSE_LEFT.isDown() && this.getEnabled()) -// { - if (this.initialClickY == -1) - { - boolean flag1 = true; - - if (this.mouseY >= this.top && this.mouseY <= this.bottom) - { - int j2 = (this.width - this.getListWidth()) / 2; - int k2 = (this.width + this.getListWidth()) / 2; - int l2 = this.mouseY - this.top + (int)this.amountScrolled - 4; - int i1 = l2 / this.getSlotHeight(); - - if (i1 < this.getSize() && this.mouseX >= j2 && this.mouseX <= k2 && i1 >= 0 && l2 >= 0) - { - } - else if (this.mouseX >= j2 && this.mouseX <= k2 && l2 < 0) - { - flag1 = false; - } - - int i3 = this.getScrollBarX(); - int j1 = i3 + 6; - - if (this.mouseX >= i3 && this.mouseX <= j1) - { - this.scrollMultiplier = -1.0F; - int k1 = this.getMaxScroll(); - - if (k1 < 1) - { - k1 = 1; - } - - int l1 = (int)((float)((this.bottom - this.top) * (this.bottom - this.top)) / (float)this.getContentHeight()); - l1 = ExtMath.clampi(l1, 32, this.bottom - this.top - 8); - this.scrollMultiplier /= (float)(this.bottom - this.top - l1) / (float)k1; - } - else - { - this.scrollMultiplier = 1.0F; - } - - if (flag1) - { - this.initialClickY = this.mouseY; - } - else - { - this.initialClickY = -2; - } - } - else - { - this.initialClickY = -2; - } - } - else if (this.initialClickY >= 0) - { - this.amountScrolled -= (float)(this.mouseY - this.initialClickY) * this.scrollMultiplier; - this.initialClickY = this.mouseY; - } -// } -// else -// { -// this.initialClickY = -1; -// } - } - } - - protected void drawSelectionBox(int x, int y, int mouseXIn, int mouseYIn) - { - int size = this.getSize(); - RenderBuffer rb = Tessellator.getBuffer(); - - for (int z = 0; z < size; z++) - { - int y1 = y + z * this.getSlotHeight(); - int h = this.getSlotHeight() - 4; - - if (this.isSelected(z)) - { - int x1 = this.left + (this.width / 2 - this.getListWidth() / 2); - int x2 = this.left + this.width / 2 + this.getListWidth() / 2; - GlState.color(1.0F, 1.0F, 1.0F, 1.0F); - GlState.disableTexture2D(); - rb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); - rb.pos((double)x1, (double)(y1 + h + 2), 0.0D).tex(0.0D, 1.0D).color(128, 128, 128, 255).endVertex(); - rb.pos((double)x2, (double)(y1 + h + 2), 0.0D).tex(1.0D, 1.0D).color(128, 128, 128, 255).endVertex(); - rb.pos((double)x2, (double)(y1 - 2), 0.0D).tex(1.0D, 0.0D).color(128, 128, 128, 255).endVertex(); - rb.pos((double)x1, (double)(y1 - 2), 0.0D).tex(0.0D, 0.0D).color(128, 128, 128, 255).endVertex(); - rb.pos((double)(x1 + 1), (double)(y1 + h + 1), 0.0D).tex(0.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - rb.pos((double)(x2 - 1), (double)(y1 + h + 1), 0.0D).tex(1.0D, 1.0D).color(0, 0, 0, 255).endVertex(); - rb.pos((double)(x2 - 1), (double)(y1 - 1), 0.0D).tex(1.0D, 0.0D).color(0, 0, 0, 255).endVertex(); - rb.pos((double)(x1 + 1), (double)(y1 - 1), 0.0D).tex(0.0D, 0.0D).color(0, 0, 0, 255).endVertex(); - Tessellator.draw(); - GlState.enableTexture2D(); - } - - boolean hover = this.getSlotIndexFromScreenCoords(mouseXIn, mouseYIn) == z; - this.getListEntry(z).draw(x, y1, mouseXIn - x, mouseYIn - y1, hover); - if(hover) - Drawing.drawRect(x - 2, y1 - 2, this.getListWidth(), this.getSlotHeight(), Gui.HOVER_COLOR); - } - } - - protected void overlayBackground(int startY, int endY, int startAlpha, int endAlpha) - { - RenderBuffer rb = Tessellator.getBuffer(); - this.gm.getTextureManager().bindTexture(Gui.DIRT_BACKGROUND); - GlState.color(1.0F, 1.0F, 1.0F, 1.0F); - float f = 32.0F; - rb.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_TEX_COLOR); - rb.pos((double)0, (double)endY, 0.0D).tex(0.0D, (double)((float)endY / 32.0F)).color(64, 64, 64, endAlpha).endVertex(); - rb.pos((double)this.gm.fb_x, (double)endY, 0.0D).tex((double)((float)this.gm.fb_x / 32.0F), (double)((float)endY / 32.0F)).color(64, 64, 64, endAlpha).endVertex(); - rb.pos((double)this.gm.fb_x, (double)startY, 0.0D).tex((double)((float)this.gm.fb_x / 32.0F), (double)((float)startY / 32.0F)).color(64, 64, 64, startAlpha).endVertex(); - rb.pos((double)0, (double)startY, 0.0D).tex(0.0D, (double)((float)startY / 32.0F)).color(64, 64, 64, startAlpha).endVertex(); - Tessellator.draw(); - } - - public void mouse(Button btn, int x, int y, boolean ctrl, boolean shift) - { - super.mouse(btn, x, y, ctrl, shift); - if (this.isMouseYWithinSlotBounds(y)) - { - int i = this.getSlotIndexFromScreenCoords(x, y); - - if (i >= 0) - { - int j = this.left + this.width / 2 - this.getListWidth() / 2 + 2; - int k = this.top + 4 - this.getAmountScrolled() + i * this.getSlotHeight(); - int l = x - j; - int i1 = y - k; - - boolean flag = i == this.selectedElement && System.currentTimeMillis() - this.lastClicked < (long)this.gm.dclickDelay; - this.selectedElement = i; - this.lastClicked = System.currentTimeMillis(); - - this.getListEntry(i).select(flag, l, i1); - } - } - if(btn == Button.MOUSE_LEFT && this.clicked(x, y) == null) - this.handleMouseInput(); - } - - public void mouserel(Button btn, int x, int y) { - super.mouserel(btn, x, y); - if(btn == Button.MOUSE_LEFT) - this.initialClickY = -1; - } - - public void scroll(int scr_x, int scr_y, int x, int y, boolean ctrl, boolean shift) { - super.scroll(scr_x, scr_y, x, y, ctrl, shift); - if(scr_y != 0 && this.clicked(x, y) == null) - this.amountScrolled -= (float)(ExtMath.clampi(scr_y, -1, 1) * this.getSlotHeight() / 2); - } - - public void drag(int x, int y) { - super.drag(x, y); - if(this.selected == null && Button.MOUSE_LEFT.isDown()) - this.handleMouseInput(); - } -} diff --git a/java/src/game/gui/element/Label.java b/java/src/game/gui/element/Label.java deleted file mode 100644 index 7e2e85b..0000000 --- a/java/src/game/gui/element/Label.java +++ /dev/null @@ -1,33 +0,0 @@ -package game.gui.element; - -import game.renderer.Drawing; -import game.util.Util; - -public class Label extends Fill { - public Label(int x, int y, int w, int h, String text, boolean top, boolean left) { - super(x, y, w, h, text, top, left); - } - - public Label(int x, int y, int w, int h, String text, boolean left) { - super(x, y, w, h, text, left); - } - - public Label(int x, int y, int w, int h, String text) { - super(x, y, w, h, text); - } - - protected void drawBackground() { - } - - protected void drawForeground(int x1, int y1, int x2, int y2) { - Drawing.drawText(this.text, x1 + this.text_x, y1 + this.text_y, this.enabled ? this.gm.style.text_label : Util.mulColor(this.gm.style.text_label, 0.5f)); - } - - protected int getMarginX() { - return 0; - } - - protected int getMarginY() { - return 0; - } -} diff --git a/java/src/game/gui/element/ListEntry.java b/java/src/game/gui/element/ListEntry.java deleted file mode 100644 index 2d5d173..0000000 --- a/java/src/game/gui/element/ListEntry.java +++ /dev/null @@ -1,7 +0,0 @@ -package game.gui.element; - -public interface ListEntry -{ - void draw(int x, int y, int mouseX, int mouseY, boolean hovered); - void select(boolean dclick, int mx, int my); -} \ No newline at end of file diff --git a/java/src/game/gui/element/Textbox.java b/java/src/game/gui/element/Textbox.java deleted file mode 100644 index ae0f452..0000000 --- a/java/src/game/gui/element/Textbox.java +++ /dev/null @@ -1,514 +0,0 @@ -package game.gui.element; - -import org.lwjgl.opengl.GL11; - -import game.gui.Font; -import game.renderer.Drawing; -import game.renderer.Drawing.Offset; -import game.renderer.Drawing.Vec2i; -import game.util.CharValidator; -import game.util.ExtMath; -import game.util.Timing; -import game.util.Util; -import game.window.Button; -import game.window.Keysym; -import game.window.Window; - -public class Textbox extends Element { - public static enum Action { - FOCUS, UNFOCUS, PREVIOUS, NEXT, FUNCTION, SEND, LINE, FORWARD, BACKWARD; - } - - public static interface Callback { - void use(Textbox elem, Action value); - } - - private final Callback func; - private final CharValidator validator; - private final int capacity; - private final boolean xbreak; - private final boolean editable; - - private long tmr_scroll; - private long tmr_leftmb; - private int scrollx; - private int scrolly; - private int sel_start = -1; - private int sel_end = -1; - private int sel_drag = -1; - private int cursorX = 0; - private int cursorY = 0; - private int tsize_x = 0; - private int tsize_y = 0; - - private Textbox(int x, int y, int w, int h, int cap, boolean line, boolean editable, Callback callback, CharValidator validator, String text) { - super(x, y, w, h, null); - this.func = callback; - this.validator = validator; - this.capacity = cap; - this.xbreak = !line; - this.editable = editable; - if(line) - this.text_y = (this.size_y - (this.margin_y1 + this.margin_y2 + Font.YGLYPH)) / 2; - this.setText(text); - } - - public Textbox(int x, int y, int w, int h, int cap, boolean line, Callback callback, String text) { - this(x, y, w, h, cap, line, true, callback, null, text); - } - - public Textbox(int x, int y, int w, int h, int cap, boolean line, Callback callback, CharValidator validator, String text) { - this(x, y, w, h, cap, line, true, callback, validator, text); - } - - public Textbox(int x, int y, int w, int h, int cap, Callback callback, String text) { - this(x, y, w, h, cap, false, true, callback, null, text); - } - - public Textbox(int x, int y, int w, int h, String text) { - this(x, y, w, h, Integer.MAX_VALUE, false, false, null, null, text); - } - - public Textbox(int x, int y, int w, int h, boolean line, String text) { - this(x, y, w, h, Integer.MAX_VALUE, line, false, null, null, text); - } - -// public void setEditable(boolean editable) { -// this.editable = editable; -// } - -// protected boolean isTextCenteredX() { -// return false; -// } -// -// protected boolean isTextCenteredY() { -// return false; -// } - -// protected boolean hasLinebreak() { -// return this.xbreak; -// } - - public void updateText() { - Vec2i size = Drawing.txt_size(this.pos_x + this.margin_x1, this.pos_y + this.margin_y1, - this.pos_x + this.margin_x1, this.pos_y + this.margin_y1, - this.xbreak ? (this.pos_x + (this.size_x - (this.margin_x1 + this.margin_x2))) : Integer.MAX_VALUE, Integer.MAX_VALUE, this.text); - this.tsize_x = size.xpos; - this.tsize_y = size.ypos; - } - - public boolean canHover() { - return false; - } - - protected int getMarginX() { - return 4; - } - - public void setText(String str) { - if(this.validator != null) - str = this.validator.filter(str); - this.text = str.length() > this.capacity ? str.substring(0, this.capacity) : str; - this.updateText(); - this.sel_start = this.sel_end = this.sel_drag = this.text.length(); - gui_text_update_cur(this.sel_start, true); - } - - public void scroll(int scr_x, int scr_y, int x, int y, boolean ctrl, boolean shift) { - if(scr_y != 0 && this.xbreak) { - int limit = Font.YGLYPH + this.tsize_y - (this.size_y - (this.margin_y1 + this.margin_y2)); - limit = ExtMath.clampi(limit, 0, 0x7fffffff); - int prev = this.text_y; - this.text_y += (scr_y < 0 ? -1 : 1) * (ctrl ? 1 : Font.YGLYPH) * this.gm.scrollLines * (shift ? 10 : 1); - this.text_y = ExtMath.clampi(this.text_y, -limit, 0); - if(this.sel_start >= 0) - this.cursorY += (this.text_y - prev); -// this.r_dirty = true; - } - else if(scr_y != 0 || scr_x != 0) { - int limit = Font.XGLYPH + this.tsize_x - (this.size_x - (this.margin_x1 + this.margin_x2)); - limit = ExtMath.clampi(limit, 0, 0x7fffffff); - int prev = this.text_x; - this.text_x += ((scr_y != 0 ? scr_y : (-scr_x)) < 0 ? -1 : 1) * (ctrl ? 1 : Font.XGLYPH) * this.gm.scrollLines * (shift ? 10 : 1); - this.text_x = ExtMath.clampi(this.text_x, -limit, 0); - if(this.sel_start >= 0) - this.cursorX += (this.text_x - prev); -// this.r_dirty = true; - } - } - - public void mouse(Button btn, int x, int y, boolean ctrl, boolean shift) { - if(btn == Button.MOUSE_LEFT) { - if(!shift && ((Timing.tmr_current - this.tmr_leftmb) <= (((long)this.gm.dclickDelay) * 1000L))) { - this.sel_start = this.sel_drag = 0; - this.sel_end = this.text.length(); -// this.r_dirty = true; - } - else { - gui_text_select(x, y, shift); - } - this.tmr_leftmb = Timing.tmr_current; - } - else if((btn == Button.MOUSE_MIDDLE) && this.func != null) { - this.func.use(this, Action.FUNCTION); - } - } - - public void mouserel() { - this.scrollx = this.scrolly = 0; - } - - public void drag(int x, int y) { - gui_text_select(x, y, true); - } - - public void character(char code) { - if(this.editable) { -// int pos = 0; -// char chr[8]; -// utf_rwriten(chr, &pos, 8, code); -// chr[pos] = 0; - insertText(Character.toString(code)); - } - } - - public void key(Keysym key, boolean ctrl, boolean shift) { - if(ctrl && key == Keysym.A) { - this.sel_start = this.sel_drag = 0; - this.sel_end = this.text.length(); -// this.r_dirty = true; - } - else if(ctrl && (key == Keysym.C) || (this.editable && (key == Keysym.X))) { - if(this.sel_start >= 0 && this.sel_start != this.sel_end) { // fix empty - // char end = this.text[this.sel_end]; - // this.text[this.sel_end] = 0; - String str = Util.strip(this.text, this.sel_start, this.sel_end - this.sel_start, '\n', (char)0, '?'); - Window.setClipboard(str); - // this.text[this.sel_end] = end; - if(key == Keysym.X) - insertText(""); - } - } - else if(this.editable && ctrl && key == Keysym.V) { - insertText(Window.getClipboard()); - } - else if(this.editable && !ctrl && key == Keysym.RETURN) { - if(this.xbreak) { - insertText("\n"); - } - else if(this.func != null) { - this.func.use(this, shift ? Action.LINE : Action.SEND); - } - } - else if(this.editable && (!ctrl) && (key == Keysym.BACKSPACE || key == Keysym.DELETE)) { - if(this.sel_start != this.sel_end) { - insertText(""); - } - else if(key == Keysym.DELETE && this.sel_start >= 0) { - if(this.sel_end < this.text.length()) { - this.sel_end += 1; - insertText(""); - } - else { - this.sel_end = this.sel_start; - } - } - else if(key == Keysym.BACKSPACE && this.sel_start > 0) { - this.sel_start -= 1; - insertText(""); - } - } - else if(!ctrl && (key == Keysym.RIGHT || key == Keysym.LEFT)) { - if(key == Keysym.RIGHT && this.sel_start != this.sel_end) { - this.sel_start = this.sel_drag = this.sel_end; - } - else if(key == Keysym.LEFT && this.sel_start != this.sel_end) { - this.sel_end = this.sel_drag = this.sel_start; - } - if(key == Keysym.RIGHT && this.sel_start >= 0) { - if(this.sel_end < this.text.length()) { - this.sel_start = this.sel_drag = this.sel_end += 1; - } - else { - this.sel_end = this.sel_drag = this.sel_start; - } - gui_text_update_cur(this.sel_end, true); - } - else if(key == Keysym.LEFT && this.sel_start >= 0) { - if(this.sel_start > 0) - this.sel_start -= 1; - this.sel_end = this.sel_drag = this.sel_start; - gui_text_update_cur(this.sel_end, true); - } - } - else if(!ctrl && (key == Keysym.DOWN || key == Keysym.UP)) { - if(this.xbreak) { - if(key == Keysym.DOWN && this.sel_start != this.sel_end) { - this.sel_start = this.sel_drag = this.sel_end; - } - else if(key == Keysym.UP && this.sel_start != this.sel_end) { - this.sel_end = this.sel_drag = this.sel_start; - } - if(key == Keysym.DOWN && this.sel_start >= 0) { - if(this.sel_end < this.text.length()) { - // char ch = this.text.charAt(this.sel_end); - // this.sel_end += 1; - int nl = this.text.indexOf('\n', this.sel_end); - // while(ch && ch != '\n') { - // ch = utf_readn(this.text, &this.sel_end); - // } - this.sel_end = nl >= 0 ? nl + 1 : this.text.length(); - // else - // this.sel_end -= 1; - this.sel_start = this.sel_drag = this.sel_end; - } - else { - this.sel_end = this.sel_drag = this.sel_start; - } - gui_text_update_cur(this.sel_end, true); - } - else if(key == Keysym.UP && this.sel_start >= 0) { - // uint ch; - if(this.sel_start > 0) { - int nl = this.text.lastIndexOf('\n', this.sel_start); - this.sel_start = nl >= 0 ? nl : 0; - // do { - // ch = utf_rreadn(this.text, &this.sel_start); - // } - // while(ch && ch != '\n'); - } - this.sel_end = this.sel_drag = this.sel_start; - gui_text_update_cur(this.sel_end, true); - } - } - else if(this.func != null) { - this.func.use(this, (key == Keysym.DOWN) ? Action.NEXT : Action.PREVIOUS); - } - } - else if((!ctrl) && key == Keysym.TAB) { - if(this.func != null) { - this.func.use(this, shift ? Action.BACKWARD : Action.FORWARD); - } - } - } - - public void select() { - if(this.func != null) { - this.func.use(this, Action.FOCUS); - } - } - - public void deselect() { - this.sel_start = this.sel_end = this.sel_drag = -1; - this.tmr_leftmb = 0L; -// this.r_dirty = true; - if(this.func != null) { - this.func.use(this, Action.UNFOCUS); - } - } - - public void update() { - if((this.scrollx != 0 && !(this.xbreak)) || (this.scrolly != 0 && this.xbreak)) { - int n; - if(!this.xbreak) - this.text_x += (n = (int)((float)((float)this.tmr_scroll) / 1000000.0f * 4.0f * ((float)this.scrollx))); - else - this.text_y += (n = (int)((float)((float)this.tmr_scroll) / 1000000.0f * 4.0f * ((float)this.scrolly))); - if(n != 0) { - gui_text_clamp_scroll(); -// this.r_dirty = true; - } - if((((long)n) * 1000000L) <= this.tmr_scroll) - this.tmr_scroll -= ((long)n) * 1000000L; - else - this.tmr_scroll = 0L; - this.tmr_scroll += Timing.tmr_delta; - } - } - - public void shift(int shift_x, int shift_y) { - super.shift(shift_x, shift_y); - this.cursorX += shift_x; - this.cursorY += shift_y; - } - - private void gui_text_clamp_scroll() { - int limit; - if(this.xbreak) { - limit = Font.YGLYPH + this.tsize_y - (this.size_y - (this.margin_y1 + this.margin_y2)); - limit = ExtMath.clampi(limit, 0, 0x7fffffff); - this.text_y = ExtMath.clampi(this.text_y, -limit, 0); - } - else { - limit = Font.XGLYPH + this.tsize_x - (this.size_x - (this.margin_x1 + this.margin_x2)); - limit = ExtMath.clampi(limit, 0, 0x7fffffff); - this.text_x = ExtMath.clampi(this.text_x, -limit, 0); - } - } - - private void gui_text_update_cur(int offset, boolean shift) { - int x1 = this.pos_x + this.margin_x1; - int y1 = this.pos_y + this.margin_y1; - int x2 = this.size_x - (this.margin_x1 + this.margin_x2); - int y2 = this.size_y - (this.margin_y1 + this.margin_y2); - gui_text_clamp_scroll(); - Vec2i coord = Drawing.txt_coord(offset, x1 + (this.xbreak ? 0 : this.text_x), y1 + this.text_y, - x1 + this.text_x, y1 + this.text_y, this.xbreak ? (this.pos_x + x2) : 0x7fffffff, 0x7fffffff, this.text); - this.cursorX = coord.xpos; - this.cursorY = coord.ypos; - if(shift) { - if(this.xbreak && this.cursorY < y1) - this.text_y += y1 - this.cursorY; - else if(this.xbreak && (this.cursorY + Font.YGLYPH) >= (y1 + y2)) - this.text_y -= (this.cursorY + Font.YGLYPH) - (y1 + y2); - if(!(this.xbreak) && this.cursorX < x1) - this.text_x += x1 - this.cursorX; - else if(!(this.xbreak) && (this.cursorX + Font.XGLYPH) >= (x1 + x2)) - this.text_x -= (this.cursorX + Font.XGLYPH) - (x1 + x2); - gui_text_update_cur(offset, false); - } -// else { -// this.r_dirty = true; -// } - } - - public void insertText(String str) { - if(str == null || (this.sel_start == -1)) - return; - str = Util.strip(str, 0, str.length(), this.xbreak ? '\n' : ' ', ' ', (char)0); - if(this.validator != null) - str = this.validator.filter(str); - // plen = strlen(&sys.work_buf[1 + olen - this.sel_end]); - // logd("t", "%d %d %d", olen, slen, plen); - if((str.length() + this.text.length() - (this.sel_end - this.sel_start)) > this.capacity) - return; - this.text = this.text.substring(0, this.sel_start) + str + this.text.substring(this.sel_end); - // memcpy(sys.work_buf, &this.text[this.sel_end], 1 + this.text.length() - this.sel_end); - // memcpy(&this.text[this.sel_start], &sys.work_buf[1 + this.text.length() - this.sel_end], str.length()); - // memcpy(&this.text[this.sel_start + str.length()], sys.work_buf, 1 + this.text.length() - this.sel_end); - this.sel_start += str.length(); - this.sel_end = this.sel_drag = this.sel_start; - this.updateText(); - gui_text_update_cur(this.sel_end, true); - } - - private void gui_text_select(int x, int y, boolean drag) { - int x1 = this.pos_x + this.margin_x1; - int y1 = this.pos_y + this.margin_y1; - int x2 = this.size_x - (this.margin_x1 + this.margin_x2); - int y2 = this.size_y - (this.margin_y1 + this.margin_y2); - Offset off = Drawing.txt_offset(x, y, x1 + (this.xbreak ? 0 : this.text_x), y1 + this.text_y, - x1 + this.text_x, y1 + this.text_y, this.xbreak ? (this.pos_x + x2) : 0x7fffffff, 0x7fffffff, this.text); - if(off != null) { - this.cursorX = off.xpos; - this.cursorY = off.ypos; - } - int offset = off == null ? 0 : off.offset; - // logd("tst", "@A %d %d -. %d %d", x1, y1, x2, y2); - // logd("tst", "@C %d %d -. %d, %d %d", x, y, offset, this.min, this.max); - if(!drag) { - this.sel_drag = this.sel_start = this.sel_end = offset; - } - else if(drag && this.sel_drag >= 0 && offset >= this.sel_drag) { - this.sel_start = this.sel_drag; - this.sel_end = offset; - } - else if(drag && this.sel_drag >= 0 && offset < this.sel_drag) { - this.sel_start = offset; - this.sel_end = this.sel_drag; - } - // logd("tst", "@S %d . %d . %d", this.sel_start, this.sel_drag, this.sel_end); -// this.r_dirty = true; - if(x < x1) - this.scrollx = x1 - x; - else if(x >= (x1 + x2)) - this.scrollx = -(x - (x1 + x2)); - if(y < y1) - this.scrolly = y1 - y; - else if(y >= (y1 + y2)) - this.scrolly = -(y - (y1 + y2)); - } - - protected void drawBackground() { - if(this.enabled) - Drawing.drawGradientBorder(this.pos_x, this.pos_y, this.size_x, this.size_y, this.gm.style.field_top, this.gm.style.field_btm, 0xff000000, this.gm.style.brdr_top, this.gm.style.brdr_btm); - else - Drawing.drawGradientBorder(this.pos_x, this.pos_y, this.size_x, this.size_y, Util.mulColor(this.gm.style.field_top, 0.5f), Util.mulColor(this.gm.style.field_btm, 0.5f), 0xff000000, Util.mulColor(this.gm.style.brdr_top, 0.5f), Util.mulColor(this.gm.style.brdr_btm, 0.5f)); - } - - protected void drawForeground(int x1, int y1, int x2, int y2) { - Drawing.txt_draw(x1 + (this.xbreak ? 0 : this.text_x), y1 + this.text_y, - x1 + this.text_x, y1 + this.text_y, - this.xbreak ? (this.pos_x + x2) : Integer.MAX_VALUE, Integer.MAX_VALUE, this.enabled ? this.gm.style.text_field : Util.mulColor(this.gm.style.text_field, 0.5f), this.text); - if(this.sel_start >= 0 && this.sel_end != this.sel_start) - Drawing.txt_overlay(this.sel_start, this.sel_end, x1 + (this.xbreak ? 0 : this.text_x), y1 + this.text_y, - x1 + this.text_x, y1 + this.text_y, - this.xbreak ? (this.pos_x + x2) : Integer.MAX_VALUE, Integer.MAX_VALUE, this.enabled ? 0x808080ff : 0x80404040, this.text); - } - - public void drawOverlay() { - if(this.editable && this.sel_start >= 0 && this.sel_end == this.sel_start && Util.ftime() % 1.0f < 0.5f) { - int x1 = this.pos_x + this.margin_x1; - int y1 = this.pos_y + this.margin_y1; - int x2 = this.size_x - (this.margin_x1 + this.margin_x2); - int y2 = this.size_y - (this.margin_y1 + this.margin_y2); - GL11.glScissor(x1 < 0 ? 0 : x1, (this.gm.fb_y - (y1 + y2)) < 0 ? 0 : (this.gm.fb_y - (y1 + y2)), x2 < 0 ? 0 : x2, y2 < 0 ? 0 : y2); - GL11.glEnable(GL11.GL_SCISSOR_TEST); - Drawing.drawRect(this.cursorX, this.cursorY, 1, Font.YGLYPH, 0xff000000 | (~Util.mixColor(this.gm.style.field_top, this.gm.style.field_btm))); - GL11.glDisable(GL11.GL_SCISSOR_TEST); - } - } - - - - - - - - - - public void deleteFromCursor() { - int num = this.getNthCharFromPos() - this.sel_start; - if(this.text.length() != 0) { - if(this.sel_start != this.sel_end) { - this.insertText(""); - } - else { -// boolean flag = num < 0; - int i = this.sel_start + num; // flag ? this.sel_start + num : this.sel_start; - int j = this.sel_start; // flag ? this.sel_start : this.sel_start + num; - String s = ""; - - if(i >= 0) { - s = this.text.substring(0, i); - } - - if(j < this.text.length()) { - s = s + this.text.substring(j); - } - -// this.setText(s); - this.text = s; - this.updateText(); - this.sel_start = this.sel_end = this.sel_drag = i; - gui_text_update_cur(this.sel_start, true); -// -// if(flag) { -// this.moveCursorBy(num); -// } - } - } - } - - public int getNthCharFromPos() { - int i = this.sel_start; - while(i > 0 && this.text.charAt(i - 1) != ' ') { - --i; - } - return i; - } - - public int getCursorPosition() { - return this.sel_start == this.sel_end ? this.sel_start : -1; - } -} diff --git a/java/src/game/gui/ingame/GuiGameOver.java b/java/src/game/gui/ingame/GuiGameOver.java deleted file mode 100755 index 780bd41..0000000 --- a/java/src/game/gui/ingame/GuiGameOver.java +++ /dev/null @@ -1,40 +0,0 @@ -package game.gui.ingame; - -import game.color.TextColor; -import game.gui.Gui; -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; -import game.gui.element.Label; - -public class GuiGameOver extends Gui { - public static final GuiGameOver INSTANCE = new GuiGameOver(); - - private ActButton button; - private int timer; - - private GuiGameOver() { - } - - public void init(int width, int height) { - this.timer = 0; - this.add(new Label(0, 0, 200, 20, "Du bist gestorben!")); - this.add(new Label(0, 32, 200, 20, "Punktestand: " + TextColor.YELLOW + this.gm.thePlayer.experienceLevel)); - this.button = this.add(new ActButton(0, 100, 200, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { - GuiGameOver.this.gm.thePlayer.respawnPlayer(); - GuiGameOver.this.gm.displayGuiScreen(null); - } - }, "Wiederbeleben")); - this.shift(); - this.button.enabled = false; - } - - public String getTitle() { - return "Game over"; - } - - public void updateScreen() { - if(++this.timer >= 20) - this.button.enabled = true; - } -} diff --git a/java/src/game/gui/ingame/GuiSign.java b/java/src/game/gui/ingame/GuiSign.java deleted file mode 100644 index a04af2f..0000000 --- a/java/src/game/gui/ingame/GuiSign.java +++ /dev/null @@ -1,49 +0,0 @@ -package game.gui.ingame; - -import game.gui.Gui; -import game.gui.element.NavButton; -import game.gui.element.Textbox; -import game.gui.element.Textbox.Action; -import game.network.ClientPlayer; -import game.packet.CPacketSign; -import game.world.BlockPos; - -public class GuiSign extends Gui implements Textbox.Callback { - private final BlockPos position; - private final Textbox[] lines = new Textbox[4]; - private final String[] tempLines = new String[this.lines.length]; - - - public void init(int width, int height) { - for(int z = 0; z < this.lines.length; z++) { - this.lines[z] = this.add(new Textbox(0, 40 * z, 300, 24, 50, true, this, this.tempLines[z] == null ? "" : this.tempLines[z])); - } - this.add(new NavButton(0, 40 * (this.lines.length + 1), 300, 24, null, "Fertig")); - this.shift(); - } - - public String getTitle() { - return "Schild bearbeiten"; - } - - - public void onGuiClosed() { - ClientPlayer nethandler = this.gm.getNetHandler(); - if(nethandler != null) { - for(int z = 0; z < this.lines.length; z++) { - this.tempLines[z] = this.lines[z].getText(); - } - nethandler.addToSendQueue(new CPacketSign(this.position, this.tempLines)); - } - } - - public GuiSign(BlockPos sign, String[] lines) { - this.position = sign; - System.arraycopy(lines, 0, this.tempLines, 0, this.lines.length); - } - - public void use(Textbox elem, Action value) { - if(value == Action.SEND) - this.gm.displayGuiScreen(null); - } -} diff --git a/java/src/game/gui/options/GuiDisplay.java b/java/src/game/gui/options/GuiDisplay.java deleted file mode 100644 index cfda61a..0000000 --- a/java/src/game/gui/options/GuiDisplay.java +++ /dev/null @@ -1,103 +0,0 @@ -package game.gui.options; - -import game.color.TextColor; -import game.gui.element.Dropdown; -import game.gui.element.Element; -import game.gui.element.Fill; -import game.gui.element.Slider; -import game.gui.element.Toggle; -import game.util.Formatter; -import game.window.Button; -import game.window.DisplayMode; -import game.window.Window; - -public class GuiDisplay extends GuiOptions { - private static final String[] DISTANCES = new String[] {"Gruselig", "Winzig", "Gering", "Normal", "Weit"}; - - private Element distanceSlider; - - protected GuiDisplay() { - } - - public void init(int width, int height) { - DisplayMode[] dmodes = Window.getDisplayModes(); - if(dmodes != null && dmodes.length > 0) { - int offset = 0; - int pos = 0; - int num = dmodes.length; - if(dmodes.length > DisplayMode.VID_MODES) { - offset = dmodes.length - DisplayMode.VID_MODES; - num = DisplayMode.VID_MODES; - } - DisplayMode[] modes = new DisplayMode[num]; - DisplayMode selected = dmodes[num + offset - 1]; - for(int z = 0; z < num; z++) { - modes[z] = dmodes[z + offset]; - if(modes[z].equals(this.gm.vidMode)) - selected = modes[z]; - } - this.add(new Dropdown(30, 80, 440, 24, false, modes, modes[modes.length - 1], selected, new Dropdown.Callback() { - public void use(Dropdown elem, DisplayMode value) { - GuiDisplay.this.gm.vidMode = value; - GuiDisplay.this.gm.full(true); - } - }, "Auflösung")); - } - else { - this.add(new Fill(30, 80, 440, 24, TextColor.RED + "Auflösung: ")); - } - - this.add(new Toggle(490, 80, 440, 24, false, GuiDisplay.this.gm.fullscreen, new Toggle.Callback() { - public void use(Toggle elem, boolean value) { - GuiDisplay.this.gm.full(value); - } - }, "Vollbild")); - this.add(new Slider(30, 120, 440, 24, 0, 0, 360 - 8, 0, (this.gm.sync < 0) ? (360 - 8) : (this.gm.sync != 0 ? ((this.gm.sync < 10) ? 1 : (this.gm.sync - 9)) : 0), new Slider.Callback() { - public void use(Slider elem, int value) { - GuiDisplay.this.gm.getVar("win_sync").parse("" + ((value > 0 && value < 360 - 8) ? (value + 9) : (value != 0 ? -1 : 0))); - GuiDisplay.this.gm.setDirty(); - } - }, new Formatter() { - public String use(Slider elem) { - int value = elem.getValue(); - return "Max. Bildrate: " + (value > 0 && value < (360 - 8) ? (value + 9) + " FPS" : (value != 0 ? "Unbegrenzt" : "VSync")); - } - })); - this.addSelector("gl_vsync_flush", 490, 120, 440, 24); - - this.addSelector("overlay_enabled", 30, 200, 440, 24); - this.addSelector("overlay_opacity", 490, 200, 440, 24); - - this.addSelector("overlay_fadeout", 30, 240, 440, 24); - this.addSelector("chat_permanent", 490, 240, 440, 24); - - this.addSelector("console_size", 30, 280, 440, 24); - this.addSelector("chat_size", 490, 280, 440, 24); - - this.addSelector("feed_size", 30, 320, 440, 24); - this.addSelector("hotbar_size", 490, 320, 440, 24); - - this.addSelector("gl_fov", 30, 400, 440, 24); - this.distanceSlider = this.addSelector("chunk_view_distance", 30, 440, 440, 24); - this.addSelector("chunk_build_time", 490, 440, 440, 24); - super.init(width, height); - } - - public String getTitle() { - return "Grafik und Anzeige"; - } - - private String getDistanceName() { - int distance = this.gm.renderDistance; - distance = distance > 16 ? 16 : distance; - String str = distance < 0 ? DISTANCES[0] : DISTANCES[(distance + 1) / 4]; - if(distance > 2 && (((distance + 1) / 2) & 1) == 1) - str = str + "+"; - return String.format("Sichtweite: %d Chunks [%d Blöcke, %s]", this.gm.renderDistance, this.gm.renderDistance * 16, str); - } - - public void updateScreen() { - if(!Button.isMouseDown()) - this.distanceSlider.setText(this.getDistanceName()); - } -} diff --git a/java/src/game/gui/options/GuiOptions.java b/java/src/game/gui/options/GuiOptions.java deleted file mode 100644 index e50ed60..0000000 --- a/java/src/game/gui/options/GuiOptions.java +++ /dev/null @@ -1,31 +0,0 @@ -package game.gui.options; - -import game.gui.Gui; -import game.gui.GuiMenu; -import game.gui.element.NavButton; - -public abstract class GuiOptions extends Gui { - private static final GuiOptions[] PAGES = {lastPage = new GuiBinds(), new GuiStyle(), new GuiDisplay(), new GuiSound()}; - - private static GuiOptions lastPage; - - public static GuiOptions getPage() { - return lastPage; - } - - public void init(int width, int height) { - lastPage = this; - this.shift(); - int x = 0; - int y = 0; - for(GuiOptions gui : PAGES) { - this.add( // gui == this ? new SelectedButton(240 * x, 24 * y, 240, 24, gui, gui.getTitle()) : - new NavButton(240 * x, 24 * y, 240, 24, gui, gui.getTitle())); - if(++x == 4) { - x = 0; - ++y; - } - } - this.add(new NavButton(width - 240, 0, 240, 24, GuiMenu.INSTANCE, "Zurück")); - } -} diff --git a/java/src/game/gui/options/GuiSound.java b/java/src/game/gui/options/GuiSound.java deleted file mode 100644 index 4fb64210..0000000 --- a/java/src/game/gui/options/GuiSound.java +++ /dev/null @@ -1,37 +0,0 @@ -package game.gui.options; - -import game.audio.Volume; -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; - -public class GuiSound extends GuiOptions { - protected GuiSound() { - } - - public void init(int width, int height) { - this.addSelector("snd_enabled", 30, 380, 440, 24); - - this.addSelector("snd_buffer_size", 30, 420, 440, 24); - this.addSelector("snd_frame_size", 490, 420, 440, 24); - - this.add(new ActButton(30, 480, 900, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { - GuiSound.this.gm.restartSound(false); - } - }, "Übernehmen und Audio-Thread neu starten")); - - int x = 30; - int y = 220; - for(Volume volume : Volume.values()) { - this.addSelector(volume.getCVarName(), x, y, 440, 24); - x = (x == 30) ? 490 : 30; - if(x == 30) - y += 40; - } - super.init(width, height); - } - - public String getTitle() { - return "Audio und Ton"; - } -} diff --git a/java/src/game/gui/options/GuiStyle.java b/java/src/game/gui/options/GuiStyle.java deleted file mode 100644 index ecba7e0..0000000 --- a/java/src/game/gui/options/GuiStyle.java +++ /dev/null @@ -1,123 +0,0 @@ -package game.gui.options; - -import game.gui.Style; -import game.gui.element.ActButton; -import game.gui.element.ActButton.Mode; -import game.gui.element.Dropdown; -import game.gui.element.Element; -import game.gui.element.SelectableButton; -import game.gui.element.Slider; -import game.gui.element.Switch; -import game.gui.element.Textbox; -import game.gui.element.Textbox.Action; -import game.gui.element.Toggle; -import game.vars.CVar; -import game.vars.ColorVar; - -public class GuiStyle extends GuiOptions implements Dropdown.Callback, ActButton.Callback, Toggle.Callback, Switch.Callback, Slider.Callback, Textbox.Callback { - private static final String[] STYLE_CVARS = { - "color_button_top", - "color_textbox_top", - "color_border_top", - - "color_button_btm", - "color_textbox_btm", - "color_border_btm", - - "color_button_text", - "color_textbox_text", - "color_label_text" - }; - - protected GuiStyle() { - } - - protected Element addSelector(String cvar, int x, int y, int w, int h) { - CVar cv = this.gm.getVar(cvar); - if(cv instanceof ColorVar) { - ColorVar color = (ColorVar)cv; - if(!color.getDisplay().isEmpty()) - this.add(color.label(x, y - 20, w, 20)); - if(this.gm.style != Style.CUSTOM) - return this.add(new Textbox(x, y, w, h, true, color.getFieldValue(this.gm.style))); - else - return this.add(color.editor(x, y, w, h)); - } - return super.addSelector(cvar, x, y, w, h); - } - - public void init(int width, int height) { - int z; - for(z = 0; z < STYLE_CVARS.length; z++) { - this.addSelector(STYLE_CVARS[z], 10 + ((z % 3) + 1) * 190, 100 + z / 3 * 50, 180, 24); - } - z = 0; - for(Style theme : Style.values()) { - ActButton.Callback callback = new ActButton.Callback() { - public void use(ActButton elem, Mode action) { - if(GuiStyle.this.gm.style != theme) { - GuiStyle.this.gm.style = theme; - GuiStyle.this.gm.setDirty(); - GuiStyle.this.gm.displayGuiScreen(GuiStyle.this); - } - } - }; - this.add( // theme == this.gm.style ? new SelectedButton(10 + (z % 3) * 320, 360 + (z / 3) * 40, 300, 24, callback, theme.name) : - new SelectableButton(10 + (z % 3) * 320, 360 + (z / 3) * 40, 300, 24, callback, theme.name, theme == this.gm.style)); - z++; - } - - String[] values = new String[] {"VALUE 1", "VALUE 2"}; - this.add(new Dropdown(10, height - 74, 300, 24, false, values, values[1], values[0], this, "DROPDOWN")); - this.add(new ActButton(330, height - 74, 300, 24, this, "BUTTON")); - this.add(new Toggle(650, height - 74, 140, 24, false, true, this, "TOGGLE")); - this.add(new Toggle(810, height - 74, 140, 24, true, false, this, "TOGGLE")); - values = new String[] {"VALUE 1", "VALUE 2", "VALUE 3", "VALUE 4"}; - this.add(new Switch(10, height - 34, 300, 24, values, values[2], values[0], this, "ENUM")); - this.add(new Slider(330, height - 34, 300, 24, 0, -20, 827, 60, 120, this, "SLIDER")); - this.add(new Textbox(650, height - 34, 300, 24, 128, true, this, "FIELD")); - - if(this.gm.style != Style.CUSTOM) { - this.add(new ActButton(200, 100 + 3 * 50, 560, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { - if(GuiStyle.this.gm.style != Style.CUSTOM) { - GuiStyle.this.gm.style.copyToCustom(); - GuiStyle.this.gm.style = Style.CUSTOM; - GuiStyle.this.gm.setDirty(); - GuiStyle.this.gm.displayGuiScreen(GuiStyle.this); - } - } - }, "In angepasstes Design kopieren")); - } - else { - this.add(new ActButton(200, 100 + 3 * 50, 560, 24, new ActButton.Callback() { - public void use(ActButton elem, Mode action) { - GuiStyle.this.gm.style = Style.CUSTOM; - for(String cvar : STYLE_CVARS) { - GuiStyle.this.gm.getVar(cvar).setDefault(); - } - GuiStyle.this.gm.setDirty(); - GuiStyle.this.gm.displayGuiScreen(GuiStyle.this); - } - }, "Angepasstes Design zurücksetzen")); - } - super.init(width, height); - } - - public String getTitle() { - return "Benutzeroberfläche"; - } - - public void use(Textbox elem, Action value) { - } - public void use(Slider elem, int value) { - } - public void use(Switch elem, String value) { - } - public void use(Toggle elem, boolean value) { - } - public void use(ActButton elem, Mode action) { - } - public void use(Dropdown elem, String value) { - } -} diff --git a/java/src/game/init/Blocks.java b/java/src/game/init/Blocks.java deleted file mode 100755 index adf4bff..0000000 --- a/java/src/game/init/Blocks.java +++ /dev/null @@ -1,360 +0,0 @@ -package game.init; - -import game.block.Block; -import game.block.BlockBeacon; -import game.block.BlockBed; -import game.block.BlockBlackenedSoil; -import game.block.BlockBush; -import game.block.BlockCactus; -import game.block.BlockCauldron; -import game.block.BlockChest; -import game.block.BlockDaylightDetector; -import game.block.BlockDeadBush; -import game.block.BlockDoublePlant; -import game.block.BlockDryLeaves; -import game.block.BlockDynamicLiquid; -import game.block.BlockFire; -import game.block.BlockFlower; -import game.block.BlockGrass; -import game.block.BlockHopper; -import game.block.BlockLeaves; -import game.block.BlockMycelium; -import game.block.BlockOre; -import game.block.BlockPistonBase; -import game.block.BlockPistonHead; -import game.block.BlockPistonMoving; -import game.block.BlockPortal; -import game.block.BlockRedstoneComparator; -import game.block.BlockRedstoneRepeater; -import game.block.BlockRedstoneWire; -import game.block.BlockReed; -import game.block.BlockSand; -import game.block.BlockSkull; -import game.block.BlockSlab; -import game.block.BlockStainedGlass; -import game.block.BlockStainedGlassPane; -import game.block.BlockStaticLiquid; -import game.block.BlockTallGrass; -import game.block.BlockTianReactor; -import game.block.BlockTripWireHook; - - -public abstract class Blocks { - public static final Block air = get("air"); - public static final Block stone = get("stone"); - public static final Block blackened_stone = get("blackened_stone"); - public static final BlockGrass grass = (BlockGrass)get("grass"); - public static final BlockBlackenedSoil blackened_soil = (BlockBlackenedSoil)get("blackened_soil"); - public static final Block dirt = get("dirt"); - public static final Block blackened_dirt = get("blackened_dirt"); - public static final Block cobblestone = get("cobblestone"); - public static final Block blackened_cobble = get("blackened_cobble"); - public static final Block oak_planks = get("oak_planks"); - public static final Block spruce_planks = get("spruce_planks"); - public static final Block birch_planks = get("birch_planks"); - public static final Block maple_planks = get("maple_planks"); - public static final Block jungle_planks = get("jungle_planks"); - public static final Block acacia_planks = get("acacia_planks"); - public static final Block dark_oak_planks = get("dark_oak_planks"); - public static final Block cherry_planks = get("cherry_planks"); - public static final Block oak_sapling = get("oak_sapling"); - public static final Block spruce_sapling = get("spruce_sapling"); - public static final Block birch_sapling = get("birch_sapling"); - public static final Block jungle_sapling = get("jungle_sapling"); - public static final Block acacia_sapling = get("acacia_sapling"); - public static final Block dark_oak_sapling = get("dark_oak_sapling"); - public static final Block cherry_sapling = get("cherry_sapling"); - public static final Block maple_sapling = get("maple_sapling"); - public static final Block bedrock = get("bedrock"); - public static final BlockDynamicLiquid flowing_water = (BlockDynamicLiquid)get("flowing_water"); - public static final BlockStaticLiquid water = (BlockStaticLiquid)get("water"); - public static final BlockDynamicLiquid flowing_lava = (BlockDynamicLiquid)get("flowing_lava"); - public static final BlockStaticLiquid lava = (BlockStaticLiquid)get("lava"); - public static final BlockDynamicLiquid flowing_goo = (BlockDynamicLiquid)get("flowing_goo"); - public static final BlockStaticLiquid goo = (BlockStaticLiquid)get("goo"); - public static final BlockSand sand = (BlockSand)get("sand"); - public static final Block gravel = get("gravel"); - public static final BlockOre gold_ore = (BlockOre)get("gold_ore"); - public static final BlockOre iron_ore = (BlockOre)get("iron_ore"); - public static final BlockOre coal_ore = (BlockOre)get("coal_ore"); - public static final BlockOre lead_ore = (BlockOre)get("lead_ore"); - public static final BlockOre copper_ore = (BlockOre)get("copper_ore"); - public static final Block oak_log = get("oak_log"); - public static final Block spruce_log = get("spruce_log"); - public static final Block birch_log = get("birch_log"); - public static final Block jungle_log = get("jungle_log"); - public static final Block acacia_log = get("acacia_log"); - public static final Block dark_oak_log = get("dark_oak_log"); - public static final Block cherry_log = get("cherry_log"); - public static final Block maple_log = get("maple_log"); - public static final Block tian_log = get("tian_log"); - public static final Block blackwood_log = get("blackwood_log"); - public static final Block oak_slab = get("oak_slab"); - public static final Block spruce_slab = get("spruce_slab"); - public static final Block birch_slab = get("birch_slab"); - public static final Block jungle_slab = get("jungle_slab"); - public static final Block acacia_slab = get("acacia_slab"); - public static final Block dark_oak_slab = get("dark_oak_slab"); - public static final Block cherry_slab = get("cherry_slab"); - public static final Block maple_slab = get("maple_slab"); - public static final Block cobblestone_slab = get("cobblestone_slab"); - public static final Block brick_slab = get("brick_slab"); - public static final Block blood_brick_slab = get("blood_brick_slab"); - public static final Block quartz_slab = get("quartz_slab"); - public static final BlockDryLeaves dry_leaves = (BlockDryLeaves)get("dry_leaves"); - public static final Block sponge = get("sponge"); - public static final Block glass = get("glass"); - public static final BlockOre lapis_ore = (BlockOre)get("lapis_ore"); - public static final Block lapis_block = get("lapis_block"); - public static final Block dispenser = get("dispenser"); - public static final Block sandstone = get("sandstone"); - public static final Block noteblock = get("noteblock"); - public static final BlockBed red_bed = (BlockBed)get("red_bed"); - public static final Block golden_rail = get("golden_rail"); - public static final Block detector_rail = get("detector_rail"); - public static final BlockPistonBase sticky_piston = (BlockPistonBase)get("sticky_piston"); - public static final Block web = get("web"); - public static final BlockTallGrass tallgrass = (BlockTallGrass)get("tallgrass"); - public static final BlockDeadBush deadbush = (BlockDeadBush)get("deadbush"); - public static final BlockPistonBase piston = (BlockPistonBase)get("piston"); - public static final BlockPistonHead piston_head = (BlockPistonHead)get("piston_head"); - public static final Block wool = get("wool"); - public static final BlockPistonMoving piston_extension = (BlockPistonMoving)get("piston_extension"); - public static final BlockFlower flower = (BlockFlower)get("flower"); - public static final BlockBush brown_mushroom = (BlockBush)get("brown_mushroom"); - public static final BlockBush red_mushroom = (BlockBush)get("red_mushroom"); - public static final Block gold_block = get("gold_block"); - public static final Block iron_block = get("iron_block"); -// public static final BlockSlab double_stone_slab = get("double_stone_slab"); -// public static final BlockSlab stone_slab = get("stone_slab"); - public static final Block brick_block = get("brick_block"); - public static final Block tnt = get("tnt"); - public static final Block bookshelf = get("bookshelf"); - public static final Block mossy_cobblestone = get("mossy_cobblestone"); - public static final Block obsidian = get("obsidian"); - public static final Block torch = get("torch"); - public static final BlockFire fire = (BlockFire)get("fire"); - public static final Block mob_spawner = get("mob_spawner"); - public static final Block oak_stairs = get("oak_stairs"); - public static final BlockChest chest = (BlockChest)get("chest"); - public static final BlockRedstoneWire redstone = (BlockRedstoneWire)get("redstone"); - public static final BlockOre diamond_ore = (BlockOre)get("diamond_ore"); - public static final Block diamond_block = get("diamond_block"); - public static final Block crafting_table = get("crafting_table"); - public static final Block wheat = get("wheat"); - public static final Block farmland = get("farmland"); - public static final Block furnace = get("furnace"); - public static final Block lit_furnace = get("lit_furnace"); - public static final Block sign = get("sign"); - public static final Block oak_door = get("oak_door"); - public static final Block spruce_door = get("spruce_door"); - public static final Block birch_door = get("birch_door"); - public static final Block jungle_door = get("jungle_door"); - public static final Block acacia_door = get("acacia_door"); - public static final Block dark_oak_door = get("dark_oak_door"); - public static final Block ladder = get("ladder"); - public static final Block rail = get("rail"); - public static final Block cobblestone_stairs = get("cobblestone_stairs"); - public static final Block wall_sign = get("wall_sign"); - public static final Block lever = get("lever"); - public static final Block stone_pressure_plate = get("stone_pressure_plate"); - public static final Block iron_door = get("iron_door"); - public static final Block wooden_pressure_plate = get("wooden_pressure_plate"); - public static final Block redstone_ore = get("redstone_ore"); - public static final Block lit_redstone_ore = get("lit_redstone_ore"); - public static final Block unlit_redstone_torch = get("unlit_redstone_torch"); - public static final Block redstone_torch = get("redstone_torch"); - public static final Block stone_button = get("stone_button"); - public static final Block snow_layer = get("snow_layer"); - public static final Block ice = get("ice"); - public static final Block snow = get("snow"); - public static final BlockCactus cactus = (BlockCactus)get("cactus"); - public static final Block clay = get("clay"); - public static final BlockReed reeds = (BlockReed)get("reeds"); - public static final Block jukebox = get("jukebox"); - public static final Block oak_fence = get("oak_fence"); - public static final Block spruce_fence = get("spruce_fence"); - public static final Block birch_fence = get("birch_fence"); - public static final Block jungle_fence = get("jungle_fence"); - public static final Block dark_oak_fence = get("dark_oak_fence"); - public static final Block acacia_fence = get("acacia_fence"); - public static final Block pumpkin = get("pumpkin"); - public static final Block hellrock = get("hellrock"); - public static final Block soul_sand = get("soul_sand"); - public static final Block glowstone = get("glowstone"); - public static final BlockPortal portal = (BlockPortal)get("portal"); - public static final Block lit_pumpkin = get("lit_pumpkin"); - public static final Block cake = get("cake"); - public static final BlockRedstoneRepeater repeater = (BlockRedstoneRepeater)get("repeater"); - public static final BlockRedstoneRepeater powered_repeater = (BlockRedstoneRepeater)get("powered_repeater"); - public static final Block trapdoor = get("trapdoor"); - public static final Block stonebrick = get("stonebrick"); - public static final Block brown_mushroom_block = get("brown_mushroom_block"); - public static final Block red_mushroom_block = get("red_mushroom_block"); - public static final Block iron_bars = get("iron_bars"); - public static final Block glass_pane = get("glass_pane"); - public static final Block melon_block = get("melon_block"); - public static final Block pumpkin_stem = get("pumpkin_stem"); - public static final Block melon_stem = get("melon_stem"); - public static final Block vine = get("vine"); - public static final Block oak_fence_gate = get("oak_fence_gate"); - public static final Block spruce_fence_gate = get("spruce_fence_gate"); - public static final Block birch_fence_gate = get("birch_fence_gate"); - public static final Block jungle_fence_gate = get("jungle_fence_gate"); - public static final Block dark_oak_fence_gate = get("dark_oak_fence_gate"); - public static final Block acacia_fence_gate = get("acacia_fence_gate"); - public static final Block brick_stairs = get("brick_stairs"); - public static final Block stonebrick_stairs = get("stonebrick_stairs"); - public static final BlockMycelium mycelium = (BlockMycelium)get("mycelium"); - public static final Block waterlily = get("waterlily"); - public static final Block blood_brick = get("blood_brick"); - public static final Block blood_brick_fence = get("blood_brick_fence"); - public static final Block blood_brick_stairs = get("blood_brick_stairs"); - public static final Block black_brick = get("black_brick"); - public static final Block black_brick_fence = get("black_brick_fence"); - public static final Block black_brick_stairs = get("black_brick_stairs"); - public static final Block soul_wart = get("soul_wart"); - public static final Block enchanting_table = get("enchanting_table"); - public static final Block brewing_stand = get("brewing_stand"); - public static final BlockCauldron cauldron = (BlockCauldron)get("cauldron"); - public static final Block floor_portal = get("floor_portal"); - public static final Block portal_frame = get("portal_frame"); - public static final Block cell_rock = get("cell_rock"); - public static final Block dragon_egg = get("dragon_egg"); - public static final Block redstone_lamp = get("redstone_lamp"); - public static final Block lit_redstone_lamp = get("lit_redstone_lamp"); -// public static final BlockSlab double_wooden_slab = get("double_wooden_slab"); -// public static final BlockSlab wooden_slab = get("wooden_slab"); - public static final Block cocoa = get("cocoa"); - public static final Block sandstone_stairs = get("sandstone_stairs"); - public static final BlockOre emerald_ore = (BlockOre)get("emerald_ore"); - public static final Block warp_chest = get("warp_chest"); - public static final BlockTripWireHook tripwire_hook = (BlockTripWireHook)get("tripwire_hook"); - public static final Block string = get("string"); - public static final Block emerald_block = get("emerald_block"); - public static final Block spruce_stairs = get("spruce_stairs"); - public static final Block birch_stairs = get("birch_stairs"); - public static final Block jungle_stairs = get("jungle_stairs"); - public static final BlockBeacon beacon = (BlockBeacon)get("beacon"); - public static final Block cobblestone_wall = get("cobblestone_wall"); - public static final Block flower_pot = get("flower_pot"); - public static final Block carrot = get("carrot"); - public static final Block potato = get("potato"); - public static final Block wooden_button = get("wooden_button"); - public static final BlockSkull skull = (BlockSkull)get("skull"); - public static final Block anvil = get("anvil"); - public static final Block trapped_chest = get("trapped_chest"); - public static final Block light_weighted_pressure_plate = get("light_weighted_pressure_plate"); - public static final Block heavy_weighted_pressure_plate = get("heavy_weighted_pressure_plate"); - public static final BlockRedstoneComparator comparator = (BlockRedstoneComparator)get("comparator"); - public static final BlockRedstoneComparator powered_comparator = (BlockRedstoneComparator)get("powered_comparator"); - public static final BlockDaylightDetector daylight_detector = (BlockDaylightDetector)get("daylight_detector"); - public static final BlockDaylightDetector daylight_detector_inverted = (BlockDaylightDetector)get("daylight_detector_inverted"); - public static final Block redstone_block = get("redstone_block"); - public static final BlockOre quartz_ore = (BlockOre)get("quartz_ore"); - public static final BlockHopper hopper = (BlockHopper)get("hopper"); - public static final Block quartz_block = get("quartz_block"); - public static final Block black_quartz_block = get("black_quartz_block"); - public static final Block quartz_stairs = get("quartz_stairs"); - public static final Block black_quartz_stairs = get("black_quartz_stairs"); - public static final Block activator_rail = get("activator_rail"); - public static final Block dropper = get("dropper"); - public static final Block stained_hardened_clay = get("stained_hardened_clay"); - public static final Block iron_trapdoor = get("iron_trapdoor"); - public static final Block hay_block = get("hay_block"); - public static final Block carpet = get("carpet"); - public static final Block hardened_clay = get("hardened_clay"); - public static final Block coal_block = get("coal_block"); - public static final Block packed_ice = get("packed_ice"); - public static final Block acacia_stairs = get("acacia_stairs"); - public static final Block dark_oak_stairs = get("dark_oak_stairs"); - public static final Block slime_block = get("slime_block"); - public static final BlockDoublePlant double_plant = (BlockDoublePlant)get("double_plant"); - public static final BlockStainedGlass stained_glass = (BlockStainedGlass)get("stained_glass"); - public static final BlockStainedGlassPane stained_glass_pane = (BlockStainedGlassPane)get("stained_glass_pane"); - public static final Block banner = get("banner"); - public static final Block wall_banner = get("wall_banner"); - - public static final BlockLeaves oak_leaves = (BlockLeaves)get("oak_leaves"); - public static final BlockLeaves spruce_leaves = (BlockLeaves)get("spruce_leaves"); - public static final BlockLeaves birch_leaves = (BlockLeaves)get("birch_leaves"); - public static final BlockLeaves jungle_leaves = (BlockLeaves)get("jungle_leaves"); - public static final BlockLeaves acacia_leaves = (BlockLeaves)get("acacia_leaves"); - public static final BlockLeaves dark_oak_leaves = (BlockLeaves)get("dark_oak_leaves"); - public static final BlockLeaves cherry_leaves = (BlockLeaves)get("cherry_leaves"); - public static final BlockLeaves maple_leaves = (BlockLeaves)get("maple_leaves"); - public static final BlockLeaves tian_leaves = (BlockLeaves)get("tian_leaves"); - public static final BlockLeaves blackwood_leaves = (BlockLeaves)get("blackwood_leaves"); - public static final Block cherry_stairs = get("cherry_stairs"); - public static final Block maple_stairs = get("maple_stairs"); - public static final Block cherry_door = get("cherry_door"); - public static final Block maple_door = get("maple_door"); - public static final Block cherry_fence = get("cherry_fence"); - public static final Block maple_fence = get("maple_fence"); - public static final Block cherry_fence_gate = get("cherry_fence_gate"); - public static final Block maple_fence_gate = get("maple_fence_gate"); - public static final Block nuke = get("nuke"); -// public static final BlockVerticalSlab stone_vslab = get("stone_vslab"); -// public static final BlockVerticalSlab stone_vslab2 = get("stone_vslab2"); -// public static final BlockVerticalSlab wooden_vslab = get("wooden_vslab"); -// public static final BlockVerticalSlab wooden_vslab2 = get("wooden_vslab2"); - public static final BlockOre thetium_ore = (BlockOre)get("thetium_ore"); - public static final BlockOre ardite_ore = (BlockOre)get("ardite_ore"); - public static final BlockOre gyriyn_ore = (BlockOre)get("gyriyn_ore"); - public static final BlockOre nichun_ore = (BlockOre)get("nichun_ore"); - public static final BlockOre ruby_ore = (BlockOre)get("ruby_ore"); - public static final BlockOre cinnabar_ore = (BlockOre)get("cinnabar_ore"); - public static final Block lamp = get("lamp"); - - public static final Block copper_block = get("copper_block"); - public static final Block tin_block = get("tin_block"); - public static final Block aluminium_block = get("aluminium_block"); - public static final Block lead_block = get("lead_block"); - - public static final Block tian = get("tian"); - public static final Block tian_soil = get("tian_soil"); - public static final BlockBush blue_mushroom = (BlockBush)get("blue_mushroom"); - public static final BlockTianReactor tian_reactor = (BlockTianReactor)get("tian_reactor"); - public static final Block red_button = get("red_button"); - public static final Block moon_rock = get("moon_rock"); - public static final Block moon_cheese = get("moon_cheese"); - public static final Block rock = get("rock"); - public static final Block ash = get("ash"); - public static final Block core = get("core"); - - public static final BlockSlab stone_slab = (BlockSlab)get("stone_slab"); - public static final BlockSlab sandstone_slab = (BlockSlab)get("sandstone_slab"); - public static final BlockSlab stonebrick_slab = (BlockSlab)get("stonebrick_slab"); - - public static final BlockDynamicLiquid flowing_blood = (BlockDynamicLiquid)get("flowing_blood"); - public static final BlockStaticLiquid blood = (BlockStaticLiquid)get("blood"); - public static final BlockDynamicLiquid flowing_mercury = (BlockDynamicLiquid)get("flowing_mercury"); - public static final BlockStaticLiquid mercury = (BlockStaticLiquid)get("mercury"); - public static final BlockDynamicLiquid flowing_magma = (BlockDynamicLiquid)get("flowing_magma"); - public static final BlockStaticLiquid magma = (BlockStaticLiquid)get("magma"); - public static final BlockDynamicLiquid flowing_hydrogen = (BlockDynamicLiquid)get("flowing_hydrogen"); - public static final BlockStaticLiquid hydrogen = (BlockStaticLiquid)get("hydrogen"); - - private static Block get(String id) { - if(!BlockRegistry.REGISTRY.containsKey(id)) - throw new RuntimeException("Block " + id + " does not exist!"); - return BlockRegistry.REGISTRY.getObject(id); - } - -// static { -// for(Field field : Blocks.class.getDeclaredFields()) { -// if(Block.class.isAssignableFrom(field.getType())) { -// if(!BlockRegistry.REGISTRY.containsKey(field.getName())) { -// throw new RuntimeException("Block " + field.getName() + " does not exist!"); -// } -// Block block = BlockRegistry.REGISTRY.getObject(field.getName()); -// try { -// field.set(null, block); -// } -// catch(IllegalArgumentException | IllegalAccessException e) { -// throw new RuntimeException(e); -// } -// } -// } -// } -} diff --git a/java/src/game/init/Config.java b/java/src/game/init/Config.java deleted file mode 100755 index 6ac62fb..0000000 --- a/java/src/game/init/Config.java +++ /dev/null @@ -1,531 +0,0 @@ -package game.init; - -import static java.lang.annotation.ElementType.FIELD; - -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Modifier; -import java.util.Map; -import java.util.TreeMap; - -import game.Server; -import game.packet.SPacketWorld; -import game.util.ExtMath; -import game.world.WorldServer; - -public abstract class Config { - public static enum ValueType { - STRING, BOOLEAN, INTEGER, FLOAT; - } - - private static interface Callback { - void run(Server server); - } - - @Target(FIELD) - @Retention(value = RetentionPolicy.RUNTIME) - private static @interface Var { - String name(); - Class callback() default Callback.class; - float min() default (float)Integer.MIN_VALUE; - float max() default (float)Integer.MAX_VALUE; - } - - public static class Value { - public final ValueType type; - public final String def; - private final Field field; - private final float min; - private final float max; - private final Callback callback; - - private Value(Field field, Var value) { - this.type = field.getType() == int.class ? ValueType.INTEGER : (field.getType() == boolean.class ? ValueType.BOOLEAN : - (field.getType() == String.class ? ValueType.STRING : (field.getType() == float.class ? ValueType.FLOAT : null))); - if(this.type == null) - throw new IllegalArgumentException(value.name() + ": Unbekannter Variablen-Typ - " + field.getType()); - this.field = field; - this.def = this.getValue(); -// Clamped clamp = this.field.getAnnotation(Clamped.class); - this.min = (this.type == ValueType.INTEGER || this.type == ValueType.FLOAT) - ? value.min() : 0; - this.max = (this.type == ValueType.INTEGER || this.type == ValueType.FLOAT) - ? value.max() : (this.type == ValueType.BOOLEAN ? 1 : 0); -// Update update = this.field.getAnnotation(Update.class); - if(value.callback() == Callback.class) { - this.callback = null; - } - else { - try { - this.callback = value.callback().getConstructor().newInstance(); - } - catch(InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException - | NoSuchMethodException e) { - throw new RuntimeException(e); - } - } - this.setValue(this.def); - } - - public String getValue() { - try { - return "" + this.field.get(null); -// switch(this.type) { -// case STRING: -// default: -// return (String)this.field.get(null); -// case BOOLEAN: -// return "" + this.field.getBoolean(null); -// case INTEGER: -// return "" + this.field.getInt(null); -// case FLOAT: -// return "" + this.field.getFloat(null); -// } - } - catch(IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } - } - - private void setValue(String value) { - try { - switch(this.type) { - case STRING: - this.field.set(null, value); - break; - case BOOLEAN: - this.field.setBoolean(null, Boolean.parseBoolean(value)); - break; - case INTEGER: - int inum = 0; - try { - inum = Integer.parseInt(value); - } - catch(NumberFormatException e) { - } - this.field.setInt(null, ExtMath.clampi(inum, (int)this.min, (int)this.max)); - break; - case FLOAT: - float fnum = 0.0f; - try { - fnum = Float.parseFloat(value); - } - catch(NumberFormatException e) { - } - fnum = ExtMath.clampf(fnum, this.min, this.max); - int round = (int)(fnum * 1000.0f); - this.field.setFloat(null, (float)round / 1000.0f); - break; - } - } - catch(IllegalArgumentException | IllegalAccessException e) { - throw new RuntimeException(e); - } - } - } - - public static final int PROTOCOL = 666; - public static final int PORT = 26666; - public static final String VERSION = "v2.2.1-alpha"; - - public static final Map VARS = new TreeMap(); - - @Var(name = "fireTick") - public static boolean fire = true; - @Var(name = "mobGriefing") - public static boolean mobGrief = true; - @Var(name = "mobSpawning") - public static boolean mobs = true; - @Var(name = "tickSpawning") - public static boolean tickSpawn = true; - @Var(name = "genSpawning") - public static boolean genSpawn = true; - @Var(name = "spawners") - public static boolean spawners = true; - @Var(name = "spawnVillagers") - public static boolean spawnVillager = true; - @Var(name = "spawnCagedVillagers") - public static boolean spawnCagedVillager = true; - @Var(name = "spawnHutMages") - public static boolean spawnHutMage = true; - @Var(name = "spawnEggChickens") - public static boolean spawnEggChicken = true; - @Var(name = "spawnMoreZombies") - public static boolean spawnMoreZombie = true; - @Var(name = "spawnSplitSlimes") - public static boolean spawnSplitSlime = true; - @Var(name = "chargeHaunter") - public static boolean chargeHaunter = true; - @Var(name = "convertVillageZombie") - public static boolean convertZombie = true; - @Var(name = "dropLoot") - public static boolean dropLoot = true; - @Var(name = "dropBlockXP") - public static boolean blockXP = true; - @Var(name = "dropBreedingXP") - public static boolean breedingXP = true; - @Var(name = "dropSmeltingXP") - public static boolean smeltingXP = true; - @Var(name = "dropFishingXP") - public static boolean fishingXP = true; - @Var(name = "dropMobXP") - public static boolean mobXP = true; - @Var(name = "dropBlocks") - public static boolean blockDrop = true; - @Var(name = "dropObjects") - public static boolean objectDrop = true; - @Var(name = "naturalRegeneration") - public static boolean regeneration = true; - @Var(name = "daylightCycle", callback = WorldCallback.class) - public static boolean dayCycle = true; - @Var(name = "weatherChanges") - public static boolean weather = true; - @Var(name = "seasonLeafUpdate") - public static boolean seasonLeaves = true; - @Var(name = "leavesDecay") - public static boolean leavesDecay = true; - @Var(name = "repairExperience") - public static boolean repairXP = true; - @Var(name = "mobTick") - public static boolean mobTick = true; - @Var(name = "mobAttacks") - public static boolean mobAttacks = true; - @Var(name = "portals") - public static boolean portals = true; - @Var(name = "portalVoid") - public static boolean voidPortal = true; - @Var(name = "dropPlayerSkulls") - public static boolean skullDrop = true; - @Var(name = "dropPlayerItems") - public static boolean playerDrop = true; - @Var(name = "blockGravity") - public static boolean blockGravity = true; - @Var(name = "liquidPhysics") - public static boolean liquidPhysics = true; - @Var(name = "lavaFire") - public static boolean lavaFire = true; - @Var(name = "mergeWater") - public static boolean mergeWater = true; - @Var(name = "mergeInfinite") - public static boolean mergeInfinite = true; - @Var(name = "infighting") - public static boolean infight = true; -// @Var(name = "infightSameType") -// public static boolean infightSame = true; - @Var(name = "damageFall") - public static boolean damageFall = true; - @Var(name = "damageFire") - public static boolean damageFire = true; - @Var(name = "damageLava") - public static boolean damageLava = true; - @Var(name = "damageMolten") - public static boolean damageMolten = true; - @Var(name = "damageLightning") - public static boolean damageLightning = true; - @Var(name = "damageSquish") - public static boolean damageSquish = true; - @Var(name = "damageAcme") - public static boolean damageAcme = true; - @Var(name = "damageRadiation") - public static boolean damageRadiation = true; - @Var(name = "damagePoison") - public static boolean damagePoison = true; - @Var(name = "damagePotion") - public static boolean damagePotion = true; - @Var(name = "damageFlyingBox") - public static boolean damageFlyingBox = true; - @Var(name = "damageVoid") - public static boolean damageVoid = true; - @Var(name = "damageThorns") - public static boolean damageThorns = true; - @Var(name = "damageFireball") - public static boolean damageFireball = true; - @Var(name = "damageArrow") - public static boolean damageArrow = true; - @Var(name = "damageBullet") - public static boolean damageBullet = true; - @Var(name = "damageMobs") - public static boolean damageMobs = true; - @Var(name = "damageExplosion") - public static boolean damageExplosion = true; - @Var(name = "damageWall") - public static boolean damageWall = true; - @Var(name = "radiation") - public static boolean radiation = true; - @Var(name = "anvilFallDecay") - public static boolean anvilFallDecay = true; - @Var(name = "anvilRepairDecay") - public static boolean anvilRepairDecay = true; - @Var(name = "attacking") - public static boolean attack = true; - @Var(name = "cactusPrickly") - public static boolean cactusDamage = true; - @Var(name = "waterMobDrying") - public static boolean waterMobDry = true; - @Var(name = "itemBurning") - public static boolean itemBurn = true; - @Var(name = "xpOrbBurning") - public static boolean xpOrbBurn = true; - @Var(name = "smackingOrb") - public static boolean knockOrb = true; - @Var(name = "smackingDynamite") - public static boolean knockDynamite = true; - @Var(name = "smackingEgg") - public static boolean knockEgg = true; - @Var(name = "smackingSnowball") - public static boolean knockSnowball = true; - @Var(name = "smackingFishHook") - public static boolean knockHook = true; - @Var(name = "entityFishing") - public static boolean hookEntity = true; - @Var(name = "hookingRequiresDamage") - public static boolean hookCheckDamage = true; - @Var(name = "grassSpread") - public static boolean grassSpread = true; - @Var(name = "blackenedSoilSpread") - public static boolean darkSoilSpread = true; - @Var(name = "blackenedDirtSpread") - public static boolean darkDirtSpread = true; - @Var(name = "grassDecay") - public static boolean grassDecay = true; - @Var(name = "blackenedSoilDecay") - public static boolean darkSoilDecay = true; - @Var(name = "grassDrying") - public static boolean grassDry = true; - @Var(name = "tallgrassDrying") - public static boolean tallgrassDry = true; - @Var(name = "flowerDrying") - public static boolean flowerDry = true; - @Var(name = "plantDrying") - public static boolean plantDry = true; - @Var(name = "leafDrying") - public static boolean leafDry = true; - @Var(name = "saplingDrying") - public static boolean saplingDry = true; - @Var(name = "reedDrying") - public static boolean reedDry = true; - @Var(name = "vineDrying") - public static boolean vineDry = true; - @Var(name = "myceliumSpread") - public static boolean mycelSpread = true; - @Var(name = "myceliumDecay") - public static boolean mycelDecay = true; - @Var(name = "farmlandDecay") - public static boolean cropDecay = true; - @Var(name = "farmlandDrying") - public static boolean cropDrying = true; - @Var(name = "farmlandSoaking") - public static boolean cropSoaking = true; - @Var(name = "farmlandTrampling") - public static boolean cropTrampling = true; - @Var(name = "iceMelting") - public static boolean iceMelt = true; - @Var(name = "snowMelting") - public static boolean snowMelt = true; - @Var(name = "snowBlockMelting") - public static boolean snowFullMelt = true; - @Var(name = "chestLocking") - public static boolean locking = true; - @Var(name = "teleFragging") - public static boolean telefrag = true; - @Var(name = "checkRespawn") - public static boolean checkBed = true; - @Var(name = "chunkLoaders") - public static boolean loaders = true; - @Var(name = "fragileItems") - public static boolean itemFallDamage = true; - @Var(name = "registration") - public static boolean register = true; - @Var(name = "preload_chunks") - public static boolean preload = true; - - @Var(name = "keepInventory") - public static boolean keepInventory = false; - @Var(name = "cleanCut") - public static boolean cleanCut = false; - @Var(name = "mergeLava") - public static boolean mergeLava = false; - @Var(name = "mergeFinite") - public static boolean mergeFinite = false; - @Var(name = "veryHungryRabbits") - public static boolean rabidRabbits = false; - @Var(name = "snowStacking") - public static boolean snowStack = false; - @Var(name = "authentication") - public static boolean auth = false; -// @Var(name = "teleportForAll") -// public static boolean teleportAllowed = false; -// @Var(name = "preload_chunks_all") // Vorsicht Lag!! -// public static boolean preloadAll = false; - -// @Var(name = "maxPolygonalPoints") -// public static int polygonalPoints = -1; -// @Var(name = "maxPolyhedronPoints") -// public static int polyhedronPoints = -1; -// @Var(name = "maxEditRadius") -// public static int editRadius = -1; -// @Var(name = "maxBrushRadius") -// public static int brushRadius = 500; -// @Var(name = "historySize") -// public static int history = 300; - - @Var(name = "randomTickSpeed") - public static int randomTick = 3; - @Var(name = "weatherTickSpeed") - public static int weatherTick = 1; - @Var(name = "lightningChance") - public static int boltChance = 100000; - @Var(name = "igniteChance") - public static int igniteChance = 100; - @Var(name = "spawnRadius") - public static int spawnRadius = 10; - @Var(name = "originRadius", min = 0, max = 262144) - public static int originRadius = 16384; - @Var(name = "respawnTime") - public static int respawnTime = 0; - @Var(name = "hurtCooldown") - public static int hurtDelay = 20; - @Var(name = "attackCooldown") - public static int attackDelay = 0; - @Var(name = "spawnGroupCount") - public static int spawnGroups = 3; - @Var(name = "spawnGroupDistance") - public static int spawnGroupDist = 6; - @Var(name = "mobSpawnRadius") - public static int mobSpawnDist = 8; - @Var(name = "mobPlayerDistance") - public static int mobPlayerDist = 24; - @Var(name = "saveInterval") - public static int saveInterval = 900; - @Var(name = "maxPlayers") - public static int playerLimit = 0; - @Var(name = "compressAbove") - public static int compression = 256; - @Var(name = "pistonPushLimit") - public static int pistonLimit = 16; - @Var(name = "gravelFlintChance") - public static int flintChance = 10; - @Var(name = "timeFlow", callback = WorldCallback.class) - public static int timeFlow = 1; - @Var(name = "emptyTicks") - public static int unloadTicks = 1200; - @Var(name = "rabbitMateChance") - public static int rabbitMateChance = 10; - @Var(name = "killerBunnyChance") - public static int killerBunnyChance = 1000; - @Var(name = "fallPortalHeight") - public static int portalHeight = 256; - @Var(name = "damageOrb") - public static int orbDamageSelf = 5; - @Var(name = "vineGrowthChance") - public static int vineGrowth = 4; - @Var(name = "blueShroomChance") - public static int blueShroomGrowth = 25; - @Var(name = "mushroomChance") - public static int shroomGrowth = 25; - @Var(name = "cropGrowthChance") - public static int cropGrowth = 26; - @Var(name = "stemGrowthChance") - public static int stemGrowth = 26; - @Var(name = "treeGrowthChance") - public static int treeGrowth = 7; - @Var(name = "wartGrowthChance") - public static int wartGrowth = 10; - @Var(name = "cocoaGrowthChance") - public static int cocoaGrowth = 5; - @Var(name = "reedGrowthHeight") - public static int reedHeight = 3; - @Var(name = "cactusGrowthHeight") - public static int cactusHeight = 3; - @Var(name = "orbThorns") - public static int orbDamageOther = 0; - @Var(name = "weatherChance") - public static int weatherChance = 48000; - @Var(name = "viewDistance", min = 2, max = 128, callback = DistanceCallback.class) - public static int distance = 10; - @Var(name = "healChance") - public static int healChance = 5; - @Var(name = "hopperCooldown", min = 0, max = 160) - public static int hopperDelay = 2; - @Var(name = "hopperCartCooldown", min = 0, max = 160) - public static int hopperCartDelay = 1; - @Var(name = "xpCooldown", min = 0, max = 10) - public static int xpDelay = 0; // 2 - @Var(name = "maxSpawns") - public static int maxMobs = 120; - @Var(name = "eggLayTime") - public static int eggTimer = 6000; - @Var(name = "connectionTimeout", min = 10, max = 300) - public static int timeout = 30; - -// @Var(name = "spawnX", min = -World.MAX_SIZE + 1, max = World.MAX_SIZE - 1) -// public static int spawnX = 0; -// @Var(name = "spawnY", min = -1, max = 511) -// public static int spawnY = 64; -// @Var(name = "spawnZ", min = -World.MAX_SIZE + 1, max = World.MAX_SIZE - 1) -// public static int spawnZ = 0; -// @Var(name = "spawnDim") -// public static int spawnDim = 0; - - @Var(name = "gravity", callback = WorldCallback.class) - public static float gravity = 1.0f; - @Var(name = "knockback") - public static float knockback = 1.0f; - - @Var(name = "spawnYaw", min = -180.0f, max = 180.0f) - public static float spawnYaw = -90.0f; - @Var(name = "spawnPitch", min = -89.0f, max = 89.0f) - public static float spawnPitch = 0.0f; - - @Var(name = "password") - public static String password = ""; - - static { - for(Field field : Config.class.getDeclaredFields()) { - if(field.isAnnotationPresent(Var.class)) { - if(!Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) - throw new IllegalArgumentException("Feld für Variable " + field + " muss statisch und änderbar sein!"); - Var value = field.getAnnotation(Var.class); - if(value.name().isEmpty()) - throw new IllegalArgumentException("Variablenname von " + field + " kann nicht leer sein!"); - if(VARS.containsKey(value.name())) - throw new IllegalArgumentException("Variable " + value.name() + " existiert bereits!"); - VARS.put(value.name(), new Config.Value(field, value)); - } - } - } - - public static void clear() { - for(Config.Value value : VARS.values()) { - value.setValue(value.def); - } - } - - public static void set(String key, String value, Server server) { - Config.Value vl = VARS.get(key); - if(vl != null) { - vl.setValue(value); - if(server != null && vl.callback != null) - vl.callback.run(server); - } - } - - public static class WorldCallback implements Callback { - public void run(Server server) { - for(WorldServer world : server.getWorlds()) { - world.updatePhysics(); - } - server.sendPacket(new SPacketWorld(WorldServer.clampGravity(), Config.dayCycle, Config.timeFlow)); - } - } - public static class DistanceCallback implements Callback { - public void run(Server server) { - for(WorldServer world : server.getWorlds()) { - world.updateViewRadius(); - } - } - } -} diff --git a/java/src/game/init/EntityEggInfo.java b/java/src/game/init/EntityEggInfo.java deleted file mode 100755 index 380ab00..0000000 --- a/java/src/game/init/EntityEggInfo.java +++ /dev/null @@ -1,22 +0,0 @@ -package game.init; - -public class EntityEggInfo -{ - public final String spawnedID; - public final String origin; - public final int primaryColor; - public final int secondaryColor; -// public final StatBase killStat; -// public final StatBase killedByStat; - - public EntityEggInfo(String id, String origin, int baseColor, int spotColor) - { - this.spawnedID = id; - this.origin = origin; - this.primaryColor = baseColor; - this.secondaryColor = spotColor; -// this.killStat = new StatBase("stat.killEntity." + this.spawnedID, EntityRegistry.getEntityName(this.spawnedID) + " getötet"); -// this.killedByStat = new StatBase("stat.entityKilledBy." + this.spawnedID, -// "Von " + EntityRegistry.getEntityName(this.spawnedID) + " getötet"); - } -} \ No newline at end of file diff --git a/java/src/game/init/FlammabilityRegistry.java b/java/src/game/init/FlammabilityRegistry.java deleted file mode 100755 index a0d5536..0000000 --- a/java/src/game/init/FlammabilityRegistry.java +++ /dev/null @@ -1,75 +0,0 @@ -package game.init; - -import game.block.Block; - -public abstract class FlammabilityRegistry { - private static void setFlammable(Block blockIn, int encouragement, int flammability) { - Blocks.fire.setFireInfo(blockIn, encouragement, flammability); - } - - static void register() { -// setFlammable(Blocks.planks, 5, 20); - for(WoodType wood : WoodType.values()) { - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_planks"), 5, 20); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_slab"), 5, 20); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_stairs"), 5, 20); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_fence"), 5, 20); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_fence_gate"), 5, 20); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_log"), 5, 5); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_leaves"), 30, 60); - setFlammable(BlockRegistry.getRegisteredBlock(wood.getName() + "_sapling"), 15, 100); - } - setFlammable(Blocks.bookshelf, 30, 20); - setFlammable(Blocks.tnt, 15, 100); - setFlammable(Blocks.tallgrass, 60, 100); - setFlammable(Blocks.double_plant, 60, 100); - setFlammable(Blocks.flower, 60, 100); - setFlammable(Blocks.deadbush, 60, 100); - setFlammable(Blocks.dry_leaves, 60, 100); - setFlammable(Blocks.wool, 30, 60); - setFlammable(Blocks.vine, 15, 100); - setFlammable(Blocks.coal_block, 5, 5); - setFlammable(Blocks.hay_block, 60, 20); - setFlammable(Blocks.carpet, 60, 20); - -// setFlammable(Blocks.double_wooden_slab, 5, 20); -// setFlammable(Blocks.wooden_slab, 5, 20); -// setFlammable(Blocks.oak_fence_gate, 5, 20); -// setFlammable(Blocks.spruce_fence_gate, 5, 20); -// setFlammable(Blocks.birch_fence_gate, 5, 20); -// setFlammable(Blocks.jungle_fence_gate, 5, 20); -// setFlammable(Blocks.dark_oak_fence_gate, 5, 20); -// setFlammable(Blocks.acacia_fence_gate, 5, 20); -// setFlammable(Blocks.oak_fence, 5, 20); -// setFlammable(Blocks.spruce_fence, 5, 20); -// setFlammable(Blocks.birch_fence, 5, 20); -// setFlammable(Blocks.jungle_fence, 5, 20); -// setFlammable(Blocks.dark_oak_fence, 5, 20); -// setFlammable(Blocks.acacia_fence, 5, 20); -// setFlammable(Blocks.oak_stairs, 5, 20); -// setFlammable(Blocks.birch_stairs, 5, 20); -// setFlammable(Blocks.spruce_stairs, 5, 20); -// setFlammable(Blocks.jungle_stairs, 5, 20); -// setFlammable(Blocks.log, 5, 5); -// setFlammable(Blocks.log2, 5, 5); -// for(BlockLeaves leaves : BlockLeaves.LEAVES) { -// setFlammable(leaves, 30, 60); -//// setFlammable(Blocks.leaves2, 30, 60); -// } -// setFlammable(Blocks.red_flower, 60, 100); -// setFlammable(Blocks.cherry_leaves, 30, 60); -// setFlammable(Blocks.maple_leaves, 30, 60); -// setFlammable(Blocks.cherry_fence_gate, 5, 20); -// setFlammable(Blocks.maple_fence_gate, 5, 20); -// setFlammable(Blocks.cherry_fence, 5, 20); -// setFlammable(Blocks.maple_fence, 5, 20); -// setFlammable(Blocks.cherry_stairs, 5, 20); -// setFlammable(Blocks.maple_stairs, 5, 20); -// setFlammable(Blocks.wooden_vslab, 5, 20); -// setFlammable(Blocks.wooden_vslab2, 5, 20); -// for(BlockSlab slab : BlockSlab.SLABS) { -// if(slab.getMaterial() == Material.wood) -// setFlammable(slab, 5, 20); -// } - } -} diff --git a/java/src/game/init/Items.java b/java/src/game/init/Items.java deleted file mode 100755 index 8ee522f..0000000 --- a/java/src/game/init/Items.java +++ /dev/null @@ -1,251 +0,0 @@ -package game.init; - -import game.item.Item; -import game.item.ItemAmmo; -import game.item.ItemArmor; -import game.item.ItemBow; -import game.item.ItemEnchantedBook; -import game.item.ItemFishingRod; -import game.item.ItemPotion; -import game.item.ItemShears; - - -public abstract class Items { - public static final Item iron_shovel = get("iron_shovel"); - public static final Item iron_pickaxe = get("iron_pickaxe"); - public static final Item iron_axe = get("iron_axe"); - public static final Item flint_and_steel = get("flint_and_steel"); - public static final Item apple = get("apple"); - public static final ItemBow bow = (ItemBow)get("bow"); - public static final Item arrow = get("arrow"); - public static final Item coal = get("coal"); - public static final Item diamond = get("diamond"); - public static final Item iron_ingot = get("iron_ingot"); - public static final Item gold_ingot = get("gold_ingot"); - public static final Item iron_sword = get("iron_sword"); - public static final Item wood_sword = get("wood_sword"); - public static final Item wood_shovel = get("wood_shovel"); - public static final Item wood_pickaxe = get("wood_pickaxe"); - public static final Item wood_axe = get("wood_axe"); - public static final Item stone_sword = get("stone_sword"); - public static final Item stone_shovel = get("stone_shovel"); - public static final Item stone_pickaxe = get("stone_pickaxe"); - public static final Item stone_axe = get("stone_axe"); - public static final Item diamond_sword = get("diamond_sword"); - public static final Item diamond_shovel = get("diamond_shovel"); - public static final Item diamond_pickaxe = get("diamond_pickaxe"); - public static final Item diamond_axe = get("diamond_axe"); - public static final Item stick = get("stick"); - public static final Item bowl = get("bowl"); - public static final Item mushroom_stew = get("mushroom_stew"); - public static final Item gold_sword = get("gold_sword"); - public static final Item gold_shovel = get("gold_shovel"); - public static final Item gold_pickaxe = get("gold_pickaxe"); - public static final Item gold_axe = get("gold_axe"); - public static final Item string = get("string"); - public static final Item feather = get("feather"); - public static final Item gunpowder = get("gunpowder"); - public static final Item wood_hoe = get("wood_hoe"); - public static final Item stone_hoe = get("stone_hoe"); - public static final Item iron_hoe = get("iron_hoe"); - public static final Item diamond_hoe = get("diamond_hoe"); - public static final Item gold_hoe = get("gold_hoe"); - public static final Item wheat = get("wheat"); - public static final Item wheats = get("wheats"); - public static final Item bread = get("bread"); - public static final ItemArmor leather_helmet = (ItemArmor)get("leather_helmet"); - public static final ItemArmor leather_chestplate = (ItemArmor)get("leather_chestplate"); - public static final ItemArmor leather_leggings = (ItemArmor)get("leather_leggings"); - public static final ItemArmor leather_boots = (ItemArmor)get("leather_boots"); - public static final ItemArmor chain_helmet = (ItemArmor)get("chain_helmet"); - public static final ItemArmor chain_chestplate = (ItemArmor)get("chain_chestplate"); - public static final ItemArmor chain_leggings = (ItemArmor)get("chain_leggings"); - public static final ItemArmor chain_boots = (ItemArmor)get("chain_boots"); - public static final ItemArmor iron_helmet = (ItemArmor)get("iron_helmet"); - public static final ItemArmor iron_chestplate = (ItemArmor)get("iron_chestplate"); - public static final ItemArmor iron_leggings = (ItemArmor)get("iron_leggings"); - public static final ItemArmor iron_boots = (ItemArmor)get("iron_boots"); - public static final ItemArmor diamond_helmet = (ItemArmor)get("diamond_helmet"); - public static final ItemArmor diamond_chestplate = (ItemArmor)get("diamond_chestplate"); - public static final ItemArmor diamond_leggings = (ItemArmor)get("diamond_leggings"); - public static final ItemArmor diamond_boots = (ItemArmor)get("diamond_boots"); - public static final ItemArmor gold_helmet = (ItemArmor)get("gold_helmet"); - public static final ItemArmor gold_chestplate = (ItemArmor)get("gold_chestplate"); - public static final ItemArmor gold_leggings = (ItemArmor)get("gold_leggings"); - public static final ItemArmor gold_boots = (ItemArmor)get("gold_boots"); - public static final Item flint = get("flint"); - public static final Item porkchop = get("porkchop"); - public static final Item cooked_porkchop = get("cooked_porkchop"); -// public static final Item painting = get("painting"); - public static final Item golden_apple = get("golden_apple"); - public static final Item sign = get("sign"); - public static final Item oak_door = get("oak_door"); - public static final Item spruce_door = get("spruce_door"); - public static final Item birch_door = get("birch_door"); - public static final Item jungle_door = get("jungle_door"); - public static final Item acacia_door = get("acacia_door"); - public static final Item dark_oak_door = get("dark_oak_door"); - public static final Item bucket = get("bucket"); - public static final Item water_bucket = get("water_bucket"); -// public static final Item lava_bucket = get("lava_bucket"); -// public static final Item fluid_bucket = get("fluid_bucket"); - public static final Item minecart = get("minecart"); - public static final Item saddle = get("saddle"); - public static final Item iron_door = get("iron_door"); - public static final Item redstone = get("redstone"); - public static final Item snowball = get("snowball"); - public static final Item boat = get("boat"); - public static final Item leather = get("leather"); - public static final Item milk_bucket = get("milk_bucket"); - public static final Item brick = get("brick"); - public static final Item clay_ball = get("clay_ball"); - public static final Item reeds = get("reeds"); - public static final Item paper = get("paper"); - public static final Item book = get("book"); - public static final Item slime_ball = get("slime_ball"); - public static final Item chest_minecart = get("chest_minecart"); -// public static final Item furnace_minecart = get("furnace_minecart"); - public static final Item egg = get("egg"); - public static final Item navigator = get("navigator"); - public static final ItemFishingRod fishing_rod = (ItemFishingRod)get("fishing_rod"); -// public static final Item clock = get("clock"); - public static final Item glowstone_dust = get("glowstone_dust"); - public static final Item fish = get("fish"); - public static final Item cooked_fish = get("cooked_fish"); - public static final Item dye = get("dye"); - public static final Item bone = get("bone"); - public static final Item sugar = get("sugar"); - public static final Item cake = get("cake"); -// public static final Item red_bed = get("red_bed"); - public static final Item repeater = get("repeater"); - public static final Item cookie = get("cookie"); - public static final ItemShears iron_shears = (ItemShears)get("iron_shears"); - public static final Item melon = get("melon"); - public static final Item pumpkin_stem = get("pumpkin_stem"); - public static final Item melon_stem = get("melon_stem"); - public static final Item beef = get("beef"); - public static final Item cooked_beef = get("cooked_beef"); - public static final Item chicken = get("chicken"); - public static final Item cooked_chicken = get("cooked_chicken"); - public static final Item rotten_flesh = get("rotten_flesh"); - public static final Item orb = get("orb"); - public static final Item blaze_rod = get("blaze_rod"); - public static final Item ghast_tear = get("ghast_tear"); - public static final Item gold_nugget = get("gold_nugget"); - public static final Item soul_wart = get("soul_wart"); - public static final ItemPotion potion = (ItemPotion)get("potion"); - public static final Item glass_bottle = get("glass_bottle"); - public static final Item spider_eye = get("spider_eye"); - public static final Item fermented_spider_eye = get("fermented_spider_eye"); - public static final Item blaze_powder = get("blaze_powder"); - public static final Item magma_cream = get("magma_cream"); - public static final Item brewing_stand = get("brewing_stand"); - public static final Item cauldron = get("cauldron"); - public static final Item charged_orb = get("charged_orb"); - public static final Item speckled_melon = get("speckled_melon"); -// public static final Item spawn_egg = get("spawn_egg"); - public static final Item experience_bottle = get("experience_bottle"); - public static final Item fire_charge = get("fire_charge"); - public static final Item writable_book = get("writable_book"); - public static final Item written_book = get("written_book"); - public static final Item emerald = get("emerald"); -// public static final Item item_frame = get("item_frame"); - public static final Item flower_pot = get("flower_pot"); - public static final Item carrot = get("carrot"); - public static final Item potato = get("potato"); - public static final Item baked_potato = get("baked_potato"); - public static final Item poisonous_potato = get("poisonous_potato"); - public static final Item golden_carrot = get("golden_carrot"); - public static final Item skull = get("skull"); - public static final Item carrot_on_a_stick = get("carrot_on_a_stick"); - public static final Item charge_crystal = get("charge_crystal"); - public static final Item pumpkin_pie = get("pumpkin_pie"); - public static final Item fireworks = get("fireworks"); - public static final Item firework_charge = get("firework_charge"); - public static final ItemEnchantedBook enchanted_book = (ItemEnchantedBook)get("enchanted_book"); - public static final Item comparator = get("comparator"); - public static final Item bloodbrick = get("bloodbrick"); - public static final Item quartz = get("quartz"); - public static final Item tnt_minecart = get("tnt_minecart"); - public static final Item hopper_minecart = get("hopper_minecart"); - public static final Item iron_horse_armor = get("iron_horse_armor"); - public static final Item gold_horse_armor = get("gold_horse_armor"); - public static final Item diamond_horse_armor = get("diamond_horse_armor"); - public static final Item lead = get("lead"); - public static final Item name_tag = get("name_tag"); - public static final Item record_13 = get("record_13"); - public static final Item record_cat = get("record_cat"); - public static final Item record_blocks = get("record_blocks"); - public static final Item record_chirp = get("record_chirp"); - public static final Item record_far = get("record_far"); - public static final Item record_mall = get("record_mall"); - public static final Item record_mellohi = get("record_mellohi"); - public static final Item record_stal = get("record_stal"); - public static final Item record_strad = get("record_strad"); - public static final Item record_ward = get("record_ward"); - public static final Item record_11 = get("record_11"); - public static final Item record_wait = get("record_wait"); - public static final Item record_delay = get("record_delay"); - public static final Item record_extend = get("record_extend"); - public static final Item banner = get("banner"); - - public static final Item portal_frame = get("portal_frame"); - - public static final Item dynamite = get("dynamite"); - public static final Item cherry_door = get("cherry_door"); - public static final Item maple_door = get("maple_door"); - public static final ItemShears diamond_shears = (ItemShears)get("diamond_shears"); - - public static final Item thi_fragment = get("thi_fragment"); - public static final Item ahrd_fragment = get("ahrd_fragment"); - public static final Item ghi_fragment = get("ghi_fragment"); - public static final Item nieh_fragment = get("nieh_fragment"); - -// public static final Item npc_spawner = get("npc_spawner"); - public static final Item wand = get("wand"); -// public static final Item navigator = get("navigator"); - - public static final Item copper_ingot = get("copper_ingot"); - public static final Item tin_ingot = get("tin_ingot"); - public static final Item aluminium_ingot = get("aluminium_ingot"); - public static final Item lead_ingot = get("lead_ingot"); - public static final Item nickel_ingot = get("nickel_ingot"); - public static final Item cobalt_ingot = get("cobalt_ingot"); - public static final Item neodymium_ingot = get("neodymium_ingot"); - - public static final Item die = get("die"); - public static final Item lightning_wand = get("lightning_wand"); - public static final Item info_wand = get("info_wand"); - public static final Item key = get("key"); - public static final Item ruby = get("ruby"); - public static final Item chick_magnet = get("chick_magnet"); - public static final Item magnet = get("magnet"); - public static final Item cinnabar = get("cinnabar"); - public static final Item chain = get("chain"); - public static final Item camera = get("camera"); - public static final Item boltgun = get("boltgun"); - public static final ItemAmmo bolt = (ItemAmmo)get("bolt"); - - private static Item get(String id) { - if(!ItemRegistry.REGISTRY.containsKey(id)) - throw new RuntimeException("Item " + id + " does not exist!"); - return ItemRegistry.REGISTRY.getObject(id); - } - -// static { -// for(Field field : Items.class.getDeclaredFields()) { -// if(Item.class.isAssignableFrom(field.getType())) { -// if(!ItemRegistry.REGISTRY.containsKey(field.getName())) { -// throw new RuntimeException("Item " + field.getName() + " does not exist!"); -// } -// Item item = ItemRegistry.REGISTRY.getObject(field.getName()); -// try { -// field.set(null, item); -// } -// catch(IllegalArgumentException | IllegalAccessException e) { -// throw new RuntimeException(e); -// } -// } -// } -// } -} diff --git a/java/src/game/init/Registry.java b/java/src/game/init/Registry.java deleted file mode 100755 index 7623cd8..0000000 --- a/java/src/game/init/Registry.java +++ /dev/null @@ -1,140 +0,0 @@ -package game.init; - -import java.awt.Desktop; -import java.io.File; -import java.io.FileOutputStream; -import java.io.PrintStream; -import java.lang.Thread.UncaughtExceptionHandler; -import java.lang.management.ManagementFactory; -import java.lang.management.ThreadInfo; -import java.lang.management.ThreadMXBean; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.Locale; - -import javax.imageio.ImageIO; - -import game.log.NettyLogger; - -public abstract class Registry { - private static boolean crashed; - - private static void register() { - NameRegistry.register(); - BlockRegistry.register(); - FlammabilityRegistry.register(); - SpeciesRegistry.register(); - EntityRegistry.registerEggs(); - ItemRegistry.register(); - TileRegistry.register(); - CraftingRegistry.register(); - SmeltingRegistry.register(); - EntityRegistry.register(); - DispenserRegistry.register(); - UniverseRegistry.register(); - RotationRegistry.register(); - ReorderRegistry.register(); - } - - public static void setup(String thread) { - Thread.currentThread().setName(thread); - Locale.setDefault(Locale.ROOT); - Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() { - public void uncaughtException(Thread thread, Throwable e) { - System.err.println("Fehler in Thread '" + thread.getName() + "'"); - e.printStackTrace(System.err); - if(crashed) - System.exit(1); - if(e instanceof OutOfMemoryError) { - System.gc(); - System.gc(); - } - if(!thread.getName().startsWith("Thread-") || e instanceof OutOfMemoryError) { - System.err.println("Beende!"); - crashed = true; - if(System.getProperty("crash.nodump") == null) { - PrintStream ps = null; - File report = null; - try { - Date date = new Date(); - File file = new File("crash-" + new SimpleDateFormat("dd.MM.yyyy_HH.mm.ss").format(date) + ".txt"); - FileOutputStream out = new FileOutputStream(file); - ps = new PrintStream(out); - ThreadMXBean bean = ManagementFactory.getThreadMXBean(); - ThreadInfo[] info = bean.dumpAllThreads(true, true); - StringBuilder sb = new StringBuilder(); - Error error = new Error(); - for(ThreadInfo threadinfo : info) { - if(threadinfo.getThreadId() == thread.getId()) - error.setStackTrace(threadinfo.getStackTrace()); - sb.append(threadinfo); - } - ps.println("************************************************ " + new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date) + " ************************************************"); - ps.println(); - ps.println("\"Wie haste das denn nu wieder geschafft, Bursche?\""); - ps.println("Unerwarteter Fehler in Thread '" + thread.getName() + "':"); - e.printStackTrace(ps); - ps.println(); - ps.println("---------------------------------------------- Thread-Dump (" + info.length + " Threads) ---------------------------------------------"); - ps.println(); - ps.print(sb.toString()); - ps.println("*********************************************************************************************************************"); - report = file; - } - catch(Throwable t) { - System.err.println("Konnte Absturzbericht nicht speichern:"); - t.printStackTrace(System.err); - } - finally { - if(ps != null) - ps.close(); - } - if(report != null) { - System.err.println("Absturzbericht gespeichert unter " + report.getPath()); - try { - Desktop.getDesktop().browse(report.toURI()); - } - catch(Throwable e1) { - System.err.println("Konnte " + report + " nicht öffnen: " + e1); - } - } - } - System.exit(1); - } - } - }); - ImageIO.setUseCache(false); - Thread timer = new Thread("Timer Hack Thread") { - public void run() { - while(true) { - try { - Thread.sleep(2147483647L); - } - catch(InterruptedException e) { - ; - } - } - } - }; - timer.setDaemon(true); - timer.start(); - System.setProperty("java.net.preferIPv4Stack", "true"); - NettyLogger.init(); - register(); - } - - public static void addShutdownHook(final Runnable hook) { - Runtime.getRuntime().addShutdownHook(new Thread("Game Shutdown Thread") { - public void run() { - if(!crashed) { - try { - hook.run(); - } - catch(Throwable e) { - e.printStackTrace(); - } - } - } - }); - } -} diff --git a/java/src/game/init/TileRegistry.java b/java/src/game/init/TileRegistry.java deleted file mode 100755 index d8d4147..0000000 --- a/java/src/game/init/TileRegistry.java +++ /dev/null @@ -1,64 +0,0 @@ -package game.init; - -import java.util.Map; - -import game.collect.Maps; - -import game.tileentity.TileEntity; -import game.tileentity.TileEntityBanner; -import game.tileentity.TileEntityBeacon; -import game.tileentity.TileEntityBrewingStand; -import game.tileentity.TileEntityChest; -import game.tileentity.TileEntityComparator; -import game.tileentity.TileEntityDaylightDetector; -import game.tileentity.TileEntityDispenser; -import game.tileentity.TileEntityDropper; -import game.tileentity.TileEntityEnchantmentTable; -import game.tileentity.TileEntityFurnace; -import game.tileentity.TileEntityHopper; -import game.tileentity.TileEntityMobSpawner; -import game.tileentity.TileEntityNote; -import game.tileentity.TileEntityPiston; -import game.tileentity.TileEntitySign; -import game.tileentity.TileEntitySkull; -import game.tileentity.TileEntityTianReactor; - -public abstract class TileRegistry { - public static final Map> nameToClassMap = Maps.>newHashMap(); - public static final Map, String> classToNameMap = Maps., String>newHashMap(); - public static final Map, Integer> classToIdMap = Maps., Integer>newHashMap(); - private static int nextId; - - private static void addMapping(Class cl, String id) { - if(nameToClassMap.containsKey(id)) - throw new IllegalArgumentException("Duplicate id: " + id); - nameToClassMap.put(id, cl); - classToNameMap.put(cl, id); - classToIdMap.put(cl, ++nextId); - } - - static void register() { - addMapping(TileEntityFurnace.class, "Furnace"); - addMapping(TileEntityChest.class, "Chest"); -// addMapping(TileEntityWarpChest.class, "WarpChest"); -// addMapping(BlockJukebox.TileEntityJukebox.class, "RecordPlayer"); - addMapping(TileEntityDispenser.class, "Trap"); - addMapping(TileEntityDropper.class, "Dropper"); - addMapping(TileEntitySign.class, "Sign"); - addMapping(TileEntityMobSpawner.class, "MobSpawner"); - addMapping(TileEntityNote.class, "Music"); - addMapping(TileEntityPiston.class, "Piston"); - addMapping(TileEntityBrewingStand.class, "Cauldron"); - addMapping(TileEntityEnchantmentTable.class, "EnchantTable"); -// addMapping(TileEntityPortal.class, "Portal"); -// addMapping(TileEntityCommandBlock.class, "Control"); - addMapping(TileEntityBeacon.class, "Beacon"); - addMapping(TileEntitySkull.class, "Skull"); - addMapping(TileEntityDaylightDetector.class, "DLDetector"); - addMapping(TileEntityHopper.class, "Hopper"); - addMapping(TileEntityComparator.class, "Comparator"); -// addMapping(TileEntityFlowerPot.class, "FlowerPot"); - addMapping(TileEntityBanner.class, "Banner"); - addMapping(TileEntityTianReactor.class, "TianReactor"); - } -} diff --git a/java/src/game/init/ToolMaterial.java b/java/src/game/init/ToolMaterial.java deleted file mode 100755 index bff7669..0000000 --- a/java/src/game/init/ToolMaterial.java +++ /dev/null @@ -1,165 +0,0 @@ -package game.init; - -import java.util.Set; - -import game.collect.Sets; - -import game.item.Item; - -public class ToolMaterial -{ - private static final int[] MAX_DAMAGE = new int[] {11, 16, 15, 13}; - private static final float[] RAD_REDUCE = new float[] {1.0f, 1.7f, 1.6f, 1.4f}; - private static final float[] MAG_REDUCE = new float[] {1.0f, 1.2f, 1.1f, 1.0f}; - - private final int harvestLevel; - private final int maxUses; - private final float efficiencyOnProperMaterial; - private final int damageVsEntity; - private final float radiationResistance; - private final float magicResistance; - private final int enchantability; - private final int maxDamageFactor; - private final int[] damageReductionAmountArray; - private final int armorEnchantability; - private final boolean tools; - private final boolean weapons; - private final boolean extras; - private boolean magnetic; - private int defColor = 0xffffffff; - private Set repair = Sets.newHashSet(); - - private ToolMaterial(float rad, float mag, int level, int uses, float efficiency, int damage, int ench, boolean tools, - boolean weapons, boolean extras, int auses, int aench, int r1, int r2, int r3, int r4) { - this.harvestLevel = level; - this.maxUses = uses; - this.efficiencyOnProperMaterial = efficiency; - this.damageVsEntity = damage; - this.enchantability = ench; - this.maxDamageFactor = auses; - this.damageReductionAmountArray = new int[] {r1, r2, r3, r4}; - this.armorEnchantability = aench; - this.radiationResistance = rad; - this.magicResistance = mag; - this.tools = tools; - this.weapons = weapons; - this.extras = extras; - } - - protected ToolMaterial(int level) { - this(0.0f, 0.0f, level, 0, 0.0f, 0, 0, false, false, false, 0, 0, 0, 0, 0, 0); - } - - protected ToolMaterial(int level, int uses, float efficiency, int damage, int ench, boolean weapons) { - this(0.0f, 0.0f, level, uses, efficiency, damage, ench, true, weapons, false, 0, ench, 0, 0, 0, 0); - } - - protected ToolMaterial(int level, float rad, float mag, int uses, int damage, int ench, int auses, int aench, int r1, int r2, int r3, int r4) { - this(rad, mag, level, uses, 0.0F, damage, ench, false, true, false, auses, aench, r1, r2, r3, r4); - } - - protected ToolMaterial(int level, float rad, float mag, int auses, int aench, int r1, int r2, int r3, int r4) { - this(rad, mag, 0, 0, 0.0F, 0, 0, false, false, false, auses, aench, r1, r2, r3, r4); - } - - protected ToolMaterial(int level, float rad, float mag, int uses, float efficiency, int damage, int ench, boolean extras, - int auses, int aench, int r1, int r2, int r3, int r4) { - this(rad, mag, level, uses, efficiency, damage, ench, true, true, extras, auses, aench, r1, r2, r3, r4); - } - - protected ToolMaterial setDyeable(int defColor) { - this.defColor = defColor; - return this; - } - - protected ToolMaterial setMagnetic() { - this.magnetic = true; - return this; - } - - protected void addRepairItem(Item item) { - this.repair.add(item); - } - - public boolean hasArmor() { - return this.maxDamageFactor > 0; - } - - public boolean hasTools() { - return this.tools; - } - - public boolean hasWeapons() { - return this.weapons; - } - - public boolean hasExtras() { - return this.extras; - } - - public int getMaxUses() - { - return this.maxUses; - } - - public float getEfficiencyOnProperMaterial() - { - return this.efficiencyOnProperMaterial; - } - - public int getDamageVsEntity() - { - return this.damageVsEntity; - } - - public int getHarvestLevel() - { - return this.harvestLevel; - } - - public int getEnchantability() - { - return this.enchantability; - } - - public boolean isRepairItem(Item item) { - return this.repair.contains(item); - } - - public int getDurability(int armorType) - { - return MAX_DAMAGE[armorType] * this.maxDamageFactor; - } - - public float getRadiationReduction(int armorType) - { - return RAD_REDUCE[armorType] * this.radiationResistance; - } - - public float getMagicReduction(int armorType) - { - return MAG_REDUCE[armorType] * this.magicResistance; - } - - public int getDamageReductionAmount(int armorType) - { - return this.damageReductionAmountArray[armorType]; - } - - public int getArmorEnchantability() - { - return this.armorEnchantability; - } - - public boolean canBeDyed() { - return this.defColor != 0xffffffff; - } - - public int getDefaultColor() { - return this.defColor; - } - - public boolean isMagnetic() { - return this.magnetic; - } -} \ No newline at end of file diff --git a/java/src/game/inventory/ContainerEnchantment.java b/java/src/game/inventory/ContainerEnchantment.java deleted file mode 100755 index 4e7bcea..0000000 --- a/java/src/game/inventory/ContainerEnchantment.java +++ /dev/null @@ -1,424 +0,0 @@ -package game.inventory; - -import java.util.List; - -import game.enchantment.EnchantmentHelper; -import game.enchantment.RngEnchantment; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.init.Items; -import game.item.ItemStack; -import game.rng.Random; -import game.world.BlockPos; -import game.world.World; - -public class ContainerEnchantment extends Container -{ - /** SlotEnchantmentTable object with ItemStack to be enchanted */ - public IInventory tableInventory; - - /** current world (for bookshelf counting) */ - private World worldPointer; - private BlockPos position; - private Random rand; - public int xpSeed; - - /** 3-member array storing the enchantment levels of each slot */ - public int[] enchantLevels; - public int[] enchantmentIds; - - public ContainerEnchantment(InventoryPlayer playerInv, World worldIn) - { - this(playerInv, worldIn, BlockPos.ORIGIN); - } - - public ContainerEnchantment(InventoryPlayer playerInv, World worldIn, BlockPos pos) - { - this.tableInventory = new InventoryBasic("Enchant", true, 1) - { - public int getInventoryStackLimit() - { - return ItemStack.MAX_SIZE; - } - public void markDirty() - { - super.markDirty(); - ContainerEnchantment.this.onCraftMatrixChanged(this); - } - }; - this.rand = new Random(); - this.enchantLevels = new int[3]; - this.enchantmentIds = new int[] { -1, -1, -1}; - this.worldPointer = worldIn; - this.position = pos; - this.xpSeed = playerInv.player.getXPSeed(); - this.addSlotToContainer(new Slot(this.tableInventory, 0, 25, 47) - { - public boolean isItemValid(ItemStack stack) - { - return true; - } - public int getSlotStackLimit() - { - return 1; - } - }); -// this.addSlotToContainer(new Slot(this.tableInventory, 1, 35, 47) -// { -// public boolean isItemValid(ItemStack stack) -// { -// return stack.getItem() == Items.dye && EnumDyeColor.byDyeDamage(stack.getMetadata()) == EnumDyeColor.BLUE; -// } -// }); - - for (int i = 0; i < 3; ++i) - { - for (int j = 0; j < 9; ++j) - { - this.addSlotToContainer(new Slot(playerInv, j + i * 9 + 9, 8 + j * 18, 84 + i * 18)); - } - } - - for (int k = 0; k < 9; ++k) - { - this.addSlotToContainer(new Slot(playerInv, k, 8 + k * 18, 142)); - } - } - - public void onCraftGuiOpened(ICrafting listener) - { - super.onCraftGuiOpened(listener); - listener.sendProgressBarUpdate(this, 0, this.enchantLevels[0]); - listener.sendProgressBarUpdate(this, 1, this.enchantLevels[1]); - listener.sendProgressBarUpdate(this, 2, this.enchantLevels[2]); - listener.sendProgressBarUpdate(this, 3, this.xpSeed & -16); - listener.sendProgressBarUpdate(this, 4, this.enchantmentIds[0]); - listener.sendProgressBarUpdate(this, 5, this.enchantmentIds[1]); - listener.sendProgressBarUpdate(this, 6, this.enchantmentIds[2]); - } - - /** - * Looks for changes made in the container, sends them to every listener. - */ - public void detectAndSendChanges() - { - super.detectAndSendChanges(); - - for (int i = 0; i < this.crafters.size(); ++i) - { - ICrafting icrafting = (ICrafting)this.crafters.get(i); - icrafting.sendProgressBarUpdate(this, 0, this.enchantLevels[0]); - icrafting.sendProgressBarUpdate(this, 1, this.enchantLevels[1]); - icrafting.sendProgressBarUpdate(this, 2, this.enchantLevels[2]); - icrafting.sendProgressBarUpdate(this, 3, this.xpSeed & -16); - icrafting.sendProgressBarUpdate(this, 4, this.enchantmentIds[0]); - icrafting.sendProgressBarUpdate(this, 5, this.enchantmentIds[1]); - icrafting.sendProgressBarUpdate(this, 6, this.enchantmentIds[2]); - } - } - - public void updateProgressBar(int id, int data) - { - if (id >= 0 && id <= 2) - { - this.enchantLevels[id] = data; - } - else if (id == 3) - { - this.xpSeed = data; - } - else if (id >= 4 && id <= 6) - { - this.enchantmentIds[id - 4] = data; - } - else - { - super.updateProgressBar(id, data); - } - } - - /** - * Callback for when the crafting matrix is changed. - */ - public void onCraftMatrixChanged(IInventory inventoryIn) - { - if (inventoryIn == this.tableInventory) - { - ItemStack itemstack = inventoryIn.getStackInSlot(0); - - if (itemstack != null && itemstack.isItemEnchantable()) - { - if (!this.worldPointer.client) - { - int l = 0; - - for (int j = -1; j <= 1; ++j) - { - for (int k = -1; k <= 1; ++k) - { - if ((j != 0 || k != 0) && this.worldPointer.isAirBlock(this.position.add(k, 0, j)) && this.worldPointer.isAirBlock(this.position.add(k, 1, j))) - { - if (this.worldPointer.getState(this.position.add(k * 2, 0, j * 2)).getBlock() == Blocks.bookshelf) - { - ++l; - } - - if (this.worldPointer.getState(this.position.add(k * 2, 1, j * 2)).getBlock() == Blocks.bookshelf) - { - ++l; - } - - if (k != 0 && j != 0) - { - if (this.worldPointer.getState(this.position.add(k * 2, 0, j)).getBlock() == Blocks.bookshelf) - { - ++l; - } - - if (this.worldPointer.getState(this.position.add(k * 2, 1, j)).getBlock() == Blocks.bookshelf) - { - ++l; - } - - if (this.worldPointer.getState(this.position.add(k, 0, j * 2)).getBlock() == Blocks.bookshelf) - { - ++l; - } - - if (this.worldPointer.getState(this.position.add(k, 1, j * 2)).getBlock() == Blocks.bookshelf) - { - ++l; - } - } - } - } - } - - this.rand.setSeed((long)this.xpSeed); - - for (int i1 = 0; i1 < 3; ++i1) - { - this.enchantLevels[i1] = EnchantmentHelper.calcItemStackEnchantability(this.rand, i1, l, itemstack); - this.enchantmentIds[i1] = -1; - - if (this.enchantLevels[i1] < i1 + 1) - { - this.enchantLevels[i1] = 0; - } - } - - for (int j1 = 0; j1 < 3; ++j1) - { - if (this.enchantLevels[j1] > 0) - { - List list = this.getRandomEnchantments(itemstack, j1, this.enchantLevels[j1]); - - if (list != null && !list.isEmpty()) - { - RngEnchantment enchantmentdata = (RngEnchantment)list.get(this.rand.zrange(list.size())); - this.enchantmentIds[j1] = enchantmentdata.enchantmentobj.effectId | enchantmentdata.enchantmentLevel << 8; - } - } - } - - this.detectAndSendChanges(); - } - } - else - { - for (int i = 0; i < 3; ++i) - { - this.enchantLevels[i] = 0; - this.enchantmentIds[i] = -1; - } - } - } - } - - /** - * Handles the given Button-click on the server, currently only used by enchanting. Name is for legacy. - */ - public boolean enchantItem(EntityNPC playerIn, int id) - { - ItemStack itemstack = this.tableInventory.getStackInSlot(0); -// ItemStack itemstack1 = this.tableInventory.getStackInSlot(1); - int i = id + 1; - -// if ((itemstack1 == null || itemstack1.stackSize < i) && !playerIn.capabilities.isCreativeMode) -// { -// return false; -// } -// else - if (this.enchantLevels[id] > 0 && itemstack != null && /* ( */ playerIn.experienceLevel >= i && playerIn.experienceLevel >= this.enchantLevels[id]) // || playerIn.creative)) - { - if (!this.worldPointer.client) - { - List list = this.getRandomEnchantments(itemstack, id, this.enchantLevels[id]); - boolean flag = itemstack.getItem() == Items.book; - - if (list != null) - { - playerIn.removeExperienceLevel(i); - - if (flag) - { - itemstack.setItem(Items.enchanted_book); - } - - for (int j = 0; j < list.size(); ++j) - { - RngEnchantment enchantmentdata = (RngEnchantment)list.get(j); - - if (flag) - { - Items.enchanted_book.addEnchantment(itemstack, enchantmentdata); - } - else - { - itemstack.addEnchantment(enchantmentdata.enchantmentobj, enchantmentdata.enchantmentLevel); - } - } - -// if (!playerIn.capabilities.isCreativeMode) -// { -// itemstack1.stackSize -= i; -// -// if (itemstack1.stackSize <= 0) -// { -// this.tableInventory.setInventorySlotContents(1, (ItemStack)null); -// } -// } - -// playerIn.triggerAchievement(StatRegistry.enchantedStat); - this.tableInventory.markDirty(); - this.xpSeed = playerIn.getXPSeed(); - this.onCraftMatrixChanged(this.tableInventory); - } - } - - return true; - } - else - { - return false; - } - } - - private List getRandomEnchantments(ItemStack stack, int id, int level) - { - this.rand.setSeed((long)(this.xpSeed + id)); - List list = EnchantmentHelper.buildEnchantmentList(this.rand, stack, level); - - if (stack.getItem() == Items.book && list != null && list.size() > 1) - { - list.remove(this.rand.zrange(list.size())); - } - - return list; - } - -// public int getLapisAmount() -// { -// ItemStack itemstack = this.tableInventory.getStackInSlot(1); -// return itemstack == null ? 0 : itemstack.stackSize; -// } - - /** - * Called when the container is closed. - */ - public void onContainerClosed(EntityNPC playerIn) - { - super.onContainerClosed(playerIn); - - if (!this.worldPointer.client) - { - for (int i = 0; i < this.tableInventory.getSizeInventory(); ++i) - { - ItemStack itemstack = this.tableInventory.removeStackFromSlot(i); - - if (itemstack != null) - { - playerIn.dropPlayerItemWithRandomChoice(itemstack, false); - } - } - } - } - - public boolean canInteractWith(EntityNPC playerIn) - { - return this.worldPointer.getState(this.position).getBlock() != Blocks.enchanting_table ? false : playerIn.getDistanceSq((double)this.position.getX() + 0.5D, (double)this.position.getY() + 0.5D, (double)this.position.getZ() + 0.5D) <= 64.0D; - } - - /** - * Take a stack from the specified inventory slot. - */ - public ItemStack transferStackInSlot(EntityNPC playerIn, int index) - { - ItemStack itemstack = null; - Slot slot = (Slot)this.inventorySlots.get(index); - - if (slot != null && slot.getHasStack()) - { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - - if (index == 0) - { - if (!this.mergeItemStack(itemstack1, 1, 37, true)) - { - return null; - } - } -// else if (index == 1) -// { -// if (!this.mergeItemStack(itemstack1, 2, 38, true)) -// { -// return null; -// } -// } -// else if (itemstack1.getItem() == Items.dye && EnumDyeColor.byDyeDamage(itemstack1.getMetadata()) == EnumDyeColor.BLUE) -// { -// if (!this.mergeItemStack(itemstack1, 1, 2, true)) -// { -// return null; -// } -// } - else - { - if (((Slot)this.inventorySlots.get(0)).getHasStack() || !((Slot)this.inventorySlots.get(0)).isItemValid(itemstack1)) - { - return null; - } - - if (itemstack1.hasTagCompound() && itemstack1.stackSize == 1) - { - ((Slot)this.inventorySlots.get(0)).putStack(itemstack1.copy()); - itemstack1.stackSize = 0; - } - else if (itemstack1.stackSize >= 1) - { - ((Slot)this.inventorySlots.get(0)).putStack(new ItemStack(itemstack1.getItem(), 1, itemstack1.getMetadata())); - --itemstack1.stackSize; - } - } - - if (itemstack1.stackSize == 0) - { - slot.putStack((ItemStack)null); - } - else - { - slot.onSlotChanged(); - } - - if (itemstack1.stackSize == itemstack.stackSize) - { - return null; - } - - slot.onPickupFromSlot(playerIn, itemstack1); - } - - return itemstack; - } -} diff --git a/java/src/game/inventory/ContainerHorseInventory.java b/java/src/game/inventory/ContainerHorseInventory.java deleted file mode 100755 index a53e790..0000000 --- a/java/src/game/inventory/ContainerHorseInventory.java +++ /dev/null @@ -1,129 +0,0 @@ -package game.inventory; - -import game.entity.animal.EntityHorse; -import game.entity.npc.EntityNPC; -import game.init.Items; -import game.item.ItemStack; - -public class ContainerHorseInventory extends Container -{ - private IInventory horseInventory; - private EntityHorse theHorse; - - public ContainerHorseInventory(IInventory playerInventory, final IInventory horseInventoryIn, final EntityHorse horse, EntityNPC player) - { - this.horseInventory = horseInventoryIn; - this.theHorse = horse; - int i = 3; - horseInventoryIn.openInventory(player); - int j = (i - 4) * 18; - this.addSlotToContainer(new Slot(horseInventoryIn, 0, 8, 18) - { - public boolean isItemValid(ItemStack stack) - { - return super.isItemValid(stack) && stack.getItem() == Items.saddle && !this.getHasStack(); - } - }); - this.addSlotToContainer(new Slot(horseInventoryIn, 1, 8, 36) - { - public boolean isItemValid(ItemStack stack) - { - return super.isItemValid(stack) && horse.canWearArmor() && EntityHorse.isArmorItem(stack.getItem()); - } - public boolean canBeHovered() - { - return horse.canWearArmor(); - } - }); - - if (horse.isChested()) - { - for (int k = 0; k < i; ++k) - { - for (int l = 0; l < 5; ++l) - { - this.addSlotToContainer(new Slot(horseInventoryIn, 2 + l + k * 5, 80 + l * 18, 18 + k * 18)); - } - } - } - - for (int i1 = 0; i1 < 3; ++i1) - { - for (int k1 = 0; k1 < 9; ++k1) - { - this.addSlotToContainer(new Slot(playerInventory, k1 + i1 * 9 + 9, 8 + k1 * 18, 102 + i1 * 18 + j)); - } - } - - for (int j1 = 0; j1 < 9; ++j1) - { - this.addSlotToContainer(new Slot(playerInventory, j1, 8 + j1 * 18, 160 + j)); - } - } - - public boolean canInteractWith(EntityNPC playerIn) - { - return this.horseInventory.isUseableByPlayer(playerIn) && this.theHorse.isEntityAlive() && this.theHorse.getDistanceToEntity(playerIn) < 8.0F; - } - - /** - * Take a stack from the specified inventory slot. - */ - public ItemStack transferStackInSlot(EntityNPC playerIn, int index) - { - ItemStack itemstack = null; - Slot slot = (Slot)this.inventorySlots.get(index); - - if (slot != null && slot.getHasStack()) - { - ItemStack itemstack1 = slot.getStack(); - itemstack = itemstack1.copy(); - - if (index < this.horseInventory.getSizeInventory()) - { - if (!this.mergeItemStack(itemstack1, this.horseInventory.getSizeInventory(), this.inventorySlots.size(), true)) - { - return null; - } - } - else if (this.getSlot(1).isItemValid(itemstack1) && !this.getSlot(1).getHasStack()) - { - if (!this.mergeItemStack(itemstack1, 1, 2, false)) - { - return null; - } - } - else if (this.getSlot(0).isItemValid(itemstack1)) - { - if (!this.mergeItemStack(itemstack1, 0, 1, false)) - { - return null; - } - } - else if (this.horseInventory.getSizeInventory() <= 2 || !this.mergeItemStack(itemstack1, 2, this.horseInventory.getSizeInventory(), false)) - { - return null; - } - - if (itemstack1.stackSize == 0) - { - slot.putStack((ItemStack)null); - } - else - { - slot.onSlotChanged(); - } - } - - return itemstack; - } - - /** - * Called when the container is closed. - */ - public void onContainerClosed(EntityNPC playerIn) - { - super.onContainerClosed(playerIn); - this.horseInventory.closeInventory(playerIn); - } -} diff --git a/java/src/game/inventory/ContainerLocalMenu.java b/java/src/game/inventory/ContainerLocalMenu.java deleted file mode 100755 index 9b2fa72..0000000 --- a/java/src/game/inventory/ContainerLocalMenu.java +++ /dev/null @@ -1,60 +0,0 @@ -package game.inventory; - -import java.util.Map; - -import game.collect.Maps; - -import game.entity.npc.EntityNPC; -import game.tileentity.ILockableContainer; -import game.tileentity.LockCode; - -public class ContainerLocalMenu extends InventoryBasic implements ILockableContainer -{ - private String guiID; - private Map field_174895_b = Maps.newHashMap(); - - public ContainerLocalMenu(String id, String title, int slotCount) - { - super(title, slotCount); - this.guiID = id; - } - - public int getField(int id) - { - return this.field_174895_b.containsKey(Integer.valueOf(id)) ? ((Integer)this.field_174895_b.get(Integer.valueOf(id))).intValue() : 0; - } - - public void setField(int id, int value) - { - this.field_174895_b.put(Integer.valueOf(id), Integer.valueOf(value)); - } - - public int getFieldCount() - { - return this.field_174895_b.size(); - } - - public boolean isLocked() - { - return false; - } - - public void setLockCode(LockCode code) - { - } - - public LockCode getLockCode() - { - return LockCode.EMPTY_CODE; - } - - public String getGuiID() - { - return this.guiID; - } - - public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) - { - throw new UnsupportedOperationException(); - } -} diff --git a/java/src/game/item/CheatTab.java b/java/src/game/item/CheatTab.java deleted file mode 100755 index 2c9363c..0000000 --- a/java/src/game/item/CheatTab.java +++ /dev/null @@ -1,164 +0,0 @@ -package game.item; - -import java.util.List; - -import game.init.Blocks; -import game.init.ItemRegistry; -import game.init.Items; - -public enum CheatTab -{ - tabBlocks("Baumaterial") - { - protected Item getTabIconItem() - { - return ItemRegistry.getItemFromBlock(Blocks.glass); - } - }, - tabNature("Gestein und Natur") - { - protected Item getTabIconItem() - { - return ItemRegistry.getItemFromBlock(Blocks.grass); - } - }, - tabWood("Holz") - { - protected Item getTabIconItem() - { - return ItemRegistry.getItemFromBlock(Blocks.maple_planks); - } - }, - tabPlants("Pflanzen") - { - protected Item getTabIconItem() - { - return ItemRegistry.getItemFromBlock(Blocks.oak_leaves); - } - }, - tabDeco("Dekoration") - { - protected Item getTabIconItem() - { - return ItemRegistry.getItemFromBlock(Blocks.hay_block); - } - }, - tabTech("Redstone & Technik") - { - protected Item getTabIconItem() - { - return ItemRegistry.getItemFromBlock(Blocks.tnt); - } - }, - tabGems("Erze & Teure Blöcke") - { - protected Item getTabIconItem() - { - return ItemRegistry.getItemFromBlock(Blocks.diamond_block); - } - }, - tabSpawners("Mob & Itemspawner") - { - protected Item getTabIconItem() - { - return Items.minecart; - } - }, - tabTools("Werkzeug") - { - protected Item getTabIconItem() - { - return Items.flint_and_steel; - } - }, - tabCombat("Kampf") - { - protected Item getTabIconItem() - { - return Items.bow; - } - }, - tabMagic("Tränke & Verzauberungen") - { - protected Item getTabIconItem() - { - return Items.potion; - } - protected int getIconItemDamage() - { - return 8261; - } - }, - tabMaterials("Werkstoffe") - { - protected Item getTabIconItem() - { - return Items.leather; - } - }, - tabMetals("Metalle und Juwelen") - { - protected Item getTabIconItem() - { - return Items.iron_ingot; - } - }, - tabMisc("Verschiedenes & Nahrung") - { - protected Item getTabIconItem() - { - return Items.charge_crystal; - } - }; - - private final String name; - private ItemStack iconItemStack; - - private CheatTab(String name) - { - this.name = name; - } - - public int getHorizontal() - { - return this.ordinal() % 12; - } - - public int getVertical() - { - return this.ordinal() / 12; - } - - public String getName() - { - return this.name; - } - - public ItemStack getIconItemStack() - { - if (this.iconItemStack == null) - { - this.iconItemStack = new ItemStack(this.getTabIconItem(), 1, this.getIconItemDamage()); - } - - return this.iconItemStack; - } - - protected abstract Item getTabIconItem(); - - protected int getIconItemDamage() - { - return 0; - } - - public void displayAllReleventItems(List list) - { - for (Item item : ItemRegistry.REGISTRY) - { - if (item != null && item.getTab() == this) - { - item.getSubItems(item, this, list); - } - } - } -} diff --git a/java/src/game/item/ItemAxe.java b/java/src/game/item/ItemAxe.java deleted file mode 100755 index ead3549..0000000 --- a/java/src/game/item/ItemAxe.java +++ /dev/null @@ -1,22 +0,0 @@ -package game.item; - -import game.block.Block; -import game.init.ToolMaterial; - -public class ItemAxe extends ItemTool -{ -// private static final Set EFFECTIVE_ON = Sets.newHashSet(new Block[] { -// Blocks.planks, Blocks.bookshelf, Blocks.log, Blocks.log2, Blocks.chest, Blocks.pumpkin, Blocks.lit_pumpkin, Blocks.melon_block, Blocks.ladder -// }); - - public ItemAxe(ToolMaterial material) - { - super(3, material); - } - - public boolean canUseOn(ItemStack stack, Block state) - { - return state.canAxeHarvest() /* state.getMaterial() != Material.wood && state.getMaterial() != Material.plants && state.getMaterial() != Material.vine ? - super.getStrVsBlock(stack, state) */; - } -} diff --git a/java/src/game/item/ItemChest.java b/java/src/game/item/ItemChest.java deleted file mode 100755 index 4974a74..0000000 --- a/java/src/game/item/ItemChest.java +++ /dev/null @@ -1,20 +0,0 @@ -package game.item; - -import game.block.Block; -import game.model.ModelBakery; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; - -public class ItemChest extends ItemBlock { - public ItemChest(Block block) { - super(block); - } - - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(ModelBakery.MODEL_ENTITY, this.getTransform()); - } - - public Transforms getTransform() { - return Transforms.DEFAULT; - } -} diff --git a/java/src/game/item/ItemPickaxe.java b/java/src/game/item/ItemPickaxe.java deleted file mode 100755 index 222e01b..0000000 --- a/java/src/game/item/ItemPickaxe.java +++ /dev/null @@ -1,46 +0,0 @@ -package game.item; - -import game.block.Block; -import game.init.ToolMaterial; - -public class ItemPickaxe extends ItemTool -{ -// private static final Set EFFECTIVE_ON = Sets.newHashSet(new Block[] { -// Blocks.activator_rail, Blocks.coal_ore, Blocks.cobblestone, Blocks.detector_rail, Blocks.diamond_block, Blocks.diamond_ore, Blocks.double_stone_slab, -// Blocks.golden_rail, Blocks.gold_block, Blocks.gold_ore, Blocks.ice, Blocks.iron_block, Blocks.iron_ore, Blocks.lapis_block, Blocks.lapis_ore, -// Blocks.lit_redstone_ore, Blocks.mossy_cobblestone, Blocks.netherrack, Blocks.packed_ice, Blocks.rail, Blocks.redstone_ore, Blocks.sandstone, -// Blocks.red_sandstone, Blocks.stone, Blocks.stone_slab -// }); - - public ItemPickaxe(ToolMaterial material) - { - super(2, material); - } - - public boolean canHarvestBlock(Block blockIn) - { - return blockIn.getMiningLevel() >= 0 && this.toolMaterial.getHarvestLevel() >= blockIn.getMiningLevel(); -// blockIn == Blocks.obsidian ? this.toolMaterial.getHarvestLevel() == 3 : -// (blockIn != Blocks.diamond_block && blockIn != Blocks.diamond_ore ? -// (blockIn != Blocks.emerald_ore && blockIn != Blocks.emerald_block ? -// (blockIn != Blocks.gold_block && blockIn != Blocks.gold_ore ? -// (blockIn != Blocks.iron_block && blockIn != Blocks.iron_ore ? -// (blockIn != Blocks.lapis_block && blockIn != Blocks.lapis_ore ? -// (blockIn != Blocks.redstone_ore && blockIn != Blocks.lit_redstone_ore ? -// (blockIn.getMaterial() == Material.rock ? true : -// (blockIn.getMaterial() == Material.iron ? true : -// blockIn.getMaterial() == Material.anvil)) : -// this.toolMaterial.getHarvestLevel() >= 2) : -// this.toolMaterial.getHarvestLevel() >= 1) : -// this.toolMaterial.getHarvestLevel() >= 1) : -// this.toolMaterial.getHarvestLevel() >= 2) : -// this.toolMaterial.getHarvestLevel() >= 2) : -// this.toolMaterial.getHarvestLevel() >= 2); - } - - public boolean canUseOn(ItemStack stack, Block state) - { - return state.getMiningLevel() >= 0 /* state.getMaterial() != Material.iron && state.getMaterial() != Material.anvil && state.getMaterial() != Material.rock - ? super.getStrVsBlock(stack, state) */; - } -} diff --git a/java/src/game/item/ItemRecord.java b/java/src/game/item/ItemRecord.java deleted file mode 100755 index 736a92c..0000000 --- a/java/src/game/item/ItemRecord.java +++ /dev/null @@ -1,13 +0,0 @@ -package game.item; - -import game.renderer.blockmodel.ModelBlock; - -public class ItemRecord extends Item { - public ItemRecord() { - this.setTab(CheatTab.tabMisc); - } - - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(this.getTransform(), "record_old"); - } -} diff --git a/java/src/game/item/ItemReed.java b/java/src/game/item/ItemReed.java deleted file mode 100755 index 99722fd..0000000 --- a/java/src/game/item/ItemReed.java +++ /dev/null @@ -1,81 +0,0 @@ -package game.item; - -import game.block.Block; -import game.block.BlockSnow; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; - -public class ItemReed extends Item -{ - private Block block; - - public ItemReed(Block block) - { - this.block = block; - } - - public Block getBlock() - { - return this.block; - } - - /** - * Called when a Block is right-clicked with this Item - */ - public boolean onItemUse(ItemStack stack, EntityNPC playerIn, World worldIn, BlockPos pos, Facing side, float hitX, float hitY, float hitZ) - { - State iblockstate = worldIn.getState(pos); - Block block = iblockstate.getBlock(); - - if (block == Blocks.snow_layer && ((Integer)iblockstate.getValue(BlockSnow.LAYERS)).intValue() < 1) - { - side = Facing.UP; - } - else if (!block.isReplaceable(worldIn, pos)) - { - pos = pos.offset(side); - } - - if (!playerIn.canPlayerEdit(pos, side, stack)) - { - return false; - } - else if (stack.stackSize == 0) - { - return false; - } - else - { - if (worldIn.canBlockBePlaced(this.block, pos, false, side, (Entity)null, stack)) - { - State iblockstate1 = this.block.onBlockPlaced(worldIn, pos, side, hitX, hitY, hitZ, 0, playerIn); - - if (worldIn.setState(pos, iblockstate1, 3)) - { - iblockstate1 = worldIn.getState(pos); - - if (iblockstate1.getBlock() == this.block) - { - ItemBlock.setTileEntityNBT(worldIn, playerIn, pos, stack); - iblockstate1.getBlock().onBlockPlacedBy(worldIn, pos, iblockstate1, playerIn, stack); - } - - worldIn.playSound(this.block.sound.getPlaceSound(), (double)((float)pos.getX() + 0.5F), (double)((float)pos.getY() + 0.5F), (double)((float)pos.getZ() + 0.5F), 1.0F); - --stack.stackSize; - return true; - } - } - - return false; - } - } - - public boolean isMagnetic() { - return this.block.isMagnetic(); - } -} diff --git a/java/src/game/item/ItemSkull.java b/java/src/game/item/ItemSkull.java deleted file mode 100755 index 2e6f50f..0000000 --- a/java/src/game/item/ItemSkull.java +++ /dev/null @@ -1,188 +0,0 @@ -package game.item; - -import game.block.Block; -import game.block.BlockSkull; -import game.entity.npc.EntityNPC; -import game.init.Blocks; -import game.model.ModelBakery; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.tileentity.TileEntity; -import game.tileentity.TileEntitySkull; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.World; - -public class ItemSkull extends Item -{ - public ItemSkull() - { - this.setTab(CheatTab.tabDeco); -// this.setMaxDamage(0); -// this.setHasSubtypes(true); - } - - public Block getBlock() - { - return Blocks.skull; - } - - /** - * Called when a Block is right-clicked with this Item - */ - public boolean onItemUse(ItemStack stack, EntityNPC playerIn, World worldIn, BlockPos pos, Facing side, float hitX, float hitY, float hitZ) - { - if (side == Facing.DOWN) - { - return false; - } - else - { - State iblockstate = worldIn.getState(pos); - Block block = iblockstate.getBlock(); - boolean flag = block.isReplaceable(worldIn, pos); - - if (!flag) - { - if (!worldIn.getState(pos).getBlock().getMaterial().isSolid()) - { - return false; - } - - pos = pos.offset(side); - } - - if (!playerIn.canPlayerEdit(pos, side, stack)) - { - return false; - } - else if (!Blocks.skull.canPlaceBlockAt(worldIn, pos)) - { - return false; - } - else - { - if (!worldIn.client) - { - worldIn.setState(pos, Blocks.skull.getState().withProperty(BlockSkull.FACING, side), 3); - int i = 0; - - if (side == Facing.UP) - { - i = ExtMath.floord((double)(playerIn.rotYaw * 16.0F / 360.0F) + 0.5D) & 15; - } - - TileEntity tileentity = worldIn.getTileEntity(pos); - - if (tileentity instanceof TileEntitySkull) - { - TileEntitySkull tileentityskull = (TileEntitySkull)tileentity; - -// if (stack.getMetadata() == 3) -// { -// String user = null; -// -// if (stack.hasTagCompound()) -// { -// NBTTagCompound nbttagcompound = stack.getTagCompound(); -// -// if (nbttagcompound.hasKey("SkullOwner", 8) && nbttagcompound.getString("SkullOwner").length() > 0) -// { -// user = nbttagcompound.getString("SkullOwner"); -// } -// } -// -// tileentityskull.setUser(user); -// } -// else -// { -// tileentityskull.setType(stack.getMetadata()); -// } - - tileentityskull.setSkullRotation(i); -// Blocks.skull.checkWitherSpawn(worldIn, pos, tileentityskull); - } - - --stack.stackSize; - } - - return true; - } - } - } - -// /** -// * returns a list of items with the same ID, but different meta (eg: dye returns 16 items) -// */ -// public void getSubItems(Item itemIn, CreativeTabs tab, List subItems) -// { -// for (int i = 0; i < skullTypes.length; ++i) -// { -// subItems.add(new ItemStack(itemIn, 1, i)); -// } -// } - -// /** -// * Converts the given ItemStack damage value into a metadata value to be placed in the world when this Item is -// * placed as a Block (mostly used with ItemBlocks). -// */ -// public int getMetadata(int damage) -// { -// return damage; -// } - -// /** -// * Returns the unlocalized name of this item. This version accepts an ItemStack so different stacks can have -// * different names based on their damage or NBT. -// */ -// public String getUnlocalizedName(ItemStack stack) -// { -// int i = stack.getMetadata(); -// -// if (i < 0 || i >= skullTypes.length) -// { -// i = 0; -// } -// -// return super.getUnlocalizedName() + "." + skullTypes[i]; -// } - -// public String getDisplay(ItemStack stack) -// { -// if (stack.hasTagCompound()) -// { -// if (stack.getTagCompound().hasKey("SkullOwner", 8)) -// { -// return super.getDisplay(stack) + " von " + stack.getTagCompound().getString("SkullOwner"); -// } -// } -// -// return super.getDisplay(stack); -// } - -// public Set getValidTags() { -// return Sets.newHashSet("SkullOwner"); -// } -// -// protected boolean validateNbt(NBTTagCompound tag) { -// if(tag.hasKey("SkullOwner")) { -//// if(!adv) { -//// return false; -//// } -// if(!tag.hasKey("SkullOwner", 8)) { -// return false; -// } -// } -// return true; -// } - - public Transforms getTransform() { - return Transforms.SKULL; - } - - public ModelBlock getModel(String name, int meta) { - return new ModelBlock(ModelBakery.MODEL_ENTITY, this.getTransform()); - } -} diff --git a/java/src/game/item/ItemSpade.java b/java/src/game/item/ItemSpade.java deleted file mode 100755 index 0ffae40..0000000 --- a/java/src/game/item/ItemSpade.java +++ /dev/null @@ -1,28 +0,0 @@ -package game.item; - -import game.block.Block; -import game.init.ToolMaterial; -import game.material.Material; - -public class ItemSpade extends ItemTool -{ -// private static final Set EFFECTIVE_ON = Sets.newHashSet(new Block[] { -// Blocks.clay, Blocks.dirt, Blocks.farmland, Blocks.grass, Blocks.gravel, Blocks.mycelium, Blocks.sand, Blocks.snow, Blocks.snow_layer, Blocks.soul_sand -// }); - - public ItemSpade(ToolMaterial material) - { - super(1, material); - } - - public boolean canUseOn(ItemStack stack, Block state) - { - return state.canShovelHarvest(); - } - - public boolean canHarvestBlock(Block blockIn) - { -// return blockIn == Blocks.snow_layer ? true : blockIn == Blocks.snow; - return blockIn.getMaterial() == Material.snow ? true : blockIn.getMaterial() == Material.craftedSnow; - } -} diff --git a/java/src/game/item/ItemTool.java b/java/src/game/item/ItemTool.java deleted file mode 100755 index 7c24492..0000000 --- a/java/src/game/item/ItemTool.java +++ /dev/null @@ -1,127 +0,0 @@ -package game.item; - -import java.util.Map; -import java.util.Set; - -import game.collect.Sets; - -import game.block.Block; -import game.entity.attributes.Attribute; -import game.entity.attributes.AttributeModifier; -import game.entity.attributes.Attributes; -import game.entity.types.EntityLiving; -import game.init.ToolMaterial; -import game.renderer.blockmodel.Transforms; -import game.world.BlockPos; -import game.world.World; - -public abstract class ItemTool extends Item -{ -// private Set effectiveBlocks; - protected float efficiencyOnProperMaterial = 4.0F; - - /** Damage versus entities. */ - private int damageVsEntity; - - /** The material this tool is made from. */ - protected ToolMaterial toolMaterial; - - public ItemTool(int attackDamage, ToolMaterial material) - { - this.toolMaterial = material; -// this.effectiveBlocks = effectiveBlocks; - this.maxStackSize = 1; - this.setMaxDamage(material.getMaxUses()); - this.efficiencyOnProperMaterial = material.getEfficiencyOnProperMaterial(); - this.damageVsEntity = attackDamage + material.getDamageVsEntity(); - this.setTab(CheatTab.tabTools); - } - - public abstract boolean canUseOn(ItemStack stack, Block state); - - public float getStrVsBlock(ItemStack stack, Block state) { - return !this.canUseOn(stack, state) ? 1.0F : this.efficiencyOnProperMaterial; - } -// { -// return this.effectiveBlocks.contains(state) ? this.efficiencyOnProperMaterial : 1.0F; -// } - - /** - * Current implementations of this method in child classes do not use the entry argument beside ev. They just raise - * the damage on the stack. - */ - public boolean hitEntity(ItemStack stack, EntityLiving target, EntityLiving attacker) - { - stack.damageItem(2, attacker); - return true; - } - - /** - * Called when a Block is destroyed using this Item. Return true to trigger the "Use Item" statistic. - */ - public boolean onBlockDestroyed(ItemStack stack, World worldIn, Block blockIn, BlockPos pos, EntityLiving playerIn) - { - if ((double)blockIn.getBlockHardness(worldIn, pos) != 0.0D) - { - stack.damageItem(1, playerIn); - } - - return true; - } - -// /** -// * Returns True is the item is renderer in full 3D when hold. -// */ -// public boolean isFull3D() -// { -// return true; -// } - - public ToolMaterial getToolMaterial() - { - return this.toolMaterial; - } - - /** - * Return the enchantability factor of the item, most of the time is based on material. - */ - public int getItemEnchantability() - { - return this.toolMaterial.getEnchantability(); - } - -// /** -// * Return the name for this tool's material. -// */ -// public String getToolMaterialName() -// { -// return this.toolMaterial.toString(); -// } - - /** - * Return whether this item is repairable in an anvil. - */ - public boolean getIsRepairable(ItemStack toRepair, ItemStack repair) - { - return this.toolMaterial.isRepairItem(repair.getItem()) ? true : super.getIsRepairable(toRepair, repair); - } - - public Map> getItemAttributeModifiers() - { - Map> multimap = super.getItemAttributeModifiers(); - multimap.put(Attributes.ATTACK_DAMAGE, Sets.newHashSet(new AttributeModifier(Attributes.ITEM_VAL_ID, "Tool modifier", this.damageVsEntity, false))); - return multimap; - } - - public boolean isMagnetic() { - return this.toolMaterial.isMagnetic(); - } - - public Transforms getTransform() { - return Transforms.TOOL; - } - - public boolean canBeWielded() { - return true; - } -} diff --git a/java/src/game/log/Message.java b/java/src/game/log/Message.java deleted file mode 100644 index 47146fe..0000000 --- a/java/src/game/log/Message.java +++ /dev/null @@ -1,11 +0,0 @@ -package game.log; - -public class Message { - public final String message; - public final long time; - - public Message(String message, long time) { - this.message = message; - this.time = time; - } -} diff --git a/java/src/game/log/NettyLogger.java b/java/src/game/log/NettyLogger.java deleted file mode 100644 index dde460e..0000000 --- a/java/src/game/log/NettyLogger.java +++ /dev/null @@ -1,170 +0,0 @@ -package game.log; - -import java.io.PrintWriter; -import java.io.StringWriter; - -import io.netty.util.internal.logging.AbstractInternalLogger; -import io.netty.util.internal.logging.FormattingTuple; -import io.netty.util.internal.logging.InternalLogger; -import io.netty.util.internal.logging.InternalLoggerFactory; -import io.netty.util.internal.logging.MessageFormatter; - -public class NettyLogger extends AbstractInternalLogger { - public static void init() { - InternalLoggerFactory.setDefaultFactory(new InternalLoggerFactory() { - protected InternalLogger newInstance(String name) { - return new NettyLogger(name); - } - }); - } - - private NettyLogger(String name) { - super(name); - } - - public boolean isTraceEnabled() { - return Log.getLevel().ordinal() >= LogLevel.TRACE.ordinal(); - } - - public void trace(String msg) { - this.log(LogLevel.TRACE, msg, null); - } - - public void trace(String format, Object arg) { - FormattingTuple ft = MessageFormatter.format(format, arg); - this.log(LogLevel.TRACE, ft.getMessage(), ft.getThrowable()); - } - - public void trace(String format, Object argA, Object argB) { - FormattingTuple ft = MessageFormatter.format(format, argA, argB); - this.log(LogLevel.TRACE, ft.getMessage(), ft.getThrowable()); - } - - public void trace(String format, Object... argArray) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - this.log(LogLevel.TRACE, ft.getMessage(), ft.getThrowable()); - } - - public void trace(String msg, Throwable t) { - this.log(LogLevel.TRACE, msg, t); - } - - public boolean isDebugEnabled() { - return Log.getLevel().ordinal() >= LogLevel.DEBUG.ordinal(); - } - - public void debug(String msg) { - this.log(LogLevel.DEBUG, msg, null); - } - - public void debug(String format, Object arg) { - FormattingTuple ft = MessageFormatter.format(format, arg); - this.log(LogLevel.DEBUG, ft.getMessage(), ft.getThrowable()); - } - - public void debug(String format, Object argA, Object argB) { - FormattingTuple ft = MessageFormatter.format(format, argA, argB); - this.log(LogLevel.DEBUG, ft.getMessage(), ft.getThrowable()); - } - - public void debug(String format, Object... argArray) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - this.log(LogLevel.DEBUG, ft.getMessage(), ft.getThrowable()); - } - - public void debug(String msg, Throwable t) { - this.log(LogLevel.DEBUG, msg, t); - } - - public boolean isInfoEnabled() { - return Log.getLevel().ordinal() >= LogLevel.INFO.ordinal(); - } - - public void info(String msg) { - this.log(LogLevel.INFO, msg, null); - } - - public void info(String format, Object arg) { - FormattingTuple ft = MessageFormatter.format(format, arg); - this.log(LogLevel.INFO, ft.getMessage(), ft.getThrowable()); - } - - public void info(String format, Object argA, Object argB) { - FormattingTuple ft = MessageFormatter.format(format, argA, argB); - this.log(LogLevel.INFO, ft.getMessage(), ft.getThrowable()); - } - - public void info(String format, Object... argArray) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - this.log(LogLevel.INFO, ft.getMessage(), ft.getThrowable()); - } - - public void info(String msg, Throwable t) { - this.log(LogLevel.INFO, msg, t); - } - - public boolean isWarnEnabled() { - return Log.getLevel().ordinal() >= LogLevel.WARN.ordinal(); - } - - public void warn(String msg) { - this.log(LogLevel.WARN, msg, null); - } - - public void warn(String format, Object arg) { - FormattingTuple ft = MessageFormatter.format(format, arg); - this.log(LogLevel.WARN, ft.getMessage(), ft.getThrowable()); - } - - public void warn(String format, Object argA, Object argB) { - FormattingTuple ft = MessageFormatter.format(format, argA, argB); - this.log(LogLevel.WARN, ft.getMessage(), ft.getThrowable()); - } - - public void warn(String format, Object... argArray) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, argArray); - this.log(LogLevel.WARN, ft.getMessage(), ft.getThrowable()); - } - - public void warn(String msg, Throwable t) { - this.log(LogLevel.WARN, msg, t); - } - - public boolean isErrorEnabled() { - return Log.getLevel().ordinal() >= LogLevel.ERROR.ordinal(); - } - - public void error(String msg) { - this.log(LogLevel.ERROR, msg, null); - } - - public void error(String format, Object arg) { - FormattingTuple ft = MessageFormatter.format(format, arg); - this.log(LogLevel.ERROR, ft.getMessage(), ft.getThrowable()); - } - - public void error(String format, Object argA, Object argB) { - FormattingTuple ft = MessageFormatter.format(format, argA, argB); - this.log(LogLevel.ERROR, ft.getMessage(), ft.getThrowable()); - } - - public void error(String format, Object... arguments) { - FormattingTuple ft = MessageFormatter.arrayFormat(format, arguments); - this.log(LogLevel.ERROR, ft.getMessage(), ft.getThrowable()); - } - - public void error(String msg, Throwable t) { - this.log(LogLevel.ERROR, msg, t); - } - - private void log(LogLevel level, String msg, Throwable t) { - Log.NETTY.log(level, msg); - if(t != null) { - StringWriter sw = new StringWriter(); - PrintWriter st = new PrintWriter(sw); - t.printStackTrace(st); - sw.flush(); - Log.NETTY.log(level, sw.toString().trim().replace('\t', ' ')); - } - } -} diff --git a/java/src/game/material/Material.java b/java/src/game/material/Material.java deleted file mode 100755 index a9205f3..0000000 --- a/java/src/game/material/Material.java +++ /dev/null @@ -1,235 +0,0 @@ -package game.material; - -public class Material -{ - public static final Material air = new MaterialTransparent(); - public static final Material grass = new Material(); - public static final Material ground = new Material(); - public static final Material wood = (new Material()).setBurning(); - public static final Material rock = (new Material()).setRequiresTool(); - public static final Material iron = (new Material()).setRequiresTool(); - public static final Material anvil = (new Material()).setRequiresTool().setImmovableMobility(); - public static final Material water = (new MaterialColdFluid()).setNoPushMobility(); - public static final Material coldFluid = (new MaterialColdFluid()).setNoPushMobility(); - public static final Material lava = (new MaterialHotFluid()).setNoPushMobility(); - public static final Material hotFluid = (new MaterialHotFluid()).setNoPushMobility(); - public static final Material leaves = (new Material()).setBurning().setTranslucent().setNoPushMobility(); - public static final Material plants = (new MaterialLogic()).setNoPushMobility(); - public static final Material vine = (new MaterialLogic()).setBurning().setNoPushMobility().setReplaceable(); - public static final Material sponge = new Material(); - public static final Material cloth = (new Material()).setBurning(); - public static final Material fire = (new MaterialTransparent()).setNoPushMobility(); - public static final Material sand = new Material(); - public static final Material circuits = (new MaterialLogic()).setNoPushMobility(); - public static final Material carpet = (new MaterialLogic()).setBurning(); - public static final Material glass = (new Material()).setTranslucent(); // .setAdventureModeExempt(); - public static final Material redstoneLight = (new Material()); // .setAdventureModeExempt(); - public static final Material tnt = (new Material()).setBurning().setTranslucent(); - public static final Material coral = (new Material()).setNoPushMobility(); - public static final Material ice = (new Material()).setTranslucent(); // .setAdventureModeExempt(); - public static final Material packedIce = (new Material()); // .setAdventureModeExempt(); - public static final Material snow = (new MaterialLogic()).setReplaceable().setTranslucent().setRequiresTool().setNoPushMobility(); - - /** The material for crafted snow. */ - public static final Material craftedSnow = (new Material()).setRequiresTool(); - public static final Material cactus = (new Material()).setTranslucent().setNoPushMobility(); - public static final Material clay = new Material(); - public static final Material gourd = (new Material()).setNoPushMobility(); - public static final Material dragonEgg = (new Material()).setNoPushMobility(); - public static final Material portal = (new MaterialPortal()).setImmovableMobility(); - public static final Material cake = (new Material()).setNoPushMobility(); - public static final Material web = (new Material() - { - public boolean blocksMovement() - { - return false; - } - }).setRequiresTool().setNoPushMobility(); - - /** Pistons' material. */ - public static final Material piston = (new Material()).setImmovableMobility(); -// public static final Material barrier = (new Material()).setRequiresTool().setImmovableMobility(); - - /** Bool defining if the block can burn or not. */ - private boolean canBurn; - - /** - * Determines whether blocks with this material can be "overwritten" by other blocks when placed - eg snow, vines - * and tall grass. - */ - private boolean replaceable; - - /** Indicates if the material is translucent */ - private boolean isTranslucent; - -// /** The color index used to draw the blocks of this material on maps. */ -// private final MapColor materialMapColor; - - /** - * Determines if the material can be harvested without a tool (or with the wrong tool) - */ - private boolean requiresNoTool = true; - - /** - * Mobility information flag. 0 indicates that this block is normal, 1 indicates that it can't push other blocks, 2 - * indicates that it can't be pushed. - */ - private int mobilityFlag; -// private boolean isAdventureModeExempt; - -// public Material(MapColor color) -// { -//// this.materialMapColor = color; -// } - - /** - * Returns if blocks of these materials are liquids. - */ - public boolean isLiquid() - { - return false; - } - - public boolean isColdLiquid() - { - return false; - } - - public boolean isHotLiquid() - { - return false; - } - - /** - * Returns true if the block is a considered solid. This is true by default. - */ - public boolean isSolid() - { - return true; - } - - /** - * Will prevent grass from growing on dirt underneath and kill any grass below it if it returns true - */ - public boolean blocksLight() - { - return true; - } - - /** - * Returns if this material is considered solid or not - */ - public boolean blocksMovement() - { - return true; - } - - /** - * Marks the material as translucent - */ - private Material setTranslucent() - { - this.isTranslucent = true; - return this; - } - - /** - * Makes blocks with this material require the correct tool to be harvested. - */ - protected Material setRequiresTool() - { - this.requiresNoTool = false; - return this; - } - - /** - * Set the canBurn bool to True and return the current object. - */ - protected Material setBurning() - { - this.canBurn = true; - return this; - } - - /** - * Returns if the block can burn or not. - */ - public boolean getCanBurn() - { - return this.canBurn; - } - - /** - * Sets {@link #replaceable} to true. - */ - public Material setReplaceable() - { - this.replaceable = true; - return this; - } - - /** - * Returns whether the material can be replaced by other blocks when placed - eg snow, vines and tall grass. - */ - public boolean isReplaceable() - { - return this.replaceable; - } - - /** - * Indicate if the material is opaque - */ - public boolean isOpaque() - { - return this.isTranslucent ? false : this.blocksMovement(); - } - - /** - * Returns true if the material can be harvested without a tool (or with the wrong tool) - */ - public boolean isToolNotRequired() - { - return this.requiresNoTool; - } - - /** - * Returns the mobility information of the material, 0 = free, 1 = can't push but can move over, 2 = total - * immobility and stop pistons. - */ - public int getMaterialMobility() - { - return this.mobilityFlag; - } - - /** - * This type of material can't be pushed, but pistons can move over it. - */ - protected Material setNoPushMobility() - { - this.mobilityFlag = 1; - return this; - } - - /** - * This type of material can't be pushed, and pistons are blocked to move. - */ - protected Material setImmovableMobility() - { - this.mobilityFlag = 2; - return this; - } - -// protected Material setAdventureModeExempt() -// { -// this.isAdventureModeExempt = true; -// return this; -// } - -// /** -// * Retrieves the color index of the block. This is is the same color used by vanilla maps to represent this block. -// */ -// public MapColor getMaterialMapColor() -// { -// return this.materialMapColor; -// } -} diff --git a/java/src/game/material/MaterialColdFluid.java b/java/src/game/material/MaterialColdFluid.java deleted file mode 100755 index 5d27283..0000000 --- a/java/src/game/material/MaterialColdFluid.java +++ /dev/null @@ -1,24 +0,0 @@ -package game.material; - -public class MaterialColdFluid extends Material { - public MaterialColdFluid() { - this.setReplaceable(); - this.setNoPushMobility(); - } - - public boolean isLiquid() { - return true; - } - - public boolean isColdLiquid() { - return true; - } - - public boolean blocksMovement() { - return false; - } - - public boolean isSolid() { - return false; - } -} diff --git a/java/src/game/material/MaterialHotFluid.java b/java/src/game/material/MaterialHotFluid.java deleted file mode 100755 index e7a31b1..0000000 --- a/java/src/game/material/MaterialHotFluid.java +++ /dev/null @@ -1,24 +0,0 @@ -package game.material; - -public class MaterialHotFluid extends Material { - public MaterialHotFluid() { - this.setReplaceable(); - this.setNoPushMobility(); - } - - public boolean isLiquid() { - return true; - } - - public boolean isHotLiquid() { - return true; - } - - public boolean blocksMovement() { - return false; - } - - public boolean isSolid() { - return false; - } -} diff --git a/java/src/game/material/MaterialLogic.java b/java/src/game/material/MaterialLogic.java deleted file mode 100755 index a5572c6..0000000 --- a/java/src/game/material/MaterialLogic.java +++ /dev/null @@ -1,28 +0,0 @@ -package game.material; - -public class MaterialLogic extends Material -{ - /** - * Returns true if the block is a considered solid. This is true by default. - */ - public boolean isSolid() - { - return false; - } - - /** - * Will prevent grass from growing on dirt underneath and kill any grass below it if it returns true - */ - public boolean blocksLight() - { - return false; - } - - /** - * Returns if this material is considered solid or not - */ - public boolean blocksMovement() - { - return false; - } -} diff --git a/java/src/game/material/MaterialPortal.java b/java/src/game/material/MaterialPortal.java deleted file mode 100755 index 56d0362..0000000 --- a/java/src/game/material/MaterialPortal.java +++ /dev/null @@ -1,28 +0,0 @@ -package game.material; - -public class MaterialPortal extends Material -{ - /** - * Returns true if the block is a considered solid. This is true by default. - */ - public boolean isSolid() - { - return false; - } - - /** - * Will prevent grass from growing on dirt underneath and kill any grass below it if it returns true - */ - public boolean blocksLight() - { - return false; - } - - /** - * Returns if this material is considered solid or not - */ - public boolean blocksMovement() - { - return false; - } -} diff --git a/java/src/game/material/MaterialTransparent.java b/java/src/game/material/MaterialTransparent.java deleted file mode 100755 index 2ab99c4..0000000 --- a/java/src/game/material/MaterialTransparent.java +++ /dev/null @@ -1,33 +0,0 @@ -package game.material; - -public class MaterialTransparent extends Material -{ - public MaterialTransparent() - { - this.setReplaceable(); - } - - /** - * Returns true if the block is a considered solid. This is true by default. - */ - public boolean isSolid() - { - return false; - } - - /** - * Will prevent grass from growing on dirt underneath and kill any grass below it if it returns true - */ - public boolean blocksLight() - { - return false; - } - - /** - * Returns if this material is considered solid or not - */ - public boolean blocksMovement() - { - return false; - } -} diff --git a/java/src/game/model/BakedModel.java b/java/src/game/model/BakedModel.java deleted file mode 100755 index 8227641..0000000 --- a/java/src/game/model/BakedModel.java +++ /dev/null @@ -1,157 +0,0 @@ -package game.model; - -import java.util.ArrayList; -import java.util.List; - -import game.collect.Lists; - -import game.renderer.blockmodel.BakedQuad; -import game.renderer.blockmodel.BreakingFour; -import game.renderer.blockmodel.ModelBlock; -import game.renderer.blockmodel.Transforms; -import game.renderer.texture.TextureAtlasSprite; -import game.world.Facing; - -public class BakedModel implements IBakedModel -{ - protected final List generalQuads; - protected final List> faceQuads; - protected final boolean ambientOcclusion; - protected final boolean gui3d; - protected final TextureAtlasSprite texture; - protected final Transforms cameraTransforms; - - public BakedModel(List generalQuadsIn, List> faceQuadsIn, boolean ambientOcclusionIn, boolean gui3dIn, TextureAtlasSprite textureIn, Transforms cameraTransformsIn) - { - this.generalQuads = generalQuadsIn; - this.faceQuads = faceQuadsIn; - this.ambientOcclusion = ambientOcclusionIn; - this.gui3d = gui3dIn; - this.texture = textureIn; - this.cameraTransforms = cameraTransformsIn; - } - - public List getFaceQuads(Facing facing) - { - return this.faceQuads.get(facing.ordinal()); - } - - public List getGeneralQuads() - { - return this.generalQuads; - } - - public boolean isAmbientOcclusion() - { - return this.ambientOcclusion; - } - - public boolean isGui3d() - { - return this.gui3d; - } - - public boolean isBuiltInRenderer() - { - return false; - } - - public TextureAtlasSprite getParticleTexture() - { - return this.texture; - } - - public Transforms getItemCameraTransforms() - { - return this.cameraTransforms; - } - - public static class Builder - { - private final List builderGeneralQuads; - private final List> builderFaceQuads; - private final boolean builderAmbientOcclusion; - private TextureAtlasSprite builderTexture; - private boolean builderGui3d; - private Transforms builderCameraTransforms; - - public Builder(ModelBlock model) - { - this(model.isAmbientOcclusion(), model.isGui3d(), model.getTransform()); - } - - public Builder(IBakedModel bakedModel, TextureAtlasSprite texture) - { - this(bakedModel.isAmbientOcclusion(), bakedModel.isGui3d(), bakedModel.getItemCameraTransforms()); - this.builderTexture = bakedModel.getParticleTexture(); - - for (Facing enumfacing : Facing.values()) - { - this.addFaceBreakingFours(bakedModel, texture, enumfacing); - } - - this.addGeneralBreakingFours(bakedModel, texture); - } - - private void addFaceBreakingFours(IBakedModel bakedModel, TextureAtlasSprite texture, Facing facing) - { - for (BakedQuad bakedquad : bakedModel.getFaceQuads(facing)) - { - this.addFaceQuad(facing, new BreakingFour(bakedquad, texture)); - } - } - - private void addGeneralBreakingFours(IBakedModel p_177647_1_, TextureAtlasSprite texture) - { - for (BakedQuad bakedquad : p_177647_1_.getGeneralQuads()) - { - this.addGeneralQuad(new BreakingFour(bakedquad, texture)); - } - } - - private Builder(boolean ambientOcclusion, boolean gui3d, Transforms cameraTransforms) - { - this.builderGeneralQuads = Lists.newArrayList(); - this.builderFaceQuads = new ArrayList>(6); - - for (Facing enumfacing : Facing.values()) - { - this.builderFaceQuads.add(Lists.newArrayList()); - } - - this.builderAmbientOcclusion = ambientOcclusion; - this.builderGui3d = gui3d; - this.builderCameraTransforms = cameraTransforms; - } - - public BakedModel.Builder addFaceQuad(Facing facing, BakedQuad quad) - { - ((List)this.builderFaceQuads.get(facing.ordinal())).add(quad); - return this; - } - - public BakedModel.Builder addGeneralQuad(BakedQuad quad) - { - this.builderGeneralQuads.add(quad); - return this; - } - - public BakedModel.Builder setTexture(TextureAtlasSprite texture) - { - this.builderTexture = texture; - return this; - } - - public BakedModel makeBakedModel() - { - if (this.builderTexture == null) - { - throw new RuntimeException("Missing particle!"); - } - else - { - return new BakedModel(this.builderGeneralQuads, this.builderFaceQuads, this.builderAmbientOcclusion, this.builderGui3d, this.builderTexture, this.builderCameraTransforms); - } - } - } -} diff --git a/java/src/game/model/BuiltInModel.java b/java/src/game/model/BuiltInModel.java deleted file mode 100755 index 82611a5..0000000 --- a/java/src/game/model/BuiltInModel.java +++ /dev/null @@ -1,53 +0,0 @@ -package game.model; - -import java.util.List; - -import game.renderer.blockmodel.BakedQuad; -import game.renderer.blockmodel.Transforms; -import game.renderer.texture.TextureAtlasSprite; -import game.world.Facing; - -public class BuiltInModel implements IBakedModel -{ - private Transforms cameraTransforms; - - public BuiltInModel(Transforms p_i46086_1_) - { - this.cameraTransforms = p_i46086_1_; - } - - public List getFaceQuads(Facing facing) - { - return null; - } - - public List getGeneralQuads() - { - return null; - } - - public boolean isAmbientOcclusion() - { - return false; - } - - public boolean isGui3d() - { - return true; - } - - public boolean isBuiltInRenderer() - { - return true; - } - - public TextureAtlasSprite getParticleTexture() - { - return null; - } - - public Transforms getItemCameraTransforms() - { - return this.cameraTransforms; - } -} diff --git a/java/src/game/model/IBakedModel.java b/java/src/game/model/IBakedModel.java deleted file mode 100755 index b37bf6c..0000000 --- a/java/src/game/model/IBakedModel.java +++ /dev/null @@ -1,25 +0,0 @@ -package game.model; - -import java.util.List; - -import game.renderer.blockmodel.BakedQuad; -import game.renderer.blockmodel.Transforms; -import game.renderer.texture.TextureAtlasSprite; -import game.world.Facing; - -public interface IBakedModel -{ - List getFaceQuads(Facing facing); - - List getGeneralQuads(); - - boolean isAmbientOcclusion(); - - boolean isGui3d(); - - boolean isBuiltInRenderer(); - - TextureAtlasSprite getParticleTexture(); - - Transforms getItemCameraTransforms(); -} diff --git a/java/src/game/nbt/NBTBase.java b/java/src/game/nbt/NBTBase.java deleted file mode 100755 index 9e9e144..0000000 --- a/java/src/game/nbt/NBTBase.java +++ /dev/null @@ -1,123 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public abstract class NBTBase -{ - public static final String[] NBT_TYPES = new String[] {"END", "BYTE", "SHORT", "INT", "LONG", "FLOAT", "DOUBLE", "BYTE[]", "STRING", "LIST", "COMPOUND", "INT[]"}; - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - abstract void write(DataOutput output) throws IOException; - - abstract void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException; - - public abstract String toString(); - - /** - * Gets the type byte for the tag. - */ - public abstract byte getId(); - - /** - * Creates a new NBTBase object that corresponds with the passed in id. - */ - protected static NBTBase createNewByType(byte id) - { - switch (id) - { - case 0: - return new NBTTagEnd(); - - case 1: - return new NBTTagByte(); - - case 2: - return new NBTTagShort(); - - case 3: - return new NBTTagInt(); - - case 4: - return new NBTTagLong(); - - case 5: - return new NBTTagFloat(); - - case 6: - return new NBTTagDouble(); - - case 7: - return new NBTTagByteArray(); - - case 8: - return new NBTTagString(); - - case 9: - return new NBTTagList(); - - case 10: - return new NBTTagCompound(); - - case 11: - return new NBTTagIntArray(); - - default: - return null; - } - } - - /** - * Creates a clone of the tag. - */ - public abstract NBTBase copy(); - - /** - * Return whether this compound has no tags. - */ - public boolean hasNoTags() - { - return false; - } - - public boolean equals(Object p_equals_1_) - { - if (!(p_equals_1_ instanceof NBTBase)) - { - return false; - } - else - { - NBTBase nbtbase = (NBTBase)p_equals_1_; - return this.getId() == nbtbase.getId(); - } - } - - public int hashCode() - { - return this.getId(); - } - - protected String getString() - { - return this.toString(); - } - - public abstract static class NBTPrimitive extends NBTBase - { - public abstract long getLong(); - - public abstract int getInt(); - - public abstract short getShort(); - - public abstract byte getByte(); - - public abstract double getDouble(); - - public abstract float getFloat(); - } -} diff --git a/java/src/game/nbt/NBTException.java b/java/src/game/nbt/NBTException.java deleted file mode 100755 index af15215..0000000 --- a/java/src/game/nbt/NBTException.java +++ /dev/null @@ -1,9 +0,0 @@ -package game.nbt; - -public class NBTException extends Exception -{ - public NBTException(String p_i45136_1_) - { - super(p_i45136_1_); - } -} diff --git a/java/src/game/nbt/NBTLoader.java b/java/src/game/nbt/NBTLoader.java deleted file mode 100755 index c135579..0000000 --- a/java/src/game/nbt/NBTLoader.java +++ /dev/null @@ -1,148 +0,0 @@ -package game.nbt; - -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.DataInput; -import java.io.DataInputStream; -import java.io.DataOutput; -import java.io.DataOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.zip.GZIPInputStream; -import java.util.zip.GZIPOutputStream; - -public class NBTLoader { - public static NBTTagCompound readGZip(File file) throws IOException { - DataInputStream in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream(file)))); - NBTTagCompound tag; - - try { - tag = read(in, NBTSizeTracker.INFINITE); - } - finally { - in.close(); - } - - return tag; - } - - public static void writeGZip(NBTTagCompound tag, File file) throws IOException { - DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(file)))); - - try { - write(tag, out); - } - finally { - out.close(); - } - } - -// public static void safeWrite(NBTTagCompound p_74793_0_, File p_74793_1_) throws IOException -// { -// File file1 = new File(p_74793_1_.getAbsolutePath() + "_tmp"); -// -// if (file1.exists()) -// { -// file1.delete(); -// } -// -// write(p_74793_0_, file1); -// -// if (p_74793_1_.exists()) -// { -// p_74793_1_.delete(); -// } -// -// if (p_74793_1_.exists()) -// { -// throw new IOException("Failed to delete " + p_74793_1_); -// } -// else -// { -// file1.renameTo(p_74793_1_); -// } -// } - -// public static void write(NBTTagCompound p_74795_0_, File p_74795_1_) throws IOException -// { -// DataOutputStream dataoutputstream = new DataOutputStream(new FileOutputStream(p_74795_1_)); -// -// try -// { -// write(p_74795_0_, dataoutputstream); -// } -// finally -// { -// dataoutputstream.close(); -// } -// } - -// public static NBTTagCompound read(File p_74797_0_) throws IOException -// { -// if (!p_74797_0_.exists()) -// { -// return null; -// } -// else -// { -// DataInputStream datainputstream = new DataInputStream(new FileInputStream(p_74797_0_)); -// NBTTagCompound nbttagcompound; -// -// try -// { -// nbttagcompound = read(datainputstream, NBTSizeTracker.INFINITE); -// } -// finally -// { -// datainputstream.close(); -// } -// -// return nbttagcompound; -// } -// } - - public static NBTTagCompound read(DataInputStream in) throws IOException { - return read(in, NBTSizeTracker.INFINITE); - } - - public static NBTTagCompound read(DataInput in, NBTSizeTracker tracker) throws IOException { - NBTBase tag = readType(in, 0, tracker); - - if(tag instanceof NBTTagCompound) { - return (NBTTagCompound)tag; - } - else { - throw new IOException("Root tag must be a named compound tag"); - } - } - - public static void write(NBTTagCompound tag, DataOutput out) throws IOException { - writeTag(tag, out); - } - - private static void writeTag(NBTBase tag, DataOutput out) throws IOException { - out.writeByte(tag.getId()); - - if(tag.getId() != 0) { - out.writeUTF(""); - tag.write(out); - } - } - - private static NBTBase readType(DataInput in, int depth, NBTSizeTracker tracker) throws IOException { - byte type = in.readByte(); - - if(type == 0) { - return new NBTTagEnd(); - } - else { - in.readUTF(); - NBTBase tag = NBTBase.createNewByType(type); - - tag.read(in, depth, tracker); - return tag; - } - } -} diff --git a/java/src/game/nbt/NBTParser.java b/java/src/game/nbt/NBTParser.java deleted file mode 100755 index e4a2e97..0000000 --- a/java/src/game/nbt/NBTParser.java +++ /dev/null @@ -1,549 +0,0 @@ -package game.nbt; - -import java.util.Stack; -import java.util.regex.Pattern; - -import game.collect.Lists; - -public class NBTParser -{ - private static final Pattern PATTERN = Pattern.compile("\\[[-+\\d|,\\s]+\\]"); - - public static NBTTagCompound parseTag(String jsonString) throws NBTException - { - jsonString = jsonString.trim(); - - if (!jsonString.startsWith("{")) - { - throw new NBTException("Invalid tag encountered, expected \'{\' as first char."); - } - else if (func_150310_b(jsonString) != 1) - { - throw new NBTException("Encountered multiple top tags, only one expected"); - } - else - { - return (NBTTagCompound)func_150316_a("tag", jsonString).parse(); - } - } - - static int func_150310_b(String p_150310_0_) throws NBTException - { - int i = 0; - boolean flag = false; - Stack stack = new Stack(); - - for (int j = 0; j < p_150310_0_.length(); ++j) - { - char c0 = p_150310_0_.charAt(j); - - if (c0 == 34) - { - if (func_179271_b(p_150310_0_, j)) - { - if (!flag) - { - throw new NBTException("Illegal use of \\\": " + p_150310_0_); - } - } - else - { - flag = !flag; - } - } - else if (!flag) - { - if (c0 != 123 && c0 != 91) - { - if (c0 == 125 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 123)) - { - throw new NBTException("Unbalanced curly brackets {}: " + p_150310_0_); - } - - if (c0 == 93 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 91)) - { - throw new NBTException("Unbalanced square brackets []: " + p_150310_0_); - } - } - else - { - if (stack.isEmpty()) - { - ++i; - } - - stack.push(Character.valueOf(c0)); - } - } - } - - if (flag) - { - throw new NBTException("Unbalanced quotation: " + p_150310_0_); - } - else if (!stack.isEmpty()) - { - throw new NBTException("Unbalanced brackets: " + p_150310_0_); - } - else - { - if (i == 0 && !p_150310_0_.isEmpty()) - { - i = 1; - } - - return i; - } - } - -// static JsonToNBT.Any func_179272_a(String s1, String s2) throws NBTException -// { -// return func_150316_a(s1, s2); -// } - - static NBTParser.Any func_150316_a(String p_150316_0_, String p_150316_1_) throws NBTException - { - p_150316_1_ = p_150316_1_.trim(); - - if (p_150316_1_.startsWith("{")) - { - p_150316_1_ = p_150316_1_.substring(1, p_150316_1_.length() - 1); - NBTParser.Compound jsontonbt$compound; - String s1; - - for (jsontonbt$compound = new NBTParser.Compound(p_150316_0_); p_150316_1_.length() > 0; p_150316_1_ = p_150316_1_.substring(s1.length() + 1)) - { - s1 = func_150314_a(p_150316_1_, true); - - if (s1.length() > 0) - { - boolean flag1 = false; - jsontonbt$compound.field_150491_b.add(func_179270_a(s1, flag1)); - } - - if (p_150316_1_.length() < s1.length() + 1) - { - break; - } - - char c1 = p_150316_1_.charAt(s1.length()); - - if (c1 != 44 && c1 != 123 && c1 != 125 && c1 != 91 && c1 != 93) - { - throw new NBTException("Unexpected token \'" + c1 + "\' at: " + p_150316_1_.substring(s1.length())); - } - } - - return jsontonbt$compound; - } - else if (p_150316_1_.startsWith("[") && !PATTERN.matcher(p_150316_1_).matches()) - { - p_150316_1_ = p_150316_1_.substring(1, p_150316_1_.length() - 1); - NBTParser.List jsontonbt$list; - String s; - - for (jsontonbt$list = new NBTParser.List(p_150316_0_); p_150316_1_.length() > 0; p_150316_1_ = p_150316_1_.substring(s.length() + 1)) - { - s = func_150314_a(p_150316_1_, false); - - if (s.length() > 0) - { - boolean flag = true; - jsontonbt$list.field_150492_b.add(func_179270_a(s, flag)); - } - - if (p_150316_1_.length() < s.length() + 1) - { - break; - } - - char c0 = p_150316_1_.charAt(s.length()); - - if (c0 != 44 && c0 != 123 && c0 != 125 && c0 != 91 && c0 != 93) - { - throw new NBTException("Unexpected token \'" + c0 + "\' at: " + p_150316_1_.substring(s.length())); - } - } - - return jsontonbt$list; - } - else - { - return new NBTParser.Primitive(p_150316_0_, p_150316_1_); - } - } - - private static NBTParser.Any func_179270_a(String p_179270_0_, boolean p_179270_1_) throws NBTException - { - String s = func_150313_b(p_179270_0_, p_179270_1_); - String s1 = func_150311_c(p_179270_0_, p_179270_1_); - return func_150316_a(s, s1); - } - - private static String func_150314_a(String p_150314_0_, boolean p_150314_1_) throws NBTException - { - int i = func_150312_a(p_150314_0_, ':'); - int j = func_150312_a(p_150314_0_, ','); - - if (p_150314_1_) - { - if (i == -1) - { - throw new NBTException("Unable to locate name/value separator for string: " + p_150314_0_); - } - - if (j != -1 && j < i) - { - throw new NBTException("Name error at: " + p_150314_0_); - } - } - else if (i == -1 || i > j) - { - i = -1; - } - - return func_179269_a(p_150314_0_, i); - } - - private static String func_179269_a(String p_179269_0_, int p_179269_1_) throws NBTException - { - Stack stack = new Stack(); - int i = p_179269_1_ + 1; - boolean flag = false; - boolean flag1 = false; - boolean flag2 = false; - - for (int j = 0; i < p_179269_0_.length(); ++i) - { - char c0 = p_179269_0_.charAt(i); - - if (c0 == 34) - { - if (func_179271_b(p_179269_0_, i)) - { - if (!flag) - { - throw new NBTException("Illegal use of \\\": " + p_179269_0_); - } - } - else - { - flag = !flag; - - if (flag && !flag2) - { - flag1 = true; - } - - if (!flag) - { - j = i; - } - } - } - else if (!flag) - { - if (c0 != 123 && c0 != 91) - { - if (c0 == 125 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 123)) - { - throw new NBTException("Unbalanced curly brackets {}: " + p_179269_0_); - } - - if (c0 == 93 && (stack.isEmpty() || ((Character)stack.pop()).charValue() != 91)) - { - throw new NBTException("Unbalanced square brackets []: " + p_179269_0_); - } - - if (c0 == 44 && stack.isEmpty()) - { - return p_179269_0_.substring(0, i); - } - } - else - { - stack.push(Character.valueOf(c0)); - } - } - - if (!Character.isWhitespace(c0)) - { - if (!flag && flag1 && j != i) - { - return p_179269_0_.substring(0, j + 1); - } - - flag2 = true; - } - } - - return p_179269_0_.substring(0, i); - } - - private static String func_150313_b(String p_150313_0_, boolean p_150313_1_) throws NBTException - { - if (p_150313_1_) - { - p_150313_0_ = p_150313_0_.trim(); - - if (p_150313_0_.startsWith("{") || p_150313_0_.startsWith("[")) - { - return ""; - } - } - - int i = func_150312_a(p_150313_0_, ':'); - - if (i == -1) - { - if (p_150313_1_) - { - return ""; - } - else - { - throw new NBTException("Unable to locate name/value separator for string: " + p_150313_0_); - } - } - else - { - return p_150313_0_.substring(0, i).trim(); - } - } - - private static String func_150311_c(String p_150311_0_, boolean p_150311_1_) throws NBTException - { - if (p_150311_1_) - { - p_150311_0_ = p_150311_0_.trim(); - - if (p_150311_0_.startsWith("{") || p_150311_0_.startsWith("[")) - { - return p_150311_0_; - } - } - - int i = func_150312_a(p_150311_0_, ':'); - - if (i == -1) - { - if (p_150311_1_) - { - return p_150311_0_; - } - else - { - throw new NBTException("Unable to locate name/value separator for string: " + p_150311_0_); - } - } - else - { - return p_150311_0_.substring(i + 1).trim(); - } - } - - private static int func_150312_a(String p_150312_0_, char p_150312_1_) - { - int i = 0; - - for (boolean flag = true; i < p_150312_0_.length(); ++i) - { - char c0 = p_150312_0_.charAt(i); - - if (c0 == 34) - { - if (!func_179271_b(p_150312_0_, i)) - { - flag = !flag; - } - } - else if (flag) - { - if (c0 == p_150312_1_) - { - return i; - } - - if (c0 == 123 || c0 == 91) - { - return -1; - } - } - } - - return -1; - } - - private static boolean func_179271_b(String p_179271_0_, int p_179271_1_) - { - return p_179271_1_ > 0 && p_179271_0_.charAt(p_179271_1_ - 1) == 92 && !func_179271_b(p_179271_0_, p_179271_1_ - 1); - } - - abstract static class Any - { - protected String json; - - public abstract NBTBase parse() throws NBTException; - } - - static class Compound extends NBTParser.Any - { - protected java.util.List field_150491_b = Lists.newArrayList(); - - public Compound(String p_i45137_1_) - { - this.json = p_i45137_1_; - } - - public NBTBase parse() throws NBTException - { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - for (NBTParser.Any jsontonbt$any : this.field_150491_b) - { - nbttagcompound.setTag(jsontonbt$any.json, jsontonbt$any.parse()); - } - - return nbttagcompound; - } - } - - static class List extends NBTParser.Any - { - protected java.util.List field_150492_b = Lists.newArrayList(); - - public List(String json) - { - this.json = json; - } - - public NBTBase parse() throws NBTException - { - NBTTagList nbttaglist = new NBTTagList(); - - for (NBTParser.Any jsontonbt$any : this.field_150492_b) - { - nbttaglist.appendTag(jsontonbt$any.parse()); - } - - return nbttaglist; - } - } - - static class Primitive extends NBTParser.Any - { - private static final Pattern DOUBLE = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[d|D]"); - private static final Pattern FLOAT = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+[f|F]"); - private static final Pattern BYTE = Pattern.compile("[-+]?[0-9]+[b|B]"); - private static final Pattern LONG = Pattern.compile("[-+]?[0-9]+[l|L]"); - private static final Pattern SHORT = Pattern.compile("[-+]?[0-9]+[s|S]"); - private static final Pattern INTEGER = Pattern.compile("[-+]?[0-9]+"); - private static final Pattern DOUBLE_UNTYPED = Pattern.compile("[-+]?[0-9]*\\.?[0-9]+"); -// private static final Splitter SPLITTER = Splitter.on(',').omitEmptyStrings(); - protected String jsonValue; - - public Primitive(String p_i45139_1_, String p_i45139_2_) - { - this.json = p_i45139_1_; - this.jsonValue = p_i45139_2_; - } - - public NBTBase parse() throws NBTException - { - try - { - if (DOUBLE.matcher(this.jsonValue).matches()) - { - return new NBTTagDouble(Double.parseDouble(this.jsonValue.substring(0, this.jsonValue.length() - 1))); - } - - if (FLOAT.matcher(this.jsonValue).matches()) - { - return new NBTTagFloat(Float.parseFloat(this.jsonValue.substring(0, this.jsonValue.length() - 1))); - } - - if (BYTE.matcher(this.jsonValue).matches()) - { - return new NBTTagByte(Byte.parseByte(this.jsonValue.substring(0, this.jsonValue.length() - 1))); - } - - if (LONG.matcher(this.jsonValue).matches()) - { - return new NBTTagLong(Long.parseLong(this.jsonValue.substring(0, this.jsonValue.length() - 1))); - } - - if (SHORT.matcher(this.jsonValue).matches()) - { - return new NBTTagShort(Short.parseShort(this.jsonValue.substring(0, this.jsonValue.length() - 1))); - } - - if (INTEGER.matcher(this.jsonValue).matches()) - { - return new NBTTagInt(Integer.parseInt(this.jsonValue)); - } - - if (DOUBLE_UNTYPED.matcher(this.jsonValue).matches()) - { - return new NBTTagDouble(Double.parseDouble(this.jsonValue)); - } - - if (this.jsonValue.equalsIgnoreCase("true") || this.jsonValue.equalsIgnoreCase("false")) - { - return new NBTTagByte((byte)(Boolean.parseBoolean(this.jsonValue) ? 1 : 0)); - } - } - catch (NumberFormatException var6) - { - this.jsonValue = this.jsonValue.replaceAll("\\\\\"", "\""); - return new NBTTagString(this.jsonValue); - } - - if (this.jsonValue.startsWith("[") && this.jsonValue.endsWith("]")) - { - String s = this.jsonValue.substring(1, this.jsonValue.length() - 1); - String[] astring = s.split(","); - - try - { - int[] aint = new int[astring.length]; - - for (int j = 0; j < astring.length; ++j) - { - aint[j] = Integer.parseInt(astring[j].trim()); - } - - return new NBTTagIntArray(aint); - } - catch (NumberFormatException var5) - { - return new NBTTagString(this.jsonValue); - } - } - else - { - if (this.jsonValue.startsWith("\"") && this.jsonValue.endsWith("\"")) - { - this.jsonValue = this.jsonValue.substring(1, this.jsonValue.length() - 1); - } - - this.jsonValue = this.jsonValue.replaceAll("\\\\\"", "\""); - StringBuilder stringbuilder = new StringBuilder(); - - for (int i = 0; i < this.jsonValue.length(); ++i) - { - if (i < this.jsonValue.length() - 1 && this.jsonValue.charAt(i) == 92 && this.jsonValue.charAt(i + 1) == 92) - { - stringbuilder.append('\\'); - ++i; - } - else - { - stringbuilder.append(this.jsonValue.charAt(i)); - } - } - - return new NBTTagString(stringbuilder.toString()); - } - } - } -} diff --git a/java/src/game/nbt/NBTSizeTracker.java b/java/src/game/nbt/NBTSizeTracker.java deleted file mode 100755 index 6075e06..0000000 --- a/java/src/game/nbt/NBTSizeTracker.java +++ /dev/null @@ -1,31 +0,0 @@ -package game.nbt; - -public class NBTSizeTracker -{ - public static final NBTSizeTracker INFINITE = new NBTSizeTracker(0L) - { - public void read(long bits) - { - } - }; - private final long max; - private long read; - - public NBTSizeTracker(long max) - { - this.max = max; - } - - /** - * Tracks the reading of the given amount of bits(!) - */ - public void read(long bits) - { - this.read += bits / 8L; - - if (this.read > this.max) - { - throw new RuntimeException("Tried to read NBT tag that was too big; tried to allocate: " + this.read + "bytes where max allowed: " + this.max); - } - } -} diff --git a/java/src/game/nbt/NBTTagByte.java b/java/src/game/nbt/NBTTagByte.java deleted file mode 100755 index 7bf606b..0000000 --- a/java/src/game/nbt/NBTTagByte.java +++ /dev/null @@ -1,103 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class NBTTagByte extends NBTBase.NBTPrimitive -{ - /** The byte value for the tag. */ - private byte data; - - NBTTagByte() - { - } - - public NBTTagByte(byte data) - { - this.data = data; - } - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - output.writeByte(this.data); - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(72L); - this.data = input.readByte(); - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)1; - } - - public String toString() - { - return "" + this.data + "b"; - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - return new NBTTagByte(this.data); - } - - public boolean equals(Object p_equals_1_) - { - if (super.equals(p_equals_1_)) - { - NBTTagByte nbttagbyte = (NBTTagByte)p_equals_1_; - return this.data == nbttagbyte.data; - } - else - { - return false; - } - } - - public int hashCode() - { - return super.hashCode() ^ this.data; - } - - public long getLong() - { - return (long)this.data; - } - - public int getInt() - { - return this.data; - } - - public short getShort() - { - return (short)this.data; - } - - public byte getByte() - { - return this.data; - } - - public double getDouble() - { - return (double)this.data; - } - - public float getFloat() - { - return (float)this.data; - } -} diff --git a/java/src/game/nbt/NBTTagByteArray.java b/java/src/game/nbt/NBTTagByteArray.java deleted file mode 100755 index eb68b0f..0000000 --- a/java/src/game/nbt/NBTTagByteArray.java +++ /dev/null @@ -1,77 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Arrays; - -public class NBTTagByteArray extends NBTBase -{ - /** The byte array stored in the tag. */ - private byte[] data; - - NBTTagByteArray() - { - } - - public NBTTagByteArray(byte[] data) - { - this.data = data; - } - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - output.writeInt(this.data.length); - output.write(this.data); - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(192L); - int i = input.readInt(); - sizeTracker.read((long)(8 * i)); - this.data = new byte[i]; - input.readFully(this.data); - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)7; - } - - public String toString() - { - return "[" + this.data.length + " bytes]"; - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - byte[] abyte = new byte[this.data.length]; - System.arraycopy(this.data, 0, abyte, 0, this.data.length); - return new NBTTagByteArray(abyte); - } - - public boolean equals(Object p_equals_1_) - { - return super.equals(p_equals_1_) ? Arrays.equals(this.data, ((NBTTagByteArray)p_equals_1_).data) : false; - } - - public int hashCode() - { - return super.hashCode() ^ Arrays.hashCode(this.data); - } - - public byte[] getByteArray() - { - return this.data; - } -} diff --git a/java/src/game/nbt/NBTTagCompound.java b/java/src/game/nbt/NBTTagCompound.java deleted file mode 100755 index 4606414..0000000 --- a/java/src/game/nbt/NBTTagCompound.java +++ /dev/null @@ -1,484 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Set; - -import game.collect.Maps; - -public class NBTTagCompound extends NBTBase -{ - private Map tagMap = Maps.newHashMap(); - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - for (String s : this.tagMap.keySet()) - { - NBTBase nbtbase = (NBTBase)this.tagMap.get(s); - writeEntry(s, nbtbase, output); - } - - output.writeByte(0); - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(384L); - - if (depth > 512) - { - throw new RuntimeException("Tried to read NBT tag with too high complexity, depth > 512"); - } - else - { - this.tagMap.clear(); - byte b0; - - while ((b0 = readType(input, sizeTracker)) != 0) - { - String s = readKey(input, sizeTracker); - sizeTracker.read((long)(224 + 16 * s.length())); - NBTBase nbtbase = readNBT(b0, s, input, depth + 1, sizeTracker); - - if (this.tagMap.put(s, nbtbase) != null) - { - sizeTracker.read(288L); - } - } - } - } - - public Set getKeySet() - { - return this.tagMap.keySet(); - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)10; - } - - /** - * Stores the given tag into the map with the given string key. This is mostly used to store tag lists. - */ - public void setTag(String key, NBTBase value) - { - this.tagMap.put(key, value); - } - - /** - * Stores a new NBTTagByte with the given byte value into the map with the given string key. - */ - public void setByte(String key, byte value) - { - this.tagMap.put(key, new NBTTagByte(value)); - } - - /** - * Stores a new NBTTagShort with the given short value into the map with the given string key. - */ - public void setShort(String key, short value) - { - this.tagMap.put(key, new NBTTagShort(value)); - } - - /** - * Stores a new NBTTagInt with the given integer value into the map with the given string key. - */ - public void setInteger(String key, int value) - { - this.tagMap.put(key, new NBTTagInt(value)); - } - - /** - * Stores a new NBTTagLong with the given long value into the map with the given string key. - */ - public void setLong(String key, long value) - { - this.tagMap.put(key, new NBTTagLong(value)); - } - - /** - * Stores a new NBTTagFloat with the given float value into the map with the given string key. - */ - public void setFloat(String key, float value) - { - this.tagMap.put(key, new NBTTagFloat(value)); - } - - /** - * Stores a new NBTTagDouble with the given double value into the map with the given string key. - */ - public void setDouble(String key, double value) - { - this.tagMap.put(key, new NBTTagDouble(value)); - } - - /** - * Stores a new NBTTagString with the given string value into the map with the given string key. - */ - public void setString(String key, String value) - { - this.tagMap.put(key, new NBTTagString(value)); - } - - /** - * Stores a new NBTTagByteArray with the given array as data into the map with the given string key. - */ - public void setByteArray(String key, byte[] value) - { - this.tagMap.put(key, new NBTTagByteArray(value)); - } - - /** - * Stores a new NBTTagIntArray with the given array as data into the map with the given string key. - */ - public void setIntArray(String key, int[] value) - { - this.tagMap.put(key, new NBTTagIntArray(value)); - } - - /** - * Stores the given boolean value as a NBTTagByte, storing 1 for true and 0 for false, using the given string key. - */ - public void setBoolean(String key, boolean value) - { - this.setByte(key, (byte)(value ? 1 : 0)); - } - - /** - * gets a generic tag with the specified name - */ - public NBTBase getTag(String key) - { - return (NBTBase)this.tagMap.get(key); - } - - /** - * Gets the ID byte for the given tag key - */ - public byte getTagId(String key) - { - NBTBase nbtbase = (NBTBase)this.tagMap.get(key); - return nbtbase != null ? nbtbase.getId() : 0; - } - - /** - * Returns whether the given string has been previously stored as a key in the map. - */ - public boolean hasKey(String key) - { - return this.tagMap.containsKey(key); - } - - public boolean hasKey(String key, int type) - { - int i = this.getTagId(key); - - if (i == type) - { - return true; - } - else if (type != 99) - { - if (i > 0) - { - ; - } - - return false; - } - else - { - return i == 1 || i == 2 || i == 3 || i == 4 || i == 5 || i == 6; - } - } - - /** - * Retrieves a byte value using the specified key, or 0 if no such key was stored. - */ - public byte getByte(String key) - { - try - { - return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getByte(); - } - catch (ClassCastException var3) - { - return (byte)0; - } - } - - /** - * Retrieves a short value using the specified key, or 0 if no such key was stored. - */ - public short getShort(String key) - { - try - { - return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getShort(); - } - catch (ClassCastException var3) - { - return (short)0; - } - } - - /** - * Retrieves an integer value using the specified key, or 0 if no such key was stored. - */ - public int getInteger(String key) - { - try - { - return !this.hasKey(key, 99) ? 0 : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getInt(); - } - catch (ClassCastException var3) - { - return 0; - } - } - - /** - * Retrieves a long value using the specified key, or 0 if no such key was stored. - */ - public long getLong(String key) - { - try - { - return !this.hasKey(key, 99) ? 0L : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getLong(); - } - catch (ClassCastException var3) - { - return 0L; - } - } - - /** - * Retrieves a float value using the specified key, or 0 if no such key was stored. - */ - public float getFloat(String key) - { - try - { - return !this.hasKey(key, 99) ? 0.0F : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getFloat(); - } - catch (ClassCastException var3) - { - return 0.0F; - } - } - - /** - * Retrieves a double value using the specified key, or 0 if no such key was stored. - */ - public double getDouble(String key) - { - try - { - return !this.hasKey(key, 99) ? 0.0D : ((NBTBase.NBTPrimitive)this.tagMap.get(key)).getDouble(); - } - catch (ClassCastException var3) - { - return 0.0D; - } - } - - /** - * Retrieves a string value using the specified key, or an empty string if no such key was stored. - */ - public String getString(String key) - { - try - { - return !this.hasKey(key, 8) ? "" : ((NBTBase)this.tagMap.get(key)).getString(); - } - catch (ClassCastException var3) - { - return ""; - } - } - - /** - * Retrieves a byte array using the specified key, or a zero-length array if no such key was stored. - */ - public byte[] getByteArray(String key) - { - return !this.hasKey(key, 7) ? new byte[0] : ((NBTTagByteArray)this.tagMap.get(key)).getByteArray(); - } - - /** - * Retrieves an int array using the specified key, or a zero-length array if no such key was stored. - */ - public int[] getIntArray(String key) - { - return !this.hasKey(key, 11) ? new int[0] : ((NBTTagIntArray)this.tagMap.get(key)).getIntArray(); - } - - /** - * Retrieves a NBTTagCompound subtag matching the specified key, or a new empty NBTTagCompound if no such key was - * stored. - */ - public NBTTagCompound getCompoundTag(String key) - { - return !this.hasKey(key, 10) ? new NBTTagCompound() : (NBTTagCompound)this.tagMap.get(key); - } - - /** - * Gets the NBTTagList object with the given name. Args: name, NBTBase type - */ - public NBTTagList getTagList(String key, int type) - { - if (this.getTagId(key) != 9) - { - return new NBTTagList(); - } - else - { - NBTTagList nbttaglist = (NBTTagList)this.tagMap.get(key); - return nbttaglist.tagCount() > 0 && nbttaglist.getTagType() != type ? new NBTTagList() : nbttaglist; - } - } - - /** - * Retrieves a boolean value using the specified key, or false if no such key was stored. This uses the getByte - * method. - */ - public boolean getBoolean(String key) - { - return this.getByte(key) != 0; - } - - /** - * Remove the specified tag. - */ - public void removeTag(String key) - { - this.tagMap.remove(key); - } - - public String toString() - { - StringBuilder stringbuilder = new StringBuilder("{"); - - for (Entry entry : this.tagMap.entrySet()) - { - if (stringbuilder.length() != 1) - { - stringbuilder.append(','); - } - - stringbuilder.append((String)entry.getKey()).append(':').append(entry.getValue()); - } - - return stringbuilder.append('}').toString(); - } - - /** - * Return whether this compound has no tags. - */ - public boolean hasNoTags() - { - return this.tagMap.isEmpty(); - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - - for (String s : this.tagMap.keySet()) - { - nbttagcompound.setTag(s, ((NBTBase)this.tagMap.get(s)).copy()); - } - - return nbttagcompound; - } - - public boolean equals(Object p_equals_1_) - { - if (super.equals(p_equals_1_)) - { - NBTTagCompound nbttagcompound = (NBTTagCompound)p_equals_1_; - return this.tagMap.entrySet().equals(nbttagcompound.tagMap.entrySet()); - } - else - { - return false; - } - } - - public int hashCode() - { - return super.hashCode() ^ this.tagMap.hashCode(); - } - - private static void writeEntry(String name, NBTBase data, DataOutput output) throws IOException - { - output.writeByte(data.getId()); - - if (data.getId() != 0) - { - output.writeUTF(name); - data.write(output); - } - } - - private static byte readType(DataInput input, NBTSizeTracker sizeTracker) throws IOException - { - return input.readByte(); - } - - private static String readKey(DataInput input, NBTSizeTracker sizeTracker) throws IOException - { - return input.readUTF(); - } - - static NBTBase readNBT(byte id, String key, DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - NBTBase nbtbase = NBTBase.createNewByType(id); - - nbtbase.read(input, depth, sizeTracker); - return nbtbase; - } - - /** - * Merges this NBTTagCompound with the given compound. Any sub-compounds are merged using the same methods, other - * types of tags are overwritten from the given compound. - */ - public void merge(NBTTagCompound other) - { - for (String s : other.tagMap.keySet()) - { - NBTBase nbtbase = (NBTBase)other.tagMap.get(s); - - if (nbtbase.getId() == 10) - { - if (this.hasKey(s, 10)) - { - NBTTagCompound nbttagcompound = this.getCompoundTag(s); - nbttagcompound.merge((NBTTagCompound)nbtbase); - } - else - { - this.setTag(s, nbtbase.copy()); - } - } - else - { - this.setTag(s, nbtbase.copy()); - } - } - } -} diff --git a/java/src/game/nbt/NBTTagDouble.java b/java/src/game/nbt/NBTTagDouble.java deleted file mode 100755 index 13d6180..0000000 --- a/java/src/game/nbt/NBTTagDouble.java +++ /dev/null @@ -1,106 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -import game.util.ExtMath; - -public class NBTTagDouble extends NBTBase.NBTPrimitive -{ - /** The double value for the tag. */ - private double data; - - NBTTagDouble() - { - } - - public NBTTagDouble(double data) - { - this.data = data; - } - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - output.writeDouble(this.data); - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(128L); - this.data = input.readDouble(); - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)6; - } - - public String toString() - { - return "" + this.data + "d"; - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - return new NBTTagDouble(this.data); - } - - public boolean equals(Object p_equals_1_) - { - if (super.equals(p_equals_1_)) - { - NBTTagDouble nbttagdouble = (NBTTagDouble)p_equals_1_; - return this.data == nbttagdouble.data; - } - else - { - return false; - } - } - - public int hashCode() - { - long i = Double.doubleToLongBits(this.data); - return super.hashCode() ^ (int)(i ^ i >>> 32); - } - - public long getLong() - { - return (long)Math.floor(this.data); - } - - public int getInt() - { - return ExtMath.floord(this.data); - } - - public short getShort() - { - return (short)(ExtMath.floord(this.data) & 65535); - } - - public byte getByte() - { - return (byte)(ExtMath.floord(this.data) & 255); - } - - public double getDouble() - { - return this.data; - } - - public float getFloat() - { - return (float)this.data; - } -} diff --git a/java/src/game/nbt/NBTTagEnd.java b/java/src/game/nbt/NBTTagEnd.java deleted file mode 100755 index dfcf2c4..0000000 --- a/java/src/game/nbt/NBTTagEnd.java +++ /dev/null @@ -1,41 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class NBTTagEnd extends NBTBase -{ - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(64L); - } - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)0; - } - - public String toString() - { - return "END"; - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - return new NBTTagEnd(); - } -} diff --git a/java/src/game/nbt/NBTTagFloat.java b/java/src/game/nbt/NBTTagFloat.java deleted file mode 100755 index c9fce4e..0000000 --- a/java/src/game/nbt/NBTTagFloat.java +++ /dev/null @@ -1,105 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -import game.util.ExtMath; - -public class NBTTagFloat extends NBTBase.NBTPrimitive -{ - /** The float value for the tag. */ - private float data; - - NBTTagFloat() - { - } - - public NBTTagFloat(float data) - { - this.data = data; - } - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - output.writeFloat(this.data); - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(96L); - this.data = input.readFloat(); - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)5; - } - - public String toString() - { - return "" + this.data + "f"; - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - return new NBTTagFloat(this.data); - } - - public boolean equals(Object p_equals_1_) - { - if (super.equals(p_equals_1_)) - { - NBTTagFloat nbttagfloat = (NBTTagFloat)p_equals_1_; - return this.data == nbttagfloat.data; - } - else - { - return false; - } - } - - public int hashCode() - { - return super.hashCode() ^ Float.floatToIntBits(this.data); - } - - public long getLong() - { - return (long)this.data; - } - - public int getInt() - { - return ExtMath.floorf(this.data); - } - - public short getShort() - { - return (short)(ExtMath.floorf(this.data) & 65535); - } - - public byte getByte() - { - return (byte)(ExtMath.floorf(this.data) & 255); - } - - public double getDouble() - { - return (double)this.data; - } - - public float getFloat() - { - return this.data; - } -} diff --git a/java/src/game/nbt/NBTTagInt.java b/java/src/game/nbt/NBTTagInt.java deleted file mode 100755 index d5622fe..0000000 --- a/java/src/game/nbt/NBTTagInt.java +++ /dev/null @@ -1,103 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class NBTTagInt extends NBTBase.NBTPrimitive -{ - /** The integer value for the tag. */ - private int data; - - NBTTagInt() - { - } - - public NBTTagInt(int data) - { - this.data = data; - } - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - output.writeInt(this.data); - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(96L); - this.data = input.readInt(); - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)3; - } - - public String toString() - { - return "" + this.data; - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - return new NBTTagInt(this.data); - } - - public boolean equals(Object p_equals_1_) - { - if (super.equals(p_equals_1_)) - { - NBTTagInt nbttagint = (NBTTagInt)p_equals_1_; - return this.data == nbttagint.data; - } - else - { - return false; - } - } - - public int hashCode() - { - return super.hashCode() ^ this.data; - } - - public long getLong() - { - return (long)this.data; - } - - public int getInt() - { - return this.data; - } - - public short getShort() - { - return (short)(this.data & 65535); - } - - public byte getByte() - { - return (byte)(this.data & 255); - } - - public double getDouble() - { - return (double)this.data; - } - - public float getFloat() - { - return (float)this.data; - } -} diff --git a/java/src/game/nbt/NBTTagIntArray.java b/java/src/game/nbt/NBTTagIntArray.java deleted file mode 100755 index d0c85b8..0000000 --- a/java/src/game/nbt/NBTTagIntArray.java +++ /dev/null @@ -1,92 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.Arrays; - -public class NBTTagIntArray extends NBTBase -{ - /** The array of saved integers */ - private int[] intArray; - - NBTTagIntArray() - { - } - - public NBTTagIntArray(int[] p_i45132_1_) - { - this.intArray = p_i45132_1_; - } - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - output.writeInt(this.intArray.length); - - for (int i = 0; i < this.intArray.length; ++i) - { - output.writeInt(this.intArray[i]); - } - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(192L); - int i = input.readInt(); - sizeTracker.read((long)(32 * i)); - this.intArray = new int[i]; - - for (int j = 0; j < i; ++j) - { - this.intArray[j] = input.readInt(); - } - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)11; - } - - public String toString() - { - String s = "["; - - for (int i : this.intArray) - { - s = s + i + ","; - } - - return s + "]"; - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - int[] aint = new int[this.intArray.length]; - System.arraycopy(this.intArray, 0, aint, 0, this.intArray.length); - return new NBTTagIntArray(aint); - } - - public boolean equals(Object p_equals_1_) - { - return super.equals(p_equals_1_) ? Arrays.equals(this.intArray, ((NBTTagIntArray)p_equals_1_).intArray) : false; - } - - public int hashCode() - { - return super.hashCode() ^ Arrays.hashCode(this.intArray); - } - - public int[] getIntArray() - { - return this.intArray; - } -} diff --git a/java/src/game/nbt/NBTTagList.java b/java/src/game/nbt/NBTTagList.java deleted file mode 100755 index 51c1e17..0000000 --- a/java/src/game/nbt/NBTTagList.java +++ /dev/null @@ -1,301 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -import game.collect.Lists; - -import game.log.Log; - -public class NBTTagList extends NBTBase -{ - private List tagList = Lists.newArrayList(); - - /** - * The type byte for the tags in the list - they must all be of the same type. - */ - private byte tagType = 0; - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - if (!this.tagList.isEmpty()) - { - this.tagType = ((NBTBase)this.tagList.get(0)).getId(); - } - else - { - this.tagType = 0; - } - - output.writeByte(this.tagType); - output.writeInt(this.tagList.size()); - - for (int i = 0; i < this.tagList.size(); ++i) - { - ((NBTBase)this.tagList.get(i)).write(output); - } - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(296L); - - if (depth > 512) - { - throw new RuntimeException("Tried to read NBT tag with too high complexity, depth > 512"); - } - else - { - this.tagType = input.readByte(); - int i = input.readInt(); - - if (this.tagType == 0 && i > 0) - { - throw new RuntimeException("Missing type on ListTag"); - } - else - { - sizeTracker.read(32L * (long)i); - this.tagList = new ArrayList(i); - - for (int j = 0; j < i; ++j) - { - NBTBase nbtbase = NBTBase.createNewByType(this.tagType); - nbtbase.read(input, depth + 1, sizeTracker); - this.tagList.add(nbtbase); - } - } - } - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)9; - } - - public String toString() - { - StringBuilder stringbuilder = new StringBuilder("["); - - for (int i = 0; i < this.tagList.size(); ++i) - { - if (i != 0) - { - stringbuilder.append(','); - } - - stringbuilder.append(i).append(':').append(this.tagList.get(i)); - } - - return stringbuilder.append(']').toString(); - } - - /** - * Adds the provided tag to the end of the list. There is no check to verify this tag is of the same type as any - * previous tag. - */ - public void appendTag(NBTBase nbt) - { - if (nbt.getId() == 0) - { - Log.JNI.warn("Ungültiger End-Tag zu Tag-Liste hinzugefügt"); - } - else - { - if (this.tagType == 0) - { - this.tagType = nbt.getId(); - } - else if (this.tagType != nbt.getId()) - { - Log.JNI.warn("Füge ungleiche Tag-Typen zu Tag-Liste hinzu"); - return; - } - - this.tagList.add(nbt); - } - } - - /** - * Set the given index to the given tag - */ - public void set(int idx, NBTBase nbt) - { - if (nbt.getId() == 0) - { - Log.JNI.warn("Ungültiger End-Tag zu Tag-Liste hinzugefügt"); - } - else if (idx >= 0 && idx < this.tagList.size()) - { - if (this.tagType == 0) - { - this.tagType = nbt.getId(); - } - else if (this.tagType != nbt.getId()) - { - Log.JNI.warn("Füge ungleiche Tag-Typen zu Tag-Liste hinzu"); - return; - } - - this.tagList.set(idx, nbt); - } - else - { - Log.JNI.warn("Index außerhalb des Bereiches um Tag in Tag-Liste zu setzen"); - } - } - - /** - * Removes a tag at the given index. - */ - public NBTBase removeTag(int i) - { - return (NBTBase)this.tagList.remove(i); - } - - /** - * Return whether this compound has no tags. - */ - public boolean hasNoTags() - { - return this.tagList.isEmpty(); - } - - /** - * Retrieves the NBTTagCompound at the specified index in the list - */ - public NBTTagCompound getCompoundTagAt(int i) - { - if (i >= 0 && i < this.tagList.size()) - { - NBTBase nbtbase = (NBTBase)this.tagList.get(i); - return nbtbase.getId() == 10 ? (NBTTagCompound)nbtbase : new NBTTagCompound(); - } - else - { - return new NBTTagCompound(); - } - } - - public int[] getIntArrayAt(int i) - { - if (i >= 0 && i < this.tagList.size()) - { - NBTBase nbtbase = (NBTBase)this.tagList.get(i); - return nbtbase.getId() == 11 ? ((NBTTagIntArray)nbtbase).getIntArray() : new int[0]; - } - else - { - return new int[0]; - } - } - - public double getDoubleAt(int i) - { - if (i >= 0 && i < this.tagList.size()) - { - NBTBase nbtbase = (NBTBase)this.tagList.get(i); - return nbtbase.getId() == 6 ? ((NBTTagDouble)nbtbase).getDouble() : 0.0D; - } - else - { - return 0.0D; - } - } - - public float getFloatAt(int i) - { - if (i >= 0 && i < this.tagList.size()) - { - NBTBase nbtbase = (NBTBase)this.tagList.get(i); - return nbtbase.getId() == 5 ? ((NBTTagFloat)nbtbase).getFloat() : 0.0F; - } - else - { - return 0.0F; - } - } - - /** - * Retrieves the tag String value at the specified index in the list - */ - public String getStringTagAt(int i) - { - if (i >= 0 && i < this.tagList.size()) - { - NBTBase nbtbase = (NBTBase)this.tagList.get(i); - return nbtbase.getId() == 8 ? nbtbase.getString() : nbtbase.toString(); - } - else - { - return ""; - } - } - - /** - * Get the tag at the given position - */ - public NBTBase get(int idx) - { - return (NBTBase)(idx >= 0 && idx < this.tagList.size() ? (NBTBase)this.tagList.get(idx) : new NBTTagEnd()); - } - - /** - * Returns the number of tags in the list. - */ - public int tagCount() - { - return this.tagList.size(); - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - NBTTagList nbttaglist = new NBTTagList(); - nbttaglist.tagType = this.tagType; - - for (NBTBase nbtbase : this.tagList) - { - NBTBase nbtbase1 = nbtbase.copy(); - nbttaglist.tagList.add(nbtbase1); - } - - return nbttaglist; - } - - public boolean equals(Object p_equals_1_) - { - if (super.equals(p_equals_1_)) - { - NBTTagList nbttaglist = (NBTTagList)p_equals_1_; - - if (this.tagType == nbttaglist.tagType) - { - return this.tagList.equals(nbttaglist.tagList); - } - } - - return false; - } - - public int hashCode() - { - return super.hashCode() ^ this.tagList.hashCode(); - } - - public int getTagType() - { - return this.tagType; - } -} diff --git a/java/src/game/nbt/NBTTagLong.java b/java/src/game/nbt/NBTTagLong.java deleted file mode 100755 index 989c6c4..0000000 --- a/java/src/game/nbt/NBTTagLong.java +++ /dev/null @@ -1,103 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class NBTTagLong extends NBTBase.NBTPrimitive -{ - /** The long value for the tag. */ - private long data; - - NBTTagLong() - { - } - - public NBTTagLong(long data) - { - this.data = data; - } - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - output.writeLong(this.data); - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(128L); - this.data = input.readLong(); - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)4; - } - - public String toString() - { - return "" + this.data + "L"; - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - return new NBTTagLong(this.data); - } - - public boolean equals(Object p_equals_1_) - { - if (super.equals(p_equals_1_)) - { - NBTTagLong nbttaglong = (NBTTagLong)p_equals_1_; - return this.data == nbttaglong.data; - } - else - { - return false; - } - } - - public int hashCode() - { - return super.hashCode() ^ (int)(this.data ^ this.data >>> 32); - } - - public long getLong() - { - return this.data; - } - - public int getInt() - { - return (int)(this.data & -1L); - } - - public short getShort() - { - return (short)((int)(this.data & 65535L)); - } - - public byte getByte() - { - return (byte)((int)(this.data & 255L)); - } - - public double getDouble() - { - return (double)this.data; - } - - public float getFloat() - { - return (float)this.data; - } -} diff --git a/java/src/game/nbt/NBTTagShort.java b/java/src/game/nbt/NBTTagShort.java deleted file mode 100755 index 3ebc2ab..0000000 --- a/java/src/game/nbt/NBTTagShort.java +++ /dev/null @@ -1,103 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class NBTTagShort extends NBTBase.NBTPrimitive -{ - /** The short value for the tag. */ - private short data; - - public NBTTagShort() - { - } - - public NBTTagShort(short data) - { - this.data = data; - } - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - output.writeShort(this.data); - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(80L); - this.data = input.readShort(); - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)2; - } - - public String toString() - { - return "" + this.data + "s"; - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - return new NBTTagShort(this.data); - } - - public boolean equals(Object p_equals_1_) - { - if (super.equals(p_equals_1_)) - { - NBTTagShort nbttagshort = (NBTTagShort)p_equals_1_; - return this.data == nbttagshort.data; - } - else - { - return false; - } - } - - public int hashCode() - { - return super.hashCode() ^ this.data; - } - - public long getLong() - { - return (long)this.data; - } - - public int getInt() - { - return this.data; - } - - public short getShort() - { - return this.data; - } - - public byte getByte() - { - return (byte)(this.data & 255); - } - - public double getDouble() - { - return (double)this.data; - } - - public float getFloat() - { - return (float)this.data; - } -} diff --git a/java/src/game/nbt/NBTTagString.java b/java/src/game/nbt/NBTTagString.java deleted file mode 100755 index 4eef986..0000000 --- a/java/src/game/nbt/NBTTagString.java +++ /dev/null @@ -1,93 +0,0 @@ -package game.nbt; - -import java.io.DataInput; -import java.io.DataOutput; -import java.io.IOException; - -public class NBTTagString extends NBTBase -{ - /** The string value for the tag (cannot be empty). */ - private String data; - - public NBTTagString() - { - this.data = ""; - } - - public NBTTagString(String data) - { - this.data = data; - - if (data == null) - { - throw new IllegalArgumentException("Empty string not allowed"); - } - } - - /** - * Write the actual data contents of the tag, implemented in NBT extension classes - */ - void write(DataOutput output) throws IOException - { - output.writeUTF(this.data); - } - - void read(DataInput input, int depth, NBTSizeTracker sizeTracker) throws IOException - { - sizeTracker.read(288L); - this.data = input.readUTF(); - sizeTracker.read((long)(16 * this.data.length())); - } - - /** - * Gets the type byte for the tag. - */ - public byte getId() - { - return (byte)8; - } - - public String toString() - { - return "\"" + this.data.replace("\"", "\\\"") + "\""; - } - - /** - * Creates a clone of the tag. - */ - public NBTBase copy() - { - return new NBTTagString(this.data); - } - - /** - * Return whether this compound has no tags. - */ - public boolean hasNoTags() - { - return this.data.isEmpty(); - } - - public boolean equals(Object p_equals_1_) - { - if (!super.equals(p_equals_1_)) - { - return false; - } - else - { - NBTTagString nbttagstring = (NBTTagString)p_equals_1_; - return this.data == null && nbttagstring.data == null || this.data != null && this.data.equals(nbttagstring.data); - } - } - - public int hashCode() - { - return super.hashCode() ^ this.data.hashCode(); - } - - public String getString() - { - return this.data; - } -} diff --git a/java/src/game/nbt/NBTUtil.java b/java/src/game/nbt/NBTUtil.java deleted file mode 100755 index f6f4f74..0000000 --- a/java/src/game/nbt/NBTUtil.java +++ /dev/null @@ -1,79 +0,0 @@ -package game.nbt; - -public final class NBTUtil -{ - public static boolean compareTags(NBTBase tag1, NBTBase tag2, boolean lists) - { - if (tag1 == tag2) - { - return true; - } - else if (tag1 == null) - { - return true; - } - else if (tag2 == null) - { - return false; - } - else if (!tag1.getClass().equals(tag2.getClass())) - { - return false; - } - else if (tag1 instanceof NBTTagCompound) - { - NBTTagCompound nbttagcompound = (NBTTagCompound)tag1; - NBTTagCompound nbttagcompound1 = (NBTTagCompound)tag2; - - for (String s : nbttagcompound.getKeySet()) - { - NBTBase nbtbase1 = nbttagcompound.getTag(s); - - if (!compareTags(nbtbase1, nbttagcompound1.getTag(s), lists)) - { - return false; - } - } - - return true; - } - else if (tag1 instanceof NBTTagList && lists) - { - NBTTagList nbttaglist = (NBTTagList)tag1; - NBTTagList nbttaglist1 = (NBTTagList)tag2; - - if (nbttaglist.tagCount() == 0) - { - return nbttaglist1.tagCount() == 0; - } - else - { - for (int i = 0; i < nbttaglist.tagCount(); ++i) - { - NBTBase nbtbase = nbttaglist.get(i); - boolean flag = false; - - for (int j = 0; j < nbttaglist1.tagCount(); ++j) - { - if (compareTags(nbtbase, nbttaglist1.get(j), lists)) - { - flag = true; - break; - } - } - - if (!flag) - { - return false; - } - } - - return true; - } - } - else - { - return tag1.equals(tag2); - } - } -} diff --git a/java/src/game/network/ClientLoginHandler.java b/java/src/game/network/ClientLoginHandler.java deleted file mode 100755 index 4122100..0000000 --- a/java/src/game/network/ClientLoginHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -package game.network; - -import game.Game; -import game.packet.RPacketDisconnect; -import game.packet.RPacketEnableCompression; -import game.packet.RPacketLoginSuccess; - -public class ClientLoginHandler extends NetHandler { - private final Game gm; - private final NetConnection networkManager; - - public ClientLoginHandler(NetConnection conn, Game gmIn) { - this.networkManager = conn; - this.gm = gmIn; - } - - public void onDisconnect(String reason) - { - this.gm.disconnected(reason); - } - - public final void handleDisconnect(RPacketDisconnect packetIn) - { - this.networkManager.closeChannel(packetIn.getReason()); - } - - public void handleLoginSuccess(RPacketLoginSuccess packetIn) - { - this.networkManager.setConnectionState(PacketRegistry.PLAY); - this.networkManager.setNetHandler(new ClientPlayer(this.gm, this.networkManager)); - } - - public final void handleEnableCompression(RPacketEnableCompression packetIn) - { - this.networkManager.setCompressionTreshold(packetIn.getValue()); - } - -// public void handlePasswordRequest(RPacketPasswordRequest packetIn) { -// if(this.server == null) { -// this.networkManager.sendPacket(new LPacketPasswordResponse(this.user, "", "")); -// } -// else if((packetIn.getPasswordRequested() && this.server.pass.isEmpty()) || -// (packetIn.getPasswordProtected() && this.server.access.isEmpty())) { -//// this.toChange = this.gm.getConnected(); -// this.accessRequired = packetIn.getPasswordProtected() && this.server.access.isEmpty(); -// this.passwordRequired = packetIn.getPasswordRequested() && this.server.pass.isEmpty(); -// this.networkManager.closeChannel(""); -// } -// else { -// this.networkManager.sendPacket(new LPacketPasswordResponse(this.user, this.access, this.pass)); -// } -// } -} diff --git a/java/src/game/network/LoginHandler.java b/java/src/game/network/LoginHandler.java deleted file mode 100755 index 061af2a..0000000 --- a/java/src/game/network/LoginHandler.java +++ /dev/null @@ -1,117 +0,0 @@ -package game.network; - -import game.Server; -import game.color.TextColor; -import game.init.Config; -import game.log.Log; -import game.packet.LPacketPasswordResponse; -import game.packet.RPacketDisconnect; - -public class LoginHandler extends NetHandler -{ - private static enum LoginState { - PASSWORD, READY_TO_ACCEPT, ACCEPTED; - } - - private final Server server; - public final NetConnection netManager; - - private LoginState state = LoginState.PASSWORD; - private int timer; - private String loginUser; - private String loginPass; - - public LoginHandler(Server server, NetConnection netManager) - { - this.netManager = netManager; - this.server = server; - } - - public void closeConnection(String reason) - { - try - { - Log.JNI.info("Trenne " + this.getConnectionInfo()); - this.netManager.sendPacket(new RPacketDisconnect(reason)); - this.netManager.closeChannel(reason); - } - catch (Exception exception) - { - Log.JNI.error(exception, "Fehler beim Trennen des Spielers beim Login"); - } - } - - public void onDisconnect(String reason) - { - Log.JNI.info(this.getConnectionInfo() + " wurde beim Login getrennt: " + TextColor.stripCodes(reason)); - } - - public String getConnectionInfo() - { - return this.loginUser != null ? (this.loginUser + " (" + this.netManager.getCutAddress() - + ")") : this.netManager.getCutAddress(); - } - - public void update() - { - if(this.state == LoginState.READY_TO_ACCEPT) - this.tryAcceptPlayer(); -// else if (this.currentLoginState == LoginState.DELAY_ACCEPT) -// { -// if (this.server.getPlayer(this.loginUser) == null) -// { -// this.currentLoginState = LoginState.ACCEPTED; -// this.server.addPlayer(this.networkManager, this.loginUser); -// } -// } - if(this.timer++ == 600) - this.closeConnection("Anmeldung dauerte zu lange"); - } - - private void tryAcceptPlayer() - { - if(this.server.getPlayer(this.loginUser) != null) { - this.closeConnection("Nutzername '" + this.loginUser + "' ist bereits vergeben."); - return; - } -// if (this.server.getPlayer(this.loginUser) != null) -// { -// this.closeConnection("Nutzername '" + this.loginUser + "' ist bereits vergeben."); -// return; -//// this.currentLoginState = LoginState.DELAY_ACCEPT; -//// player.netHandler.kick("Du hast dich von einen anderen Ort verbunden"); -// } -// this.networkManager.sendPacket(new RPacketLoginSuccess()); - String kick = this.server.addPlayer(this.netManager, this.loginUser, this.loginPass); - if(kick != null) - this.closeConnection(kick); - else - this.state = LoginState.ACCEPTED; - } - -// public void processLoginStart(LPacketLoginStart packetIn) -// { -// if(this.state != LoginState.HELLO) -// throw new IllegalStateException("Unerwartetes Start-Paket"); -// if(!this.netManager.isLocalChannel()) { -// this.state = LoginState.PASSWORD; -// this.netManager.sendPacket(new RPacketPasswordRequest()); // !Config.password.isEmpty(), Config.auth -// } -// } - - public void processPasswordResponse(LPacketPasswordResponse packetIn) { - if(this.state != LoginState.PASSWORD) - throw new IllegalStateException("Unerwartetes Passwort-Paket"); - this.loginUser = packetIn.getUser(); - this.loginPass = packetIn.getPassword(); - if(this.loginUser.isEmpty() || !Player.isValidUser(this.loginUser)) - throw new IllegalStateException("Ungültiger Nutzername!"); -// if(!this.checkConnect(packetIn.getAccess())) -// return; - if(!Config.password.isEmpty() && !Config.password.equals(packetIn.getAccess())) { - this.closeConnection("Falsches Zugangspasswort"); - return; - } - this.state = LoginState.READY_TO_ACCEPT; - } -} diff --git a/java/src/game/network/NetConnection.java b/java/src/game/network/NetConnection.java deleted file mode 100755 index b975e47..0000000 --- a/java/src/game/network/NetConnection.java +++ /dev/null @@ -1,433 +0,0 @@ -package game.network; - -import java.net.InetAddress; -import java.net.SocketAddress; -import java.util.Queue; -import java.util.concurrent.ConcurrentLinkedQueue; -import java.util.concurrent.locks.ReentrantReadWriteLock; -import java.util.regex.Pattern; - -import game.future.ThreadFactoryBuilder; - -import game.log.Log; -import game.network.NetHandler.ThreadQuickExitException; -import io.netty.bootstrap.Bootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelException; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandler; -import io.netty.channel.ChannelHandlerContext; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.EventLoopGroup; -import io.netty.channel.SimpleChannelInboundHandler; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.SocketChannel; -import io.netty.channel.socket.nio.NioSocketChannel; -import io.netty.handler.timeout.ReadTimeoutHandler; -import io.netty.handler.timeout.TimeoutException; -import io.netty.util.AttributeKey; -import io.netty.util.concurrent.Future; -import io.netty.util.concurrent.GenericFutureListener; - -public class NetConnection extends SimpleChannelInboundHandler -{ - private static final Pattern IP_REPLACER = Pattern.compile("([0-9]*)\\.([0-9]*)\\.[0-9]*\\.[0-9]*"); - public static final AttributeKey ATTR_STATE = AttributeKey.valueOf("protocol"); - public static final LazyLoadBase CLIENT_NIO_EVENTLOOP = new LazyLoadBase() - { - protected NioEventLoopGroup load() - { - return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Client IO #%d").setDaemon(true).build()); - } - }; - private final Queue outboundPacketsQueue = new ConcurrentLinkedQueue(); - private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock(); - - private Channel channel; - private SocketAddress socketAddress; - private NetHandler packetListener; - private String terminationReason; - private boolean disconnected; - - public void channelActive(ChannelHandlerContext p_channelActive_1_) throws Exception - { - super.channelActive(p_channelActive_1_); - this.channel = p_channelActive_1_.channel(); - this.socketAddress = this.channel.remoteAddress(); - - try - { - this.setConnectionState(PacketRegistry.HANDSHAKE); - } - catch (Throwable throwable) - { - Log.JNI.error(throwable, "Fehler beim Aufbauen der Verbindung für Handshake"); - } - } - - /** - * Sets the new connection state and registers which packets this channel may send and receive - */ - public void setConnectionState(PacketRegistry newState) - { - this.channel.attr(ATTR_STATE).set(newState); - this.channel.config().setAutoRead(true); -// Log.debug("Automatisches Lesen eingeschaltet"); - } - - public void channelInactive(ChannelHandlerContext p_channelInactive_1_) throws Exception - { - this.closeChannel("Ende der Datenübertragung"); - } - - public void exceptionCaught(ChannelHandlerContext p_exceptionCaught_1_, Throwable p_exceptionCaught_2_) throws Exception - { - String comp; - - if (p_exceptionCaught_2_ instanceof TimeoutException) - { - comp = "Zeitüberschreitung"; - } - else - { - comp = "Interner Fehler: " + p_exceptionCaught_2_; - Log.SYSTEM.error(p_exceptionCaught_2_, "Fehler in der Verbindung mit %s", this.getCutAddress()); - } - - this.closeChannel(comp); - } - - protected void channelRead0(ChannelHandlerContext p_channelRead0_1_, Packet p_channelRead0_2_) throws Exception - { - if (this.channel.isOpen()) - { - try - { - p_channelRead0_2_.processPacket(this.packetListener); - } - catch (ThreadQuickExitException e) - { - ; - } - } - } - - /** - * Sets the NetHandler for this NetworkManager, no checks are made if this handler is suitable for the particular - * connection state (protocol) - */ - public void setNetHandler(NetHandler handler) - { - if (handler == null) { - throw new NullPointerException("Handler ist Null"); - } -// Log.debug("Setze Handler von " + this + " auf " + handler); - this.packetListener = handler; - } - - public void sendPacket(Packet packetIn) - { - if (this.isChannelOpen()) - { - this.flushOutboundQueue(); - this.dispatchPacket(packetIn, null); - } - else - { - this.readWriteLock.writeLock().lock(); - - try - { - this.outboundPacketsQueue.add(new NetConnection.InboundHandlerTuplePacketListener(packetIn, null)); - } - finally - { - this.readWriteLock.writeLock().unlock(); - } - } - } - - public void sendPacket(Packet packetIn, GenericFutureListener > listener) - { - if (this.isChannelOpen()) - { - this.flushOutboundQueue(); - this.dispatchPacket(packetIn, new GenericFutureListener[] {listener}); - } - else - { - this.readWriteLock.writeLock().lock(); - - try - { - this.outboundPacketsQueue.add(new NetConnection.InboundHandlerTuplePacketListener(packetIn, listener)); - } - finally - { - this.readWriteLock.writeLock().unlock(); - } - } - } - - /** - * Will commit the packet to the channel. If the current thread 'owns' the channel it will write and flush the - * packet, otherwise it will add a task for the channel eventloop thread to do that. - */ - private void dispatchPacket(final Packet inPacket, final GenericFutureListener > [] futureListeners) - { - final PacketRegistry enumconnectionstate = PacketRegistry.getType(inPacket); - final PacketRegistry enumconnectionstate1 = (PacketRegistry)this.channel.attr(ATTR_STATE).get(); - - if (enumconnectionstate1 != enumconnectionstate) - { -// Log.debug("Automatisches Lesen ausgeschaltet"); - this.channel.config().setAutoRead(false); - } - - if (this.channel.eventLoop().inEventLoop()) - { - if (enumconnectionstate != enumconnectionstate1) - { - this.setConnectionState(enumconnectionstate); - } - - ChannelFuture channelfuture = this.channel.writeAndFlush(inPacket); - - if (futureListeners != null) - { - channelfuture.addListeners(futureListeners); - } - - channelfuture.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); - } - else - { - this.channel.eventLoop().execute(new Runnable() - { - public void run() - { - if (enumconnectionstate != enumconnectionstate1) - { - NetConnection.this.setConnectionState(enumconnectionstate); - } - - ChannelFuture channelfuture1 = NetConnection.this.channel.writeAndFlush(inPacket); - - if (futureListeners != null) - { - channelfuture1.addListeners(futureListeners); - } - - channelfuture1.addListener(ChannelFutureListener.FIRE_EXCEPTION_ON_FAILURE); - } - }); - } - } - - /** - * Will iterate through the outboundPacketQueue and dispatch all Packets - */ - private void flushOutboundQueue() - { - if (this.channel != null && this.channel.isOpen()) - { - this.readWriteLock.readLock().lock(); - - try - { - while (!this.outboundPacketsQueue.isEmpty()) - { - NetConnection.InboundHandlerTuplePacketListener networkmanager$inboundhandlertuplepacketlistener = (NetConnection.InboundHandlerTuplePacketListener)this.outboundPacketsQueue.poll(); - if(networkmanager$inboundhandlertuplepacketlistener != null) { // NPE Fix - this.dispatchPacket(networkmanager$inboundhandlertuplepacketlistener.packet, networkmanager$inboundhandlertuplepacketlistener.futureListeners); - } - } - } - finally - { - this.readWriteLock.readLock().unlock(); - } - } - } - - /** - * Checks timeouts and processes all packets received - */ - public void processReceivedPackets() - { - this.flushOutboundQueue(); - this.packetListener.update(); -// if (this.packetListener instanceof ITickable) -// { -// ((ITickable)this.packetListener).update(); -// } - if(this.channel != null) - this.channel.flush(); - } - -// /** -// * Returns the socket address of the remote side. Server-only. -// */ -// public SocketAddress getRemoteAddress() -// { -// return this.socketAddress; -// } - - public String getCutAddress() { - return this.socketAddress == null ? "?.?.*.*" : IP_REPLACER.matcher(this.socketAddress.toString()).replaceAll("$1.$2.*.*"); - } - - /** - * Closes the channel, the parameter can be used for an exit message (not certain how it gets sent) - */ - public void closeChannel(String message) - { - if (this.channel.isOpen()) - { - this.channel.close().awaitUninterruptibly(); - this.terminationReason = message; - } - } - - /** - * Create a new NetworkManager from the server host and connect it to the server - * - * @param address The address of the server - * @param serverPort The server port - */ - public static NetConnection createNetworkManagerAndConnect(InetAddress address, int serverPort) - { - final NetConnection networkmanager = new NetConnection(); - Class oclass; - LazyLoadBase lazyloadbase; - -// if (Epoll.isAvailable()) -// { -// oclass = EpollSocketChannel.class; -// lazyloadbase = CLIENT_EPOLL_EVENTLOOP; -// } -// else -// { - oclass = NioSocketChannel.class; - lazyloadbase = CLIENT_NIO_EVENTLOOP; -// } - - ((Bootstrap)((Bootstrap)((Bootstrap)(new Bootstrap()).group((EventLoopGroup)lazyloadbase.getValue())).handler(new ChannelInitializer() - { - protected void initChannel(Channel p_initChannel_1_) throws Exception - { - try - { - p_initChannel_1_.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true)); - } - catch (ChannelException var3) - { - ; - } - - p_initChannel_1_.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(30))).addLast((String)"splitter", (ChannelHandler)(new PacketSplitter())).addLast((String)"decoder", (ChannelHandler)(new PacketDecoder(false))).addLast((String)"prepender", (ChannelHandler)(new PacketPrepender())).addLast((String)"encoder", (ChannelHandler)(new PacketEncoder(true))).addLast((String)"packet_handler", (ChannelHandler)networkmanager); - } - })).channel(oclass)).connect(address, serverPort).syncUninterruptibly(); - return networkmanager; - } - - public boolean isChannelOpen() - { - return this.channel != null && this.channel.isOpen(); - } - - public boolean hasNoChannel() - { - return this.channel == null; - } - - /** - * Gets the current handler for processing packets - */ - public NetHandler getNetHandler() - { - return this.packetListener; - } - - /** - * Switches the channel to manual reading modus - */ - public void disableAutoRead() - { - this.channel.config().setAutoRead(false); - } - - public void setCompressionTreshold(int treshold) - { - if (treshold >= 0) - { - if (this.channel.pipeline().get("decompress") instanceof NettyCompressionDecoder) - { - ((NettyCompressionDecoder)this.channel.pipeline().get("decompress")).setCompressionTreshold(treshold); - } - else - { - this.channel.pipeline().addBefore("decoder", "decompress", new NettyCompressionDecoder(treshold)); - } - - if (this.channel.pipeline().get("compress") instanceof NettyCompressionEncoder) - { - ((NettyCompressionEncoder)this.channel.pipeline().get("compress")).setCompressionTreshold(treshold); - } - else - { - this.channel.pipeline().addBefore("encoder", "compress", new NettyCompressionEncoder(treshold)); - } - } - else - { - if (this.channel.pipeline().get("decompress") instanceof NettyCompressionDecoder) - { - this.channel.pipeline().remove("decompress"); - } - - if (this.channel.pipeline().get("compress") instanceof NettyCompressionEncoder) - { - this.channel.pipeline().remove("compress"); - } - } - } - - public void checkDisconnected() - { - if (this.channel != null && !this.channel.isOpen()) - { - if (!this.disconnected) - { - this.disconnected = true; - - if (this.terminationReason != null) - { - this.getNetHandler().onDisconnect(this.terminationReason); - } - else if (this.getNetHandler() != null) - { - this.getNetHandler().onDisconnect("Verbindung getrennt"); - } - } - else - { - Log.JNI.warn("handleDisconnection() zweifach aufgerufen"); - } - } - } - - static class InboundHandlerTuplePacketListener - { - private final Packet packet; - private final GenericFutureListener > [] futureListeners; - - public InboundHandlerTuplePacketListener(Packet inPacket, GenericFutureListener > inFutureListener) - { - this.packet = inPacket; - this.futureListeners = inFutureListener == null ? null : new GenericFutureListener[] {inFutureListener}; - } - } -} diff --git a/java/src/game/network/NetHandler.java b/java/src/game/network/NetHandler.java deleted file mode 100755 index db1d6c2..0000000 --- a/java/src/game/network/NetHandler.java +++ /dev/null @@ -1,41 +0,0 @@ -package game.network; - -public abstract class NetHandler { - private static final ThreadQuickExitException EXIT = new ThreadQuickExitException(); - - public static final class ThreadQuickExitException extends RuntimeException { - private ThreadQuickExitException() { - this.setStackTrace(new StackTraceElement[0]); - } - - public synchronized Throwable fillInStackTrace() { - this.setStackTrace(new StackTraceElement[0]); - return this; - } - } - - public abstract void onDisconnect(String reason); - - public void update() { - } - - public static void checkThread(final Packet packet, final T handler, IThreadListener listener) - throws ThreadQuickExitException { - if(!listener.isMainThread()) { - listener.schedule(new Runnable() { - public void run() { - packet.processPacket(handler); - } - }); - throw EXIT; - } - } - - public static void checkThread(final Packet packet, final T handler, IThreadListener listener, Object check) - throws ThreadQuickExitException { - if(check == null && listener.isMainThread()) { - throw EXIT; - } - checkThread(packet, handler, listener); - } -} diff --git a/java/src/game/network/NettyCompressionDecoder.java b/java/src/game/network/NettyCompressionDecoder.java deleted file mode 100755 index 0d7d95e..0000000 --- a/java/src/game/network/NettyCompressionDecoder.java +++ /dev/null @@ -1,62 +0,0 @@ -package game.network; - -import java.util.List; -import java.util.zip.DataFormatException; -import java.util.zip.Inflater; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; -import io.netty.handler.codec.DecoderException; - -public class NettyCompressionDecoder extends ByteToMessageDecoder -{ - private final Inflater inflater; - private int treshold; - - public NettyCompressionDecoder(int treshold) - { - this.treshold = treshold; - this.inflater = new Inflater(); - } - - protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List p_decode_3_) throws DataFormatException, Exception - { - if (p_decode_2_.readableBytes() != 0) - { - PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_); - int i = packetbuffer.readVarIntFromBuffer(); - - if (i == 0) - { - p_decode_3_.add(packetbuffer.readBytes(packetbuffer.readableBytes())); - } - else - { - if (i < this.treshold) - { - throw new DecoderException("Badly compressed packet - size of " + i + " is below server threshold of " + this.treshold); - } - - if (i > 2097152) - { - throw new DecoderException("Badly compressed packet - size of " + i + " is larger than protocol maximum of " + 2097152); - } - - byte[] abyte = new byte[packetbuffer.readableBytes()]; - packetbuffer.readBytes(abyte); - this.inflater.setInput(abyte); - byte[] abyte1 = new byte[i]; - this.inflater.inflate(abyte1); - p_decode_3_.add(Unpooled.wrappedBuffer(abyte1)); - this.inflater.reset(); - } - } - } - - public void setCompressionTreshold(int treshold) - { - this.treshold = treshold; - } -} diff --git a/java/src/game/network/NettyCompressionEncoder.java b/java/src/game/network/NettyCompressionEncoder.java deleted file mode 100755 index b19cfd2..0000000 --- a/java/src/game/network/NettyCompressionEncoder.java +++ /dev/null @@ -1,53 +0,0 @@ -package game.network; - -import java.util.zip.Deflater; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; - -public class NettyCompressionEncoder extends MessageToByteEncoder -{ - private final byte[] buffer = new byte[8192]; - private final Deflater deflater; - private int treshold; - - public NettyCompressionEncoder(int treshold) - { - this.treshold = treshold; - this.deflater = new Deflater(); - } - - protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception - { - int i = p_encode_2_.readableBytes(); - PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_); - - if (i < this.treshold) - { - packetbuffer.writeVarIntToBuffer(0); - packetbuffer.writeBytes(p_encode_2_); - } - else - { - byte[] abyte = new byte[i]; - p_encode_2_.readBytes(abyte); - packetbuffer.writeVarIntToBuffer(abyte.length); - this.deflater.setInput(abyte, 0, i); - this.deflater.finish(); - - while (!this.deflater.finished()) - { - int j = this.deflater.deflate(this.buffer); - packetbuffer.writeBytes((byte[])this.buffer, 0, j); - } - - this.deflater.reset(); - } - } - - public void setCompressionTreshold(int treshold) - { - this.treshold = treshold; - } -} diff --git a/java/src/game/network/PacketBuffer.java b/java/src/game/network/PacketBuffer.java deleted file mode 100755 index ccc6b8e..0000000 --- a/java/src/game/network/PacketBuffer.java +++ /dev/null @@ -1,465 +0,0 @@ -package game.network; - -import java.io.IOException; -import java.nio.charset.Charset; - -import game.init.ItemRegistry; -import game.item.ItemStack; -import game.nbt.NBTLoader; -import game.nbt.NBTSizeTracker; -import game.nbt.NBTTagCompound; -import game.world.BlockPos; -import io.netty.buffer.ByteBuf; -import io.netty.buffer.ByteBufInputStream; -import io.netty.buffer.ByteBufOutputStream; -import io.netty.handler.codec.DecoderException; -import io.netty.handler.codec.EncoderException; - -public class PacketBuffer -{ - private static final Charset UTF_8 = Charset.forName("UTF-8"); - - private final ByteBuf buf; - - public PacketBuffer(ByteBuf wrapped) - { - this.buf = wrapped; - } - - /** - * Calculates the number of bytes required to fit the supplied int (0-5) if it were to be read/written using - * readVarIntFromBuffer or writeVarIntToBuffer - */ - public static int getVarIntSize(int input) - { - for (int i = 1; i < 5; ++i) - { - if ((input & -1 << i * 7) == 0) - { - return i; - } - } - - return 5; - } - - public void writeByteArray(byte[] array) - { - this.writeVarIntToBuffer(array.length); - this.writeBytes(array); - } - - public byte[] readByteArray() - { - byte[] abyte = new byte[this.readVarIntFromBuffer()]; - this.readBytes(abyte); - return abyte; - } - - public BlockPos readBlockPos() - { -// return new BlockPos(this.readInt(), this.readInt(), this.readInt()); - return BlockPos.fromLong(this.readLong()); - } - - public void writeBlockPos(BlockPos pos) - { - this.writeLong(pos.toLong()); -// this.writeInt(pos.getX()); -// this.writeInt(pos.getY()); -// this.writeInt(pos.getZ()); - } - -// public Text readChatComponent() throws IOException -// { -// return Text.toComponent(this.readNBTTagCompoundFromBuffer()); -// } -// -// public void writeChatComponent(Text component) throws IOException -// { -// this.writeNBTTagCompoundToBuffer(Text.toNbt(component)); -//// String s = ; -//// if(s.length() > 32767) { -//// s = component.getFormattedText(); -//// s = s.length() > 32720 ? s.substring(0, 32720) : s; -//// s = TextSerializer.toNbt(new TextComponent(s + ChatFormat.GRAY + ChatFormat.ITALIC + " [...]")); -//// } -//// this.writeString(s); -// } - - public > T readEnumValue(Class enumClass) - { - return (T)((Enum[])enumClass.getEnumConstants())[this.readVarIntFromBuffer()]; - } - - public > T readEnumOrNull(Class enumClass) - { - int n = this.readVarIntFromBuffer(); - return n < 0 ? null : (T)((Enum[])enumClass.getEnumConstants())[n]; - } - - public void writeEnumValue(Enum value) - { - this.writeVarIntToBuffer(value.ordinal()); - } - - public void writeEnumOrNull(Enum value) - { - this.writeVarIntToBuffer(value == null ? -1 : value.ordinal()); - } - - /** - * Reads a compressed int from the buffer. To do so it maximally reads 5 byte-sized chunks whose most significant - * bit dictates whether another byte should be read. - */ - public int readVarIntFromBuffer() - { - int i = 0; - int j = 0; - - while (true) - { - byte b0 = this.readByte(); - i |= (b0 & 127) << j++ * 7; - - if (j > 5) - { - throw new RuntimeException("VarInt too big"); - } - - if ((b0 & 128) != 128) - { - break; - } - } - - return i; - } - - public long readVarLong() - { - long i = 0L; - int j = 0; - - while (true) - { - byte b0 = this.readByte(); - i |= (long)(b0 & 127) << j++ * 7; - - if (j > 10) - { - throw new RuntimeException("VarLong too big"); - } - - if ((b0 & 128) != 128) - { - break; - } - } - - return i; - } - -// public void writeUuid(UUID uuid) -// { -// this.writeLong(uuid.getMostSignificantBits()); -// this.writeLong(uuid.getLeastSignificantBits()); -// } -// -// public UUID readUuid() -// { -// return new UUID(this.readLong(), this.readLong()); -// } - - /** - * Writes a compressed int to the buffer. The smallest number of bytes to fit the passed int will be written. Of - * each such byte only 7 bits will be used to describe the actual value since its most significant bit dictates - * whether the next byte is part of that same int. Micro-optimization for int values that are expected to have - * values below 128. - */ - public void writeVarIntToBuffer(int input) - { - while ((input & -128) != 0) - { - this.writeByte(input & 127 | 128); - input >>>= 7; - } - - this.writeByte(input); - } - - public void writeVarLong(long value) - { - while ((value & -128L) != 0L) - { - this.writeByte((int)(value & 127L) | 128); - value >>>= 7; - } - - this.writeByte((int)value); - } - - /** - * Writes a compressed NBTTagCompound to this buffer - */ - public void writeNBTTagCompoundToBuffer(NBTTagCompound nbt) - { - if (nbt == null) - { - this.writeByte(0); - } - else - { - try - { - NBTLoader.write(nbt, new ByteBufOutputStream(this.buf)); - } - catch (IOException ioexception) - { - throw new EncoderException(ioexception); - } - } - } - - /** - * Reads a compressed NBTTagCompound from this buffer - */ - public NBTTagCompound readNBTTagCompoundFromBuffer() throws IOException - { - int i = this.buf.readerIndex(); - byte b0 = this.readByte(); - - if (b0 == 0) - { - return null; - } - else - { - this.buf.readerIndex(i); - return NBTLoader.read(new ByteBufInputStream(this.buf), new NBTSizeTracker(2097152L)); - } - } - - /** - * Writes the ItemStack's ID (short), then size (byte), then damage. (short) - */ - public void writeItemStackToBuffer(ItemStack stack) - { - if (stack == null) - { - this.writeShort(-1); - } - else - { - this.writeShort(ItemRegistry.getIdFromItem(stack.getItem())); - this.writeVarIntToBuffer(stack.stackSize); - this.writeShort(stack.getMetadata()); - NBTTagCompound nbttagcompound = null; - - if (stack.getItem().isDamageable() || stack.getItem().getShareTag()) - { - nbttagcompound = stack.getTagCompound(); - } - - this.writeNBTTagCompoundToBuffer(nbttagcompound); - } - } - - /** - * Reads an ItemStack from this buffer - */ - public ItemStack readItemStackFromBuffer() throws IOException - { - ItemStack itemstack = null; - int i = this.readShort(); - - if (i >= 0) - { - int j = this.readVarIntFromBuffer(); - int k = this.readShort(); - itemstack = new ItemStack(ItemRegistry.getItemById(i), j, k); - itemstack.setTagCompound(this.readNBTTagCompoundFromBuffer()); - } - - return itemstack; - } - - /** - * Reads a string from this buffer. Expected parameter is maximum allowed string length. Will throw IOException if - * string length exceeds this value! - */ - public String readStringFromBuffer(int maxLength) - { - int i = this.readVarIntFromBuffer(); - - if (i > maxLength * 4) - { - throw new DecoderException("The received encoded string buffer length is longer than maximum allowed (" + i + " > " + maxLength * 4 + ")"); - } - else if (i < 0) - { - throw new DecoderException("The received encoded string buffer length is less than zero! Weird string!"); - } - else - { - byte[] abyte = new byte[i]; - this.readBytes(abyte); - String s = new String(abyte, UTF_8); // this.readBytes(i).array() - - if (s.length() > maxLength) - { - throw new DecoderException("The received string length is longer than maximum allowed (" + i + " > " + maxLength + ")"); - } - else - { - return s; - } - } - } - - public PacketBuffer writeString(String string) - { - byte[] abyte = string.getBytes(UTF_8); - - if (abyte.length > 32767) - { - throw new EncoderException("String too big (was " + string.length() + " bytes encoded, max " + 32767 + ")"); - } - else - { - this.writeVarIntToBuffer(abyte.length); - this.writeBytes(abyte); - return this; - } - } - - public int readableBytes() - { - return this.buf.readableBytes(); - } - - public ByteBuf ensureWritable(int p_ensureWritable_1_) - { - return this.buf.ensureWritable(p_ensureWritable_1_); - } - - public boolean readBoolean() - { - return this.buf.readBoolean(); - } - - public byte readByte() - { - return this.buf.readByte(); - } - - public short readUnsignedByte() - { - return this.buf.readUnsignedByte(); - } - - public short readShort() - { - return this.buf.readShort(); - } - - public int readUnsignedShort() - { - return this.buf.readUnsignedShort(); - } - - public int readInt() - { - return this.buf.readInt(); - } - - public long readUnsignedInt() - { - return this.buf.readUnsignedInt(); - } - - public long readLong() - { - return this.buf.readLong(); - } - - public float readFloat() - { - return this.buf.readFloat(); - } - - public double readDouble() - { - return this.buf.readDouble(); - } - - public ByteBuf readBytes(int p_readBytes_1_) - { - return this.buf.readBytes(p_readBytes_1_); - } - - public ByteBuf readBytes(byte[] p_readBytes_1_) - { - return this.buf.readBytes(p_readBytes_1_); - } - - public ByteBuf writeBoolean(boolean p_writeBoolean_1_) - { - return this.buf.writeBoolean(p_writeBoolean_1_); - } - - public ByteBuf writeByte(int p_writeByte_1_) - { - return this.buf.writeByte(p_writeByte_1_); - } - - public ByteBuf writeShort(int p_writeShort_1_) - { - return this.buf.writeShort(p_writeShort_1_); - } - - public ByteBuf writeInt(int p_writeInt_1_) - { - return this.buf.writeInt(p_writeInt_1_); - } - - public ByteBuf writeLong(long p_writeLong_1_) - { - return this.buf.writeLong(p_writeLong_1_); - } - - public ByteBuf writeFloat(float p_writeFloat_1_) - { - return this.buf.writeFloat(p_writeFloat_1_); - } - - public ByteBuf writeDouble(double p_writeDouble_1_) - { - return this.buf.writeDouble(p_writeDouble_1_); - } - - public ByteBuf writeBytes(ByteBuf p_writeBytes_1_) - { - return this.buf.writeBytes(p_writeBytes_1_); - } - - public ByteBuf writeBytes(ByteBuf p_writeBytes_1_, int p_writeBytes_2_, int p_writeBytes_3_) - { - return this.buf.writeBytes(p_writeBytes_1_, p_writeBytes_2_, p_writeBytes_3_); - } - - public ByteBuf writeBytes(byte[] p_writeBytes_1_) - { - return this.buf.writeBytes(p_writeBytes_1_); - } - - public ByteBuf writeBytes(byte[] p_writeBytes_1_, int p_writeBytes_2_, int p_writeBytes_3_) - { - return this.buf.writeBytes(p_writeBytes_1_, p_writeBytes_2_, p_writeBytes_3_); - } - - public boolean release() - { - return this.buf.release(); - } -} diff --git a/java/src/game/network/PacketDecoder.java b/java/src/game/network/PacketDecoder.java deleted file mode 100755 index 3fb1715..0000000 --- a/java/src/game/network/PacketDecoder.java +++ /dev/null @@ -1,51 +0,0 @@ -package game.network; - -import java.io.IOException; -import java.util.List; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; - -public class PacketDecoder extends ByteToMessageDecoder -{ - private final boolean client; - - public PacketDecoder(boolean client) - { - this.client = client; - } - - protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List p_decode_3_) throws IOException, InstantiationException, IllegalAccessException, Exception - { - if (p_decode_2_.readableBytes() != 0) - { - PacketBuffer packetbuffer = new PacketBuffer(p_decode_2_); - int i = packetbuffer.readVarIntFromBuffer(); - Packet packet = ((PacketRegistry)p_decode_1_.channel().attr(NetConnection.ATTR_STATE).get()).getPacket(this.client, i); - - if (packet == null) - { - throw new IOException("Ungültige Paket-ID " + i); - } - else - { - packet.readPacketData(packetbuffer); - - if (packetbuffer.readableBytes() > 0) - { - throw new IOException("Paket " + ((PacketRegistry)p_decode_1_.channel().attr(NetConnection.ATTR_STATE).get()).ordinal() + "/" + i + " (" + packet.getClass() + ") war größer als erwartet, " + packetbuffer.readableBytes() + " weitere Bytes wurden beim Lesen von Paket " + i + " gefunden"); - } - else - { - p_decode_3_.add(packet); - -// if (Log.isTraceEnabled()) -// { -// Log.SYSTEM.info("EIN: [" + p_decode_1_.channel().attr(NetConnection.ATTR_STATE).get() + ":" + i + "] " + packet.getClass().getName()); -// } - } - } - } - } -} diff --git a/java/src/game/network/PacketEncoder.java b/java/src/game/network/PacketEncoder.java deleted file mode 100755 index e00af33..0000000 --- a/java/src/game/network/PacketEncoder.java +++ /dev/null @@ -1,47 +0,0 @@ -package game.network; - -import java.io.IOException; - -import game.log.Log; -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; - -public class PacketEncoder extends MessageToByteEncoder -{ - private final boolean client; - - public PacketEncoder(boolean client) - { - this.client = client; - } - - protected void encode(ChannelHandlerContext p_encode_1_, Packet p_encode_2_, ByteBuf p_encode_3_) throws IOException, Exception - { - Integer integer = ((PacketRegistry)p_encode_1_.channel().attr(NetConnection.ATTR_STATE).get()).getId(this.client, p_encode_2_); - -// if (Log.isTraceEnabled()) -// { -// Log.debug("AUS: [" + p_encode_1_.channel().attr(NetConnection.ATTR_STATE).get() + ":" + integer + "] " + p_encode_2_.getClass().getName()); -// } - - if (integer == null) - { - throw new IOException("Kann nicht registriertes Paket nicht serialisieren"); - } - else - { - PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_); - packetbuffer.writeVarIntToBuffer(integer.intValue()); - - try - { - p_encode_2_.writePacketData(packetbuffer); - } - catch (Throwable throwable) - { - Log.JNI.error(throwable, "Fehler beim Schreiben der Paketdaten"); - } - } - } -} diff --git a/java/src/game/network/PacketPrepender.java b/java/src/game/network/PacketPrepender.java deleted file mode 100755 index 9dd9ab7..0000000 --- a/java/src/game/network/PacketPrepender.java +++ /dev/null @@ -1,26 +0,0 @@ -package game.network; - -import io.netty.buffer.ByteBuf; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.MessageToByteEncoder; - -public class PacketPrepender extends MessageToByteEncoder -{ - protected void encode(ChannelHandlerContext p_encode_1_, ByteBuf p_encode_2_, ByteBuf p_encode_3_) throws Exception - { - int i = p_encode_2_.readableBytes(); - int j = PacketBuffer.getVarIntSize(i); - - if (j > 3) - { - throw new IllegalArgumentException("unable to fit " + i + " into " + 3); - } - else - { - PacketBuffer packetbuffer = new PacketBuffer(p_encode_3_); - packetbuffer.ensureWritable(j + i); - packetbuffer.writeVarIntToBuffer(i); - packetbuffer.writeBytes(p_encode_2_, p_encode_2_.readerIndex(), i); - } - } -} diff --git a/java/src/game/network/PacketRegistry.java b/java/src/game/network/PacketRegistry.java deleted file mode 100755 index cbfaffc..0000000 --- a/java/src/game/network/PacketRegistry.java +++ /dev/null @@ -1,259 +0,0 @@ -package game.network; - -import java.util.Map; - -import game.collect.BiMap; -import game.collect.HashBiMap; -import game.collect.Maps; - -import game.packet.CPacketAction; -import game.packet.CPacketBook; -import game.packet.CPacketBreak; -import game.packet.CPacketCheat; -import game.packet.CPacketClick; -import game.packet.CPacketComplete; -import game.packet.CPacketInput; -import game.packet.CPacketKeepAlive; -import game.packet.CPacketMessage; -import game.packet.CPacketPlace; -import game.packet.CPacketPlayer; -import game.packet.CPacketSign; -import game.packet.CPacketSkin; -import game.packet.HPacketHandshake; -import game.packet.LPacketPasswordResponse; -import game.packet.RPacketDisconnect; -import game.packet.RPacketEnableCompression; -import game.packet.RPacketLoginSuccess; -import game.packet.S14PacketEntity; -import game.packet.S18PacketEntityTeleport; -import game.packet.S19PacketEntityHeadLook; -import game.packet.S1APacketEntityStatus; -import game.packet.S1BPacketEntityAttach; -import game.packet.S1CPacketEntityMetadata; -import game.packet.S1DPacketEntityEffect; -import game.packet.S1EPacketRemoveEntityEffect; -import game.packet.S20PacketEntityProperties; -import game.packet.S27PacketExplosion; -import game.packet.S28PacketEffect; -import game.packet.S29PacketSoundEffect; -import game.packet.S2APacketParticles; -import game.packet.S2BPacketChangeGameState; -import game.packet.S2CPacketSpawnGlobalEntity; -import game.packet.S2DPacketOpenWindow; -import game.packet.S2EPacketCloseWindow; -import game.packet.S2FPacketSetSlot; -import game.packet.S30PacketWindowItems; -import game.packet.S31PacketWindowProperty; -import game.packet.S32PacketConfirmTransaction; -import game.packet.S33PacketUpdateSign; -import game.packet.S35PacketUpdateTileEntity; -import game.packet.S36PacketSignEditorOpen; -import game.packet.S38PacketPlayerListItem; -import game.packet.S39PacketPlayerAbilities; -import game.packet.S3APacketTabComplete; -import game.packet.S43PacketUpdateEntityNBT; -import game.packet.SPacketAnimation; -import game.packet.SPacketBiomes; -import game.packet.SPacketBlockAction; -import game.packet.SPacketBlockBreakAnim; -import game.packet.SPacketBlockChange; -import game.packet.SPacketCamera; -import game.packet.SPacketCharacterList; -import game.packet.SPacketChunkData; -import game.packet.SPacketCollectItem; -import game.packet.SPacketDestroyEntities; -import game.packet.SPacketDimensionName; -import game.packet.SPacketDisconnect; -import game.packet.SPacketEntityEquipment; -import game.packet.SPacketEntityVelocity; -import game.packet.SPacketHeldItemChange; -import game.packet.SPacketJoinGame; -import game.packet.SPacketKeepAlive; -import game.packet.SPacketLoading; -import game.packet.SPacketMapChunkBulk; -import game.packet.SPacketMessage; -import game.packet.SPacketMultiBlockChange; -import game.packet.SPacketPlayerPosLook; -import game.packet.SPacketRespawn; -import game.packet.SPacketServerTick; -import game.packet.SPacketSetExperience; -import game.packet.SPacketSkin; -import game.packet.SPacketSpawnMob; -import game.packet.SPacketSpawnObject; -import game.packet.SPacketSpawnPlayer; -import game.packet.SPacketTimeUpdate; -import game.packet.SPacketTrades; -import game.packet.SPacketUpdateHealth; -import game.packet.SPacketWorld; - -public enum PacketRegistry -{ - HANDSHAKE - { - { - this.client(HPacketHandshake.class); - } - }, - LOGIN - { - { - this.server(RPacketDisconnect.class); - this.server(RPacketLoginSuccess.class); - this.server(RPacketEnableCompression.class); -// this.server(RPacketPasswordRequest.class); -// this.client(LPacketLoginStart.class); - this.client(LPacketPasswordResponse.class); - } - }, - PLAY - { - { - this.server(SPacketKeepAlive.class); - this.server(SPacketJoinGame.class); - this.server(SPacketMessage.class); -// this.server(SPacketMessage.class); - this.server(SPacketTimeUpdate.class); - this.server(SPacketEntityEquipment.class); - this.server(SPacketUpdateHealth.class); - this.server(SPacketRespawn.class); - this.server(SPacketPlayerPosLook.class); - this.server(SPacketHeldItemChange.class); - this.server(SPacketAnimation.class); - this.server(SPacketSpawnPlayer.class); - this.server(SPacketCollectItem.class); - this.server(SPacketSpawnObject.class); - this.server(SPacketSpawnMob.class); -// this.server(SPacketSpawnPainting.class); -// this.server(SPacketSpawnExperienceOrb.class); - this.server(SPacketEntityVelocity.class); - this.server(SPacketDestroyEntities.class); - this.server(S14PacketEntity.class); - this.server(S14PacketEntity.S15PacketEntityRelMove.class); - this.server(S14PacketEntity.S16PacketEntityLook.class); - this.server(S14PacketEntity.S17PacketEntityLookMove.class); - this.server(S18PacketEntityTeleport.class); - this.server(S19PacketEntityHeadLook.class); - this.server(S1APacketEntityStatus.class); - this.server(S1BPacketEntityAttach.class); - this.server(S1CPacketEntityMetadata.class); - this.server(S1DPacketEntityEffect.class); - this.server(S1EPacketRemoveEntityEffect.class); - this.server(SPacketSetExperience.class); - this.server(S20PacketEntityProperties.class); - this.server(SPacketChunkData.class); - this.server(SPacketMultiBlockChange.class); - this.server(SPacketBlockChange.class); - this.server(SPacketBlockAction.class); - this.server(SPacketBlockBreakAnim.class); - this.server(SPacketMapChunkBulk.class); - this.server(S27PacketExplosion.class); - this.server(S28PacketEffect.class); - this.server(S29PacketSoundEffect.class); - this.server(S2APacketParticles.class); - this.server(S2BPacketChangeGameState.class); - this.server(S2CPacketSpawnGlobalEntity.class); - this.server(S2DPacketOpenWindow.class); - this.server(S2EPacketCloseWindow.class); - this.server(S2FPacketSetSlot.class); - this.server(S30PacketWindowItems.class); - this.server(S31PacketWindowProperty.class); - this.server(S32PacketConfirmTransaction.class); - this.server(S33PacketUpdateSign.class); -// this.server(S34PacketMaps.class); - this.server(S35PacketUpdateTileEntity.class); - this.server(S36PacketSignEditorOpen.class); -// this.server(S37PacketStatistics.class); - this.server(S38PacketPlayerListItem.class); - this.server(S39PacketPlayerAbilities.class); - this.server(S3APacketTabComplete.class); -// this.server(SPacketDisplay.class); - this.server(SPacketSkin.class); - this.server(SPacketDisconnect.class); - this.server(SPacketWorld.class); -// this.server(SPacketCapes.class); - this.server(SPacketCamera.class); - this.server(SPacketBiomes.class); -// this.server(S42PacketTitle.class); - this.server(S43PacketUpdateEntityNBT.class); -// this.server(SPacketBook.class); - this.server(SPacketTrades.class); -// this.server(SPacketNotify.class); - this.server(SPacketDimensionName.class); - this.server(SPacketCharacterList.class); - this.server(SPacketServerTick.class); - this.server(SPacketLoading.class); - - this.client(CPacketKeepAlive.class); - this.client(CPacketMessage.class); - this.client(CPacketAction.class); - this.client(CPacketPlayer.class); - this.client(CPacketPlayer.C04PacketPlayerPosition.class); - this.client(CPacketPlayer.C05PacketPlayerLook.class); - this.client(CPacketPlayer.C06PacketPlayerPosLook.class); - this.client(CPacketBreak.class); - this.client(CPacketPlace.class); - this.client(CPacketInput.class); - this.client(CPacketClick.class); - this.client(CPacketCheat.class); - this.client(CPacketComplete.class); - this.client(CPacketSkin.class); - this.client(CPacketSign.class); - this.client(CPacketBook.class); -// this.client(CPacketCmdBlock.class); - } - }; - - private static final Map, PacketRegistry> STATES = Maps., PacketRegistry>newHashMap(); - - private final BiMap> server = HashBiMap.>create(); - private final BiMap> client = HashBiMap.>create(); - - protected void server(Class clazz) - { - if(this.server.containsValue(clazz)) - throw new IllegalArgumentException("S-Paket " + clazz + " ist bereits bekannt unter ID " + this.server.inverse().get(clazz)); - this.server.put(Integer.valueOf(this.server.size()), clazz); - } - - protected void client(Class clazz) - { - if(this.client.containsValue(clazz)) - throw new IllegalArgumentException("C-Paket " + clazz + " ist bereits bekannt unter ID " + this.client.inverse().get(clazz)); - this.client.put(Integer.valueOf(this.client.size()), clazz); - } - - public Integer getId(boolean client, Packet packet) - { - return (client ? this.client : this.server).inverse().get(packet.getClass()); - } - - public Packet getPacket(boolean client, int id) throws InstantiationException, IllegalAccessException { - Class oclass = (client ? this.client : this.server).get(id); - return oclass == null ? null : oclass.newInstance(); - } - - public static PacketRegistry getType(Packet packetIn) - { - return STATES.get(packetIn.getClass()); - } - - static { - for(PacketRegistry reg : values()) { - for(BiMap> map : new BiMap[] {reg.server, reg.client}) { - for(Class clazz : map.values()) { - if(STATES.containsKey(clazz) && STATES.get(clazz) != reg) { - throw new Error("Paket " + clazz + " ist bereits zu ID " + STATES.get(clazz) - + " zugewiesen - kann nicht auf " + reg + " neu zuweisen"); - } - try { - clazz.newInstance(); - } - catch(Throwable e) { - throw new Error("Paket " + clazz + " kann nicht instanziert werden!"); - } - STATES.put(clazz, reg); - } - } - } - } -} diff --git a/java/src/game/network/PacketSplitter.java b/java/src/game/network/PacketSplitter.java deleted file mode 100755 index dec0660..0000000 --- a/java/src/game/network/PacketSplitter.java +++ /dev/null @@ -1,55 +0,0 @@ -package game.network; - -import java.util.List; - -import io.netty.buffer.ByteBuf; -import io.netty.buffer.Unpooled; -import io.netty.channel.ChannelHandlerContext; -import io.netty.handler.codec.ByteToMessageDecoder; -import io.netty.handler.codec.CorruptedFrameException; - -public class PacketSplitter extends ByteToMessageDecoder -{ - protected void decode(ChannelHandlerContext p_decode_1_, ByteBuf p_decode_2_, List p_decode_3_) throws Exception - { - p_decode_2_.markReaderIndex(); - byte[] abyte = new byte[3]; - - for (int i = 0; i < abyte.length; ++i) - { - if (!p_decode_2_.isReadable()) - { - p_decode_2_.resetReaderIndex(); - return; - } - - abyte[i] = p_decode_2_.readByte(); - - if (abyte[i] >= 0) - { - PacketBuffer packetbuffer = new PacketBuffer(Unpooled.wrappedBuffer(abyte)); - - try - { - int j = packetbuffer.readVarIntFromBuffer(); - - if (p_decode_2_.readableBytes() >= j) - { - p_decode_3_.add(p_decode_2_.readBytes(j)); - return; - } - - p_decode_2_.resetReaderIndex(); - } - finally - { - packetbuffer.release(); - } - - return; - } - } - - throw new CorruptedFrameException("length wider than 21-bit"); - } -} diff --git a/java/src/game/network/PlayerController.java b/java/src/game/network/PlayerController.java deleted file mode 100755 index 1646602..0000000 --- a/java/src/game/network/PlayerController.java +++ /dev/null @@ -1,603 +0,0 @@ -package game.network; - -import game.Game; -import game.audio.PositionedSound; -import game.block.Block; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.init.BlockRegistry; -import game.init.EntityRegistry; -import game.item.ItemBlock; -import game.item.ItemControl; -import game.item.ItemStack; -import game.material.Material; -import game.packet.CPacketAction; -import game.packet.CPacketBreak; -import game.packet.CPacketClick; -import game.packet.CPacketPlace; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.Vec3; -import game.world.World; -import game.world.WorldClient; - -public class PlayerController -{ - private final Game gm; - private final ClientPlayer netClientHandler; - private BlockPos currentBlock = new BlockPos(-1, -1, -1); - private ItemStack currentItemHittingBlock; - private float curBlockDamageMP; - private float stepSoundTickCounter; - private int blockHitDelay; - private boolean isHittingBlock; - private boolean noclip; - private int currentPlayerItem; - private boolean interacting; - - public PlayerController(Game gmIn, ClientPlayer netHandler) - { - this.gm = gmIn; - this.netClientHandler = netHandler; - } - -// public static void clickBlockCreative(Game gmIn, PlayerController playerController, BlockPos pos, Facing facing) -// { -// if (!gmIn.theWorld.extinguishFire(gmIn.thePlayer, pos, facing)) -// { -// playerController.onPlayerDestroyBlock(pos, facing); -// } -// } - -// public void setPlayerCapabilities() -// { -// this.gm.thePlayer.flying &= this.gm.thePlayer.hasEffect(Potion.flying) || this.gm.thePlayer.noclip; -// } - -// public boolean isNoclip() -// { -// return this.gm.thePlayer.capabilities.noClip; -// } - -// public void setNoclip(boolean noclip) -// { -// this.noclip = noclip; -// } - -// public void setCheat(boolean cheat) -// { -// this.cheat = cheat; -// this.setPlayerCapabilities(); -// } - - - -// public boolean shouldDrawHUD() -// { -// return !this.creative; -// } - - /** - * Called when a player completes the destruction of a block - */ - public boolean onPlayerDestroyBlock(BlockPos pos, Facing side) - { -// if (this.gamemode.isAdventure()) -// { -// if (this.gamemode == Gamemode.SPECTATOR) -// { -// return false; -// } - -// if (!this.gm.thePlayer.isAllowEdit()) -// { -// Block block = this.gm.theWorld.getBlockState(pos).getBlock(); -// ItemStack itemstack = this.gm.thePlayer.getCurrentEquippedItem(); -// -// if (itemstack == null) -// { -// return false; -// } -// -// if (!itemstack.canDestroy(block)) -// { -// return false; -// } -// } -// } - -// if (this.gm.thePlayer.getHeldItem() != null && !this.gm.thePlayer.getHeldItem().getItem().canBreakBlocks()) -// { -// return false; -// } -// else -// { - World world = this.gm.theWorld; - State iblockstate = world.getState(pos); - Block block1 = iblockstate.getBlock(); - - if (block1.getMaterial() == Material.air) - { - return false; - } - else - { - world.playAuxSFX(2001, pos, BlockRegistry.getStateId(iblockstate)); - boolean flag = world.setBlockToAir(pos); - - if (flag) - { - block1.onBlockDestroyedByPlayer(world, pos, iblockstate); - } - - this.currentBlock = new BlockPos(this.currentBlock.getX(), -1, this.currentBlock.getZ()); - -// if (!this.creative) -// { - ItemStack itemstack1 = this.gm.thePlayer.getCurrentEquippedItem(); - - if (itemstack1 != null) - { - itemstack1.onBlockDestroyed(world, block1, pos, this.gm.thePlayer); - - if (itemstack1.stackSize == 0) - { - this.gm.thePlayer.destroyCurrentEquippedItem(); - } - } -// } - - return flag; - } -// } - } - - /** - * Called when the player is hitting a block with an item. - */ - public boolean clickBlock(BlockPos loc, Facing face) - { -// if (this.gamemode.isAdventure()) -// { -// if (this.gamemode == Gamemode.SPECTATOR) -// { -// return false; -// } - -// if (!this.gm.thePlayer.isAllowEdit()) -// { -// Block block = this.gm.theWorld.getBlockState(loc).getBlock(); -// ItemStack itemstack = this.gm.thePlayer.getCurrentEquippedItem(); -// -// if (itemstack == null) -// { -// return false; -// } -// -// if (!itemstack.canDestroy(block)) -// { -// return false; -// } -// } -// } - - if (!World.isValidXZ(loc)) - { - return false; - } - else - { - ItemStack stack = this.gm.thePlayer.getHeldItem(); - if(stack != null && stack.getItem().onAction(stack, this.gm.thePlayer, this.gm.theWorld, ItemControl.PRIMARY, loc)) { - this.interacting = true; - this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, loc, face)); - return true; - } -// if (this.creative) -// { -// this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, loc, face)); -// clickBlockCreative(this.gm, this, loc, face); -// this.blockHitDelay = 5; -// } -// else - if (!this.isHittingBlock || !this.isHittingPosition(loc)) - { - if (this.isHittingBlock) - { - this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.ABORT_DESTROY_BLOCK, this.currentBlock, face)); - } - - this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, loc, face)); - Block block1 = this.gm.theWorld.getState(loc).getBlock(); - boolean flag = block1.getMaterial() != Material.air; - - if (flag && this.curBlockDamageMP == 0.0F) - { - block1.onBlockClicked(this.gm.theWorld, loc, this.gm.thePlayer); - } - - if (flag && block1.getPlayerRelativeBlockHardness(this.gm.thePlayer, this.gm.thePlayer.worldObj, loc) >= 1.0F) - { - this.onPlayerDestroyBlock(loc, face); -// if(this.cheat && block1.getPlayerRelativeBlockHardness(this.gm.thePlayer, this.gm.thePlayer.worldObj, loc) < 1.0F) - this.blockHitDelay = 3; - } - else - { - this.isHittingBlock = true; - this.currentBlock = loc; - this.currentItemHittingBlock = this.gm.thePlayer.getHeldItem(); - this.curBlockDamageMP = 0.0F; - this.stepSoundTickCounter = 0.0F; - this.gm.theWorld.sendBlockBreakProgress(this.gm.thePlayer.getId(), this.currentBlock, (int)(this.curBlockDamageMP * 10.0F) - 1); - } - } - - return true; - } - } - - /** - * Resets current block damage and isHittingBlock - */ - public void resetBlockRemoving() - { - if (this.isHittingBlock) - { - this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.ABORT_DESTROY_BLOCK, this.currentBlock, Facing.DOWN)); - this.isHittingBlock = false; - this.curBlockDamageMP = 0.0F; - this.gm.theWorld.sendBlockBreakProgress(this.gm.thePlayer.getId(), this.currentBlock, -1); - } - } - - public void resetInteraction() - { - this.interacting = false; - } - - public boolean onPlayerDamageBlock(BlockPos posBlock, Facing directionFacing) - { - if(this.interacting) - return false; - this.syncCurrentPlayItem(); - - if (this.blockHitDelay > 0) - { - --this.blockHitDelay; - return true; - } -// else if (this.creative && World.isValidXZ(posBlock)) -// { -// this.blockHitDelay = 5; -// this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.START_DESTROY_BLOCK, posBlock, directionFacing)); -// clickBlockCreative(this.gm, this, posBlock, directionFacing); -// return true; -// } - else if (this.isHittingPosition(posBlock)) - { - Block block = this.gm.theWorld.getState(posBlock).getBlock(); - - if (block.getMaterial() == Material.air) - { - this.isHittingBlock = false; - return false; - } - else - { - this.curBlockDamageMP += block.getPlayerRelativeBlockHardness(this.gm.thePlayer, this.gm.thePlayer.worldObj, posBlock); - - if (this.stepSoundTickCounter % 4.0F == 0.0F && block.sound.getStepSound() != null) - { - this.gm.getSoundManager().playSound(new PositionedSound(block.sound.getStepSound(), 0.25F, /* block.sound.getFrequency() * 0.5F, */ (float)posBlock.getX() + 0.5F, (float)posBlock.getY() + 0.5F, (float)posBlock.getZ() + 0.5F)); - } - - ++this.stepSoundTickCounter; - - if (this.curBlockDamageMP >= 1.0F) - { - this.isHittingBlock = false; - this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.STOP_DESTROY_BLOCK, posBlock, directionFacing)); - this.onPlayerDestroyBlock(posBlock, directionFacing); - this.curBlockDamageMP = 0.0F; - this.stepSoundTickCounter = 0.0F; - this.blockHitDelay = 5; - } - - this.gm.theWorld.sendBlockBreakProgress(this.gm.thePlayer.getId(), this.currentBlock, (int)(this.curBlockDamageMP * 10.0F) - 1); - return true; - } - } - else - { - return this.clickBlock(posBlock, directionFacing); - } - } - -// /** -// * player reach distance = 4F -// */ -// public float getBlockReachDistance() -// { -// return ; -// } - - public void updateController() - { - this.syncCurrentPlayItem(); - - if (this.netClientHandler.getNetworkManager().isChannelOpen()) - { - this.netClientHandler.getNetworkManager().processReceivedPackets(); - } - else - { - this.netClientHandler.getNetworkManager().checkDisconnected(); - } - } - - private boolean isHittingPosition(BlockPos pos) - { - ItemStack itemstack = this.gm.thePlayer.getHeldItem(); - boolean flag = this.currentItemHittingBlock == null && itemstack == null; - - if (this.currentItemHittingBlock != null && itemstack != null) - { - flag = itemstack.getItem() == this.currentItemHittingBlock.getItem() && ItemStack.areItemStackTagsEqual(itemstack, this.currentItemHittingBlock) && (itemstack.isItemStackDamageable() || itemstack.getMetadata() == this.currentItemHittingBlock.getMetadata()); - } - - return pos.equals(this.currentBlock) && flag; - } - - /** - * Syncs the current player item with the server - */ - private void syncCurrentPlayItem() - { - int i = this.gm.thePlayer.inventory.currentItem; - - if (i != this.currentPlayerItem) - { - this.currentPlayerItem = i; - this.netClientHandler.addToSendQueue(new CPacketAction(CPacketAction.Action.SET_ITEMSLOT, this.currentPlayerItem)); - } - } - - public boolean onPlayerRightClick(EntityNPC player, WorldClient worldIn, ItemStack heldStack, BlockPos hitPos, Facing side, Vec3 hitVec) - { - this.syncCurrentPlayItem(); - float f = (float)(hitVec.xCoord - (double)hitPos.getX()); - float f1 = (float)(hitVec.yCoord - (double)hitPos.getY()); - float f2 = (float)(hitVec.zCoord - (double)hitPos.getZ()); - boolean flag = false; - - if (!World.isValidXZ(hitPos)) - { - return false; - } - else - { - if(heldStack == null || !heldStack.getItem().onAction(heldStack, player, worldIn, ItemControl.SECONDARY, hitPos)) { -// if (this.gamemode != Gamemode.SPECTATOR) -// { - State iblockstate = worldIn.getState(hitPos); - - if ((!player.isSneaking() || player.getHeldItem() == null) // && (player.getHeldItem() == null || !player.getHeldItem().getItem().ignoresBlocks()) - && iblockstate.getBlock().onBlockActivated(worldIn, hitPos, iblockstate, player, side, f, f1, f2)) - { - flag = true; - } - - if (!flag && heldStack != null && heldStack.getItem() instanceof ItemBlock) - { - ItemBlock itemblock = (ItemBlock)heldStack.getItem(); - - if (!itemblock.canPlaceBlockOnSide(worldIn, hitPos, side, player, heldStack)) - { - return false; - } - } -// } - } - else { - heldStack.getItem().onItemUse(heldStack, player, worldIn, hitPos, side, f, f1, f2); - flag = true; - } - - this.netClientHandler.addToSendQueue(new CPacketPlace(hitPos, side.getIndex(), player.inventory.getCurrentItem(), f, f1, f2)); - - if (!flag) // && this.gamemode != Gamemode.SPECTATOR) - { - if (heldStack == null) - { - return false; - } -// else if (this.creative) -// { -// int i = heldStack.getMetadata(); -// int j = heldStack.stackSize; -// boolean flag1 = heldStack.onItemUse(player, worldIn, hitPos, side, f, f1, f2); -// heldStack.setItemDamage(i); -// heldStack.stackSize = j; -// return flag1; -// } - else - { - return heldStack.onItemUse(player, worldIn, hitPos, side, f, f1, f2); - } - } - else - { - return true; - } - } - } - - /** - * Notifies the server of things like consuming food, etc... - */ - public boolean sendUseItem(EntityNPC playerIn, World worldIn, ItemStack itemStackIn) - { -// if (this.gamemode == Gamemode.SPECTATOR) -// { -// return false; -// } -// else -// { - this.syncCurrentPlayItem(); - this.netClientHandler.addToSendQueue(new CPacketPlace(playerIn.inventory.getCurrentItem())); - int i = itemStackIn.stackSize; - ItemStack itemstack = itemStackIn.useItemRightClick(worldIn, playerIn); - - if (itemstack != itemStackIn || itemstack != null && itemstack.stackSize != i) - { - playerIn.inventory.mainInventory[playerIn.inventory.currentItem] = itemstack; - - if (itemstack.stackSize == 0) - { - playerIn.inventory.mainInventory[playerIn.inventory.currentItem] = null; - } - - return true; - } - else - { - return false; - } -// } - } - - public EntityNPC createPlayerEntity(WorldClient worldIn, int type) - { - EntityNPC player = (EntityNPC)EntityRegistry.createEntityByID(type, worldIn); - player.setClientPlayer(this.gm, this.netClientHandler); - return player; - } - - /** - * Attacks an entity - */ - public void attackEntity(EntityNPC playerIn, Entity targetEntity) - { - this.syncCurrentPlayItem(); - this.netClientHandler.addToSendQueue(new CPacketAction(CPacketAction.Action.ATTACK, targetEntity.getId())); - -// if (this.gamemode != Gamemode.SPECTATOR) -// { - playerIn.attackTargetEntityWithCurrentItem(targetEntity); -// } - } - - /** - * Send packet to server - player is interacting with another entity (left click) - */ - public boolean interactWithEntitySendPacket(EntityNPC playerIn, Entity targetEntity) - { - this.syncCurrentPlayItem(); - this.netClientHandler.addToSendQueue(new CPacketAction(CPacketAction.Action.INTERACT, targetEntity.getId())); - return /* this.gamemode != Gamemode.SPECTATOR && */ playerIn.interactWith(targetEntity); - } - -// /** -// * Return true when the player rightclick on an entity -// * -// * @param player The player's instance -// * @param entityIn The entity clicked -// * @param movingObject The object clicked -// */ -// public boolean isPlayerRightClickingOnEntity(EntityNPC player, Entity entityIn, MovingObjectPosition movingObject) -// { -// this.syncCurrentPlayItem(); -// Vec3 vec3 = new Vec3(movingObject.hitVec.xCoord - entityIn.posX, movingObject.hitVec.yCoord - entityIn.posY, movingObject.hitVec.zCoord - entityIn.posZ); -// this.netClientHandler.addToSendQueue(new C02PacketUseEntity(entityIn, vec3)); -// return this.gamemode != Gamemode.SPECTATOR && entityIn.interactAt(player, vec3); -// } - - /** - * Handles slot clicks sends a packet to the server. - */ - public ItemStack windowClick(int windowId, int slotId, int mouseButtonClicked, int mode, EntityNPC playerIn) - { - short short1 = playerIn.openContainer.getNextTransactionID(playerIn.inventory); - ItemStack itemstack = playerIn.openContainer.slotClick(slotId, mouseButtonClicked, mode, playerIn); - this.netClientHandler.addToSendQueue(new CPacketClick(windowId, slotId, mouseButtonClicked, mode, itemstack, short1)); - return itemstack; - } - - /** - * GuiEnchantment uses this during multiplayer to tell PlayerControllerMP to send a packet indicating the - * enchantment action the player has taken. - * - * @param windowID The ID of the current window - * @param button The button id (enchantment selected) - */ - public void sendEnchantPacket(int windowID, int button) - { - this.netClientHandler.addToSendQueue(new CPacketAction(CPacketAction.Action.ENCHANT_ITEM, windowID | (button << 8))); - } - -// /** -// * Used in PlayerControllerMP to update the server with an ItemStack in a slot. -// */ -// public void sendCheatPacket(ItemStack itemStackIn, boolean full) -// { -// } - -// /** -// * Sends a Packet107 to the server to drop the item on the ground -// */ -// public void sendPacketDropItem(ItemStack itemStackIn) -// { -// if (this.creative && itemStackIn != null) -// { -// this.netClientHandler.addToSendQueue(new CPacketCreative(-1, itemStackIn)); -// } -// } - - public void onStoppedUsingItem(EntityNPC playerIn) - { - this.syncCurrentPlayItem(); - this.netClientHandler.addToSendQueue(new CPacketBreak(CPacketBreak.Action.RELEASE_USE_ITEM, BlockPos.ORIGIN, Facing.DOWN)); - playerIn.stopUsingItem(); - } - - - -// /** -// * Checks if the player is not creative, used for checking if it should break a block instantly -// */ -// public boolean isNotCreative() -// { -// return !this.creative; -// } - -// /** -// * returns true if player is in creative mode -// */ -// public boolean isCreative() -// { -// return this.creative; -// } - -// /** -// * Checks if the player is riding a horse, used to chose the GUI to open -// */ -// public boolean isRidingHorse() -// { -// return ; -// } - -// public Gamemode getGamemode() -// { -// return this.gamemode; -// } - - /** - * Return isHittingBlock - */ - public boolean getIsHittingBlock() - { - return this.isHittingBlock; - } -} diff --git a/java/src/game/packet/APacketEmpty.java b/java/src/game/packet/APacketEmpty.java deleted file mode 100755 index f6dbe4c..0000000 --- a/java/src/game/packet/APacketEmpty.java +++ /dev/null @@ -1,15 +0,0 @@ -package game.packet; - -import java.io.IOException; - -import game.network.NetHandler; -import game.network.Packet; -import game.network.PacketBuffer; - -public abstract class APacketEmpty implements Packet { - public final void readPacketData(PacketBuffer buf) throws IOException { - } - - public final void writePacketData(PacketBuffer buf) throws IOException { - } -} diff --git a/java/src/game/packet/CPacketBook.java b/java/src/game/packet/CPacketBook.java deleted file mode 100755 index 271924e..0000000 --- a/java/src/game/packet/CPacketBook.java +++ /dev/null @@ -1,52 +0,0 @@ -package game.packet; - -import java.io.IOException; - -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; - -public class CPacketBook implements Packet -{ - private String[] pages; - - public CPacketBook() - { - } - - public CPacketBook(String[] pages) - { - this.pages = pages; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - int pages = (int)buf.readByte(); - if(pages > 50) { - this.pages = new String[0]; - return; - } - this.pages = new String[pages]; - for(int z = 0; z < pages; z++) { - this.pages[z] = buf.readStringFromBuffer(1024); - } - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeByte(this.pages.length); - for(int z = 0; z < this.pages.length; z++) { - buf.writeString(this.pages[z]); - } - } - - public void processPacket(Player handler) - { - handler.processBook(this); - } - - public String[] getPages() - { - return this.pages; - } -} diff --git a/java/src/game/packet/CPacketPlayer.java b/java/src/game/packet/CPacketPlayer.java deleted file mode 100755 index 11fc2f0..0000000 --- a/java/src/game/packet/CPacketPlayer.java +++ /dev/null @@ -1,192 +0,0 @@ -package game.packet; - -import java.io.IOException; - -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; - -public class CPacketPlayer implements Packet -{ - protected double x; - protected double y; - protected double z; - protected float yaw; - protected float pitch; - protected boolean onGround; - protected boolean moving; - protected boolean rotating; - - public CPacketPlayer() - { - } - - public CPacketPlayer(boolean isOnGround) - { - this.onGround = isOnGround; - } - - public void processPacket(Player handler) - { - handler.processPlayer(this); - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - this.onGround = buf.readUnsignedByte() != 0; - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeByte(this.onGround ? 1 : 0); - } - - public double getPositionX() - { - return this.x; - } - - public double getPositionY() - { - return this.y; - } - - public double getPositionZ() - { - return this.z; - } - - public float getYaw() - { - return this.yaw; - } - - public float getPitch() - { - return this.pitch; - } - - public boolean isOnGround() - { - return this.onGround; - } - - public boolean isMoving() - { - return this.moving; - } - - public boolean getRotating() - { - return this.rotating; - } - - public void setMoving(boolean isMoving) - { - this.moving = isMoving; - } - - public static class C04PacketPlayerPosition extends CPacketPlayer - { - public C04PacketPlayerPosition() - { - this.moving = true; - } - - public C04PacketPlayerPosition(double posX, double posY, double posZ, boolean isOnGround) - { - this.x = posX; - this.y = posY; - this.z = posZ; - this.onGround = isOnGround; - this.moving = true; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - this.x = buf.readDouble(); - this.y = buf.readDouble(); - this.z = buf.readDouble(); - super.readPacketData(buf); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeDouble(this.x); - buf.writeDouble(this.y); - buf.writeDouble(this.z); - super.writePacketData(buf); - } - } - - public static class C05PacketPlayerLook extends CPacketPlayer - { - public C05PacketPlayerLook() - { - this.rotating = true; - } - - public C05PacketPlayerLook(float playerYaw, float playerPitch, boolean isOnGround) - { - this.yaw = playerYaw; - this.pitch = playerPitch; - this.onGround = isOnGround; - this.rotating = true; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - this.yaw = buf.readFloat(); - this.pitch = buf.readFloat(); - super.readPacketData(buf); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeFloat(this.yaw); - buf.writeFloat(this.pitch); - super.writePacketData(buf); - } - } - - public static class C06PacketPlayerPosLook extends CPacketPlayer - { - public C06PacketPlayerPosLook() - { - this.moving = true; - this.rotating = true; - } - - public C06PacketPlayerPosLook(double playerX, double playerY, double playerZ, float playerYaw, float playerPitch, boolean playerIsOnGround) - { - this.x = playerX; - this.y = playerY; - this.z = playerZ; - this.yaw = playerYaw; - this.pitch = playerPitch; - this.onGround = playerIsOnGround; - this.rotating = true; - this.moving = true; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - this.x = buf.readDouble(); - this.y = buf.readDouble(); - this.z = buf.readDouble(); - this.yaw = buf.readFloat(); - this.pitch = buf.readFloat(); - super.readPacketData(buf); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeDouble(this.x); - buf.writeDouble(this.y); - buf.writeDouble(this.z); - buf.writeFloat(this.yaw); - buf.writeFloat(this.pitch); - super.writePacketData(buf); - } - } -} diff --git a/java/src/game/packet/CPacketSkin.java b/java/src/game/packet/CPacketSkin.java deleted file mode 100755 index b039eae..0000000 --- a/java/src/game/packet/CPacketSkin.java +++ /dev/null @@ -1,64 +0,0 @@ -package game.packet; - -import java.awt.image.BufferedImage; -import java.io.IOException; - -import game.init.SpeciesRegistry.ModelType; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; -import game.renderer.texture.EntityTexManager; - -public class CPacketSkin implements Packet { - private byte[] texture; - private String character; - - public CPacketSkin() { - } - - public CPacketSkin(BufferedImage image, String character, ModelType model) { - if(image == null) { - this.texture = null; - this.character = character; - } - else { - int[] img = new int[model.texWidth * model.texHeight]; - image.getRGB(0, 0, image.getWidth(), image.getHeight(), img, 0, image.getWidth()); - this.texture = EntityTexManager.imageToComp(img, model); - this.character = null; - } - } - - public byte[] getCompressed() { - return this.texture; - } - - public String getCharacter() { - return this.character; - } - - public void readPacketData(PacketBuffer buf) throws IOException { - if(buf.readBoolean()) { - this.texture = null; - this.character = buf.readStringFromBuffer(64); - } - else { - this.texture = buf.readByteArray(); - this.character = null; - if(this.texture.length == 0 || this.texture.length > EntityTexManager.MAX_SKIN_SIZE) - this.texture = new byte[EntityTexManager.MAX_SKIN_SIZE]; - } - } - - public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeBoolean(this.texture == null); - if(this.texture == null) - buf.writeString(this.character); - else - buf.writeByteArray(this.texture); - } - - public void processPacket(Player handler) { - handler.processSkin(this); - } -} diff --git a/java/src/game/packet/RPacketEnableCompression.java b/java/src/game/packet/RPacketEnableCompression.java deleted file mode 100755 index f338992..0000000 --- a/java/src/game/packet/RPacketEnableCompression.java +++ /dev/null @@ -1,20 +0,0 @@ -package game.packet; - -import game.network.ClientLoginHandler; - -public class RPacketEnableCompression extends APacketVarInt -{ - public RPacketEnableCompression() - { - } - - public RPacketEnableCompression(int comp) - { - super(comp); - } - - public void processPacket(ClientLoginHandler handler) - { - handler.handleEnableCompression(this); - } -} diff --git a/java/src/game/packet/RPacketLoginSuccess.java b/java/src/game/packet/RPacketLoginSuccess.java deleted file mode 100755 index 047cffc..0000000 --- a/java/src/game/packet/RPacketLoginSuccess.java +++ /dev/null @@ -1,11 +0,0 @@ -package game.packet; - -import game.network.ClientLoginHandler; - -public class RPacketLoginSuccess extends APacketEmpty -{ - public void processPacket(ClientLoginHandler handler) - { - handler.handleLoginSuccess(this); - } -} diff --git a/java/src/game/packet/S14PacketEntity.java b/java/src/game/packet/S14PacketEntity.java deleted file mode 100755 index 9c42bc2..0000000 --- a/java/src/game/packet/S14PacketEntity.java +++ /dev/null @@ -1,208 +0,0 @@ -package game.packet; - -import java.io.IOException; - -import game.entity.Entity; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.World; - -public class S14PacketEntity implements Packet -{ - protected int entityId; - protected byte posX; - protected byte posY; - protected byte posZ; - protected byte yaw; - protected byte pitch; - protected boolean onGround; - protected boolean rotation; - - public S14PacketEntity() - { - } - - public S14PacketEntity(int entityIdIn) - { - this.entityId = entityIdIn; - } - - /** - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer buf) throws IOException - { - this.entityId = buf.readVarIntFromBuffer(); - } - - /** - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeVarIntToBuffer(this.entityId); - } - - /** - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(ClientPlayer handler) - { - handler.handleEntityMovement(this); - } - - public String toString() - { - return "Entity_" + super.toString(); - } - - public Entity getEntity(World worldIn) - { - return worldIn.getEntityByID(this.entityId); - } - - public byte getPosX() - { - return this.posX; - } - - public byte getPosY() - { - return this.posY; - } - - public byte getPosZ() - { - return this.posZ; - } - - public byte getYaw() - { - return this.yaw; - } - - public byte getPitch() - { - return this.pitch; - } - - public boolean hasRotations() - { - return this.rotation; - } - - public boolean getOnGround() - { - return this.onGround; - } - - public static class S15PacketEntityRelMove extends S14PacketEntity - { - public S15PacketEntityRelMove() - { - } - - public S15PacketEntityRelMove(int entityIdIn, byte x, byte y, byte z, boolean onGroundIn) - { - super(entityIdIn); - this.posX = x; - this.posY = y; - this.posZ = z; - this.onGround = onGroundIn; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - super.readPacketData(buf); - this.posX = buf.readByte(); - this.posY = buf.readByte(); - this.posZ = buf.readByte(); - this.onGround = buf.readBoolean(); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - super.writePacketData(buf); - buf.writeByte(this.posX); - buf.writeByte(this.posY); - buf.writeByte(this.posZ); - buf.writeBoolean(this.onGround); - } - } - - public static class S16PacketEntityLook extends S14PacketEntity - { - public S16PacketEntityLook() - { - this.rotation = true; - } - - public S16PacketEntityLook(int entityIdIn, byte yawIn, byte pitchIn, boolean onGroundIn) - { - super(entityIdIn); - this.yaw = yawIn; - this.pitch = pitchIn; - this.rotation = true; - this.onGround = onGroundIn; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - super.readPacketData(buf); - this.yaw = buf.readByte(); - this.pitch = buf.readByte(); - this.onGround = buf.readBoolean(); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - super.writePacketData(buf); - buf.writeByte(this.yaw); - buf.writeByte(this.pitch); - buf.writeBoolean(this.onGround); - } - } - - public static class S17PacketEntityLookMove extends S14PacketEntity - { - public S17PacketEntityLookMove() - { - this.rotation = true; - } - - public S17PacketEntityLookMove(int p_i45973_1_, byte p_i45973_2_, byte p_i45973_3_, byte p_i45973_4_, byte p_i45973_5_, byte p_i45973_6_, boolean p_i45973_7_) - { - super(p_i45973_1_); - this.posX = p_i45973_2_; - this.posY = p_i45973_3_; - this.posZ = p_i45973_4_; - this.yaw = p_i45973_5_; - this.pitch = p_i45973_6_; - this.onGround = p_i45973_7_; - this.rotation = true; - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - super.readPacketData(buf); - this.posX = buf.readByte(); - this.posY = buf.readByte(); - this.posZ = buf.readByte(); - this.yaw = buf.readByte(); - this.pitch = buf.readByte(); - this.onGround = buf.readBoolean(); - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - super.writePacketData(buf); - buf.writeByte(this.posX); - buf.writeByte(this.posY); - buf.writeByte(this.posZ); - buf.writeByte(this.yaw); - buf.writeByte(this.pitch); - buf.writeBoolean(this.onGround); - } - } -} diff --git a/java/src/game/packet/S20PacketEntityProperties.java b/java/src/game/packet/S20PacketEntityProperties.java deleted file mode 100755 index ad22227..0000000 --- a/java/src/game/packet/S20PacketEntityProperties.java +++ /dev/null @@ -1,128 +0,0 @@ -package game.packet; - -import java.io.IOException; -import java.util.Collection; -import java.util.List; - -import game.collect.Lists; - -import game.entity.attributes.AttributeInstance; -import game.entity.attributes.AttributeModifier; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; - -public class S20PacketEntityProperties implements Packet -{ - private int entityId; - private final List field_149444_b = Lists.newArrayList(); - - public S20PacketEntityProperties() - { - } - - public S20PacketEntityProperties(int entityIdIn, Collection p_i45236_2_) - { - this.entityId = entityIdIn; - - for (AttributeInstance iattributeinstance : p_i45236_2_) - { - this.field_149444_b.add(new S20PacketEntityProperties.Snapshot(iattributeinstance.getAttribute().getUnlocalizedName(), iattributeinstance.getBaseValue(), iattributeinstance.getModifiers())); - } - } - - /** - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer buf) throws IOException - { - this.entityId = buf.readVarIntFromBuffer(); - int i = buf.readInt(); - - for (int j = 0; j < i; ++j) - { - String s = buf.readStringFromBuffer(64); - double d0 = buf.readDouble(); - List list = Lists.newArrayList(); - int k = buf.readVarIntFromBuffer(); - - for (int l = 0; l < k; ++l) - { - long id = buf.readLong(); - list.add(new AttributeModifier(id, "Unknown synced attribute modifier", buf.readDouble(), buf.readBoolean())); - } - - this.field_149444_b.add(new S20PacketEntityProperties.Snapshot(s, d0, list)); - } - } - - /** - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeVarIntToBuffer(this.entityId); - buf.writeInt(this.field_149444_b.size()); - - for (S20PacketEntityProperties.Snapshot s20packetentityproperties$snapshot : this.field_149444_b) - { - buf.writeString(s20packetentityproperties$snapshot.func_151409_a()); - buf.writeDouble(s20packetentityproperties$snapshot.func_151410_b()); - buf.writeVarIntToBuffer(s20packetentityproperties$snapshot.func_151408_c().size()); - - for (AttributeModifier attributemodifier : s20packetentityproperties$snapshot.func_151408_c()) - { - buf.writeLong(attributemodifier.getID()); - buf.writeDouble(attributemodifier.getAmount()); - buf.writeBoolean(attributemodifier.isMultiplied()); - } - } - } - - /** - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(ClientPlayer handler) - { - handler.handleEntityProperties(this); - } - - public int getEntityId() - { - return this.entityId; - } - - public List func_149441_d() - { - return this.field_149444_b; - } - - public class Snapshot - { - private final String field_151412_b; - private final double field_151413_c; - private final Collection field_151411_d; - - public Snapshot(String p_i45235_2_, double p_i45235_3_, Collection p_i45235_5_) - { - this.field_151412_b = p_i45235_2_; - this.field_151413_c = p_i45235_3_; - this.field_151411_d = p_i45235_5_; - } - - public String func_151409_a() - { - return this.field_151412_b; - } - - public double func_151410_b() - { - return this.field_151413_c; - } - - public Collection func_151408_c() - { - return this.field_151411_d; - } - } -} diff --git a/java/src/game/packet/S38PacketPlayerListItem.java b/java/src/game/packet/S38PacketPlayerListItem.java deleted file mode 100755 index b3309d2..0000000 --- a/java/src/game/packet/S38PacketPlayerListItem.java +++ /dev/null @@ -1,55 +0,0 @@ -package game.packet; - -import java.io.IOException; -import java.util.Collection; -import java.util.Map; -import java.util.Map.Entry; - -import game.collect.Maps; - -import game.network.ClientPlayer; -import game.network.Player; -import game.network.Packet; -import game.network.PacketBuffer; - -public class S38PacketPlayerListItem implements Packet { - private final Map players = Maps.newHashMap(); - - public S38PacketPlayerListItem() { - } - - public S38PacketPlayerListItem(boolean remove, Player... conns) { - for(Player conn : conns) { - this.players.put(conn.getUser(), remove ? -1 : conn.getLatency()); - } - } - - public S38PacketPlayerListItem(Iterable conns) { - for(Player conn : conns) { - this.players.put(conn.getUser(), conn.getLatency()); - } - } - - public void readPacketData(PacketBuffer buf) throws IOException { - int n = buf.readVarIntFromBuffer(); - for(int z = 0; z < n; z++) { - this.players.put(buf.readStringFromBuffer(16), buf.readVarIntFromBuffer()); - } - } - - public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeVarIntToBuffer(this.players.size()); - for(Entry data : this.players.entrySet()) { - buf.writeString(data.getKey()); - buf.writeVarIntToBuffer(data.getValue()); - } - } - - public void processPacket(ClientPlayer handler) { - handler.handlePlayerListItem(this); - } - - public Collection> getEntries() { - return this.players.entrySet(); - } -} diff --git a/java/src/game/packet/S43PacketUpdateEntityNBT.java b/java/src/game/packet/S43PacketUpdateEntityNBT.java deleted file mode 100755 index d069803..0000000 --- a/java/src/game/packet/S43PacketUpdateEntityNBT.java +++ /dev/null @@ -1,62 +0,0 @@ -package game.packet; - -import java.io.IOException; - -import game.entity.Entity; -import game.nbt.NBTTagCompound; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.World; - -public class S43PacketUpdateEntityNBT implements Packet -{ - private int entityId; - private NBTTagCompound tagCompound; - - public S43PacketUpdateEntityNBT() - { - } - - public S43PacketUpdateEntityNBT(int entityIdIn, NBTTagCompound tagCompoundIn) - { - this.entityId = entityIdIn; - this.tagCompound = tagCompoundIn; - } - - /** - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer buf) throws IOException - { - this.entityId = buf.readVarIntFromBuffer(); - this.tagCompound = buf.readNBTTagCompoundFromBuffer(); - } - - /** - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeVarIntToBuffer(this.entityId); - buf.writeNBTTagCompoundToBuffer(this.tagCompound); - } - - /** - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(ClientPlayer handler) - { - handler.handleEntityNBT(this); - } - - public NBTTagCompound getTagCompound() - { - return this.tagCompound; - } - - public Entity getEntity(World worldIn) - { - return worldIn.getEntityByID(this.entityId); - } -} diff --git a/java/src/game/packet/SPacketBiomes.java b/java/src/game/packet/SPacketBiomes.java deleted file mode 100755 index 5edc5d6..0000000 --- a/java/src/game/packet/SPacketBiomes.java +++ /dev/null @@ -1,50 +0,0 @@ -package game.packet; - -import java.io.IOException; - -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; - -public class SPacketBiomes implements Packet { - private int chunkX; - private int chunkZ; - private byte[] biomes; - - public SPacketBiomes() { - } - - public SPacketBiomes(int chunkX, int chunkZ, byte[] biomes) { - this.chunkX = chunkX; - this.chunkZ = chunkZ; - this.biomes = biomes; - } - - public void readPacketData(PacketBuffer buf) throws IOException { - this.chunkX = buf.readInt(); - this.chunkZ = buf.readInt(); - buf.readBytes(this.biomes = new byte[256]); - } - - public void writePacketData(PacketBuffer buf) throws IOException { - buf.writeInt(this.chunkX); - buf.writeInt(this.chunkZ); - buf.writeBytes(this.biomes); - } - - public void processPacket(ClientPlayer handler) { - handler.handleBiomes(this); - } - - public int getChunkX() { - return this.chunkX; - } - - public int getChunkZ() { - return this.chunkZ; - } - - public byte[] getBiomes() { - return this.biomes; - } -} diff --git a/java/src/game/packet/SPacketChunkData.java b/java/src/game/packet/SPacketChunkData.java deleted file mode 100755 index 7e62e3a..0000000 --- a/java/src/game/packet/SPacketChunkData.java +++ /dev/null @@ -1,163 +0,0 @@ -package game.packet; - -import java.io.IOException; -import java.util.List; - -import game.collect.Lists; - -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockArray; -import game.world.Chunk; - -public class SPacketChunkData implements Packet -{ - private int chunkX; - private int chunkZ; - private SPacketChunkData.Extracted extractedData; - private boolean biomes; - - public SPacketChunkData() - { - } - - public SPacketChunkData(Chunk chunkIn, boolean biomes, int segUpdate) - { - this.chunkX = chunkIn.xPos; - this.chunkZ = chunkIn.zPos; - this.biomes = biomes; - this.extractedData = getExtractedData(chunkIn, biomes, !chunkIn.getWorld().dimension.hasNoLight(), segUpdate); - } - - /** - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer buf) throws IOException - { - this.chunkX = buf.readInt(); - this.chunkZ = buf.readInt(); - this.biomes = buf.readBoolean(); - this.extractedData = new SPacketChunkData.Extracted(); - this.extractedData.dataSize = buf.readInt(); - this.extractedData.data = buf.readByteArray(); - } - - /** - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeInt(this.chunkX); - buf.writeInt(this.chunkZ); - buf.writeBoolean(this.biomes); - buf.writeInt(this.extractedData.dataSize); - buf.writeByteArray(this.extractedData.data); - } - - /** - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(ClientPlayer handler) - { - handler.handleChunkData(this); - } - - public byte[] getExtractedDataBytes() - { - return this.extractedData.data; - } - - protected static int getSize(int segments, boolean overworld, boolean biomes) - { - int i = segments * 2 * 16 * 16 * 16; - int j = segments * 16 * 16 * 16 / 2; - int k = overworld ? segments * 16 * 16 * 16 / 2 : 0; - int l = biomes ? 256 : 0; - return i + j + k + l; - } - - public static SPacketChunkData.Extracted getExtractedData(Chunk chunk, boolean biomes, boolean overworld, int segUpdate) - { - BlockArray[] aextendedblockstorage = chunk.getStorage(); - SPacketChunkData.Extracted s21packetchunkdata$extracted = new SPacketChunkData.Extracted(); - List list = Lists.newArrayList(); - - for (int i = 0; i < aextendedblockstorage.length; ++i) - { - BlockArray extendedblockstorage = aextendedblockstorage[i]; - - if (extendedblockstorage != null && (!biomes || !extendedblockstorage.isEmpty()) && (segUpdate & 1 << i) != 0) - { - s21packetchunkdata$extracted.dataSize |= 1 << i; - list.add(extendedblockstorage); - } - } - - s21packetchunkdata$extracted.data = new byte[getSize(Integer.bitCount(s21packetchunkdata$extracted.dataSize), overworld, biomes)]; - int j = 0; - - for (BlockArray extendedblockstorage1 : list) - { - char[] achar = extendedblockstorage1.getData(); - - for (char c0 : achar) - { - s21packetchunkdata$extracted.data[j++] = (byte)(c0 & 255); - s21packetchunkdata$extracted.data[j++] = (byte)(c0 >> 8 & 255); - } - } - - for (BlockArray extendedblockstorage2 : list) - { - j = copyTo(extendedblockstorage2.getBlocklight().getData(), s21packetchunkdata$extracted.data, j); - } - - if (overworld) - { - for (BlockArray extendedblockstorage3 : list) - { - j = copyTo(extendedblockstorage3.getSkylight().getData(), s21packetchunkdata$extracted.data, j); - } - } - - if (biomes) - { - copyTo(chunk.getBiomes(), s21packetchunkdata$extracted.data, j); - } - - return s21packetchunkdata$extracted; - } - - private static int copyTo(byte[] src, byte[] dest, int offset) - { - System.arraycopy(src, 0, dest, offset, src.length); - return offset + src.length; - } - - public int getChunkX() - { - return this.chunkX; - } - - public int getChunkZ() - { - return this.chunkZ; - } - - public int getExtractedSize() - { - return this.extractedData.dataSize; - } - - public boolean hasBiomes() - { - return this.biomes; - } - - public static class Extracted - { - public byte[] data; - public int dataSize; - } -} diff --git a/java/src/game/packet/SPacketDisconnect.java b/java/src/game/packet/SPacketDisconnect.java deleted file mode 100755 index 640a002..0000000 --- a/java/src/game/packet/SPacketDisconnect.java +++ /dev/null @@ -1,27 +0,0 @@ -package game.packet; - -import java.io.IOException; - -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; - -public class SPacketDisconnect implements Packet -{ - public SPacketDisconnect() - { - } - - public void readPacketData(PacketBuffer buf) throws IOException - { - } - - public void writePacketData(PacketBuffer buf) throws IOException - { - } - - public void processPacket(ClientPlayer handler) - { - handler.handleDisconnect(this); - } -} diff --git a/java/src/game/packet/SPacketKeepAlive.java b/java/src/game/packet/SPacketKeepAlive.java deleted file mode 100755 index 9fb15cd..0000000 --- a/java/src/game/packet/SPacketKeepAlive.java +++ /dev/null @@ -1,20 +0,0 @@ -package game.packet; - -import game.network.ClientPlayer; - -public class SPacketKeepAlive extends APacketVarInt -{ - public SPacketKeepAlive() - { - } - - public SPacketKeepAlive(int key) - { - super(key); - } - - public void processPacket(ClientPlayer handler) - { - handler.handleKeepAlive(this); - } -} diff --git a/java/src/game/packet/SPacketMultiBlockChange.java b/java/src/game/packet/SPacketMultiBlockChange.java deleted file mode 100755 index 47f8622..0000000 --- a/java/src/game/packet/SPacketMultiBlockChange.java +++ /dev/null @@ -1,110 +0,0 @@ -package game.packet; - -import java.io.IOException; - -import game.init.BlockRegistry; -import game.network.ClientPlayer; -import game.network.Packet; -import game.network.PacketBuffer; -import game.world.BlockPos; -import game.world.Chunk; -import game.world.ChunkPos; -import game.world.State; - -public class SPacketMultiBlockChange implements Packet -{ - private ChunkPos chunkPosCoord; - private SPacketMultiBlockChange.BlockUpdateData[] changedBlocks; - - public SPacketMultiBlockChange() - { - } - - public SPacketMultiBlockChange(int p_i45181_1_, int[] crammedPositionsIn, Chunk chunkIn) - { - this.chunkPosCoord = new ChunkPos(chunkIn.xPos, chunkIn.zPos); - this.changedBlocks = new SPacketMultiBlockChange.BlockUpdateData[p_i45181_1_]; - - for (int i = 0; i < this.changedBlocks.length; ++i) - { - this.changedBlocks[i] = new SPacketMultiBlockChange.BlockUpdateData(crammedPositionsIn[i], chunkIn); - } - } - - /** - * Reads the raw packet data from the data stream. - */ - public void readPacketData(PacketBuffer buf) throws IOException - { - this.chunkPosCoord = new ChunkPos(buf.readInt(), buf.readInt()); - this.changedBlocks = new SPacketMultiBlockChange.BlockUpdateData[buf.readVarIntFromBuffer()]; - - for (int i = 0; i < this.changedBlocks.length; ++i) - { - this.changedBlocks[i] = new SPacketMultiBlockChange.BlockUpdateData(buf.readInt(), (State)BlockRegistry.STATEMAP.getByValue(buf.readVarIntFromBuffer())); - } - } - - /** - * Writes the raw packet data to the data stream. - */ - public void writePacketData(PacketBuffer buf) throws IOException - { - buf.writeInt(this.chunkPosCoord.x); - buf.writeInt(this.chunkPosCoord.z); - buf.writeVarIntToBuffer(this.changedBlocks.length); - - for (SPacketMultiBlockChange.BlockUpdateData s22packetmultiblockchange$blockupdatedata : this.changedBlocks) - { - buf.writeInt(s22packetmultiblockchange$blockupdatedata.getRawPos()); - buf.writeVarIntToBuffer(BlockRegistry.STATEMAP.get(s22packetmultiblockchange$blockupdatedata.getBlockState())); - } - } - - /** - * Passes this Packet on to the NetHandler for processing. - */ - public void processPacket(ClientPlayer handler) - { - handler.handleMultiBlockChange(this); - } - - public SPacketMultiBlockChange.BlockUpdateData[] getChangedBlocks() - { - return this.changedBlocks; - } - - public class BlockUpdateData - { - private final int position; - private final State blockState; - - public BlockUpdateData(int raw, State state) - { - this.position = raw; - this.blockState = state; - } - - public BlockUpdateData(int raw, Chunk chunkIn) - { - this.position = raw; - this.blockState = chunkIn.getState(this.getPos()); - } - - public BlockPos getPos() - { - ChunkPos r = SPacketMultiBlockChange.this.chunkPosCoord; - return new BlockPos(new BlockPos((r.x << 4) + (this.position >> 13 & 15), this.position & 511, (r.z << 4) + (this.position >> 9 & 15))); - } - - public int getRawPos() - { - return this.position; - } - - public State getBlockState() - { - return this.blockState; - } - } -} diff --git a/java/src/game/pathfinding/PathCache.java b/java/src/game/pathfinding/PathCache.java deleted file mode 100755 index 55d88e8..0000000 --- a/java/src/game/pathfinding/PathCache.java +++ /dev/null @@ -1,38 +0,0 @@ -package game.pathfinding; - -import game.init.Blocks; -import game.world.BlockPos; -import game.world.Chunk; -import game.world.ChunkCache; -import game.world.IBlockAccess; -import game.world.State; -import game.world.World; - -public class PathCache extends ChunkCache implements IBlockAccess -{ - public PathCache(World worldIn, BlockPos posFromIn, BlockPos posToIn) - { - super(worldIn, posFromIn, posToIn, 0); - } - - public State getState(BlockPos pos) - { - if (pos.getY() >= 0 && pos.getY() < 512) - { - int i = (pos.getX() >> 4) - this.chunkX; - int j = (pos.getZ() >> 4) - this.chunkZ; - - if (i >= 0 && i < this.chunkArray.length && j >= 0 && j < this.chunkArray[i].length) - { - Chunk chunk = this.chunkArray[i][j]; - - if (chunk != null) - { - return chunk.getState(pos); - } - } - } - - return Blocks.air.getState(); - } -} diff --git a/java/src/game/pattern/BlockStateHelper.java b/java/src/game/pattern/BlockStateHelper.java deleted file mode 100755 index 2bbb7ae..0000000 --- a/java/src/game/pattern/BlockStateHelper.java +++ /dev/null @@ -1,62 +0,0 @@ -package game.pattern; - -import java.util.Map; -import java.util.Map.Entry; - -import java.util.function.Predicate; -import game.collect.Maps; - -import game.block.Block; -import game.properties.IProperty; -import game.world.State; - -public class BlockStateHelper implements Predicate -{ - private final Block block; - private final Map predicates = Maps.newHashMap(); - - private BlockStateHelper(Block blockStateIn) - { - this.block = blockStateIn; - } - - public static BlockStateHelper forBlock(Block blockIn) - { - return new BlockStateHelper(blockIn); - } - - public boolean test(State p_apply_1_) - { - if (p_apply_1_ != null && p_apply_1_.getBlock().equals(this.block)) - { - for (Entry entry : this.predicates.entrySet()) - { - Object object = p_apply_1_.getValue((IProperty)entry.getKey()); - - if (!((Predicate)entry.getValue()).test(object)) - { - return false; - } - } - - return true; - } - else - { - return false; - } - } - - public > BlockStateHelper where(IProperty property, Predicate is) - { - if (!this.block.getPropertyMap().contains(property)) - { - throw new IllegalArgumentException(this.block + " cannot support property " + property); - } - else - { - this.predicates.put(property, is); - return this; - } - } -} diff --git a/java/src/game/properties/IStringSerializable.java b/java/src/game/properties/IStringSerializable.java deleted file mode 100755 index b98fa26..0000000 --- a/java/src/game/properties/IStringSerializable.java +++ /dev/null @@ -1,6 +0,0 @@ -package game.properties; - -public interface IStringSerializable -{ - String getName(); -} diff --git a/java/src/game/renderer/BlockLayer.java b/java/src/game/renderer/BlockLayer.java deleted file mode 100755 index c57b910..0000000 --- a/java/src/game/renderer/BlockLayer.java +++ /dev/null @@ -1,21 +0,0 @@ -package game.renderer; - -public enum BlockLayer -{ - SOLID("Solid"), - CUTOUT_MIPPED("Mipped Cutout"), - CUTOUT("Cutout"), - TRANSLUCENT("Translucent"); - - private final String layerName; - - private BlockLayer(String layerNameIn) - { - this.layerName = layerNameIn; - } - - public String toString() - { - return this.layerName; - } -} diff --git a/java/src/game/renderer/ItemMeshDefinition.java b/java/src/game/renderer/ItemMeshDefinition.java deleted file mode 100755 index 827f812..0000000 --- a/java/src/game/renderer/ItemMeshDefinition.java +++ /dev/null @@ -1,8 +0,0 @@ -package game.renderer; - -import game.item.ItemStack; - -public interface ItemMeshDefinition -{ - String getModelLocation(ItemStack stack); -} diff --git a/java/src/game/renderer/VertexFormatElement.java b/java/src/game/renderer/VertexFormatElement.java deleted file mode 100755 index 58804dd..0000000 --- a/java/src/game/renderer/VertexFormatElement.java +++ /dev/null @@ -1,156 +0,0 @@ -package game.renderer; - -import org.lwjgl.opengl.GL11; - -import game.log.Log; - -public class VertexFormatElement -{ - private final VertexFormatElement.EnumType type; - private final VertexFormatElement.EnumUsage usage; - private int index; - private int elementCount; - - public VertexFormatElement(int indexIn, VertexFormatElement.EnumType typeIn, VertexFormatElement.EnumUsage usageIn, int count) - { - if (!this.isValid(indexIn, usageIn)) - { - Log.JNI.warn("Mehrere Vertex-Elemente des gleichen Typs außer UVs sind nicht unterstützt. Erzwinge Typ UV."); - this.usage = VertexFormatElement.EnumUsage.UV; - } - else - { - this.usage = usageIn; - } - - this.type = typeIn; - this.index = indexIn; - this.elementCount = count; - } - - private final boolean isValid(int index, VertexFormatElement.EnumUsage usage) - { - return index == 0 || usage == VertexFormatElement.EnumUsage.UV; - } - - public final VertexFormatElement.EnumType getType() - { - return this.type; - } - - public final VertexFormatElement.EnumUsage getUsage() - { - return this.usage; - } - - public final int getElementCount() - { - return this.elementCount; - } - - public final int getIndex() - { - return this.index; - } - - public String toString() - { - return this.elementCount + "," + this.usage.getDisplayName() + "," + this.type.getDisplayName(); - } - - public final int getSize() - { - return this.type.getSize() * this.elementCount; - } - - public final boolean isPositionElement() - { - return this.usage == VertexFormatElement.EnumUsage.POSITION; - } - - public boolean equals(Object p_equals_1_) - { - if (this == p_equals_1_) - { - return true; - } - else if (p_equals_1_ != null && this.getClass() == p_equals_1_.getClass()) - { - VertexFormatElement vertexformatelement = (VertexFormatElement)p_equals_1_; - return this.elementCount != vertexformatelement.elementCount ? false : (this.index != vertexformatelement.index ? false : (this.type != vertexformatelement.type ? false : this.usage == vertexformatelement.usage)); - } - else - { - return false; - } - } - - public int hashCode() - { - int i = this.type.hashCode(); - i = 31 * i + this.usage.hashCode(); - i = 31 * i + this.index; - i = 31 * i + this.elementCount; - return i; - } - - public static enum EnumType - { - FLOAT(4, "Float", GL11.GL_FLOAT), - UBYTE(1, "Unsigned Byte", GL11.GL_UNSIGNED_BYTE), - BYTE(1, "Byte", GL11.GL_BYTE), - USHORT(2, "Unsigned Short", GL11.GL_UNSIGNED_SHORT), - SHORT(2, "Short", GL11.GL_SHORT), - UINT(4, "Unsigned Int", GL11.GL_UNSIGNED_INT), - INT(4, "Int", GL11.GL_INT); - - private final int size; - private final String displayName; - private final int glConstant; - - private EnumType(int sizeIn, String displayNameIn, int glConstantIn) - { - this.size = sizeIn; - this.displayName = displayNameIn; - this.glConstant = glConstantIn; - } - - public int getSize() - { - return this.size; - } - - public String getDisplayName() - { - return this.displayName; - } - - public int getGlConstant() - { - return this.glConstant; - } - } - - public static enum EnumUsage - { - POSITION("Position"), - NORMAL("Normal"), - COLOR("Vertex Color"), - UV("UV"), -// MATRIX("Bone Matrix"), -// BLEND_WEIGHT("Blend Weight"), - PADDING("Padding"); - - private final String displayName; - - private EnumUsage(String displayNameIn) - { - this.displayName = displayNameIn; - } - - public String getDisplayName() - { - return this.displayName; - } - } -} diff --git a/java/src/game/renderer/blockmodel/ModelBlock.java b/java/src/game/renderer/blockmodel/ModelBlock.java deleted file mode 100755 index 3fc27ac..0000000 --- a/java/src/game/renderer/blockmodel/ModelBlock.java +++ /dev/null @@ -1,342 +0,0 @@ -package game.renderer.blockmodel; - -import java.util.List; - -import game.collect.Lists; -import game.collect.Maps; - -import game.model.ModelBakery; -import game.model.ModelRotation; -import game.renderer.Vector3f; -import game.renderer.texture.TextureMap; -import game.world.Facing; - -public class ModelBlock { - private final List elements; - private final boolean gui3d; - private final String primary; - private final String[] layers; - private final ModelBlock parent; - - private boolean occlusion; - private ModelRotation rotation; - private boolean uvLock; - private Transforms transform; - - private BlockPart lastPart; - private BlockPartFace[] last; - - - public ModelBlock slab(boolean upper) { - return this.slab(upper, this.primary, this.primary); - } - - public ModelBlock slab(boolean upper, String du) { - return this.slab(upper, du, du); - } - - public ModelBlock slab(boolean upper, String down, String up) { - return this.add(0, upper ? 8 : 0, 0, 16, upper ? 16 : 8, 16).nswe().uv(0, upper ? 0 : 8, 16, upper ? 8 : 16) - .d(down).cull(upper ? null : Facing.DOWN).u(up).cull(upper ? Facing.UP : null); - } - - public ModelBlock vslab(Facing dir) { - return this.vslab(dir, this.primary, this.primary); - } - - public ModelBlock vslab(Facing dir, String du) { - return this.vslab(dir, du, du); - } - - public ModelBlock vslab(Facing dir, String down, String up) { - return this.add(0, 0, 0, 16, 16, 8).du().uv(0, 8, 16, 16).we().uv(0, 8, 16, 16).rot(90).n(down).s(up).noCull().rotate(ModelRotation.getNorthRot(dir)); - } - - public ModelBlock cross() { - return this.noOcclude() - .add(0.8f, 0f, 8f, 15.2f, 16f, 8f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) - .ns().uv(0, 0, 16, 16).noCull() - .add(8f, 0f, 0.8f, 8f, 16f, 15.2f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) - .we().uv(0, 0, 16, 16).noCull(); - } - - public ModelBlock crossTint() { - return this.noOcclude() - .add(0.8f, 0f, 8f, 15.2f, 16f, 8f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) - .ns().uv(0, 0, 16, 16).noCull().tint() - .add(8f, 0f, 0.8f, 8f, 16f, 15.2f).noShade().rotate(8, 8, 8, Facing.Axis.Y, 45, true) - .we().uv(0, 0, 16, 16).noCull().tint(); - } - - public ModelBlock stairs(boolean upper, boolean inner, boolean outer, boolean left, Facing dir, String down, String up) { - this.add(0, 0, 0, 16, 8, 16).d(down).uv(0, 0, 16, 16).u(up).noCull().uv(0, 0, 16, 16).nswe().uv(0, 8, 16, 16); - if(outer) - this.add(8, 8, 8, 16, 16, 16).d(down).uv(8, 0, 16, 8).u(up).uv(8, 8, 16, 16).n().noCull().uv(0, 0, 8, 8).s().uv(8, 0, 16, 8) - .w().noCull().uv(8, 0, 16, 8).e().uv(0, 0, 8, 8); - else - this.add(8, 8, 0, 16, 16, 16).d(down).uv(inner ? 8 : 0, 0, 16, 16).u(up).uv(inner ? 8 : 0, 0, 16, 16).n().uv(0, 0, 8, 8) - .s().uv(8, 0, 16, 8).w().noCull().uv(0, 0, 16, 8).e().uv(0, 0, 16, 8); - if(inner) - this.add(0, 8, 8, 8, 16, 16).d(down).uv(0, 0, 8, 8).u(up).uv(0, 8, 8, 16).n().noCull().uv(8, 0, 16, 8).s().uv(0, 0, 8, 8) - .w().uv(8, 0, 16, 8).e().uv(0, 0, 8, 8); - return this.rotate(ModelRotation.getEastRot(left ? Facing.getHorizontal(dir.getHorizontalIndex() + 3) : dir, upper)).uvLock(); - } - - - - public ModelBlock noOcclude() { - this.occlusion = false; - return this; - } - - public ModelBlock uvLock() { - this.uvLock = true; - return this; - } - - public ModelBlock rotate(ModelRotation rot) { - this.rotation = rot; - return this; - } - - public ModelBlock add(float x1, float y1, float z1, float x2, float y2, float z2) { - this.elements.add(this.lastPart = new BlockPart(new Vector3f(x1, y1, z1), new Vector3f(x2, y2, z2), - Maps.newEnumMap(Facing.class), null, true)); - return this; - } - - public ModelBlock add() { - return this.add(0, 0, 0, 16, 16, 16); - } - - public ModelBlock noShade() { - this.lastPart.shade = false; - return this; - } - - public ModelBlock rotate(float x, float y, float z, Facing.Axis axisIn, float angleIn, boolean rescaleIn) { - this.lastPart.partRotation = new BlockPartRotation(x, y, z, axisIn, angleIn, rescaleIn); - return this; - } - - public ModelBlock face(String texture, Facing ... faces) { - texture = !texture.equals(TextureMap.LOCATION_MISSING_TEXTURE) && texture.indexOf('/') == -1 ? "blocks/" + texture : texture; - this.last = new BlockPartFace[faces.length]; - for(int z = 0; z < faces.length; z++) { - this.lastPart.mapFaces.put(faces[z], this.last[z] = - new BlockPartFace(faces[z], -1, texture, new BlockFaceUV(this.lastPart.getFaceUvs(faces[z]), 0))); - } - return this; - } - - public ModelBlock d(String textureIn) { - return this.face(textureIn, Facing.DOWN); - } - - public ModelBlock u(String textureIn) { - return this.face(textureIn, Facing.UP); - } - - public ModelBlock n(String textureIn) { - return this.face(textureIn, Facing.NORTH); - } - - public ModelBlock s(String textureIn) { - return this.face(textureIn, Facing.SOUTH); - } - - public ModelBlock w(String textureIn) { - return this.face(textureIn, Facing.WEST); - } - - public ModelBlock e(String textureIn) { - return this.face(textureIn, Facing.EAST); - } - - public ModelBlock nswe(String textureIn) { - return this.face(textureIn, Facing.NORTH, Facing.SOUTH, Facing.WEST, Facing.EAST); - } - - public ModelBlock dnswe(String textureIn) { - return this.face(textureIn, Facing.DOWN, Facing.NORTH, Facing.SOUTH, Facing.WEST, Facing.EAST); - } - - public ModelBlock du(String textureIn) { - return this.face(textureIn, Facing.DOWN, Facing.UP); - } - - public ModelBlock ns(String textureIn) { - return this.face(textureIn, Facing.NORTH, Facing.SOUTH); - } - - public ModelBlock we(String textureIn) { - return this.face(textureIn, Facing.WEST, Facing.EAST); - } - - public ModelBlock all(String textureIn) { - return this.face(textureIn, Facing.DOWN, Facing.UP, Facing.NORTH, Facing.SOUTH, Facing.WEST, Facing.EAST); - } - - public ModelBlock d() { - return this.d(this.primary); - } - - public ModelBlock u() { - return this.u(this.primary); - } - - public ModelBlock n() { - return this.n(this.primary); - } - - public ModelBlock s() { - return this.s(this.primary); - } - - public ModelBlock w() { - return this.w(this.primary); - } - - public ModelBlock e() { - return this.e(this.primary); - } - - public ModelBlock nswe() { - return this.nswe(this.primary); - } - - public ModelBlock dnswe() { - return this.dnswe(this.primary); - } - - public ModelBlock du() { - return this.du(this.primary); - } - - public ModelBlock ns() { - return this.ns(this.primary); - } - - public ModelBlock we() { - return this.we(this.primary); - } - - public ModelBlock all() { - return this.all(this.primary); - } - - public ModelBlock cull(Facing cull) { - for(BlockPartFace last : this.last) { - last.cull = cull; - } - return this; - } - - public ModelBlock noCull() { - return this.cull(null); - } - - public ModelBlock tint() { - for(BlockPartFace last : this.last) { - last.tint = 0; - } - return this; - } - - public ModelBlock rot(int rot) { - for(BlockPartFace last : this.last) { - last.uv = new BlockFaceUV(last.uv.uvs, rot); - } - return this; - } - - public ModelBlock uv(float x1, float y1, float x2, float y2) { - for(BlockPartFace last : this.last) { - last.uv = new BlockFaceUV(new float[] {x1, y1, x2, y2}, last.uv.rotation); - } - return this; - } - - - public ModelBlock(String primary) { - this(null, Lists.newArrayList(), primary != null && primary.indexOf('/') == -1 ? "blocks/" + primary : primary, true, true, Transforms.DEFAULT, null); - } - - public ModelBlock(String primary, Transforms transform, String ... layers) { - this(ModelBakery.MODEL_GENERATED, ModelBakery.MODEL_GENERATED.elements, - primary.indexOf('/') == -1 ? "items/" + primary : primary, false, false, transform, layers); - } - - public ModelBlock(Transforms transform, String ... layers) { - this(ModelBakery.MODEL_GENERATED, ModelBakery.MODEL_GENERATED.elements, - layers[0].indexOf('/') == -1 ? "items/" + layers[0] : layers[0], false, false, transform, layers); - } - - protected ModelBlock(String primary, List elements, Transforms transform, String ... layers) { - this(null, elements, primary, false, false, transform, layers); - } - - public ModelBlock(ModelBlock parent, Transforms transform) { - this(parent, Lists.newArrayList(), parent.getPrimary(), false, true, transform, null); - } - - private ModelBlock(ModelBlock parent, List elements, String primary, boolean occlude, boolean gui3d, - Transforms transform, String[] layers) { - for(int z = 0; layers != null && z < layers.length; z++) { - layers[z] = layers[z].indexOf('/') == -1 ? "items/" + layers[z] : layers[z]; - } - this.elements = parent == null ? elements : parent.getElements(); - this.occlusion = parent == null ? occlude : parent.isAmbientOcclusion(); - this.gui3d = gui3d; - this.primary = primary == null ? TextureMap.LOCATION_MISSING_TEXTURE : primary; - this.parent = parent; - this.transform = transform; - this.uvLock = false; - this.rotation = ModelRotation.X0_Y0; - this.layers = layers; - } - - public List getElements() { - return this.elements; - } - - public boolean isAmbientOcclusion() { - return this.occlusion; - } - - public boolean isGui3d() { - return this.gui3d; - } - - public String getPrimary() { - return this.primary; - } - - public String[] getTextures() { - return this.layers; - } - - public int getNumTextures() { - return this.layers == null ? 0 : this.layers.length; - } - - public String getTexture(int layer) { - return this.layers == null || this.layers[layer] == null ? TextureMap.LOCATION_MISSING_TEXTURE : this.layers[layer]; - } - - public ModelBlock getParent() { - return this.parent; - } - - public Transforms getTransform() { - return this.transform; - } - - public ModelRotation getRotation() { - return this.rotation; - } - - public boolean isUvLocked() { - return this.uvLock; - } -} diff --git a/java/src/game/renderer/blockmodel/SingleStateMap.java b/java/src/game/renderer/blockmodel/SingleStateMap.java deleted file mode 100755 index 8d236e4..0000000 --- a/java/src/game/renderer/blockmodel/SingleStateMap.java +++ /dev/null @@ -1,13 +0,0 @@ -package game.renderer.blockmodel; - -import game.init.BlockRegistry; -import game.world.State; - - -public class SingleStateMap extends StateMap -{ - protected String getResourceLocation(State state) - { - return BlockRegistry.REGISTRY.getNameForObject(state.getBlock()).toString() + '#' + this.getPropertyString(state.getProperties()); - } -} diff --git a/java/src/game/renderer/blockmodel/Transform.java b/java/src/game/renderer/blockmodel/Transform.java deleted file mode 100755 index ea6f47f..0000000 --- a/java/src/game/renderer/blockmodel/Transform.java +++ /dev/null @@ -1,37 +0,0 @@ -package game.renderer.blockmodel; - -import game.renderer.Vector3f; - -public class Transform { - static final Transform IDENTITY = new Transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f); - - public final Vector3f rotation; - public final Vector3f translation; - public final Vector3f scale; - - public Transform(float rx, float ry, float rz, float tx, float ty, float tz, float sx, float sy, float sz) { - this.rotation = new Vector3f(rx, ry, rz); - this.translation = (Vector3f)new Vector3f(tx, ty, tz).scale(0.0625F); - this.scale = new Vector3f(sx, sy, sz); - } - - public boolean equals(Object obj) { - if(this == obj) { - return true; - } - else if(this.getClass() != obj.getClass()) { - return false; - } - else { - Transform other = (Transform)obj; - return this.rotation.equals(other.rotation) && this.scale.equals(other.scale) && this.translation.equals(other.translation); - } - } - - public int hashCode() { - int i = this.rotation.hashCode(); - i = 31 * i + this.translation.hashCode(); - i = 31 * i + this.scale.hashCode(); - return i; - } -} diff --git a/java/src/game/renderer/blockmodel/Transforms.java b/java/src/game/renderer/blockmodel/Transforms.java deleted file mode 100755 index 09a2e34..0000000 --- a/java/src/game/renderer/blockmodel/Transforms.java +++ /dev/null @@ -1,178 +0,0 @@ -package game.renderer.blockmodel; - -import org.lwjgl.opengl.GL11; - -public enum Transforms { - DEFAULT( - Transform.IDENTITY, - Transform.IDENTITY, - Transform.IDENTITY, - Transform.IDENTITY - ), - ANVIL( - new Transform(10.0f, -45.0f, 170.0f, 0.25f, 1.5f, -2.5f, 0.375f, 0.375f, 0.375f), - Transform.IDENTITY, - Transform.IDENTITY, - Transform.IDENTITY - ), - BLOCK( - new Transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f, 0.375f, 0.375f), - Transform.IDENTITY, - Transform.IDENTITY, - Transform.IDENTITY - ), - ITEM( - new Transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -3.0f, 0.55f, 0.55f, 0.55f), - new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - TOOL_FLIP( - new Transform(180.0f, 90.0f, -35.0f, 0.0f, 0.0f, -3.5f, 0.85f, 0.85f, 0.85f), - new Transform(0.0f, 45.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - TOOL( - new Transform(0.0f, 90.0f, -35.0f, 0.0f, 1.25f, -3.5f, 0.85f, 0.85f, 0.85f), - new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - OFFSET2( - new Transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.25f, 0.55f, 0.55f, 0.55f), - new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - LAYER( - new Transform(10.0f, -45.0f, 170.0f, 0.0f, 0.25f, -2.75f, 0.375f, 0.375f, 0.375f), - new Transform(0.0f, 0.0f, 0.0f, 0.0f, 5.25f, 0.0f, 1.0f, 1.0f, 1.0f), - Transform.IDENTITY, - Transform.IDENTITY - ), - DICE( - new Transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -1.75f, 0.15f, 0.15f, 0.15f), - new Transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.4f, 0.4f, 0.4f), - new Transform(135.0f, -55.0f, 180.0f, 0.0f, 0.0f, 0.0f, 1.1f, 1.1f, 1.1f), - new Transform(0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.4f, 0.4f, 0.4f) - ), - STAIRS( - new Transform(10.0f, -45.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f, 0.375f, 0.375f), - Transform.IDENTITY, - new Transform(0.0f, 180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f), - Transform.IDENTITY - ), - OFFSET1( - new Transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.5f, 0.55f, 0.55f, 0.55f), - new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - GATE( - new Transform(0.0f, -90.0f, 170.0f, 0.0f, 1.5f, -2.75f, 0.375f, 0.375f, 0.375f), - new Transform(0.0f, 90.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f), - Transform.IDENTITY, - Transform.IDENTITY - ), - NUGGET( - new Transform(-90.0f, 0.0f, 0.0f, 0.0f, 1.0f, -2.0f, 0.55f, 0.55f, 0.55f), - new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - SKULL( - new Transform(180.0f, -45.0f, 0.0f, 0.0f, 1.0f, -2.5f, 0.25f, 0.25f, 0.25f), - new Transform(0.0f, -180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.55f, 0.55f, 0.55f), - new Transform(0.0f, 180.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.7f, 0.7f, 0.7f), - Transform.IDENTITY - ), - BUTTON( - new Transform(10.0f, -45.0f, 170.0f, 0.0f, 1.0f, -1.75f, 0.375f, 0.375f, 0.375f), - Transform.IDENTITY, - Transform.IDENTITY, - Transform.IDENTITY - ), - RANGED( - new Transform(5.0f, 80.0f, -45.0f, 0.75f, 0.0f, 0.25f, 1.0f, 1.0f, 1.0f), - new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - BANNER( - new Transform(0.0f, 90.0f, -90.0f, 0.0f, 0.0f, -4.0f, 0.5f, 0.5f, 0.5f), - new Transform(0.0f, 225.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f), - new Transform(0.0f, -65.0f, 0.0f, 0.0f, -3.0f, 0.0f, 0.85f, 0.85f, 0.85f), - Transform.IDENTITY - ), - FENCE( - new Transform(0.0f, 0.0f, 180.0f, 0.0f, 1.5f, -2.75f, 0.375f, 0.375f, 0.375f), - Transform.IDENTITY, - new Transform(0.0f, 90.0f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f), - Transform.IDENTITY - ), - FLAT( - new Transform(10.0f, -45.0f, 170.0f, 0.0f, 0.25f, -2.75f, 0.375f, 0.375f, 0.375f), - new Transform(0.0f, 0.0f, 0.0f, 0.0f, 5.0f, 0.0f, 1.0f, 1.0f, 1.0f), - Transform.IDENTITY, - Transform.IDENTITY - ), - ROD( - new Transform(0.0f, 90.0f, -35.0f, 0.0f, 0.75f, -3.5f, 0.85f, 0.85f, 0.85f), - new Transform(0.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ), - KEY( - new Transform(0.0f, 270.0f, -35.0f, 0.0f, 1.25f, -3.5f, 0.85f, 0.85f, 0.85f), - new Transform(180.0f, -135.0f, 25.0f, 0.0f, 4.0f, 2.0f, 1.7f, 1.7f, 1.7f), - Transform.IDENTITY, - Transform.IDENTITY - ); - - public static enum Camera { - NONE, - THIRD_PERSON, - FIRST_PERSON, - GUI, - GROUND; - } - - public final Transform third; - public final Transform first; - public final Transform gui; - public final Transform ground; - - private Transforms(Transform third, Transform first, Transform gui, Transform ground) { - this.third = third; - this.first = first; - this.gui = gui; - this.ground = ground; - } - - public void apply(Camera type) { - Transform vec = this.get(type); - if(vec != Transform.IDENTITY) { - GL11.glTranslatef(vec.translation.x, vec.translation.y, vec.translation.z); - GL11.glRotatef(vec.rotation.y, 0.0F, 1.0F, 0.0F); - GL11.glRotatef(vec.rotation.x, 1.0F, 0.0F, 0.0F); - GL11.glRotatef(vec.rotation.z, 0.0F, 0.0F, 1.0F); - GL11.glScalef(vec.scale.x, vec.scale.y, vec.scale.z); - } - } - - public Transform get(Camera type) { - switch(type) { - case THIRD_PERSON: - return this.third; - case FIRST_PERSON: - return this.first; - case GUI: - return this.gui; - case GROUND: - return this.ground; - default: - return Transform.IDENTITY; - } - } -} diff --git a/java/src/game/renderer/model/ModelHumanoidHead.java b/java/src/game/renderer/model/ModelHumanoidHead.java deleted file mode 100755 index 4950f71..0000000 --- a/java/src/game/renderer/model/ModelHumanoidHead.java +++ /dev/null @@ -1,36 +0,0 @@ -package game.renderer.model; - -import game.entity.Entity; - -public class ModelHumanoidHead extends ModelHead -{ - private final ModelRenderer head = new ModelRenderer(this, 32, 0); - - public ModelHumanoidHead() - { - super(0, 0, 64, 64); - this.head.addBox(-4.0F, -8.0F, -4.0F, 8, 8, 8, 0.25F); - this.head.setRotationPoint(0.0F, 0.0F, 0.0F); - } - - /** - * Sets the models various rotation angles then renders the model. - */ - public void render(Entity entityIn, float p_78088_2_, float p_78088_3_, float p_78088_4_, float p_78088_5_, float p_78088_6_, float scale) - { - super.render(entityIn, p_78088_2_, p_78088_3_, p_78088_4_, p_78088_5_, p_78088_6_, scale); - this.head.render(scale); - } - - /** - * Sets the model's various rotation angles. For bipeds, par1 and par2 are used for animating the movement of arms - * and legs, where par1 represents the time(so that arms and legs swing back and forth) and par2 represents how - * "far" arms and legs can swing at most. - */ - public void setRotationAngles(float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch, float scaleFactor, Entity entityIn) - { - super.setRotationAngles(limbSwing, limbSwingAmount, ageInTicks, netHeadYaw, headPitch, scaleFactor, entityIn); - this.head.rotateAngleY = this.mainHead.rotateAngleY; - this.head.rotateAngleX = this.mainHead.rotateAngleX; - } -} diff --git a/java/src/game/renderer/tileentity/TileEntityItemStackRenderer.java b/java/src/game/renderer/tileentity/TileEntityItemStackRenderer.java deleted file mode 100755 index 08829fb..0000000 --- a/java/src/game/renderer/tileentity/TileEntityItemStackRenderer.java +++ /dev/null @@ -1,76 +0,0 @@ -package game.renderer.tileentity; - -import org.lwjgl.opengl.GL11; - -import game.block.Block; -import game.init.Blocks; -import game.init.Items; -import game.item.ItemStack; -import game.renderer.GlState; -import game.tileentity.TileEntityBanner; -import game.tileentity.TileEntityChest; -import game.tileentity.TileEntitySkull; -import game.world.Facing; - -public class TileEntityItemStackRenderer -{ - public static TileEntityItemStackRenderer instance = new TileEntityItemStackRenderer(); - private TileEntityChest field_147717_b = new TileEntityChest(0); - private TileEntityChest field_147718_c = new TileEntityChest(1); -// private TileEntityWarpChest warpChest = new TileEntityWarpChest(); - private TileEntityBanner banner = new TileEntityBanner(); - private TileEntitySkull skull = new TileEntitySkull(); - - public void renderByItem(ItemStack itemStackIn) - { - if (itemStackIn.getItem() == Items.banner) - { - this.banner.setItemValues(itemStackIn); - TileEntityRendererDispatcher.instance.renderTileEntityAt(this.banner, 0.0D, 0.0D, 0.0D, 0.0F); - } - else if (itemStackIn.getItem() == Items.skull) - { -// String user = null; -// -// if (itemStackIn.hasTagCompound()) -// { -// NBTTagCompound nbttagcompound = itemStackIn.getTagCompound(); -// -// if (nbttagcompound.hasKey("SkullOwner", 8) && nbttagcompound.getString("SkullOwner").length() > 0) -// { -// user = nbttagcompound.getString("SkullOwner"); -// } -// } - - if (TileEntitySkullRenderer.instance != null) - { - GL11.glPushMatrix(); - GL11.glTranslatef(-0.5F, 0.0F, -0.5F); - GL11.glScalef(2.0F, 2.0F, 2.0F); - boolean flag = GlState.isCullEnabled(); - GlState.disableCull(); - TileEntitySkullRenderer.instance.renderSkull(0.0F, 0.0F, 0.0F, Facing.UP, 0.0F, -1); - if(flag) - GlState.enableCull(); - GL11.glPopMatrix(); - } - } - else - { - Block block = itemStackIn.getItem().getBlock(); - -// if (block == Blocks.warp_chest) -// { -// TileEntityRendererDispatcher.instance.renderTileEntityAt(this.warpChest, 0.0D, 0.0D, 0.0D, 0.0F); -// } - if (block == Blocks.trapped_chest) - { - TileEntityRendererDispatcher.instance.renderTileEntityAt(this.field_147718_c, 0.0D, 0.0D, 0.0D, 0.0F); - } - else - { - TileEntityRendererDispatcher.instance.renderTileEntityAt(this.field_147717_b, 0.0D, 0.0D, 0.0D, 0.0F); - } - } - } -} diff --git a/java/src/game/renderer/tileentity/TileEntityMobSpawnerRenderer.java b/java/src/game/renderer/tileentity/TileEntityMobSpawnerRenderer.java deleted file mode 100755 index 96aa199..0000000 --- a/java/src/game/renderer/tileentity/TileEntityMobSpawnerRenderer.java +++ /dev/null @@ -1,38 +0,0 @@ -package game.renderer.tileentity; - -import org.lwjgl.opengl.GL11; - -import game.Game; -import game.entity.Entity; -import game.tileentity.TileEntityMobSpawner; - -public class TileEntityMobSpawnerRenderer extends TileEntitySpecialRenderer -{ - public void renderTileEntityAt(TileEntityMobSpawner te, double x, double y, double z, float partialTicks, int destroyStage) - { - GL11.glPushMatrix(); - GL11.glTranslatef((float)x + 0.5F, (float)y, (float)z + 0.5F); - renderMob(te, x, y, z, partialTicks); - GL11.glPopMatrix(); - } - - /** - * Render the mob inside the mob spawner. - */ - public static void renderMob(TileEntityMobSpawner mobSpawnerLogic, double posX, double posY, double posZ, float partialTicks) - { - Entity entity = mobSpawnerLogic.createRenderEntity(mobSpawnerLogic.getWorld()); - - if (entity != null) - { - float f = 0.4375F; - GL11.glTranslatef(0.0F, 0.4F, 0.0F); - GL11.glRotatef((float)(mobSpawnerLogic.getPrevMobRotation() + (mobSpawnerLogic.getMobRotation() - mobSpawnerLogic.getPrevMobRotation()) * (double)partialTicks) * 10.0F, 0.0F, 1.0F, 0.0F); - GL11.glRotatef(-30.0F, 1.0F, 0.0F, 0.0F); - GL11.glTranslatef(0.0F, -0.4F, 0.0F); - GL11.glScalef(f, f, f); - entity.setLocationAndAngles(posX, posY, posZ, 0.0F, 0.0F); - Game.getGame().getRenderManager().renderEntity(entity, 0.0D, 0.0D, 0.0D, partialTicks); - } - } -} diff --git a/java/src/game/renderer/tileentity/TileEntitySkullRenderer.java b/java/src/game/renderer/tileentity/TileEntitySkullRenderer.java deleted file mode 100755 index 7a6ef45..0000000 --- a/java/src/game/renderer/tileentity/TileEntitySkullRenderer.java +++ /dev/null @@ -1,124 +0,0 @@ -package game.renderer.tileentity; - -import org.lwjgl.opengl.GL11; - -import game.renderer.GlState; -import game.renderer.model.ModelHumanoidHead; -import game.tileentity.TileEntitySkull; -import game.world.Facing; - - -public class TileEntitySkullRenderer extends TileEntitySpecialRenderer -{ - private static final String TEXTURE_SKULL = "textures/entity/skull.png"; - public static TileEntitySkullRenderer instance; - - private final ModelHumanoidHead humanoidHead = new ModelHumanoidHead(); - - public void renderTileEntityAt(TileEntitySkull te, double x, double y, double z, float partialTicks, int destroyStage) - { - Facing enumfacing = Facing.getFront(te.getBlockMetadata() & 7); - this.renderSkull((float)x, (float)y, (float)z, enumfacing, (float)(te.getSkullRotation() * 360) / 16.0F, destroyStage); - } - - public void setRendererDispatcher(TileEntityRendererDispatcher rendererDispatcherIn) - { - super.setRendererDispatcher(rendererDispatcherIn); - instance = this; - } - - public void renderSkull(float x, float y, float z, Facing dir, float rot, int destroyStage) - { -// ModelBase modelbase = this.skeletonHead; - - if (destroyStage >= 0) - { - this.bindTexture(DESTROY_STAGES[destroyStage]); - GL11.glMatrixMode(GL11.GL_TEXTURE); - GL11.glPushMatrix(); - GL11.glScalef(4.0F, 2.0F, 1.0F); - GL11.glTranslatef(0.0625F, 0.0625F, 0.0625F); - GL11.glMatrixMode(GL11.GL_MODELVIEW); - } - else - { -// switch (p_180543_6_) -// { -// case 0: -// default: -// this.bindTexture(SKELETON_TEXTURES); -// break; -// -// case 1: -// this.bindTexture(WITHER_SKELETON_TEXTURES); -// break; -// -// case 2: -// this.bindTexture(ZOMBIE_TEXTURES); -// modelbase = this.humanoidHead; -// break; -// -// case 3: -// modelbase = this.humanoidHead; -// String tex = TEXTURE_SKULL; // EntitySkinManager.TEXTURE_DEF; - -// if (user != null && EntityTexManager.getModel(user) == ModelType.HUMANOID) -// { -// tex = EntityTexManager.getSkin(user, ModelType.HUMANOID); -// } - - this.bindTexture(TEXTURE_SKULL); -// break; -// -// case 4: -// this.bindTexture(CREEPER_TEXTURES); -// } - } - - GL11.glPushMatrix(); - GlState.disableCull(); - - if (dir != Facing.UP) - { - switch (dir) - { - case NORTH: - GL11.glTranslatef(x + 0.5F, y + 0.25F, z + 0.74F); - break; - - case SOUTH: - GL11.glTranslatef(x + 0.5F, y + 0.25F, z + 0.26F); - rot = 180.0F; - break; - - case WEST: - GL11.glTranslatef(x + 0.74F, y + 0.25F, z + 0.5F); - rot = 270.0F; - break; - - case EAST: - default: - GL11.glTranslatef(x + 0.26F, y + 0.25F, z + 0.5F); - rot = 90.0F; - } - } - else - { - GL11.glTranslatef(x + 0.5F, y, z + 0.5F); - } - - float f = 0.0625F; - GlState.enableRescaleNormal(); - GL11.glScalef(-1.0F, -1.0F, 1.0F); - GlState.enableAlpha(); - this.humanoidHead.render(null, 0.0F, 0.0F, 0.0F, rot, 0.0F, f); - GL11.glPopMatrix(); - - if (destroyStage >= 0) - { - GL11.glMatrixMode(GL11.GL_TEXTURE); - GL11.glPopMatrix(); - GL11.glMatrixMode(GL11.GL_MODELVIEW); - } - } -} diff --git a/java/src/game/tileentity/ILockableContainer.java b/java/src/game/tileentity/ILockableContainer.java deleted file mode 100755 index 54e6125..0000000 --- a/java/src/game/tileentity/ILockableContainer.java +++ /dev/null @@ -1,12 +0,0 @@ -package game.tileentity; - -import game.inventory.IInventory; - -public interface ILockableContainer extends IInventory, IInteractionObject -{ - boolean isLocked(); - - void setLockCode(LockCode code); - - LockCode getLockCode(); -} diff --git a/java/src/game/tileentity/LocalBlockIntercommunication.java b/java/src/game/tileentity/LocalBlockIntercommunication.java deleted file mode 100755 index 7c1d406..0000000 --- a/java/src/game/tileentity/LocalBlockIntercommunication.java +++ /dev/null @@ -1,51 +0,0 @@ -package game.tileentity; - -import game.entity.npc.EntityNPC; -import game.inventory.Container; -import game.inventory.InventoryPlayer; - -public class LocalBlockIntercommunication implements IInteractionObject -{ - private String guiID; - private String displayName; - - public LocalBlockIntercommunication(String guiIdIn, String displayNameIn) - { - this.guiID = guiIdIn; - this.displayName = displayNameIn; - } - - public Container createContainer(InventoryPlayer playerInventory, EntityNPC playerIn) - { - throw new UnsupportedOperationException(); - } - - /** - * Get the name of this object. For players this returns their username - */ - public String getName() - { - return this.displayName; - } - - /** - * Returns true if this thing is named - */ - public boolean hasCustomName() - { - return true; - } - - public String getGuiID() - { - return this.guiID; - } - - /** - * Get the formatted ChatComponent that will be used for the sender's username in chat - */ - public String getCommandName() - { - return this.displayName; - } -} diff --git a/java/src/game/tileentity/LockCode.java b/java/src/game/tileentity/LockCode.java deleted file mode 100755 index 39b276e..0000000 --- a/java/src/game/tileentity/LockCode.java +++ /dev/null @@ -1,42 +0,0 @@ -package game.tileentity; - -import game.nbt.NBTTagCompound; - -public class LockCode -{ - public static final LockCode EMPTY_CODE = new LockCode(""); - private final String lock; - - public LockCode(String code) - { - this.lock = code; - } - - public boolean isEmpty() - { - return this.lock == null || this.lock.isEmpty(); - } - - public String getLock() - { - return this.lock; - } - - public void toNBT(NBTTagCompound nbt) - { - nbt.setString("Lock", this.lock); - } - - public static LockCode fromNBT(NBTTagCompound nbt) - { - if (nbt.hasKey("Lock", 8)) - { - String s = nbt.getString("Lock"); - return new LockCode(s); - } - else - { - return EMPTY_CODE; - } - } -} diff --git a/java/src/game/tileentity/TileEntityComparator.java b/java/src/game/tileentity/TileEntityComparator.java deleted file mode 100755 index 4506c20..0000000 --- a/java/src/game/tileentity/TileEntityComparator.java +++ /dev/null @@ -1,34 +0,0 @@ -package game.tileentity; - -import game.nbt.NBTTagCompound; - -public class TileEntityComparator extends TileEntity -{ - private int outputSignal; - - public void writeToNBT(NBTTagCompound compound) - { - super.writeToNBT(compound); - compound.setInteger("OutputSignal", this.outputSignal); - } - - public void readFromNBT(NBTTagCompound compound) - { - super.readFromNBT(compound); - this.outputSignal = compound.getInteger("OutputSignal"); - } - - public int getOutputSignal() - { - return this.outputSignal; - } - - public void setOutputSignal(int p_145995_1_) - { - this.outputSignal = p_145995_1_; - } - - public int getColor() { - return 0xaf0000; - } -} diff --git a/java/src/game/tileentity/TileEntityMobSpawner.java b/java/src/game/tileentity/TileEntityMobSpawner.java deleted file mode 100755 index 0b99b0d..0000000 --- a/java/src/game/tileentity/TileEntityMobSpawner.java +++ /dev/null @@ -1,243 +0,0 @@ -package game.tileentity; - -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.init.EntityRegistry; -import game.nbt.NBTTagCompound; -import game.network.Packet; -import game.packet.S35PacketUpdateTileEntity; -import game.renderer.particle.ParticleType; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.World; - -public class TileEntityMobSpawner extends TileEntity implements ITickable -{ - private int spawnDelay = 20; - private String mobID = "Pig"; - private double mobRotation; - private double prevMobRotation; - private int minSpawnDelay = 200; - private int maxSpawnDelay = 800; - private int spawnCount = 4; - private Entity cachedEntity; - private int maxNearbyEntities = 6; - private int activatingRangeFromPlayer = 16; - private int spawnRange = 4; - - public Packet getDescriptionPacket() - { - return new S35PacketUpdateTileEntity(this); - } - - public boolean receiveClientEvent(int id, int type) - { - if (id == 1 && this.worldObj.client) - { - this.spawnDelay = this.minSpawnDelay; - return true; - } - else - { - return super.receiveClientEvent(id, type); - } - } - -// public boolean hasSpecialNBT() -// { -// return true; -// } - - public int getColor() { - return 0xff0000; - } - - public void update() - { - BlockPos blockpos = this.pos; - if (this.worldObj.isAnyPlayerWithinRangeAt((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 0.5D, (double)blockpos.getZ() + 0.5D, (double)this.activatingRangeFromPlayer)) - { - if (this.worldObj.client) - { - double d3 = (double)((float)blockpos.getX() + this.worldObj.rand.floatv()); - double d4 = (double)((float)blockpos.getY() + this.worldObj.rand.floatv()); - double d5 = (double)((float)blockpos.getZ() + this.worldObj.rand.floatv()); - this.worldObj.spawnParticle(ParticleType.SMOKE_NORMAL, d3, d4, d5, 0.0D, 0.0D, 0.0D); - this.worldObj.spawnParticle(ParticleType.FLAME, d3, d4, d5, 0.0D, 0.0D, 0.0D); - - if (this.spawnDelay > 0) - { - --this.spawnDelay; - } - - this.prevMobRotation = this.mobRotation; - this.mobRotation = (this.mobRotation + (double)(1000.0F / ((float)this.spawnDelay + 200.0F))) % 360.0D; - } - else - { - if(!Config.mobs || !Config.spawners) { - return; - } - - if (this.spawnDelay == -1) - { - this.resetTimer(); - } - - if (this.spawnDelay > 0) - { - --this.spawnDelay; - return; - } - - boolean flag = false; - - for (int i = 0; i < this.spawnCount; ++i) - { - Entity entity = EntityRegistry.createEntityByName(this.mobID, this.worldObj); - - if (entity == null) - { - return; - } - - int j = this.worldObj.getEntitiesWithinAABB(entity.getClass(), (new BoundingBox((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ(), (double)(blockpos.getX() + 1), (double)(blockpos.getY() + 1), (double)(blockpos.getZ() + 1))).expand((double)this.spawnRange, (double)this.spawnRange, (double)this.spawnRange)).size(); - - if (j >= this.maxNearbyEntities) - { - this.resetTimer(); - return; - } - - double d0 = (double)blockpos.getX() + (this.worldObj.rand.doublev() - this.worldObj.rand.doublev()) * (double)this.spawnRange + 0.5D; - double d1 = (double)(blockpos.getY() + this.worldObj.rand.zrange(3) - 1); - double d2 = (double)blockpos.getZ() + (this.worldObj.rand.doublev() - this.worldObj.rand.doublev()) * (double)this.spawnRange + 0.5D; - EntityLiving entityliving = entity instanceof EntityLiving ? (EntityLiving)entity : null; - entity.setLocationAndAngles(d0, d1, d2, this.worldObj.rand.floatv() * 360.0F, 0.0F); - - if (entityliving == null || entityliving.getCanSpawnHere() && entityliving.isNotColliding()) - { - if (entity instanceof EntityLiving && entity.worldObj != null) - { -// if (entity instanceof EntityLiving) -// { - ((EntityLiving)entity).onInitialSpawn(null); -// } - - entity.worldObj.spawnEntityInWorld(entity); - } - this.worldObj.playAuxSFX(2004, blockpos, 0); - - if (entityliving != null) - { - entityliving.spawnExplosionParticle(); - } - - flag = true; - } - } - - if (flag) - { - this.resetTimer(); - } - } - } - } - - private void resetTimer() - { - if (this.maxSpawnDelay <= this.minSpawnDelay) - { - this.spawnDelay = this.minSpawnDelay; - } - else - { - int i = this.maxSpawnDelay - this.minSpawnDelay; - this.spawnDelay = this.minSpawnDelay + this.worldObj.rand.zrange(i); - } - - this.worldObj.addBlockEvent(TileEntityMobSpawner.this.pos, Blocks.mob_spawner, 1, 0); - } - - public void readFromNBT(NBTTagCompound nbt) - { - super.readFromNBT(nbt); - this.mobID = nbt.getString("EntityId"); - this.spawnDelay = nbt.getShort("Delay"); - - if (nbt.hasKey("MinSpawnDelay", 99)) - { - this.minSpawnDelay = nbt.getShort("MinSpawnDelay"); - this.maxSpawnDelay = nbt.getShort("MaxSpawnDelay"); - this.spawnCount = nbt.getShort("SpawnCount"); - } - - if (nbt.hasKey("MaxNearbyEntities", 99)) - { - this.maxNearbyEntities = nbt.getShort("MaxNearbyEntities"); - this.activatingRangeFromPlayer = nbt.getShort("RequiredPlayerRange"); - } - - if (nbt.hasKey("SpawnRange", 99)) - { - this.spawnRange = nbt.getShort("SpawnRange"); - } - - if (this.worldObj != null) - { - this.cachedEntity = null; - } - } - - public void writeToNBT(NBTTagCompound nbt) - { - super.writeToNBT(nbt); - String s = this.mobID; - - if (s != null && !s.isEmpty()) - { - nbt.setString("EntityId", s); - nbt.setShort("Delay", (short)this.spawnDelay); - nbt.setShort("MinSpawnDelay", (short)this.minSpawnDelay); - nbt.setShort("MaxSpawnDelay", (short)this.maxSpawnDelay); - nbt.setShort("SpawnCount", (short)this.spawnCount); - nbt.setShort("MaxNearbyEntities", (short)this.maxNearbyEntities); - nbt.setShort("RequiredPlayerRange", (short)this.activatingRangeFromPlayer); - nbt.setShort("SpawnRange", (short)this.spawnRange); - } - } - - public Entity createRenderEntity(World worldIn) - { - if (this.cachedEntity == null) - { - this.cachedEntity = EntityRegistry.createEntityByName(this.mobID, worldIn); - -// if (entity != null) -// { -//// entity = this.spawnNewEntity(entity, false); -// this.cachedEntity = entity; -// } - } - - return this.cachedEntity; - } - - public double getMobRotation() - { - return this.mobRotation; - } - - public double getPrevMobRotation() - { - return this.prevMobRotation; - } - - public void setEntityName(String name) - { - this.mobID = name; - } -} diff --git a/java/src/game/tileentity/TileEntityNote.java b/java/src/game/tileentity/TileEntityNote.java deleted file mode 100755 index ee2bf52..0000000 --- a/java/src/game/tileentity/TileEntityNote.java +++ /dev/null @@ -1,74 +0,0 @@ -package game.tileentity; - -import game.init.Blocks; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.World; - -public class TileEntityNote extends TileEntity -{ - /** Note to play */ - public byte note; - - /** stores the latest redstone state */ - public boolean previousRedstoneState; - - public void writeToNBT(NBTTagCompound compound) - { - super.writeToNBT(compound); - compound.setByte("note", this.note); - } - - public void readFromNBT(NBTTagCompound compound) - { - super.readFromNBT(compound); - this.note = compound.getByte("note"); - this.note = (byte)ExtMath.clampi(this.note, 0, 24); - } - - /** - * change pitch by -> (currentPitch + 1) % 25 - */ - public void changePitch() - { - this.note = (byte)((this.note + 1) % 25); - this.markDirty(); - } - - public void triggerNote(World worldIn, BlockPos p_175108_2_) - { - if (worldIn.getState(p_175108_2_.up()).getBlock().getMaterial() == Material.air) - { -// Material material = worldIn.getBlockState(p_175108_2_.down()).getBlock().getMaterial(); -// int i = 0; -// -// if (material == Material.rock) -// { -// i = 1; -// } -// -// if (material == Material.sand) -// { -// i = 2; -// } -// -// if (material == Material.glass) -// { -// i = 3; -// } -// -// if (material == Material.wood) -// { -// i = 4; -// } - - worldIn.addBlockEvent(p_175108_2_, Blocks.noteblock, 0, this.note); - } - } - - public int getColor() { - return 0x80ff00; - } -} diff --git a/java/src/game/tileentity/TileEntitySkull.java b/java/src/game/tileentity/TileEntitySkull.java deleted file mode 100755 index 66becb1..0000000 --- a/java/src/game/tileentity/TileEntitySkull.java +++ /dev/null @@ -1,61 +0,0 @@ -package game.tileentity; - -import game.nbt.NBTTagCompound; -import game.network.Packet; -import game.packet.S35PacketUpdateTileEntity; - -public class TileEntitySkull extends TileEntity -{ - private int skullRotation; -// private String user = null; - - public void writeToNBT(NBTTagCompound compound) - { - super.writeToNBT(compound); - compound.setByte("Rot", (byte)(this.skullRotation & 255)); -// if(this.user != null) -// compound.setString("Owner", this.user); - } - - public void readFromNBT(NBTTagCompound compound) - { - super.readFromNBT(compound); - this.skullRotation = compound.getByte("Rot"); -// if(compound.hasKey("Owner", 8)) -// this.user = compound.getString("Owner"); - } - -// public String getUser() -// { -// return this.user; -// } - - /** - * Allows for a specialized description packet to be created. This is often used to sync tile entity data from the - * server to the client easily. For example this is used by signs to synchronise the text to be displayed. - */ - public Packet getDescriptionPacket() - { - return new S35PacketUpdateTileEntity(this); - } - -// public void setUser(String user) -// { -// this.user = user; -// this.markDirty(); -// } - - public int getSkullRotation() - { - return this.skullRotation; - } - - public void setSkullRotation(int rotation) - { - this.skullRotation = rotation; - } - - public int getColor() { - return 0x00ff00; - } -} diff --git a/java/src/game/util/FileUtils.java b/java/src/game/util/FileUtils.java deleted file mode 100644 index b2b86d2..0000000 --- a/java/src/game/util/FileUtils.java +++ /dev/null @@ -1,97 +0,0 @@ -package game.util; - -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; - -import game.log.Log; -import io.netty.util.CharsetUtil; - -public class FileUtils { - public static String read(InputStream input) throws IOException { - return new String(readBytes(input), CharsetUtil.UTF_8); - } - - public static byte[] readBytes(InputStream input) throws IOException { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - byte[] buffer = new byte[4096]; - long count = 0L; - int n; - for(boolean u = false; -1 != (n = input.read(buffer)); count += (long)n) { - output.write(buffer, 0, n); - } - return output.toByteArray(); - } - - public static String read(File file) throws IOException { - FileInputStream in = null; - String s; - try { - in = new FileInputStream(file); - s = FileUtils.read(in); - } - finally { - try { - if(in != null) - in.close(); - } - catch(IOException e) { - } - } - return s; - } - - public static void write(File file, String data) throws IOException { - FileOutputStream out = null; - try { - out = new FileOutputStream(file); - if(out != null) { - out.write(data.getBytes(CharsetUtil.UTF_8)); - out.close(); - } - } - finally { - try { - if(out != null) - out.close(); - } - catch(IOException e) { - } - } - } - - public static InputStream getResource(String path) throws FileNotFoundException { - InputStream in = FileUtils.class.getResourceAsStream("/" + path); - if(in == null) - throw new FileNotFoundException(path); - return in; - } - - public static boolean deleteFiles(File[] files) { - if(files == null) { - Log.JNI.warn("Konnte Ordner nicht löschen"); - return false; - } - - for(int i = 0; i < files.length; ++i) { - File file = files[i]; - Log.JNI.info("Lösche " + file); - - if(file.isDirectory() && !deleteFiles(file.listFiles())) { - Log.JNI.warn("Konnte Ordner " + file + " nicht löschen"); - return false; - } - - if(!file.delete()) { - Log.JNI.warn("Konnte Datei " + file + " nicht löschen"); - return false; - } - } - - return true; - } -} diff --git a/java/src/game/util/Timing.java b/java/src/game/util/Timing.java deleted file mode 100644 index 59f312d..0000000 --- a/java/src/game/util/Timing.java +++ /dev/null @@ -1,30 +0,0 @@ -package game.util; - -public class Timing { - public static long tmr_timer; - public static long tmr_start; - public static long tmr_current; - public static long tmr_last; - - public static long tmr_delta; - public static long tmr_update; - public static long tmr_frames; - public static long tmr_iters; - - public static long tick_torun; - public static long tick_done; - public static long tick_total; - public static long tick_time; - public static long tick_stime; - public static long tick_ftime; - - public static long tick_ttime; - public static long tick_update; - - public static double tick_fraction; - public static float framerate; - public static float tickrate; - public static float fdelta; - public static int tickTarget; - public static int tickFrame; -} diff --git a/java/src/game/util/Tuple.java b/java/src/game/util/Tuple.java deleted file mode 100644 index f41da46..0000000 --- a/java/src/game/util/Tuple.java +++ /dev/null @@ -1,11 +0,0 @@ -package game.util; - -public class Tuple { - public final S first; - public final T second; - - public Tuple(S first, T second) { - this.first = first; - this.second = second; - } -} diff --git a/java/src/game/util/Util.java b/java/src/game/util/Util.java deleted file mode 100644 index 4e12a61..0000000 --- a/java/src/game/util/Util.java +++ /dev/null @@ -1,392 +0,0 @@ -package game.util; - -import java.awt.GraphicsEnvironment; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - -import javax.swing.JOptionPane; - -import game.collect.Lists; -import game.collect.Maps; -import game.log.Log; -import game.properties.IStringSerializable; - -public abstract class Util { - private static long start = getTime(); - - public static String strip(String str, int offset, int len, char newl, char tab, char unk) { - StringBuilder sb = new StringBuilder(); - for(int pos = offset; pos < offset + len; pos++) { - char c = str.charAt(pos); - if(c == '\n') { - if(newl == 0) - return sb.toString(); - sb.append(newl); - } - else if((c == '\t') && tab != 0) { - for(int z = 0; z < 4; z++) - sb.append(tab); - } - else if(c == Log.CHR_UNK) { - if(unk != 0) - sb.append(unk); - } - else if(c >= Log.CHR_SPC && c <= 0xff) { - sb.append(c); - } - } - return sb.toString(); - } - -/* -uint utf_read(const char **ptr) { - uint ch; - byte utf; - char c = *((*ptr)++); - for(utf = 0; (utf < 6) && (c & (0x80 >> utf)); utf++) { - ; - } - if(utf == 1) - return CHR_UNK; - for(ch = ((!utf) || ((((uint)c) << 6) | (((**ptr) & 0x3f) & ~(0xff >> utf)))) ? (c & (0x7f >> utf)) : 0; utf > 1; utf--) { - if(((c = **ptr) & 0xc0) == 0x80) { - // if(ch) { - ch <<= 6; - ch |= c & 0x3f; - // } - } - else { - return c ? CHR_UNK : 0; - } - (*ptr)++; - } - // fprintf(stderr, "%d / %c\n", ch, ch); - return (utf && !ch) ? CHR_UNK : ch; -} - -uint utf_readn(const char *ptr, int *pos) { - const char *str = &ptr[*pos]; - uint ch = utf_read(&str); - *pos = (int)(str-ptr); - return ch; -} - -byte utf_write(char **ptr, int *len, uint ch) { - uint test; - uint mask = 0xffffff80; - char utf; - char c; - if(ch & 0x80000000) { - return 1; - } - for(utf = 0; ch & mask & ~(test = (0xffffffff << ((utf + 1) * 6 + (5 - utf)))); utf++) { - mask &= test; - } - // fprintf(stderr, "%d\n", utf); - if(utf + 1 >= (*len)) { - return 0; - } - (*len) -= utf + 1; - *((*ptr)++) = utf ? (~(0x7f >> utf) | (((uint)(ch >> (utf * 6))) & (0x3f >> utf))) : ch; - for(--utf; utf >= 0; utf--) { - *((*ptr)++) = 0x80 | (((uint)(ch >> (utf * 6))) & 0x3f); - } - return 1; -} - -byte utf_rwriten(char *ptr, int *pos, int len, uint ch) { - char *str = &ptr[*pos]; - len -= (*pos); - byte res = utf_write(&str, &len, ch); - *pos = (int)(str-ptr); - return res; -} - -uint utf_rread(const char **ptr, const char *start) { - const char *tp = *ptr; - uint ch; - char c; - do { - if(tp == start) - return 0; - tp--; - } while(((c = (*tp)) & 0xc0) == 0x80); - *ptr = tp; - return (ch = utf_read(&tp)) ? ch : CHR_UNK; -} - -uint utf_rreadn(const char *ptr, int *pos) { - const char *str = &ptr[*pos]; - uint ch = utf_rread(&str, ptr); - *pos = (int)(str-ptr); - return ch; -} - -int utf_len(const char *str) { - int len; - for(len = 0; utf_read(&str); len++) { - ; - } - return len; -} -*/ - - public static int compareLower(String str1, String str2) { - if(str2.length() > str1.length()) - return 0; - for(int z = 0; z < str2.length(); z++) { - if(Character.toLowerCase(str1.charAt(z)) != Character.toLowerCase(str2.charAt(z))) - return 0; - } - return str2.length() == str1.length() ? 0x7fffffff : str2.length(); - } - - public static Integer parseInt(String str, int base) { - char c; - boolean tbase = false; - int digits = 0; - long v = 0; - long nbase = base != 0 ? (base < 0 ? -base : base) : 10; - long nsign = 1; - for(int pos = 0; pos < str.length(); pos++) { - c = Character.toLowerCase(str.charAt(pos)); - if(pos == 0 && ((c == '+') || ((c == '-') && (base >= 0)))) - nsign = (c == '+') ? 1 : -1; - else if(pos == 0 && c == '0') { - tbase = true; - digits++; - } - else if(tbase && pos == 1 && c == 'x') { - nbase = 16; - digits--; - } - else if(((nbase == 16) && (c >= 'a' && c <= 'f')) || (c >= '0' && c <= '9')) { - v *= nbase; - v += ((long)((c >= '0' && c <= '9') ? (c - '0') : (10 + (c - 'a')))); - digits++; - } - else - return null; - } - if(digits == 0) - return null; - v *= nsign; - if((base < 0) ? (v < 0L || v > 0xffffffffL) : (v < -0x80000000L || v > 0x7fffffffL)) { - return null; - } - return (int)((base < 0) ? (v & 0xffffffff) : (((v >> 32) & 0x80000000) | (v & 0x7fffffff))); - } - - public static T parseEnum(Class clazz, String str) { - boolean name = IStringSerializable.class.isAssignableFrom(clazz); - T[] values = clazz.getEnumConstants(); - Integer value; - if((value = parseInt(str, 0)) != null && (value >= 0) && (value < values.length)) { - return values[value]; - } - int comp; - int max = 0; - T best = null; - for(int z = 0; z < values.length; z++) { - if((comp = compareLower(name ? ((IStringSerializable)values[z]).getName() : values[z].toString(), str)) > max) { - max = comp; - best = values[z]; - } - } - return best; - } - - public static T parseEnum(Class base, String str, Class ... enums) { - int comp; - int max = 0; - T best = null; - for(Class clazz : enums) { - if(!base.isAssignableFrom(clazz)) - throw new IllegalArgumentException("Klasse " + clazz.getSimpleName() + " ist nicht " + base.getSimpleName() + " untergeordnet"); - boolean name = IStringSerializable.class.isAssignableFrom(clazz); - Enum[] values = clazz.getEnumConstants(); - for(int z = 0; z < values.length; z++) { - if((comp = compareLower(name ? ((IStringSerializable)values[z]).getName() : values[z].toString(), str)) > max) { - max = comp; - best = (T)values[z]; - } - } - } - return best; - } - - public static int indexOf(T[] array, T elem) { - for(int z = 0; z < array.length; z++) { - if(array[z] == elem) - return z; - } - return -1; - } - - public static int indexOfChecked(T[] array, T elem) { - for(int z = 0; z < array.length; z++) { - if(array[z] == elem) - return z; - } - throw new IllegalArgumentException("Objekt ist nicht in Array"); - } - - public static Boolean parseBoolean(String str) { - if("1".equals(str) || "true".equalsIgnoreCase(str) || "on".equalsIgnoreCase(str) || "yes".equalsIgnoreCase(str) || "y".equalsIgnoreCase(str)) - return true; - else if("0".equals(str) || "false".equalsIgnoreCase(str) || "off".equalsIgnoreCase(str) || "no".equalsIgnoreCase(str) || "n".equalsIgnoreCase(str)) - return false; - return null; - } - - public static String buildLines(String separator, Function func, Iterable elems) { - StringBuilder sb = new StringBuilder(); - for(T elem : elems) { - if(sb.length() > 0) - sb.append(separator); - sb.append(func.apply(elem)); - } - return sb.toString(); - } - - public static String buildLines(Function func, Iterable elems) { - return buildLines("\n", func, elems); - } - - public static String buildLines(String separator, Iterable elems) { - return buildLines(separator, new Function() { - public String apply(T t) { - return String.valueOf(t); - } - }, elems); - } - - public static String buildLines(Iterable elems) { - return buildLines("\n", elems); - } - - public static String buildLines(String separator, Function func, T ... elems) { - StringBuilder sb = new StringBuilder(); - for(T elem : elems) { - if(sb.length() > 0) - sb.append(separator); - sb.append(func.apply(elem)); - } - return sb.toString(); - } - - public static String buildLines(Function func, T ... elems) { - return buildLines("\n", func, elems); - } - - public static String buildLines(String separator, T ... elems) { - return buildLines(separator, new Function() { - public String apply(T t) { - return String.valueOf(t); - } - }, elems); - } - - public static String buildLines(T ... elems) { - return buildLines("\n", elems); - } - - public static int mixColor(int c1, int c2) { - return ((((c1 >> 24 & 255) + (c2 >> 24 & 255)) / 2) << 24) | ((((c1 >> 16 & 255) + (c2 >> 16 & 255)) / 2) << 16) | ((((c1 >> 8 & 255) + (c2 >> 8 & 255)) / 2) << 8) | - (((c1 & 255) + (c2 & 255)) / 2); - } - - public static int mulColor(int color, float brightness) { - int mul = ExtMath.clampi((int)(brightness * 255.0f), 0, 255); - return (color & 0xff000000) | ((((color >> 16 & 255) * mul) / 255) << 16) | ((((color >> 8 & 255) * mul) / 255) << 8) | - (((color & 255) * mul) / 255); - } - - public static void checkOs() { - if(System.getProperty("os.name").startsWith("Windows") || System.getProperty("os.name").startsWith("Mac")) { - String info = "Inkompatibles Betriebssystem"; - String msg = "Linux oder *BSD ist erforderlich, um dieses Programm auszuführen.\n" + - "Alle Versionen von Windows und Mac OS (X) sind nicht kompatibel."; - System.err.println("#################################################################"); - System.err.println("*** " + info + " ***"); - System.err.println(msg); - System.err.println("#################################################################"); - if(!GraphicsEnvironment.isHeadless()) - JOptionPane.showMessageDialog(null, msg, info, JOptionPane.ERROR_MESSAGE); - System.exit(1); - } - } - - public static Tuple getKeyValue(String text, char separator) { - int index = text.indexOf(separator); - if(index == -1) - return new Tuple(text, null); - return new Tuple(text.substring(0, index), text.substring(index + 1)); - } - - public static Tuple getKeyValue(String text) { - return getKeyValue(text, ' '); - } - - private static Object parseObject(String arg) { - try { - return Float.parseFloat(arg); - } - catch(NumberFormatException e) { - } - try { - return Integer.parseInt(arg); - } - catch(NumberFormatException e) { - } - return arg; - } - - public static Map parseArgsSimple(String[] args) { - Map map = Maps.newHashMap(); - List list = Lists.newArrayList(); - String option = null; - boolean parse = true; - for(int z = 0; z < args.length; z++) { - String arg = args[z]; - if(arg.startsWith("--")) { - if(arg.length() == 2) { - parse = false; - continue; - } - if(option != null) - map.put(option, null); - option = arg.substring(2); - } - else if(arg.startsWith("-") && arg.length() == 2) { - if(option != null) - map.put(option, null); - option = arg.substring(1); - } - else if(option != null) { - map.put(option, parseObject(arg)); - option = null; - } - else { - list.add(parseObject(arg)); - } - } - if(option != null) - map.put(option, null); - map.put("__pos", list); - return map; - } - - public static long getTime() { - return System.nanoTime() / 1000L; // glfwGetTimerValue() / (glfwGetTimerFrequency() / 1000000L); - } - - public static long rtime() { - return Util.getTime() - start; - } - - public static double ftime() { - return ((double)rtime()) / 1000000.0; - } -} diff --git a/java/src/game/village/MerchantRecipe.java b/java/src/game/village/MerchantRecipe.java deleted file mode 100755 index c17d4a6..0000000 --- a/java/src/game/village/MerchantRecipe.java +++ /dev/null @@ -1,78 +0,0 @@ -package game.village; - -import game.item.Item; -import game.item.ItemStack; -import game.nbt.NBTTagCompound; - -public class MerchantRecipe -{ - private ItemStack itemToBuy; - private ItemStack secondItemToBuy; - private ItemStack itemToSell; - - public MerchantRecipe(NBTTagCompound tagCompound) - { - this.readFromTags(tagCompound); - } - - public MerchantRecipe(ItemStack buy1, ItemStack buy2, ItemStack sell) - { - this.itemToBuy = buy1; - this.secondItemToBuy = buy2; - this.itemToSell = sell; - } - - public MerchantRecipe(ItemStack buy1, ItemStack sell) - { - this(buy1, (ItemStack)null, sell); - } - - public MerchantRecipe(ItemStack buy1, Item sellItem) - { - this(buy1, new ItemStack(sellItem)); - } - - public ItemStack getItemToBuy() - { - return this.itemToBuy; - } - - public ItemStack getSecondItemToBuy() - { - return this.secondItemToBuy; - } - - public boolean hasSecondItemToBuy() - { - return this.secondItemToBuy != null; - } - - public ItemStack getItemToSell() - { - return this.itemToSell; - } - - public void readFromTags(NBTTagCompound tagCompound) - { - NBTTagCompound nbttagcompound = tagCompound.getCompoundTag("buy"); - this.itemToBuy = ItemStack.loadItemStackFromNBT(nbttagcompound); - NBTTagCompound nbttagcompound1 = tagCompound.getCompoundTag("sell"); - this.itemToSell = ItemStack.loadItemStackFromNBT(nbttagcompound1); - if (tagCompound.hasKey("buyB", 10)) - { - this.secondItemToBuy = ItemStack.loadItemStackFromNBT(tagCompound.getCompoundTag("buyB")); - } - } - - public NBTTagCompound writeToTags() - { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setTag("buy", this.itemToBuy.writeToNBT(new NBTTagCompound())); - nbttagcompound.setTag("sell", this.itemToSell.writeToNBT(new NBTTagCompound())); - if (this.secondItemToBuy != null) - { - nbttagcompound.setTag("buyB", this.secondItemToBuy.writeToNBT(new NBTTagCompound())); - } - return nbttagcompound; - } -} diff --git a/java/src/game/village/MerchantRecipeList.java b/java/src/game/village/MerchantRecipeList.java deleted file mode 100755 index abc4098..0000000 --- a/java/src/game/village/MerchantRecipeList.java +++ /dev/null @@ -1,132 +0,0 @@ -package game.village; - -import java.util.ArrayList; - -import game.item.ItemStack; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.nbt.NBTUtil; - -public class MerchantRecipeList extends ArrayList -{ - public MerchantRecipeList() - { - } - - public MerchantRecipeList(NBTTagCompound compound) - { - this.readRecipiesFromTags(compound); - } - - /** - * can par1,par2 be used to in crafting recipe par3 - */ - public MerchantRecipe canRecipeBeUsed(ItemStack p_77203_1_, ItemStack p_77203_2_, int p_77203_3_) - { - if (p_77203_3_ > 0 && p_77203_3_ < this.size()) - { - MerchantRecipe merchantrecipe1 = (MerchantRecipe)this.get(p_77203_3_); - return !this.func_181078_a(p_77203_1_, merchantrecipe1.getItemToBuy()) || (p_77203_2_ != null || merchantrecipe1.hasSecondItemToBuy()) && (!merchantrecipe1.hasSecondItemToBuy() || !this.func_181078_a(p_77203_2_, merchantrecipe1.getSecondItemToBuy())) || p_77203_1_.stackSize < merchantrecipe1.getItemToBuy().stackSize || merchantrecipe1.hasSecondItemToBuy() && p_77203_2_.stackSize < merchantrecipe1.getSecondItemToBuy().stackSize ? null : merchantrecipe1; - } - else - { - for (int i = 0; i < this.size(); ++i) - { - MerchantRecipe merchantrecipe = (MerchantRecipe)this.get(i); - - if (this.func_181078_a(p_77203_1_, merchantrecipe.getItemToBuy()) && p_77203_1_.stackSize >= merchantrecipe.getItemToBuy().stackSize && (!merchantrecipe.hasSecondItemToBuy() && p_77203_2_ == null || merchantrecipe.hasSecondItemToBuy() && this.func_181078_a(p_77203_2_, merchantrecipe.getSecondItemToBuy()) && p_77203_2_.stackSize >= merchantrecipe.getSecondItemToBuy().stackSize)) - { - return merchantrecipe; - } - } - - return null; - } - } - - private boolean func_181078_a(ItemStack p_181078_1_, ItemStack p_181078_2_) - { - return ItemStack.areItemsEqual(p_181078_1_, p_181078_2_) && (!p_181078_2_.hasTagCompound() || p_181078_1_.hasTagCompound() && NBTUtil.compareTags(p_181078_2_.getTagCompound(), p_181078_1_.getTagCompound(), false)); - } - -// public void writeToBuf(PacketBuffer buffer) -// { -// buffer.writeByte((byte)(this.size() & 255)); -// -// for (int i = 0; i < this.size(); ++i) -// { -// MerchantRecipe merchantrecipe = (MerchantRecipe)this.get(i); -// buffer.writeItemStackToBuffer(merchantrecipe.getItemToBuy()); -// buffer.writeItemStackToBuffer(merchantrecipe.getItemToSell()); -// ItemStack itemstack = merchantrecipe.getSecondItemToBuy(); -// buffer.writeBoolean(itemstack != null); -// -// if (itemstack != null) -// { -// buffer.writeItemStackToBuffer(itemstack); -// } -// -// buffer.writeBoolean(merchantrecipe.isRecipeDisabled()); -// buffer.writeInt(merchantrecipe.getToolUses()); -// buffer.writeInt(merchantrecipe.getMaxTradeUses()); -// } -// } -// -// public static MerchantRecipeList readFromBuf(PacketBuffer buffer) throws IOException -// { -// MerchantRecipeList merchantrecipelist = new MerchantRecipeList(); -// int i = buffer.readByte() & 255; -// -// for (int j = 0; j < i; ++j) -// { -// ItemStack itemstack = buffer.readItemStackFromBuffer(); -// ItemStack itemstack1 = buffer.readItemStackFromBuffer(); -// ItemStack itemstack2 = null; -// -// if (buffer.readBoolean()) -// { -// itemstack2 = buffer.readItemStackFromBuffer(); -// } -// -// boolean flag = buffer.readBoolean(); -// int k = buffer.readInt(); -// int l = buffer.readInt(); -// MerchantRecipe merchantrecipe = new MerchantRecipe(itemstack, itemstack2, itemstack1, k, l); -// -// if (flag) -// { -// merchantrecipe.compensateToolUses(); -// } -// -// merchantrecipelist.add(merchantrecipe); -// } -// -// return merchantrecipelist; -// } - - public void readRecipiesFromTags(NBTTagCompound compound) - { - NBTTagList nbttaglist = compound.getTagList("Recipes", 10); - - for (int i = 0; i < nbttaglist.tagCount(); ++i) - { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); - this.add(new MerchantRecipe(nbttagcompound)); - } - } - - public NBTTagCompound getRecipiesAsTags() - { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - NBTTagList nbttaglist = new NBTTagList(); - - for (int i = 0; i < this.size(); ++i) - { - MerchantRecipe merchantrecipe = (MerchantRecipe)this.get(i); - nbttaglist.appendTag(merchantrecipe.writeToTags()); - } - - nbttagcompound.setTag("Recipes", nbttaglist); - return nbttagcompound; - } -} diff --git a/java/src/game/window/Input.java b/java/src/game/window/Input.java deleted file mode 100644 index 848f2b6..0000000 --- a/java/src/game/window/Input.java +++ /dev/null @@ -1,8 +0,0 @@ -package game.window; - -import game.properties.IStringSerializable; -import game.util.Displayable; - -public interface Input extends IStringSerializable, Displayable { - public boolean read(); -} diff --git a/java/src/game/window/WindowEvent.java b/java/src/game/window/WindowEvent.java deleted file mode 100644 index d370a06..0000000 --- a/java/src/game/window/WindowEvent.java +++ /dev/null @@ -1,13 +0,0 @@ -package game.window; - -public class WindowEvent { - public final WindowAction action; - public final int param1; - public final int param2; - - public WindowEvent(WindowAction action, int p1, int p2) { - this.action = action; - this.param1 = p1; - this.param2 = p2; - } -} diff --git a/java/src/game/world/ChunkCache.java b/java/src/game/world/ChunkCache.java deleted file mode 100755 index cd79161..0000000 --- a/java/src/game/world/ChunkCache.java +++ /dev/null @@ -1,25 +0,0 @@ -package game.world; - -public class ChunkCache -{ - protected final int chunkX; - protected final int chunkZ; - protected final Chunk[][] chunkArray; - - public ChunkCache(World worldIn, BlockPos posFromIn, BlockPos posToIn, int subIn) - { - this.chunkX = posFromIn.getX() - subIn >> 4; - this.chunkZ = posFromIn.getZ() - subIn >> 4; - int i = posToIn.getX() + subIn >> 4; - int j = posToIn.getZ() + subIn >> 4; - this.chunkArray = new Chunk[i - this.chunkX + 1][j - this.chunkZ + 1]; - - for (int k = this.chunkX; k <= i; ++k) - { - for (int l = this.chunkZ; l <= j; ++l) - { - this.chunkArray[k - this.chunkX][l - this.chunkZ] = worldIn.getChunk(k, l); - } - } - } -} diff --git a/java/src/game/world/EmptyChunk.java b/java/src/game/world/EmptyChunk.java deleted file mode 100755 index 14e327f..0000000 --- a/java/src/game/world/EmptyChunk.java +++ /dev/null @@ -1,99 +0,0 @@ -package game.world; - -import java.util.List; - -import java.util.function.Predicate; - -import game.block.Block; -import game.entity.Entity; -import game.init.Blocks; -import game.tileentity.TileEntity; - -public class EmptyChunk extends Chunk { - public EmptyChunk(WorldClient world) { - super(world, 0, 0); - } - - public int getHeight(int x, int z) { - return 0; - } - - public void genHeights() { - } - - public void genSkyLight() { - } - - public Block getBlock(BlockPos pos) { - return Blocks.air; - } - - public int getOpacity(BlockPos pos) { - return 255; - } - - public int getMeta(BlockPos pos) { - return 0; - } - - public int getLight(LightType type, BlockPos pos) { - return type.defValue; - } - - public void setLight(LightType type, BlockPos pos, int value) { - } - - public int getLightSub(BlockPos pos, int amount) { - return 0; - } - - public void addEntity(Entity entity) { - } - - public void removeEntity(Entity entity) { - } - - public boolean canSeeSky(BlockPos pos) { - return false; - } - - public TileEntity getTileEntity(BlockPos pos, TileEntity.EnumCreateEntityType type) { - return null; - } - - public void addTileEntity(TileEntity tile) { - } - - public void addTileEntity(BlockPos pos, TileEntity tile) { - } - - public void removeTileEntity(BlockPos pos) { - } - - public void onChunkLoad() { - } - - public void onChunkUnload() { - } - - public void setModified() { - } - - public void getEntities(Entity exclude, BoundingBox bb, List list, Predicate pred) { - } - - public void getEntities(Class clazz, BoundingBox bb, List list, Predicate pred) { - } - - public boolean isDirty() { - return false; - } - - public boolean isEmpty() { - return true; - } - - public boolean isEmpty(int bottom, int top) { - return true; - } -} diff --git a/java/src/game/world/Position.java b/java/src/game/world/Position.java deleted file mode 100755 index 3453499..0000000 --- a/java/src/game/world/Position.java +++ /dev/null @@ -1,19 +0,0 @@ -package game.world; - -public class Position { - public final double x; - public final double y; - public final double z; - public final float yaw; - public final float pitch; - public final int dim; - - public Position(double x, double y, double z, float yaw, float pitch, int dim) { - this.x = x; - this.y = y; - this.z = z; - this.yaw = yaw; - this.pitch = pitch; - this.dim = dim; - } -} diff --git a/java/src/game/worldgen/GeneratorDebug.java b/java/src/game/worldgen/GeneratorDebug.java deleted file mode 100755 index 4168d4f..0000000 --- a/java/src/game/worldgen/GeneratorDebug.java +++ /dev/null @@ -1,60 +0,0 @@ -package game.worldgen; - -import java.util.List; - -import game.collect.Lists; - -import game.block.Block; -import game.init.BlockRegistry; -import game.util.ExtMath; -import game.world.State; -import game.world.WorldServer; - -public class GeneratorDebug implements ChunkGenerator -{ - private static final List STATES = Lists.newArrayList(); - private static final int XSTRETCH; - private static final int ZSTRETCH; - - static { - for(Block block : BlockRegistry.REGISTRY) { - STATES.addAll(block.getValidStates()); - } - XSTRETCH = ExtMath.ceilf(ExtMath.sqrtf((float)STATES.size())); - ZSTRETCH = ExtMath.ceilf((float)STATES.size() / (float)XSTRETCH); - } - - public static State getState(int x, int z) { - State state = null; - if(x > 0 && z > 0 && x % 2 != 0 && z % 2 != 0) { - x = x / 2; - z = z / 2; - if(x <= XSTRETCH && z <= ZSTRETCH) { - int idx = ExtMath.absi(x * XSTRETCH + z); - if(idx < STATES.size()) { - state = STATES.get(idx); - } - } - } - return state; - } - - public int getMaximumHeight() { - return 72; - } - - public void generateChunk(WorldServer world, int x, int z, ChunkPrimer primer) - { - for(int bx = 0; bx < 16; ++bx) { - for(int bz = 0; bz < 16; ++bz) { - int sx = x * 16 + bx; - int sz = z * 16 + bz; -// primer.set(bx, 60, bz, Blocks.glass.getDefaultState()); - State state = getState(sx, sz); - if(state != null) { - primer.set(bx, 1, bz, state); - } - } - } - } -} diff --git a/khronos_license.txt b/khronos_license.txt deleted file mode 100644 index d7e6e9d..0000000 --- a/khronos_license.txt +++ /dev/null @@ -1,22 +0,0 @@ -/* -** Copyright (c) 2013-2014 The Khronos Group Inc. -** -** Permission is hereby granted, free of charge, to any person obtaining a -** copy of this software and/or associated documentation files (the -** "Materials"), to deal in the Materials without restriction, including -** without limitation the rights to use, copy, modify, merge, publish, -** distribute, sublicense, and/or sell copies of the Materials, and to -** permit persons to whom the Materials are furnished to do so, subject to -** the following conditions: -** -** The above copyright notice and this permission notice shall be included -** in all copies or substantial portions of the Materials. -** -** THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -** EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -** MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -** IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -** CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -** TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -** MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS. -*/ \ No newline at end of file diff --git a/libffi_license.txt b/libffi_license.txt deleted file mode 100644 index 7b64447..0000000 --- a/libffi_license.txt +++ /dev/null @@ -1,21 +0,0 @@ -libffi - Copyright (c) 1996-2020 Anthony Green, Red Hat, Inc and others. -See source files for details. - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -``Software''), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED ``AS IS'', WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/liburing_license.txt b/liburing_license.txt deleted file mode 100644 index 67bc330..0000000 --- a/liburing_license.txt +++ /dev/null @@ -1,7 +0,0 @@ -Copyright 2020 Jens Axboe - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/lwjgl_license.txt b/lwjgl_license.txt deleted file mode 100644 index a17ad0a..0000000 --- a/lwjgl_license.txt +++ /dev/null @@ -1,29 +0,0 @@ -Copyright (c) 2012-present Lightweight Java Game Library -All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - -- Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - -- Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - -- Neither the name Lightweight Java Game Library nor the names of - its contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED -TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR -PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, -EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR -PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. \ No newline at end of file diff --git a/server/build.gradle.kts b/server/build.gradle.kts new file mode 100644 index 0000000..86f419c --- /dev/null +++ b/server/build.gradle.kts @@ -0,0 +1,28 @@ + +plugins { + application + id("com.gradleup.shadow") version "8.3.6" +} + +dependencies { + implementation(project(":common")) +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(21) + } +} + +application { + mainClass = "server.Server" + tasks.run.get().workingDir = rootProject.file("dev/server") + tasks.run.get().workingDir.mkdirs() + tasks.run.get().systemProperties.put("runtime.devmode", "") + tasks.run.get().standardInput = System.`in` +} + +tasks.shadowJar { + destinationDirectory = rootProject.file("dev") + archiveFileName = "tcr_server.jar" +} diff --git a/java/src/game/Server.java b/server/src/main/java/server/Server.java similarity index 51% rename from java/src/game/Server.java rename to server/src/main/java/server/Server.java index 4c0c661..2145dda 100755 --- a/java/src/game/Server.java +++ b/server/src/main/java/server/Server.java @@ -1,16 +1,25 @@ -package game; +package server; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; import java.net.InetAddress; +import java.security.KeyPair; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.text.SimpleDateFormat; import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Collection; import java.util.Collections; +import java.util.Date; import java.util.Iterator; import java.util.List; +import java.util.Locale; import java.util.Map; import java.util.Queue; import java.util.concurrent.Callable; @@ -18,91 +27,99 @@ import java.util.concurrent.ExecutionException; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; -import game.collect.Lists; -import game.collect.Maps; -import game.future.Futures; -import game.future.ListenableFuture; -import game.future.ListenableFutureTask; -import game.future.ThreadFactoryBuilder; +import common.Version; +import common.collect.Lists; +import common.collect.Maps; +import common.color.TextColor; +import common.dimension.Dimension; +import common.dimension.Space; +import common.entity.Entity; +import common.entity.npc.EntityHuman; +import common.entity.npc.EntityNPC; +import common.future.Futures; +import common.future.ListenableFuture; +import common.future.ListenableFutureTask; +import common.future.ThreadFactoryBuilder; +import common.init.EntityRegistry; +import common.init.Registry; +import common.init.UniverseRegistry; +import common.log.Log; +import common.net.bootstrap.ServerBootstrap; +import common.net.channel.Channel; +import common.net.channel.ChannelException; +import common.net.channel.ChannelFuture; +import common.net.channel.ChannelFutureListener; +import common.net.channel.ChannelHandler; +import common.net.channel.ChannelInitializer; +import common.net.channel.ChannelOption; +import common.net.channel.nio.NioEventLoopGroup; +import common.net.channel.socket.nio.NioServerSocketChannel; +import common.net.handler.timeout.ReadTimeoutHandler; +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; +import common.network.IPlayer; +import common.network.IThreadListener; +import common.network.NetConnection; +import common.network.Packet; +import common.network.PacketDecoder; +import common.network.PacketEncoder; +import common.network.PacketPrepender; +import common.network.PacketSplitter; +import common.network.NetHandler.ThreadQuickExitException; +import common.packet.RPacketEnableCompression; +import common.packet.RPacketLoginSuccess; +import common.packet.SPacketEntityEffect; +import common.packet.SPacketChangeGameState; +import common.packet.SPacketPlayerListItem; +import common.packet.SPacketPlayerAbilities; +import common.packet.SPacketDisconnect; +import common.packet.SPacketHeldItemChange; +import common.packet.SPacketJoinGame; +import common.packet.SPacketRespawn; +import common.packet.SPacketSetExperience; +import common.packet.SPacketSkin; +import common.packet.SPacketTimeUpdate; +import common.packet.SPacketWorld; +import common.potion.PotionEffect; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.EncryptUtil; +import common.util.ExtMath; +import common.util.LazyLoader; +import common.util.PortalType; +import common.util.Position; +import common.util.Util; +import common.util.Var; +import common.util.WorldPos; +import common.vars.Vars; +import common.world.World; +import server.biome.GenBiome; +import server.clipboard.ReorderRegistry; +import server.clipboard.RotationRegistry; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.network.HandshakeHandler; +import server.network.Player; +import server.network.User; +import server.vars.SVar; +import server.vars.SVars; +import server.world.Converter; +import server.world.Region; +import server.world.WorldServer; -import game.color.TextColor; -import game.command.CommandEnvironment; -import game.command.FixedExecutor; -import game.dimension.Dimension; -import game.dimension.Space; -import game.entity.Entity; -import game.entity.npc.EntityHuman; -import game.entity.npc.EntityNPC; -import game.init.Config; -import game.init.EntityRegistry; -import game.init.Registry; -import game.init.UniverseRegistry; -import game.log.Log; -import game.nbt.NBTLoader; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.network.IThreadListener; -import game.network.LazyLoadBase; -import game.network.NetConnection; -import game.network.NetHandler.ThreadQuickExitException; -import game.network.HandshakeHandler; -import game.network.Player; -import game.network.Packet; -import game.network.PacketDecoder; -import game.network.PacketEncoder; -import game.network.PacketPrepender; -import game.network.PacketSplitter; -import game.packet.RPacketEnableCompression; -import game.packet.RPacketLoginSuccess; -import game.packet.S1DPacketEntityEffect; -import game.packet.S2BPacketChangeGameState; -import game.packet.S38PacketPlayerListItem; -import game.packet.S39PacketPlayerAbilities; -import game.packet.SPacketDisconnect; -import game.packet.SPacketHeldItemChange; -import game.packet.SPacketJoinGame; -import game.packet.SPacketRespawn; -import game.packet.SPacketSetExperience; -import game.packet.SPacketSkin; -import game.packet.SPacketTimeUpdate; -import game.packet.SPacketWorld; -import game.potion.PotionEffect; -import game.util.ExtMath; -import game.util.Tuple; -import game.util.Util; -import game.world.BlockPos; -import game.world.PortalType; -import game.world.Position; -import game.world.Region; -import game.world.Region.FolderInfo; -import game.world.World; -import game.world.WorldPos; -import game.world.WorldServer; -import io.netty.bootstrap.ServerBootstrap; -import io.netty.channel.Channel; -import io.netty.channel.ChannelException; -import io.netty.channel.ChannelFuture; -import io.netty.channel.ChannelFutureListener; -import io.netty.channel.ChannelHandler; -import io.netty.channel.ChannelInitializer; -import io.netty.channel.ChannelOption; -import io.netty.channel.nio.NioEventLoopGroup; -import io.netty.channel.socket.nio.NioServerSocketChannel; -import io.netty.handler.timeout.ReadTimeoutHandler; -import io.netty.util.concurrent.Future; -import io.netty.util.concurrent.GenericFutureListener; - -public final class Server implements IThreadListener { - private static final LazyLoadBase SERVER_NIO_EVENTLOOP = new LazyLoadBase() { +public final class Server implements IThreadListener, Executor { + private static final LazyLoader SERVER_NIO_EVENTLOOP = new LazyLoader() { protected NioEventLoopGroup load() { return new NioEventLoopGroup(0, (new ThreadFactoryBuilder()).setNameFormat("Netty Server IO #%d").setDaemon(true).build()); } }; private final Thread serverThread = Thread.currentThread(); + private final Map variables = Maps.newTreeMap(); private final List clients = Collections.synchronizedList(Lists.newArrayList()); private final List players = Lists.newArrayList(); - private final Map usermap = Maps.newHashMap(); + private final Map online = Maps.newHashMap(); + private final Map users = Maps.newTreeMap(); private final Queue> queue = new ArrayDeque>(); private final long[] tickTimes = new long[100]; private final Map dimensions = Maps.newTreeMap(); @@ -111,15 +128,16 @@ public final class Server implements IThreadListener { private final List unload = Lists.newArrayList(); private final Map warps = Maps.newTreeMap(); private final CommandEnvironment scriptEnv = new CommandEnvironment(this); - private final boolean debug; - private final boolean ipcpipe; + private KeyPair keyPair; private WorldServer space; private ChannelFuture endpoint; - + private Position execPos; + private boolean running = true; private boolean stopped; private boolean started; + private String endMessage = "Server beendet"; private long currentTime = System.nanoTime() / 1000L; private long tpsTarget; @@ -138,105 +156,238 @@ public final class Server implements IThreadListener { private int perfTimer; public static void main(String[] args) { - Util.checkOs(); - Registry.setup("Server thread"); - boolean debug = System.getProperty("server.debug", null) != null; - boolean ipc = debug || System.getProperty("server.pipe", null) != null; - int port = Integer.parseInt(System.getProperty("server.port", "" + Config.PORT)); - final Server server = new Server(debug, ipc); - Registry.addShutdownHook(new Runnable() { + long time = System.currentTimeMillis(); + Util.checkPlatform(); + Thread.currentThread().setName("Server thread"); + Locale.setDefault(Locale.ROOT); + Util.setupHandlers(); + Log.init(); + Log.SYSTEM.info("Java " + System.getProperty("java.version")); + Log.SYSTEM.info("Starte " + Version.NAME + " Server " + Util.VERSION + " (Protokoll #" + Util.PROTOCOL + ")"); + if(Util.DEVMODE) + Log.SYSTEM.warn("Entwicklungsmodus aktiv - Debugging-Features sind verfügbar"); + Registry.register(); + GenBiome.setAsProvider(); + UniverseRegistry.register(); + RotationRegistry.register(); + ReorderRegistry.register(); + final Server server = new Server(); + Util.addShutdownHook(new Runnable() { public void run() { server.stopServer(); + Log.flushLog(); } }); - server.run(port); + Log.setSync(server); + server.run(time); Region.killIO(); Log.flushLog(); } - private Server(boolean debug, boolean ipc) { - this.debug = debug; - this.ipcpipe = ipc; + private void saveServerConfig(long time) { + TagObject data = new TagObject(); + data.setLong("Time", time); + data.setLong("LastAccess", System.currentTimeMillis()); + data.setString("Version", Util.VERSION); + TagObject cfg = new TagObject(); + for(String cvar : this.variables.keySet()) { + SVar value = this.variables.get(cvar); + if(!value.noDef || !value.def.equals(value.get())) + cfg.setString(cvar, value.get()); + } + data.setObject("Config", cfg); + data.setObject("Universe", UniverseRegistry.toTags()); + if(this.keyPair != null) { + data.setByteArray("PrivateKey", this.keyPair.getPrivate().getEncoded()); + data.setByteArray("PublicKey", this.keyPair.getPublic().getEncoded()); + } + File nfile = new File("server.cdt.tmp"); + File lfile = new File("server.cdt"); + try { + TagObject.writeGZip(data, nfile); + if(lfile.exists()) + lfile.delete(); + nfile.renameTo(lfile); + } + catch(Exception e) { + Log.IO.error(e, "Fehler beim Schreiben von " + nfile); + } + } + + private long loadServerConfig() { + File file = new File("server.cdt"); + if(!file.exists()) + file = new File("server.cdt.tmp"); + if(file.exists()) { + try { + TagObject tag = TagObject.readGZip(file); + TagObject cfg = tag.getObject("Config"); + for(String key : cfg.keySet()) { + SVar svar = this.variables.get(key); + if(svar != null) + svar.set(cfg.getString(key), false, false); + } + UniverseRegistry.fromTags(tag.getObject("Universe")); + long lastPlayed = tag.getLong("LastAccess"); + String version = tag.hasString("Version") ? tag.getString("Version") : null; + version = version != null && version.isEmpty() ? "" : version; + long time = tag.hasLong("Time") ? tag.getLong("Time") : World.START_TIME; + Log.IO.info("Config-Version: %s", version); + Log.IO.info("Weltzeit: %d Ticks / %d Sekunden", time, time / 20L); + Log.IO.info("Zuletzt geladen: %s", new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(new Date(lastPlayed))); + if(System.getProperty("server.regenkey") == null && tag.hasByteArray("PrivateKey") && tag.hasByteArray("PublicKey")) { + PrivateKey key = EncryptUtil.decodePrivateKey(tag.getByteArray("PrivateKey")); + PublicKey pubkey = EncryptUtil.decodePublicKey(tag.getByteArray("PublicKey")); + if(key != null && pubkey != null) + this.keyPair = new KeyPair(pubkey, key); + } + return time; + } + catch(Exception e) { + Log.IO.error(e, "Fehler beim Lesen von " + file); + for(SVar svar : this.variables.values()) { + svar.set(svar.def, svar.noDef, false); + } + UniverseRegistry.clear(); + } + } + Log.IO.info("Erstelle neue Welt und Konfiguration"); + return World.START_TIME; + } + + private void setCallback(Runnable callback, String ... vars) { + for(String key : vars) { + this.variables.get(key).setCallback(callback); + } + } + + public Map getVariables() { + return this.variables; + } + + private Server() { + for(Class clazz : new Class[] {Vars.class, SVars.class}) { + for(Field field : clazz.getDeclaredFields()) { + if(field.isAnnotationPresent(Var.class)) { + if(!Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) + throw new IllegalArgumentException("Feld für Variable " + field + " muss statisch und änderbar sein!"); + Var value = field.getAnnotation(Var.class); + if(value.name().isEmpty()) + throw new IllegalArgumentException("Variablenname von " + field + " kann nicht leer sein!"); + if(this.variables.containsKey(value.name())) + throw new IllegalArgumentException("Variable " + value.name() + " existiert bereits!"); + this.variables.put(value.name(), new SVar(field, value)); + } + } + } + this.setCallback(new Runnable() { + public void run() { + for(WorldServer world : Server.this.getWorlds()) { + world.updatePhysics(); + } + Server.this.sendPacket(new SPacketWorld(WorldServer.clampGravity(), SVars.dayCycle, SVars.timeFlow)); + } + }, "daylightCycle", "timeFlow", "gravity"); + this.setCallback(new Runnable() { + public void run() { + for(WorldServer world : Server.this.getWorlds()) { + world.updateViewRadius(); + } + } + }, "viewDistance"); + this.setCallback(new Runnable() { + public void run() { + Server.this.bind(SVars.port); + } + }, "port"); + this.setCallback(new Runnable() { + public void run() { + if((!SVars.password.isEmpty() && SVars.password.length() < 8) || SVars.password.length() > IPlayer.MAX_PASS_LENGTH) + Log.IO.warn("Passwort muss aus 8-" + IPlayer.MAX_PASS_LENGTH + " Zeichen bestehen, Login wird nicht möglich sein"); + } + }, "password"); } public CommandEnvironment getScriptEnvironment() { return this.scriptEnv; } - public String[] getUsers() { - String[] list = this.debug ? null : new File("players").list(); - if(list == null) { - list = new String[0]; - } + public List getPlayerFilenames() { + String[] list = new File("players").list(); + if(list == null) + return Lists.newArrayList(); + List names = Lists.newArrayList(); for(int i = 0; i < list.length; ++i) { - if(list[i].endsWith(".nbt")) { - list[i] = list[i].substring(0, list[i].length() - 4); -// Player player = this.getPlayer(list[i]); -// if(player != null) -// list[i] = player.getUser(); + if(list[i].endsWith(".cdt")) { + String name = list[i].substring(0, list[i].length() - 4); + if(IPlayer.isValidUser(name)) + names.add(name); } } - return list; + return names; } public void saveWorldInfo() { - if(!this.debug) { - Region.saveWorldInfo(null, this.space.getDayTime()); - WorldServer.saveWarps(this.warps); + this.saveServerConfig(this.space.getDayTime()); + WorldServer.saveWarps(this.warps); + } + + public TagObject loadPlayerData(String user) { + if(!IPlayer.isValidUser(user)) + return null; + TagObject tag = null; + try { + File dat = new File(new File("players"), user + ".cdt"); + + if(dat.exists() && dat.isFile()) { + tag = TagObject.readGZip(dat); + } + } + catch(Exception e) { + Log.IO.error(e, "Konnte Spielerdaten für " + user + " (offline) nicht laden"); + } + return tag; + } + + public void writePlayerData(String user, TagObject tag) { + if(!IPlayer.isValidUser(user)) + return; + try { + File tmp = new File(new File("players"), user + ".cdt.tmp"); + File dat = new File(new File("players"), user + ".cdt"); + TagObject.writeGZip(tag, tmp); + if(dat.exists()) { + dat.delete(); + } + tmp.renameTo(dat); + } + catch(Exception e) { + Log.IO.error(e, "Konnte Spielerdaten für " + user + " (offline) nicht speichern"); } } public Position getOfflinePosition(String user) { - if(this.debug || !Player.isValidUser(user)) - return null; - NBTTagCompound tag = null; - try { - File dat = new File(new File("players"), user + ".nbt"); - - if(dat.exists() && dat.isFile()) { - tag = NBTLoader.readGZip(dat); - } - } - catch(Exception e) { - Log.JNI.error(e, "Konnte Spielerdaten für " + user + " (offline) nicht laden"); - } + TagObject tag = this.loadPlayerData(user); if(tag == null) return null; - NBTTagList pos = tag.getTagList("Pos", 6); - NBTTagList rot = tag.getTagList("Rotation", 5); - double posX = pos.getDoubleAt(0); - double posY = pos.getDoubleAt(1); - double posZ = pos.getDoubleAt(2); - float rotYaw = rot.getFloatAt(0); - float rotPitch = rot.getFloatAt(1); - int dimension = tag.getInteger("Dimension"); + double posX = tag.getDouble("PosX"); + double posY = tag.getDouble("PosY"); + double posZ = tag.getDouble("PosZ"); + float rotYaw = tag.getFloat("Yaw"); + float rotPitch = tag.getFloat("Pitch"); + int dimension = tag.getInt("Dimension"); return new Position(posX, posY, posZ, rotYaw, rotPitch, dimension); } - private void saveAllWorlds(boolean message) { - if(this.debug) - return; - if(message) { - this.startProgress(true, this.worlds.size()); - } - int done = 0; + public void saveAllWorlds(boolean message) { + if(message) + Log.TICK.info("Speichere Welt"); this.saveWorldInfo(); for(WorldServer world : this.worlds) { - if(message) { - this.setProgress(done); - } - ++done; world.saveAllChunks(); } - this.setProgress(-1); } - private void startProgress(boolean save, int amount) { - this.setTotal(amount); - this.setProgress(0); - Log.JNI.info((save ? "Speichere" : "Generiere und lade") + " Welt"); - } - public void unloadWorld(WorldServer world) { if(world != this.space) this.unloadWorld(world.dimension); @@ -252,65 +403,30 @@ public final class Server implements IThreadListener { } } - public void run(int port) { - long time = System.currentTimeMillis(); - Log.JNI.info("Starte Server Version " + Config.VERSION); - if(!this.debug) { - this.setMessage("Welt wird erstellt und geladen"); - FolderInfo info = Region.loadWorldInfo(null); -// if(dtime == -1L) // { -// dtime = World.START_TIME; -//// Config.set("spawnDim", "1", null); -//// } - this.worlds.add(this.space = new WorldServer(this, info == null ? World.START_TIME : info.time, - Space.INSTANCE, false)); - this.dimensions.put(this.space.dimension.getDimensionId(), this.space); - new File("players").mkdirs(); -// if(Config.spawnY < 0) { -// WorldServer world = this.getWorld(Config.spawnDim); -// world = world == null ? this.space : world; -// Random rand = new Random(world.getSeed()); -// int x = 0; -// int z = 0; -// int count = 0; -// while(!(world.getGroundAboveSeaLevel(new BlockPos(x, 0, z)) == Blocks.grass)) { -// if(count == 1000) { -// SKC.warn("Konnte keine Spawn-Position finden"); -// break; -// } -// x += rand.zrange(64) - rand.zrange(64); -// z += rand.zrange(64) - rand.zrange(64); -// ++count; -// } -// Config.set("spawnX", "" + x, null); -// Config.set("spawnY", "" + world.getSeaLevel(), null); -// Config.set("spawnZ", "" + z, null); -// Config.set("spawnYaw", "" + (-180.0f + rand.floatv() * 360.0f), null); -// Config.set("spawnPitch", "0.0", null); -// } - } - else { - Config.clear(); - UniverseRegistry.clear(); - Config.set("daylightCycle", "false", null); - Config.set("weatherChanges", "false", null); - Config.set("mobSpawning", "false", null); - Config.set("spawnRadius", "0", null); - this.worlds.add(this.space = new WorldServer(this, World.START_TIME, - Space.INSTANCE, true)); - this.dimensions.put(this.space.dimension.getDimensionId(), this.space); + public void run(long time) { + Converter.convert(this); + long wtime = this.loadServerConfig(); + if(this.keyPair == null) { + Log.SYSTEM.info("Generiere neues Schlüsselpaar"); + this.keyPair = EncryptUtil.createKeypair(); } + User.loadDatabase(this.users); + this.worlds.add(this.space = new WorldServer(this, wtime, Space.INSTANCE)); + this.dimensions.put(this.space.dimension.getDimensionId(), this.space); + new File("players").mkdirs(); this.setTpsTarget(20.0f); - if(!this.debug) { - for(Dimension dim : UniverseRegistry.getDimensions()) { - if(WorldServer.needsLoading(dim)) { - this.getWorld(dim.getDimensionId()).loadForcedChunks(); - } - WorldServer.loadWarps(dim, this.warps); + for(Dimension dim : UniverseRegistry.getDimensions()) { + if(WorldServer.needsLoading(dim)) { + this.getWorld(dim.getDimensionId()).loadForcedChunks(); } + WorldServer.loadWarps(dim, this.warps); } - if(port >= 0) - this.bind(port); + if(SVars.port >= 0) + this.bind(SVars.port); + else + Log.SYSTEM.warn("Kein Port definiert, verwende 'sv port <1024-32767>' um einen Hosting-Port festzulegen"); + if(SVars.accessRequired && SVars.password.length() < 8) + Log.SYSTEM.warn("Kein Passwort definiert, verwende 'sv password <8-" + IPlayer.MAX_PASS_LENGTH + " Zeichen>' um ein Zugangspasswort festzulegen"); Thread con = new Thread(new Runnable() { private final BufferedReader reader = new BufferedReader(new InputStreamReader(new BufferedInputStream(System.in))); @@ -325,17 +441,10 @@ public final class Server implements IThreadListener { } if(line == null) break; - if(line.startsWith("#")) { - line = line.substring(1); - Tuple data = Util.getKeyValue(line); - if(data.first.equals("end")) - Server.this.shutdown(); - continue; - } final String cmd = line; Server.this.schedule(new Runnable() { public void run() { - Server.this.scriptEnv.execute(cmd, new FixedExecutor(Server.this, "#con", "KONSOLE", null)); + Server.this.scriptEnv.execute(cmd, Server.this); } }); } @@ -343,18 +452,18 @@ public final class Server implements IThreadListener { }, "Server console handler"); con.setDaemon(true); con.start(); - Log.JNI.info("Server gestartet in " + String.format("%.1f", (double)(System.currentTimeMillis() - time) / 1000.0) + " Sekunden"); + Log.SYSTEM.info("Server gestartet in " + String.format("%.1f", (double)(System.currentTimeMillis() - time) / 1000.0) + " Sekunden"); while(this.running) { this.currentTime = System.nanoTime() / 1000L; this.timePassed = this.currentTime - this.lastSchedule; this.lastSchedule = this.currentTime; if(this.timePassed < 0L) { - Log.JNI.warn("Zeit lief rückwärts! Hat sich die Systemzeit geändert?"); + Log.TICK.warn("Zeit lief rückwärts! Hat sich die Systemzeit geändert?"); this.timePassed = 0L; this.ticksTodo = 0L; } if(this.timePassed > 2000000L && this.currentTime - this.lastWarning >= 15000000L) { - Log.JNI.warn("Kann Server-Tick nicht aufrecht erhalten! Hat sich die Systemzeit geändert, oder ist der Server überlastet? " + + Log.TICK.warn("Kann Server-Tick nicht aufrecht erhalten! Hat sich die Systemzeit geändert, oder ist der Server überlastet? " + "Liege " + (this.timePassed / 1000L) + " ms zurück, überspringe " + ((this.timePassed * this.tpsTarget) / 1000000000L) + " Tick(s)"); this.timePassed = 0L; this.lastWarning = this.currentTime; @@ -371,104 +480,43 @@ public final class Server implements IThreadListener { this.lastPoll = this.currentTime; this.ticksDone = 0L; } - if(!this.started) { - this.started = true; - this.sendPipeIPC("running", true); - } + this.started = true; } try { this.stopServer(); this.stopped = true; - this.sendPipeIPC("running", false); } catch(Throwable e) { - Log.JNI.error(e, "Fehler beim Beenden des Servers"); + Log.SYSTEM.error(e, "Fehler beim Beenden des Servers"); } finally { this.stopped = true; - this.sendPipeIPC("running", false); - Log.JNI.info("Server wurde beendet"); + Log.SYSTEM.info("Server wurde beendet"); } } - public void preload(WorldServer world, int bx, int bz, Player callback) { + public void preload(WorldServer world, int bx, int bz) { int done = 0; - int total = Config.distance * 2 + 1; + int total = SVars.distance * 2 + 1; total *= total; - if(callback != null) { - callback.displayLoading("Lade Welt ..."); - callback.sendTask("Landschaft wird generiert", total); - } - else { - this.setMessage("Landschaft wird generiert"); - this.startProgress(false, total); - } -// WorldServer world = this.getWorld(Config.spawnDim); -// world = world == null ? this.space : world; + Log.TICK.info("Generiere und lade Welt"); bx = bx >> 4; bz = bz >> 4; long last = System.currentTimeMillis(); - for(int x = -Config.distance; x <= Config.distance; x++) { - for(int z = -Config.distance; z <= Config.distance; z++) { + for(int x = -SVars.distance; x <= SVars.distance; x++) { + for(int z = -SVars.distance; z <= SVars.distance; z++) { long time = System.currentTimeMillis(); - if(time - last >= 10L) { - if(callback != null) { - callback.sendProgress(done); - } - else { - this.setProgress(done); - if(time - last > 1000L) { - Log.JNI.info("Bereite Spawnbereich vor" + ": " + (done * 100 / total) + "%"); - last = time; - } - } + if(time - last > 1000L) { + Log.TICK.info("Bereite Spawnbereich vor" + ": " + (done * 100 / total) + "%"); + last = time; } ++done; world.loadChunk(bx + x, bz + z); } } - if(callback != null) - callback.sendProgress(-1); - else - this.setProgress(-1); } - -// public void resetProgress() { -// this.setProgress(-1); -// } -// -// public void setDone() { -// this.setProgress(-2); -// } private void tick() { -// boolean pause = this.paused; -// this.paused = this.pause; -// if(!pause && this.paused) { -// if(!this.debug) -// Log.info("Speichere und pausiere Spiel..."); -// this.saveAllPlayerData(true); -// this.saveAllWorlds(true); -// } -// if(this.paused) { -// synchronized(this.queue) { -// while(!this.queue.isEmpty()) { -// FutureTask task = this.queue.poll(); -// try { -// task.run(); -// task.get(); -// } -// catch(ExecutionException e1) { -// if(!(e1.getCause() instanceof ThreadQuickExitException)) -// Log.error("Fehler beim Ausführen von Pause-Task " + task, e1); -// } -// catch(InterruptedException e2) { -// Log.error("Fehler beim Ausführen von Pause-Task " + task, e2); -// } -// } -// } -// return; -// } long now = System.currentTimeMillis(); synchronized(this.queue) { while(!this.queue.isEmpty()) { @@ -479,10 +527,10 @@ public final class Server implements IThreadListener { } catch(ExecutionException e1) { if(!(e1.getCause() instanceof ThreadQuickExitException)) - Log.JNI.error(e1, "Fehler beim Ausführen von Server-Task " + task); // throw new RuntimeException(e1); + Log.SYSTEM.error(e1, "Fehler beim Ausführen von Server-Task " + task); // throw new RuntimeException(e1); } catch(InterruptedException e2) { - Log.JNI.error(e2, "Fehler beim Ausführen von Server-Task " + task); + Log.SYSTEM.error(e2, "Fehler beim Ausführen von Server-Task " + task); } } } @@ -504,19 +552,19 @@ public final class Server implements IThreadListener { } this.networkTick(); if(++this.pingTimer > 600) { - this.sendPacket(new S38PacketPlayerListItem(this.players)); + this.sendPacket(new SPacketPlayerListItem((List)this.getPlayers())); this.pingTimer = 0; } - if(Config.saveInterval > 0 && ++this.saveTimer >= Config.saveInterval) { + if(SVars.saveInterval > 0 && ++this.saveTimer >= SVars.saveInterval) { this.saveAllPlayerData(false); this.saveAllWorlds(false); this.saveTimer = 0; } + Log.flushLog(); this.tickTimes[this.perfTimer++] = System.currentTimeMillis() - now; if(this.perfTimer == 100) { this.perfTimer = 0; } - this.sendPipeIPC("tick", this.getLastTick()); } public WorldServer getSpace() { @@ -529,8 +577,7 @@ public final class Server implements IThreadListener { Dimension dim = UniverseRegistry.getDimension(dimension); if(dim == null) return null; - world = new WorldServer(this, this.space.getDayTime(), - dim, this.debug); + world = new WorldServer(this, this.space.getDayTime(), dim); this.worlds.add(world); this.dimensions.put(dimension, world); } @@ -550,6 +597,10 @@ public final class Server implements IThreadListener { return this.worlds; } + public void resetSaveTimer() { + this.saveTimer = 0; + } + public long[] getTickTimes() { return this.tickTimes; } @@ -580,7 +631,7 @@ public final class Server implements IThreadListener { this.timePassed = this.ticksTodo = this.ticksDone = 0L; } - public List getAllUsernames() { + public List getAllPlayerNames() { List list = new ArrayList(this.players.size()); for(int z = 0; z < this.players.size(); z++) { list.add(this.players.get(z).getUser()); @@ -588,32 +639,24 @@ public final class Server implements IThreadListener { return list; } + public List getAllUserNames() { + return Lists.newArrayList(this.users.keySet()); + } + public List getPlayers() { return this.players; } + public Collection getUsers() { + return this.users.values(); + } + public Player getPlayer(String user) { - return this.usermap.get(user); + return this.online.get(user); } - - private void setMessage(String message) { - this.sendPipeIPC("message", message); - } - - private void setProgress(int progress) { - this.sendPipeIPC("progress", progress); - } - - private void setTotal(int total) { - this.sendPipeIPC("total", total); - } - - public void setVar(String cv, String value) { - this.schedule(new Runnable() { - public void run() { - Config.set(cv, value, Server.this); - } - }); + + public User getUser(String user) { + return this.users.get(user); } private ListenableFuture callFromMainThread(Callable callable) { @@ -629,6 +672,7 @@ public final class Server implements IThreadListener { return Futures.immediateFuture(callable.call()); } catch(Exception exception) { + Log.SYSTEM.error(exception, "Fehler beim sofortigen Ausführen von Server-Task " + callable); return Futures.immediateFailedFuture(exception); } } @@ -642,27 +686,11 @@ public final class Server implements IThreadListener { return Thread.currentThread() == this.serverThread; } -// private void movePlayerToSpawn(EntityNPC player) { -// BlockPos pos = new BlockPos(Config.spawnX, Config.spawnY, Config.spawnZ); -// int radius = Config.spawnRadius; -// if(radius > 0) { -// pos = ((WorldServer)player.worldObj).getTopSolidOrLiquidBlock(pos.add( -// ExtMath.clampi(player.worldObj.rand.excl(-radius, radius), -World.MAX_SIZE + 1, World.MAX_SIZE - 1), 0, -// ExtMath.clampi(player.worldObj.rand.excl(-radius, radius), -World.MAX_SIZE + 1, World.MAX_SIZE - 1))); -// } -// player.moveToBlockPosAndAngles(pos, radius > 0 ? (-180.0f + player.worldObj.rand.floatv() * 360.0f) : Config.spawnYaw, -// radius > 0 ? 0.0f : Config.spawnPitch); -// while(radius >= 0 && !player.worldObj.getCollidingBoundingBoxes(player, player.getEntityBoundingBox()).isEmpty() -// && player.posY < 511.0D) { -// player.setPosition(player.posX, player.posY + 1.0D, player.posZ); -// } -// } - public Position getRandomSpawnPosition(WorldPos origin) { WorldServer world = this.getWorld(origin.getDimension()); world = world == null ? this.space : world; BlockPos pos = origin; - int radius = Config.spawnRadius; + int radius = SVars.spawnRadius; if(radius > 0) { pos = world.getTopSolidOrLiquidBlock(pos.add( ExtMath.clampi(world.rand.excl(-radius, radius), -World.MAX_SIZE + 1, World.MAX_SIZE - 1), 0, @@ -671,107 +699,90 @@ public final class Server implements IThreadListener { int y = pos.getY(); while(world.getState(new BlockPos(pos.getX(), y, pos.getZ())).getBlock().getMaterial().blocksMovement() && y < 511) y++; - return new Position(pos.getX() + 0.5d, (double)y, pos.getZ() + 0.5d, - radius > 0 ? (-180.0f + world.rand.floatv() * 360.0f) : Config.spawnYaw, - radius > 0 ? 0.0f : Config.spawnPitch, world.dimension.getDimensionId()); + return new Position(pos.getX() + 0.5, (double)y, pos.getZ() + 0.5, -180.0f + world.rand.floatv() * 360.0f, 0.0f, world.dimension.getDimensionId()); + } + + public void addUser(User user) { + this.users.put(user.getUser(), user); } - public String addPlayer(NetConnection connection, String loginUser, String loginPass) { - NBTTagCompound tag = this.readPlayer(loginUser); + public void addPlayer(NetConnection connection, String loginUser) { + TagObject tag = this.readPlayer(loginUser); Player conn = new Player(this, connection, loginUser); if(tag != null) - conn.readFromNBT(tag); - if(Config.playerLimit > 0 && this.players.size() >= Config.playerLimit && !conn.isAdmin()) - return String.format("Der Server ist voll (%d/%d)!", this.players.size(), Config.playerLimit); - if(/* !connection.isLocalChannel() && */ Config.auth) { - if(conn.getPassword() == null) { - if(!Config.register) - return "Anmeldung neuer Accounts ist auf diesem Server deaktiviert (Whitelisted)"; - if(loginPass.length() == 0) - return "Ein neues Passwort ist erforderlich um diesen Server zu betreten (mindestens 8 Zeichen)"; - if(loginPass.length() < 8) - return "Passwort ist zu kurz, mindestens 8 Zeichen"; - conn.setPassword(loginPass); - Log.JNI.info(loginUser + " registrierte sich mit Passwort"); - } - else if(!conn.getPassword().equals(loginPass)) { - return "Falsches Passwort"; - } - else { - Log.JNI.info(loginUser + " loggte sich mit Passwort ein"); - } - } - if(Config.compression >= 0) { - connection.sendPacket(new RPacketEnableCompression(Config.compression), new ChannelFutureListener() { + conn.readTags(tag); + if(SVars.compression >= 0) { + connection.sendPacket(new RPacketEnableCompression(SVars.compression), new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { - connection.setCompressionTreshold(Config.compression); + connection.setCompressionTreshold(SVars.compression); } }); } connection.sendPacket(new RPacketLoginSuccess()); connection.setNetHandler(conn); this.players.add(conn); - this.usermap.put(loginUser, conn); + User user = this.users.remove(loginUser); + if(user != null) + conn.copyFrom(user); + this.users.put(loginUser, conn); + this.online.put(loginUser, conn); tag = conn.readCharacter(); - WorldServer world = tag == null ? this.space : this.getWorld(tag.getInteger("Dimension")); + WorldServer world = tag == null ? this.space : this.getWorld(tag.getInt("Dimension")); world = world == null ? this.space : world; EntityNPC player = conn.createPlayer(world, tag == null ? EntityRegistry.getEntityString(EntityHuman.class) : tag.getString("id")); if(tag != null) - player.readFromNBT(tag); + player.readTags(tag); else player.onInitialSpawn(null); -// player.setWorld(world); if(tag == null) - /* this.movePlayerToSpawn(player); */ player.moveToBlockPosAndAngles(new BlockPos(0, 16384, 0), 0.0f, 0.0f); + player.moveToBlockPosAndAngles(new BlockPos(0, 16384, 0), 0.0f, 0.0f); - Log.JNI.info(loginUser + "[" + connection.getCutAddress() + "] hat sich mit Objekt-ID " + Log.NETWORK.info(loginUser + "[" + connection.getCutAddress() + "] hat sich mit Objekt-ID " + player.getId() + " auf Level " + world.dimension.getDimensionId() + ": " + String.format("%.2f %.2f %.2f", player.posX, player.posY, player.posZ) + " verbunden (" + (tag == null ? "Charakter-Editor" : "'" + player.getCommandName() + "'") + ")"); - if(Config.preload && /* conn.isLocal() && */ this.players.size() == 1) - this.preload(world, (int)player.posX, (int)player.posZ, conn); - conn.sendPacket(new SPacketJoinGame(player.getId(), world.dimension, EntityRegistry.getEntityID(player), tag == null)); conn.sendPacket(new SPacketHeldItemChange(player.inventory.currentItem)); conn.sendPacket(new SPacketWorld(WorldServer.clampGravity(), - Config.dayCycle, Config.timeFlow)); -// conn.initializeStats(); - this.sendPacket(new S38PacketPlayerListItem(false, conn)); + SVars.dayCycle, SVars.timeFlow)); + this.sendPacket(new SPacketPlayerListItem(false, conn)); world.spawnEntityInWorld(player); this.preparePlayer(player, null); for(int i = 0; i < this.players.size(); ++i) { Player other = this.players.get(i); - conn.sendPacket(new S38PacketPlayerListItem(false, other)); + conn.sendPacket(new SPacketPlayerListItem(false, other)); } conn.sendPacket(new SPacketSkin(player.getId(), player.getSkin())); // , player.getModel())); conn.setPlayerLocation(player.posX, player.posY, player.posZ, player.rotYaw, player.rotPitch); this.updateTimeAndWeatherForPlayer(conn, world); for(PotionEffect effect : player.getEffects()) { - conn.sendPacket(new S1DPacketEntityEffect(player.getId(), effect)); + conn.sendPacket(new SPacketEntityEffect(player.getId(), effect)); } - conn.sendPacket(new S39PacketPlayerAbilities(player)); + conn.sendPacket(new SPacketPlayerAbilities(player)); conn.addSelfToInternalCraftingInventory(); conn.onConnect(); - return null; } public void removePlayer(Player conn) { EntityNPC player = conn.getEntity(); player.unmount(); this.writePlayer(conn); - WorldServer world = player.getServerWorld(); + WorldServer world = (WorldServer)player.getServerWorld(); world.removeEntity(player); world.removePlayer(player); this.players.remove(conn); - this.usermap.remove(conn.getUser()); - this.sendPacket(new S38PacketPlayerListItem(true, conn)); + this.online.remove(conn.getUser()); + User user = new User(conn.getUser()); + user.copyFrom(conn); + this.users.put(conn.getUser(), user); + this.sendPacket(new SPacketPlayerListItem(true, conn)); } private void preparePlayer(EntityNPC player, WorldServer oldWorld) { - WorldServer newWorld = player.getServerWorld(); + WorldServer newWorld = (WorldServer)player.getServerWorld(); if(oldWorld != null) { oldWorld.removePlayer(player); } @@ -779,59 +790,54 @@ public final class Server implements IThreadListener { newWorld.loadChunk((int)player.posX >> 4, (int)player.posZ >> 4); } - private NBTTagCompound readPlayer(String user) { - if(this.debug) - return null; - NBTTagCompound tag = null; + private TagObject readPlayer(String user) { + TagObject tag = null; try { - File dat = new File(new File("players"), user + ".nbt"); + File dat = new File(new File("players"), user + ".cdt"); if(dat.exists() && dat.isFile()) { - tag = NBTLoader.readGZip(dat); + tag = TagObject.readGZip(dat); } } catch(Exception e) { - Log.JNI.error(e, "Konnte Spielerdaten für " + user + " nicht laden"); + Log.IO.error(e, "Konnte Spielerdaten für " + user + " nicht laden"); } return tag; } private void writePlayer(Player conn) { - if(this.debug) - return; try { - NBTTagCompound tag = new NBTTagCompound(); + TagObject tag = new TagObject(); EntityNPC entity = conn.getPresentEntity(); if(entity != null) { - NBTTagCompound etag = new NBTTagCompound(); - entity.writeToNBT(etag); - etag.setInteger("Dimension", entity.worldObj.dimension.getDimensionId()); + TagObject etag = new TagObject(); + entity.writeTags(etag); + etag.setInt("Dimension", entity.worldObj.dimension.getDimensionId()); etag.setString("id", EntityRegistry.getEntityString(entity)); conn.writeCharacter(etag); } -// else -// etag = new NBTTagCompound(); - conn.writeToNBT(tag); - File tmp = new File(new File("players"), conn.getUser() + ".nbt.tmp"); - File dat = new File(new File("players"), conn.getUser() + ".nbt"); - NBTLoader.writeGZip(tag, tmp); + conn.writeTags(tag); + File tmp = new File(new File("players"), conn.getUser() + ".cdt.tmp"); + File dat = new File(new File("players"), conn.getUser() + ".cdt"); + TagObject.writeGZip(tag, tmp); if(dat.exists()) { dat.delete(); } tmp.renameTo(dat); } catch(Exception e) { - Log.JNI.error(e, "Konnte Spielerdaten für " + conn.getUser() + " nicht speichern"); + Log.IO.error(e, "Konnte Spielerdaten für " + conn.getUser() + " nicht speichern"); } } public void recreatePlayer(Player conn) { EntityNPC old = conn.getEntity(); BlockPos pos = old.getPosition(); - old.getServerWorld().removePlayerFromTrackers(old); - old.getServerWorld().untrackEntity(old); - old.getServerWorld().removePlayer(old); - old.getServerWorld().removePlayerEntityDangerously(old); + WorldServer oldWorld = (WorldServer)old.getServerWorld(); + oldWorld.removePlayerFromTrackers(old); + oldWorld.untrackEntity(old); + oldWorld.removePlayer(old); + oldWorld.removePlayerEntityDangerously(old); WorldPos bed = old.getSpawnPoint(); WorldPos origin = old.getOrigin(); BlockPos spawn = null; @@ -865,11 +871,10 @@ public final class Server implements IThreadListener { } else { Position rpos = this.getRandomSpawnPosition(origin); - nplayer.setLocationAndAngles(rpos.x, rpos.y, rpos.z, rpos.yaw, rpos.pitch); -// this.movePlayerToSpawn(nplayer); + nplayer.setLocationAndAngles(rpos.x(), rpos.y(), rpos.z(), rpos.yaw(), rpos.pitch()); } world.loadChunk((int)nplayer.posX >> 4, (int)nplayer.posZ >> 4); - if(bed != null ? Config.checkBed : Config.spawnRadius >= 0) { + if(bed != null ? SVars.checkBed : SVars.spawnRadius >= 0) { while(!world.getCollidingBoundingBoxes(nplayer, nplayer.getEntityBoundingBox()).isEmpty() && nplayer.posY < 512.0D) { nplayer.setPosition(nplayer.posX, nplayer.posY + 1.0D, nplayer.posZ); } @@ -889,32 +894,30 @@ public final class Server implements IThreadListener { old.worldObj.dimension.getFormattedName(false)); } - public NBTTagCompound swapPlayer(Player conn, NBTTagCompound tag, Class clazz) { + public TagObject swapPlayer(Player conn, TagObject tag, Class clazz) { EntityNPC old = conn.getEntity(); old.unmount(); - NBTTagCompound oldTag = new NBTTagCompound(); - old.writeToNBT(oldTag); - oldTag.setInteger("Dimension", old.worldObj.dimension.getDimensionId()); + TagObject oldTag = new TagObject(); + old.writeTags(oldTag); + oldTag.setInt("Dimension", old.worldObj.dimension.getDimensionId()); oldTag.setString("id", EntityRegistry.getEntityString(old)); + + WorldServer oldWorld = (WorldServer)old.getServerWorld(); + oldWorld.removePlayerFromTrackers(old); + oldWorld.untrackEntity(old); + oldWorld.removePlayer(old); + oldWorld.removePlayerEntityDangerously(old); - old.getServerWorld().removePlayerFromTrackers(old); - old.getServerWorld().untrackEntity(old); - old.getServerWorld().removePlayer(old); - old.getServerWorld().removePlayerEntityDangerously(old); -// old.dead = false; - - WorldServer world = tag == null ? this.space : this.getWorld(tag.getInteger("Dimension")); + WorldServer world = tag == null ? this.space : this.getWorld(tag.getInt("Dimension")); world = world == null ? this.space : world; EntityNPC nplayer = conn.createPlayer(world, tag == null ? EntityRegistry.getEntityString(clazz) : tag.getString("id")); -// conn.sendPacket(new SPacketRespawn(world.dimension, EntityRegistry.getEntityID(nplayer))); if(tag != null) - nplayer.readFromNBT(tag); + nplayer.readTags(tag); else nplayer.onInitialSpawn(null); -// nplayer.clonePlayer(old); nplayer.setId(old.getId()); if(tag == null) - /* this.movePlayerToSpawn(nplayer); */ nplayer.moveToBlockPosAndAngles(new BlockPos(0, 16384, 0), 0.0f, 0.0f); + nplayer.moveToBlockPosAndAngles(new BlockPos(0, 16384, 0), 0.0f, 0.0f); world.loadChunk((int)nplayer.posX >> 4, (int)nplayer.posZ >> 4); world.addPlayer(nplayer); world.spawnEntityInWorld(nplayer); @@ -922,21 +925,19 @@ public final class Server implements IThreadListener { conn.sendPacket(new SPacketSkin(nplayer.getId(), nplayer.getSkin())); // , nplayer.getModel())); conn.setPlayerLocation(nplayer.posX, nplayer.posY, nplayer.posZ, nplayer.rotYaw, nplayer.rotPitch); conn.sendPacket(new SPacketSetExperience(nplayer.experience, nplayer.experienceTotal, nplayer.experienceLevel)); -// conn.initializeStats(); conn.addSelfToInternalCraftingInventory(); nplayer.setHealth(nplayer.getHealth()); this.updateTimeAndWeatherForPlayer(conn, world); this.syncPlayerInventory(nplayer); for(PotionEffect effect : nplayer.getEffects()) { - conn.sendPacket(new S1DPacketEntityEffect(nplayer.getId(), effect)); + conn.sendPacket(new SPacketEntityEffect(nplayer.getId(), effect)); } conn.sendPlayerAbilities(); return oldTag; } public void transferToDimension(EntityNPC player, int dimension, BlockPos pos, float yaw, float pitch, PortalType portal) { - WorldServer oldWorld = player.getServerWorld(); // this.getWorld(player.dimension); -// player.dimension = dimension; + WorldServer oldWorld = (WorldServer)player.getServerWorld(); // this.getWorld(player.dimension); WorldServer newWorld = this.getWorld(dimension); player.connection.sendPacket(new SPacketRespawn(newWorld.dimension, EntityRegistry.getEntityID(player), player.connection.isInEditor())); oldWorld.removePlayerEntityDangerously(player); @@ -951,11 +952,10 @@ public final class Server implements IThreadListener { player.connection.setPlayerLocation(player.posX, player.posY, player.posZ, pos != null ? yaw : player.rotYaw, pos != null ? pitch : player.rotPitch); if(pos != null) player.setRotationYawHead(yaw); -// player.interactManager.setWorld(newWorld); - this.updateTimeAndWeatherForPlayer(player.connection, newWorld); + this.updateTimeAndWeatherForPlayer((Player)player.connection, newWorld); this.syncPlayerInventory(player); for(PotionEffect effect : player.getEffects()) { - player.connection.sendPacket(new S1DPacketEntityEffect(player.getId(), effect)); + player.connection.sendPacket(new SPacketEntityEffect(player.getId(), effect)); } player.connection.sendPlayerAbilities(); } @@ -1026,24 +1026,22 @@ public final class Server implements IThreadListener { } public void saveAllPlayerData(boolean message) { - if(this.debug) - return; if(message) { - Log.JNI.info("Speichere Spielerdaten"); + Log.TICK.info("Speichere Spielerdaten"); } for(Player conn : this.players) { this.writePlayer(conn); } -// this.saveUsers(); + User.saveDatabase(this.users); } private void updateTimeAndWeatherForPlayer(Player conn, WorldServer world) { conn.sendPacket(new SPacketTimeUpdate(world.getDayTime(), this.getInfo())); - conn.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.SET_WEATHER, world.getWeather().getID())); - conn.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.RAIN_STRENGTH, world.getRainStrength())); - conn.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.DARKNESS, world.getDarkness())); - conn.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.FOG_STRENGTH, world.getFogStrength())); - conn.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.TEMPERATURE, world.getTempOffset())); + conn.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.SET_WEATHER, world.getWeather().getID())); + conn.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.RAIN_STRENGTH, world.getRainStrength())); + conn.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.DARKNESS, world.getDarkness())); + conn.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.FOG_STRENGTH, world.getFogStrength())); + conn.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.TEMPERATURE, world.getTempOffset())); } public void syncPlayerInventory(EntityNPC player) { @@ -1051,51 +1049,21 @@ public final class Server implements IThreadListener { player.connection.setPlayerHealthUpdated(); player.connection.sendPacket(new SPacketHeldItemChange(player.inventory.currentItem)); } - - private void setLanEndpoint(int port) throws IOException { - synchronized(this.serverThread) { - if(this.endpoint != null) - this.unsetLanEndpoint(); - // throw new IllegalStateException("Eingangspunkt bereits gesetzt"); - Log.JNI.info("Öffne Port %d auf 0.0.0.0 (Timeout %ds)", port, Config.timeout); - this.endpoint = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(NioServerSocketChannel.class)).childHandler(new ChannelInitializer() { - protected void initChannel(Channel channel) throws Exception { - try { - channel.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true)); - } - catch(ChannelException e) { - } - channel.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(Config.timeout))) - .addLast((String)"splitter", (ChannelHandler)(new PacketSplitter())) - .addLast((String)"decoder", (ChannelHandler)(new PacketDecoder(true))) - .addLast((String)"prepender", (ChannelHandler)(new PacketPrepender())) - .addLast((String)"encoder", (ChannelHandler)(new PacketEncoder(false))); - NetConnection manager = new NetConnection(); - Server.this.clients.add(manager); - channel.pipeline().addLast((String)"packet_handler", (ChannelHandler)manager); - manager.setNetHandler(new HandshakeHandler(Server.this, manager)); - } - }).group(SERVER_NIO_EVENTLOOP.getValue()).localAddress((InetAddress)null, port)).bind().syncUninterruptibly(); - } - } - private void unsetLanEndpoint() { - for(Player conn : Lists.newArrayList(this.players)) { - conn.disconnect(); - } - this.terminateEndpoint(); - } - - private void terminateEndpoint() { + private void terminateEndpoint(String message) { + if(this.started) + for(Player conn : Lists.newArrayList(this.players)) { + conn.disconnect(message); + } synchronized(this.serverThread) { if(this.endpoint != null) { - Log.JNI.info("Schließe Port"); + Log.NETWORK.info("Schließe Port"); try { this.endpoint.channel().close().sync(); this.endpoint = null; } catch(InterruptedException e) { - Log.JNI.warn("Unterbrochen beim Schließen des Kanals"); + Log.NETWORK.warn("Unterbrochen beim Schließen des Kanals"); } } } @@ -1116,8 +1084,8 @@ public final class Server implements IThreadListener { manager.processReceivedPackets(); } catch(Exception e) { - Log.JNI.error(e, "Konnte Paket von " + manager.getCutAddress() + " nicht verarbeiten"); - manager.sendPacket(new SPacketDisconnect(), new GenericFutureListener>() { + Log.NETWORK.error(e, "Konnte Paket von " + manager.getCutAddress() + " nicht verarbeiten"); + manager.sendPacket(new SPacketDisconnect(e.getMessage()), new GenericFutureListener>() { public void operationComplete(Future future) throws Exception { manager.closeChannel("Fehlerhaftes Datenpaket"); } @@ -1133,25 +1101,13 @@ public final class Server implements IThreadListener { public Map getWarps() { return this.warps; } -// -// public void start() { -// this.serverThread.start(); -// } private void stopServer() { if(!this.stopped) { - this.setProgress(-1); - this.setMessage("Stoppe server"); - Log.JNI.info("Beende Server"); - if(this.started) - for(Player conn : Lists.newArrayList(this.players)) { - conn.disconnect(); - } - this.terminateEndpoint(); + Log.SYSTEM.info("Beende Server"); + this.terminateEndpoint(this.endMessage); if(this.started) { - Log.JNI.info("Speichere Spieler"); this.saveAllPlayerData(true); - Log.JNI.info("Speichere Welt"); this.saveAllWorlds(true); Region.finishWrite(); } @@ -1159,34 +1115,45 @@ public final class Server implements IThreadListener { } public void bind(int port) { -// this.schedule(new Runnable() { -// public void run() { - if(port >= 0) { - try { - Server.this.setLanEndpoint(port); + synchronized(this.serverThread) { + if(port >= 0) { + try { + if(this.endpoint != null) + this.terminateEndpoint("Wechsele auf Port " + port); + Log.NETWORK.info("Öffne Port %d auf 0.0.0.0 (Timeout %ds)", port, SVars.timeout); + this.endpoint = ((ServerBootstrap)((ServerBootstrap)(new ServerBootstrap()).channel(NioServerSocketChannel.class)).childHandler(new ChannelInitializer() { + protected void initChannel(Channel channel) throws Exception { + try { + channel.config().setOption(ChannelOption.TCP_NODELAY, Boolean.valueOf(true)); + } + catch(ChannelException e) { + } + channel.pipeline().addLast((String)"timeout", (ChannelHandler)(new ReadTimeoutHandler(SVars.timeout))) + .addLast((String)"splitter", (ChannelHandler)(new PacketSplitter())) + .addLast((String)"decoder", (ChannelHandler)(new PacketDecoder(true))) + .addLast((String)"prepender", (ChannelHandler)(new PacketPrepender())) + .addLast((String)"encoder", (ChannelHandler)(new PacketEncoder(false))); + NetConnection manager = new NetConnection(); + Server.this.clients.add(manager); + channel.pipeline().addLast((String)"packet_handler", (ChannelHandler)manager); + manager.setNetHandler(new HandshakeHandler(Server.this, manager)); + } + }).group(SERVER_NIO_EVENTLOOP.getValue()).localAddress((InetAddress)null, port)).bind().syncUninterruptibly(); + } + catch(Throwable e) { + Log.NETWORK.error(e, "**** KONNTE NICHT AN PORT " + port + " ANBINDEN!"); + } } - catch(IOException e) { - Log.JNI.error(e, "**** KONNTE NICHT AN PORT " + port + " ANBINDEN!"); + else { + if(this.endpoint != null) + this.terminateEndpoint("Trenne Verbindung"); } } - else { - Server.this.unsetLanEndpoint(); - } -// } -// }); } - public void shutdown() { -// Futures.getUnchecked(this.schedule(new Runnable() { -// public void run() { -// for(Player conn : Lists.newArrayList(Server.this.players)) { // = Server.this.getPlayer(Server.this.owner); -// // if(conn != null) -// if(conn.isLocal()) -// Server.this.removePlayer(conn); -// } -// } -// })); + public void shutdown(String message) { this.running = false; + this.endMessage = message; } public String getInfo() { @@ -1194,17 +1161,27 @@ public final class Server implements IThreadListener { "Geladen: " + this.getWorlds().size() + " Welten, " + WorldServer.getLoadedInfo(this); } - private void sendPipeIPC(String key, Object value) { - if(this.ipcpipe) { - System.out.println("#" + key + (value == null ? "" : " " + String.valueOf(value))); - System.out.flush(); - } + public PublicKey getPublicKey() { + return this.keyPair.getPublic(); + } + + public PrivateKey getPrivateKey() { + return this.keyPair.getPrivate(); } - public void logConsole(String message) { - if(this.ipcpipe) - this.sendPipeIPC("console", message); - else - Log.CONSOLE.info(message); + public void log(String msg) { + Log.CONSOLE.info(msg); + } + + public Position getExecPos() { + return this.execPos; + } + + public void setExecPos(Position pos) { + this.execPos = pos; + } + + public boolean isConsole() { + return true; } } diff --git a/java/src/game/biome/BiomeBeach.java b/server/src/main/java/server/biome/BiomeBeach.java similarity index 57% rename from java/src/game/biome/BiomeBeach.java rename to server/src/main/java/server/biome/BiomeBeach.java index 982f2c6..a4dbee5 100755 --- a/java/src/game/biome/BiomeBeach.java +++ b/server/src/main/java/server/biome/BiomeBeach.java @@ -1,13 +1,14 @@ -package game.biome; +package server.biome; -import game.init.Blocks; -import game.rng.WeightedList; +import common.biome.Biome; +import common.init.Blocks; +import common.rng.WeightedList; -public class BiomeBeach extends Biome +public class BiomeBeach extends GenBiome { - public BiomeBeach(int id) + public BiomeBeach(boolean cold) { - super(id); + super(cold ? Biome.COLDBEACH : Biome.BEACH); this.topBlock = Blocks.sand.getState(); this.fillerBlock = Blocks.sand.getState(); this.treesPerChunk = -999; diff --git a/java/src/game/biome/BiomeBlackened.java b/server/src/main/java/server/biome/BiomeBlackened.java similarity index 59% rename from java/src/game/biome/BiomeBlackened.java rename to server/src/main/java/server/biome/BiomeBlackened.java index 996197e..04383c2 100644 --- a/java/src/game/biome/BiomeBlackened.java +++ b/server/src/main/java/server/biome/BiomeBlackened.java @@ -1,19 +1,20 @@ -package game.biome; +package server.biome; -import game.block.BlockFlower; -import game.entity.npc.EntityMetalhead; -import game.init.Blocks; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.worldgen.tree.WorldGenBaseTree; -import game.worldgen.tree.WorldGenTree; +import common.biome.Biome; +import common.block.foliage.BlockFlower; +import common.entity.npc.EntityMetalhead; +import common.init.Blocks; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import server.worldgen.tree.WorldGenBaseTree; +import server.worldgen.tree.WorldGenTree; -public class BiomeBlackened extends Biome { +public class BiomeBlackened extends GenBiome { protected final WorldGenTree treeGen = new WorldGenBaseTree(false, Blocks.blackwood_log.getState(), Blocks.blackwood_leaves.getState()); - public BiomeBlackened(int id) { - super(id); + public BiomeBlackened() { + super(Biome.BLACKENED); this.topBlock = Blocks.blackened_soil.getState(); this.fillerBlock = Blocks.blackened_dirt.getState(); this.treesPerChunk = 3; diff --git a/java/src/game/biome/BiomeChaos.java b/server/src/main/java/server/biome/BiomeChaos.java similarity index 65% rename from java/src/game/biome/BiomeChaos.java rename to server/src/main/java/server/biome/BiomeChaos.java index 01203b9..0bd3c45 100755 --- a/java/src/game/biome/BiomeChaos.java +++ b/server/src/main/java/server/biome/BiomeChaos.java @@ -1,23 +1,24 @@ -package game.biome; +package server.biome; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.EntityRegistry; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; -import game.worldgen.foliage.WorldGenMushroom; +import common.biome.Biome; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.EntityRegistry; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; +import server.worldgen.foliage.WorldGenMushroom; -public class BiomeChaos extends Biome +public class BiomeChaos extends GenBiome { protected FeatureGenerator mushroomBlueGen = new WorldGenMushroom(Blocks.blue_mushroom); - public BiomeChaos(int id) + public BiomeChaos() { - super(id); + super(Biome.CHAOS); this.topBlock = Blocks.obsidian.getState(); this.fillerBlock = Blocks.obsidian.getState(); } diff --git a/java/src/game/biome/BiomeDesert.java b/server/src/main/java/server/biome/BiomeDesert.java similarity index 66% rename from java/src/game/biome/BiomeDesert.java rename to server/src/main/java/server/biome/BiomeDesert.java index 895310a..0171ff5 100755 --- a/java/src/game/biome/BiomeDesert.java +++ b/server/src/main/java/server/biome/BiomeDesert.java @@ -1,17 +1,18 @@ -package game.biome; +package server.biome; -import game.init.Blocks; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.feature.WorldGenDesertWells; +import common.biome.Biome; +import common.init.Blocks; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.feature.WorldGenDesertWells; -public class BiomeDesert extends Biome +public class BiomeDesert extends GenBiome { - public BiomeDesert(int id) + public BiomeDesert(boolean hills) { - super(id); + super(hills ? Biome.DESERTHILLS : Biome.DESERT); this.topBlock = Blocks.sand.getState(); this.fillerBlock = Blocks.sand.getState(); this.treesPerChunk = -999; diff --git a/server/src/main/java/server/biome/BiomeExterminated.java b/server/src/main/java/server/biome/BiomeExterminated.java new file mode 100755 index 0000000..78b55fd --- /dev/null +++ b/server/src/main/java/server/biome/BiomeExterminated.java @@ -0,0 +1,22 @@ +package server.biome; + +import common.biome.Biome; +import common.init.Blocks; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import server.world.WorldServer; + +public class BiomeExterminated extends GenBiome { + public BiomeExterminated() { + super(Biome.EXTERMINATED); + this.topBlock = Blocks.air.getState(); + this.fillerBlock = Blocks.air.getState(); + } + + protected void addMobs(WeightedList mobs) { + } + + public void decorate(WorldServer worldIn, Random rand, BlockPos pos) { + } +} diff --git a/java/src/game/biome/BiomeForest.java b/server/src/main/java/server/biome/BiomeForest.java similarity index 81% rename from java/src/game/biome/BiomeForest.java rename to server/src/main/java/server/biome/BiomeForest.java index 01a409c..23709f9 100755 --- a/java/src/game/biome/BiomeForest.java +++ b/server/src/main/java/server/biome/BiomeForest.java @@ -1,24 +1,25 @@ -package game.biome; +package server.biome; -import game.block.BlockDoublePlant; -import game.block.BlockFlower; -import game.color.Colorizer; -import game.entity.animal.EntityWolf; -import game.entity.npc.EntityElf; -import game.entity.npc.EntityWoodElf; -import game.init.Blocks; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.foliage.WorldGenBigMushroom; -import game.worldgen.tree.WorldGenBaseTree; -import game.worldgen.tree.WorldGenBigTree; -import game.worldgen.tree.WorldGenBirch; -import game.worldgen.tree.WorldGenDarkOak; -import game.worldgen.tree.WorldGenTree; +import common.biome.Biome; +import common.block.foliage.BlockDoublePlant; +import common.block.foliage.BlockFlower; +import common.entity.animal.EntityFox; +import common.entity.animal.EntityWolf; +import common.entity.npc.EntityElf; +import common.entity.npc.EntityWoodElf; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import server.world.WorldServer; +import server.worldgen.foliage.WorldGenBigMushroom; +import server.worldgen.tree.WorldGenBaseTree; +import server.worldgen.tree.WorldGenBigTree; +import server.worldgen.tree.WorldGenBirch; +import server.worldgen.tree.WorldGenDarkOak; +import server.worldgen.tree.WorldGenTree; -public class BiomeForest extends Biome +public class BiomeForest extends GenBiome { private static final BlockDoublePlant.EnumPlantType[] FLOWER_TYPES = new BlockDoublePlant.EnumPlantType[] { BlockDoublePlant.EnumPlantType.SYRINGA, BlockDoublePlant.EnumPlantType.ROSE, BlockDoublePlant.EnumPlantType.PAEONIA @@ -42,9 +43,9 @@ public class BiomeForest extends Biome protected WorldGenBigTree mapleBig = new WorldGenBigTree(false, Blocks.maple_log.getState(), // .withProperty(BlockNewLog.VARIANT, BlockPlanks.EnumType.MAPLE), Blocks.maple_leaves.getState()); // .withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen())); - public BiomeForest(int id, int type) + public BiomeForest(Biome base, int type) { - super(id); + super(base); this.subType = type; this.treesPerChunk = 10; this.grassPerChunk = 2; @@ -65,22 +66,16 @@ public class BiomeForest extends Biome this.waterlilyPerChunk = 4; } - this.setTemperature(8.0f).setHumidity(80.0f); - - if (this.subType == 2) - { - this.setColor(3175492); - this.setTemperature(4.0f).setHumidity(60.0f); - } - if (this.subType == 0) { - this.mobs.add(new RngSpawn(EntityWolf.class, 5, 4, 4)); + this.mobs.add(new RngSpawn(EntityWolf.class, 5, 2, 4)); + this.mobs.add(new RngSpawn(EntityFox.class, 1, 2, 6)); } if (this.subType == 3) { this.treesPerChunk = -999; + this.mobs.add(new RngSpawn(EntityFox.class, 1, 2, 4)); } if(this.subType != 4) { @@ -89,6 +84,7 @@ public class BiomeForest extends Biome else { this.mobs.add(new RngSpawn(EntityWoodElf.class, 100, 4, 16)); this.mobs.add(new RngSpawn(EntityElf.class, 12, 4, 16)); + this.mobs.add(new RngSpawn(EntityFox.class, 3, 2, 5)); } } @@ -203,37 +199,23 @@ public class BiomeForest extends Biome super.decorate(worldIn, rand, pos); } - public int getGrassColorAtPos(BlockPos pos) + protected GenBiome createMutatedBiome(Biome base) { - return this.subType == 4 ? Colorizer.getGrassColor(1.0f, this.humidity * 0.01f) : - (this.subType == 3 ? (super.getGrassColorAtPos(pos) & 16711422) + 2634762 >> 1 : - super.getGrassColorAtPos(pos)); - } - - public int getFoliageColorAtPos(BlockPos pos) - { - return this.subType == 4 ? Colorizer.getFoliageColor(1.0f, this.humidity * 0.01f) : super.getFoliageColorAtPos(pos); - } - - protected Biome createMutatedBiome(final int id) - { - if (this.id == Biome.forest.id) + if (this.base == Biome.FOREST) { - BiomeForest biomegenforest = new BiomeForest(id, 1); + BiomeForest biomegenforest = new BiomeForest(base, 1); biomegenforest.setScaling(this.depth, this.scale + 0.2F); - biomegenforest.setBiomeName("flowerForest", "Blumenwald"); - biomegenforest.setColor(6976549); return biomegenforest; } else { - return this.id != Biome.birchForest.id && this.id != Biome.birchForestHills.id ? new BiomeMutated(id, this) + return this.base != Biome.BIRCHFOREST && this.base != Biome.BIRCHFORESTHILLS ? new BiomeMutated(base, this) { public void decorate(WorldServer worldIn, Random rand, BlockPos pos) { this.baseBiome.decorate(worldIn, rand, pos); } - }: new BiomeMutated(id, this) + }: new BiomeMutated(base, this) { public WorldGenTree genBigTreeChance(Random rand) { diff --git a/java/src/game/biome/BiomeHell.java b/server/src/main/java/server/biome/BiomeHell.java similarity index 82% rename from java/src/game/biome/BiomeHell.java rename to server/src/main/java/server/biome/BiomeHell.java index 8f4d3c3..7e82667 100755 --- a/java/src/game/biome/BiomeHell.java +++ b/server/src/main/java/server/biome/BiomeHell.java @@ -1,23 +1,24 @@ -package game.biome; +package server.biome; -import game.entity.npc.EntityBloodElf; -import game.entity.npc.EntityCultivator; -import game.entity.npc.EntityFireDemon; -import game.entity.npc.EntityMagma; -import game.entity.npc.EntityMetalhead; -import game.entity.npc.EntityTiefling; -import game.init.Blocks; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureOres; -import game.worldgen.feature.WorldGenFire; -import game.worldgen.feature.WorldGenGlowStone; -import game.worldgen.feature.WorldGenHellLava; -import game.worldgen.foliage.WorldGenMushroom; +import common.biome.Biome; +import common.entity.npc.EntityBloodElf; +import common.entity.npc.EntityCultivator; +import common.entity.npc.EntityFireDemon; +import common.entity.npc.EntityMagma; +import common.entity.npc.EntityMetalhead; +import common.entity.npc.EntityTiefling; +import common.init.Blocks; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureOres; +import server.worldgen.feature.WorldGenFire; +import server.worldgen.feature.WorldGenGlowStone; +import server.worldgen.feature.WorldGenHellLava; +import server.worldgen.foliage.WorldGenMushroom; -public class BiomeHell extends Biome +public class BiomeHell extends GenBiome { private final int subtype; private final WorldGenFire fireGen; @@ -29,9 +30,9 @@ public class BiomeHell extends Biome private final WorldGenMushroom brownMushroomGen; private final WorldGenMushroom redMushroomGen; - public BiomeHell(int id, int subtype) + public BiomeHell(Biome base, int subtype) { - super(id); + super(base); this.subtype = subtype; if(this.subtype == 0) { this.mobs.add(new RngSpawn(EntityBloodElf.class, 10, 1, 2)); @@ -125,14 +126,4 @@ public class BiomeHell extends Biome // { // return this.subtype == 0 ? new DecoratorHell() : super.createBiomeDecorator(); // } - - public int getGrassColorAtPos(BlockPos pos) - { - return 0; - } - - public int getFoliageColorAtPos(BlockPos pos) - { - return 0; - } } diff --git a/java/src/game/biome/BiomeHills.java b/server/src/main/java/server/biome/BiomeHills.java similarity index 77% rename from java/src/game/biome/BiomeHills.java rename to server/src/main/java/server/biome/BiomeHills.java index 7f86b7b..1ec2ed9 100755 --- a/java/src/game/biome/BiomeHills.java +++ b/server/src/main/java/server/biome/BiomeHills.java @@ -1,15 +1,16 @@ -package game.biome; +package server.biome; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; -import game.worldgen.FeatureOres; -import game.worldgen.tree.WorldGenTaiga2; -import game.worldgen.tree.WorldGenTree; +import common.biome.Biome; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; +import server.worldgen.FeatureOres; +import server.worldgen.tree.WorldGenTaiga2; +import server.worldgen.tree.WorldGenTree; -public class BiomeHills extends Biome +public class BiomeHills extends GenBiome { // private FeatureGenerator theWorldGenerator = new FeatureOres(Blocks.monster_egg.getDefaultState().withProperty(BlockSilverfish.VARIANT, BlockSilverfish.EnumType.STONE), false, 7, 9, 0, 64); private FeatureOres theEmeraldGenerator = new FeatureOres(Blocks.emerald_ore.getState(), 3, 5, 1, 4, 32, false); @@ -19,12 +20,12 @@ public class BiomeHills extends Biome private int field_150637_aG = 2; private int field_150638_aH; - protected BiomeHills(int id, boolean p_i45373_2_) + protected BiomeHills(Biome base, boolean large) { - super(id); + super(base); this.field_150638_aH = this.field_150635_aE; - if (p_i45373_2_) + if (large) { this.treesPerChunk = 3; this.field_150638_aH = this.field_150636_aF; @@ -86,19 +87,15 @@ public class BiomeHills extends Biome /** * this creates a mutation specific to Hills biomes */ - private BiomeHills mutateHills(Biome p_150633_1_) + private BiomeHills mutateHills(GenBiome p_150633_1_) { this.field_150638_aH = this.field_150637_aG; - this.setColor(p_150633_1_.color); - this.setBiomeName(p_150633_1_.name + "M", p_150633_1_.display + " M"); this.setScaling(p_150633_1_.depth, p_150633_1_.scale); - this.setTemperature(p_150633_1_.temperature); - this.setHumidity(p_150633_1_.humidity); return this; } - protected Biome createMutatedBiome(int p_180277_1_) + protected GenBiome createMutatedBiome(Biome base) { - return (new BiomeHills(p_180277_1_, false)).mutateHills(this); + return (new BiomeHills(base, false)).mutateHills(this); } } diff --git a/java/src/game/biome/BiomeJungle.java b/server/src/main/java/server/biome/BiomeJungle.java similarity index 74% rename from java/src/game/biome/BiomeJungle.java rename to server/src/main/java/server/biome/BiomeJungle.java index ce45cb2..34faff3 100755 --- a/java/src/game/biome/BiomeJungle.java +++ b/server/src/main/java/server/biome/BiomeJungle.java @@ -1,23 +1,24 @@ -package game.biome; +package server.biome; -import game.block.BlockTallGrass; -import game.entity.animal.EntityChicken; -import game.entity.animal.EntityOcelot; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; -import game.worldgen.foliage.WorldGenMelon; -import game.worldgen.foliage.WorldGenShrub; -import game.worldgen.foliage.WorldGenTallGrass; -import game.worldgen.foliage.WorldGenVines; -import game.worldgen.tree.WorldGenBaseTree; -import game.worldgen.tree.WorldGenJungle; -import game.worldgen.tree.WorldGenTree; +import common.biome.Biome; +import common.block.foliage.BlockTallGrass; +import common.entity.animal.EntityChicken; +import common.entity.animal.EntityOcelot; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; +import server.worldgen.foliage.WorldGenMelon; +import server.worldgen.foliage.WorldGenShrub; +import server.worldgen.foliage.WorldGenTallGrass; +import server.worldgen.foliage.WorldGenVines; +import server.worldgen.tree.WorldGenBaseTree; +import server.worldgen.tree.WorldGenJungle; +import server.worldgen.tree.WorldGenTree; -public class BiomeJungle extends Biome +public class BiomeJungle extends GenBiome { private static final State LOG = Blocks.jungle_log.getState(); // .withProperty(BlockOldLog.VARIANT, BlockPlanks.EnumType.JUNGLE); private static final State LEAVES = Blocks.jungle_leaves.getState(); // .withProperty(BlockOldLeaf.VARIANT, BlockPlanks.EnumType.JUNGLE); // .withProperty(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false)); @@ -25,9 +26,9 @@ public class BiomeJungle extends Biome private final boolean edge; - public BiomeJungle(int id, boolean edge) + public BiomeJungle(Biome base, boolean edge) { - super(id); + super(base); this.edge = edge; if (edge) diff --git a/java/src/game/biome/BiomeMesa.java b/server/src/main/java/server/biome/BiomeMesa.java similarity index 87% rename from java/src/game/biome/BiomeMesa.java rename to server/src/main/java/server/biome/BiomeMesa.java index edf1000..19251d3 100755 --- a/java/src/game/biome/BiomeMesa.java +++ b/server/src/main/java/server/biome/BiomeMesa.java @@ -1,24 +1,24 @@ -package game.biome; +package server.biome; import java.util.Arrays; -import game.block.Block; -import game.block.BlockColored; -import game.block.BlockDirt; -import game.block.BlockSand; -import game.color.DyeColor; -import game.init.Blocks; -import game.material.Material; -import game.rng.PerlinGen; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; -import game.worldgen.tree.WorldGenTree; +import common.biome.Biome; +import common.block.Block; +import common.block.BlockColored; +import common.block.natural.BlockDirt; +import common.block.natural.BlockSand; +import common.color.DyeColor; +import common.init.Blocks; +import common.rng.PerlinGen; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; +import server.worldgen.tree.WorldGenTree; -public class BiomeMesa extends Biome +public class BiomeMesa extends GenBiome { private final boolean bryce; private final boolean soil; @@ -29,14 +29,13 @@ public class BiomeMesa extends Biome private PerlinGen highBryceGen; private PerlinGen clayColorGen; - public BiomeMesa(int id, boolean bryce, boolean soil) + public BiomeMesa(Biome base, boolean bryce, boolean soil) { - super(id); + super(base); this.bryce = bryce; this.soil = soil; // this.setDisableRain(); // this.setTemperatureLegacy(2.0F).setHumidity(0.0F); - this.setHumidity(0.0f); // this.mobs.clear(); this.topBlock = Blocks.sand.getState().withProperty(BlockSand.VARIANT, BlockSand.EnumType.RED_SAND); this.fillerBlock = Blocks.stained_hardened_clay.getState(); @@ -61,16 +60,6 @@ public class BiomeMesa extends Biome return this.worldGeneratorTrees; } - public int getFoliageColorAtPos(BlockPos pos) - { - return 10387789; - } - - public int getGrassColorAtPos(BlockPos pos) - { - return 9470285; - } - public void decorate(WorldServer worldIn, Random rand, BlockPos pos) { super.decorate(worldIn, rand, pos); @@ -132,7 +121,7 @@ public class BiomeMesa extends Biome for (int i1 = chunkPrimerIn.height - 1; i1 >= 0; --i1) { - if (chunkPrimerIn.get(k1, i1, j1).getBlock().getMaterial() == Material.air && i1 < (int)d4) + if (chunkPrimerIn.get(k1, i1, j1).getBlock() == Blocks.air && i1 < (int)d4) { chunkPrimerIn.set(k1, i1, j1, worldState); } @@ -145,7 +134,7 @@ public class BiomeMesa extends Biome // { State iblockstate1 = chunkPrimerIn.get(k1, i1, j1); - if (iblockstate1.getBlock().getMaterial() == Material.air) + if (iblockstate1.getBlock() == Blocks.air) { l = -1; } @@ -166,7 +155,7 @@ public class BiomeMesa extends Biome iblockstate3 = this.fillerBlock; } - if (i1 < l1 && (iblockstate == null || iblockstate.getBlock().getMaterial() == Material.air)) + if (i1 < l1 && (iblockstate == null || iblockstate.getBlock() == Blocks.air)) { iblockstate = liquid; } @@ -327,22 +316,16 @@ public class BiomeMesa extends Biome return this.layers[(y + i + 64) % 64]; } - protected Biome createMutatedBiome(int id) + protected GenBiome createMutatedBiome(Biome base) { - boolean bryce = this.id == Biome.mesa.id; - BiomeMesa mesa = new BiomeMesa(id, bryce, this.soil); + boolean bryce = this.base == Biome.MESA; + BiomeMesa mesa = new BiomeMesa(base, bryce, this.soil); if (!bryce) { mesa.setScaling(Scaling.HILLS_LOW); - mesa.setBiomeName(this.name + "M", this.display + " M"); - } - else - { - mesa.setBiomeName(this.name + "Bryce", this.display + " (Bryce)"); } - mesa.setColor(this.color); return mesa; } } diff --git a/java/src/game/biome/BiomeMoon.java b/server/src/main/java/server/biome/BiomeMoon.java similarity index 56% rename from java/src/game/biome/BiomeMoon.java rename to server/src/main/java/server/biome/BiomeMoon.java index 6a3baad..cab5cfc 100755 --- a/java/src/game/biome/BiomeMoon.java +++ b/server/src/main/java/server/biome/BiomeMoon.java @@ -1,17 +1,18 @@ -package game.biome; +package server.biome; -import game.init.Blocks; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureOres; +import common.biome.Biome; +import common.init.Blocks; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureOres; -public class BiomeMoon extends Biome { +public class BiomeMoon extends GenBiome { private FeatureOres cheeseGenerator = new FeatureOres(Blocks.moon_cheese.getState(), 8, 8, 12, 24, 52, false); - public BiomeMoon(int id) { - super(id); + public BiomeMoon() { + super(Biome.MOON); this.topBlock = Blocks.moon_rock.getState(); this.fillerBlock = Blocks.moon_rock.getState(); } diff --git a/java/src/game/biome/BiomeMushroom.java b/server/src/main/java/server/biome/BiomeMushroom.java similarity index 59% rename from java/src/game/biome/BiomeMushroom.java rename to server/src/main/java/server/biome/BiomeMushroom.java index 07ebec9..1e00da7 100755 --- a/java/src/game/biome/BiomeMushroom.java +++ b/server/src/main/java/server/biome/BiomeMushroom.java @@ -1,14 +1,15 @@ -package game.biome; +package server.biome; -import game.entity.animal.EntityMooshroom; -import game.init.Blocks; -import game.rng.WeightedList; +import common.biome.Biome; +import common.entity.animal.EntityMooshroom; +import common.init.Blocks; +import common.rng.WeightedList; -public class BiomeMushroom extends Biome +public class BiomeMushroom extends GenBiome { - public BiomeMushroom(int id) + public BiomeMushroom() { - super(id); + super(Biome.MUSHROOMPLAINS); this.treesPerChunk = -100; this.flowersPerChunk = -100; this.grassPerChunk = -100; diff --git a/java/src/game/biome/BiomeMutated.java b/server/src/main/java/server/biome/BiomeMutated.java similarity index 67% rename from java/src/game/biome/BiomeMutated.java rename to server/src/main/java/server/biome/BiomeMutated.java index 95d4d93..91b3dfb 100755 --- a/java/src/game/biome/BiomeMutated.java +++ b/server/src/main/java/server/biome/BiomeMutated.java @@ -1,30 +1,25 @@ -package game.biome; +package server.biome; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; -import game.worldgen.tree.WorldGenTree; +import common.biome.Biome; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; +import server.worldgen.tree.WorldGenTree; -public class BiomeMutated extends Biome +public class BiomeMutated extends GenBiome { - protected Biome baseBiome; + protected GenBiome baseBiome; - public BiomeMutated(int id, Biome biome) + public BiomeMutated(Biome base, GenBiome biome) { - super(id); + super(base); this.baseBiome = biome; - this.setColor(biome.color); - this.name = biome.name + "M"; - this.display = biome.display + " M"; this.topBlock = biome.topBlock; this.fillerBlock = biome.fillerBlock; // this.minHeight = biome.minHeight; // this.maxHeight = biome.maxHeight; - this.temperature = biome.temperature; - this.humidity = biome.humidity; - this.waterColor = biome.waterColor; this.allowColdBeach = biome.allowColdBeach; // this.enableRain = biome.enableRain; // this.mobs.clear(); @@ -67,18 +62,8 @@ public class BiomeMutated extends Biome { return this.baseBiome.genBigTreeChance(rand); } - - public int getFoliageColorAtPos(BlockPos pos) - { - return this.baseBiome.getFoliageColorAtPos(pos); - } - - public int getGrassColorAtPos(BlockPos pos) - { - return this.baseBiome.getGrassColorAtPos(pos); - } - - public Class getBiomeClass() + + public Class getBiomeClass() { return this.baseBiome.getBiomeClass(); } @@ -86,7 +71,7 @@ public class BiomeMutated extends Biome /** * returns true if the biome specified is equal to this biome */ - public boolean isEqualTo(Biome biome) + public boolean isEqualTo(GenBiome biome) { return this.baseBiome.isEqualTo(biome); } diff --git a/java/src/game/biome/BiomeNone.java b/server/src/main/java/server/biome/BiomeNone.java similarity index 57% rename from java/src/game/biome/BiomeNone.java rename to server/src/main/java/server/biome/BiomeNone.java index bac124c..f3ef796 100755 --- a/java/src/game/biome/BiomeNone.java +++ b/server/src/main/java/server/biome/BiomeNone.java @@ -1,15 +1,16 @@ -package game.biome; +package server.biome; -import game.init.Blocks; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; +import common.biome.Biome; +import common.init.Blocks; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; -public class BiomeNone extends Biome { - public BiomeNone(int id) { - super(id); +public class BiomeNone extends GenBiome { + public BiomeNone() { + super(Biome.NONE); this.topBlock = Blocks.air.getState(); this.fillerBlock = Blocks.air.getState(); } diff --git a/java/src/game/biome/BiomePlains.java b/server/src/main/java/server/biome/BiomePlains.java similarity index 90% rename from java/src/game/biome/BiomePlains.java rename to server/src/main/java/server/biome/BiomePlains.java index 35ee03b..15a969a 100755 --- a/java/src/game/biome/BiomePlains.java +++ b/server/src/main/java/server/biome/BiomePlains.java @@ -1,13 +1,14 @@ -package game.biome; +package server.biome; -import game.block.BlockDoublePlant; -import game.block.BlockFlower; -import game.entity.animal.EntityHorse; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; +import common.biome.Biome; +import common.block.foliage.BlockDoublePlant; +import common.block.foliage.BlockFlower; +import common.entity.animal.EntityHorse; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; -public class BiomePlains extends Biome +public class BiomePlains extends GenBiome { private static final BlockFlower.EnumFlowerType[] TULIP_TYPES = new BlockFlower.EnumFlowerType[] { BlockFlower.EnumFlowerType.ORANGE_TULIP, BlockFlower.EnumFlowerType.RED_TULIP, @@ -20,10 +21,9 @@ public class BiomePlains extends Biome // protected boolean field_150628_aC; - protected BiomePlains(int id) + protected BiomePlains() { - super(id); - this.setTemperature(12.0f).setHumidity(40.0f); + super(Biome.PLAINS); this.setScaling(Scaling.PLAINS_LOW); this.mobs.add(new RngSpawn(EntityHorse.class, 5, 2, 6)); this.treesPerChunk = -999; diff --git a/java/src/game/biome/BiomeSavanna.java b/server/src/main/java/server/biome/BiomeSavanna.java similarity index 73% rename from java/src/game/biome/BiomeSavanna.java rename to server/src/main/java/server/biome/BiomeSavanna.java index fd987cf..f2124ae 100755 --- a/java/src/game/biome/BiomeSavanna.java +++ b/server/src/main/java/server/biome/BiomeSavanna.java @@ -1,23 +1,24 @@ -package game.biome; +package server.biome; -import game.block.BlockDirt; -import game.block.BlockDoublePlant; -import game.entity.animal.EntityHorse; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; -import game.worldgen.tree.WorldGenSavanna; -import game.worldgen.tree.WorldGenTree; +import common.biome.Biome; +import common.block.foliage.BlockDoublePlant; +import common.block.natural.BlockDirt; +import common.entity.animal.EntityHorse; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; +import server.worldgen.tree.WorldGenSavanna; +import server.worldgen.tree.WorldGenTree; -public class BiomeSavanna extends Biome +public class BiomeSavanna extends GenBiome { private static final WorldGenSavanna field_150627_aC = new WorldGenSavanna(false); - protected BiomeSavanna(int id) + protected BiomeSavanna(boolean plateau) { - super(id); + super(plateau ? Biome.SAVANNAPLATEAU : Biome.SAVANNA); this.mobs.add(new RngSpawn(EntityHorse.class, 1, 2, 6)); this.treesPerChunk = 1; this.flowersPerChunk = 4; @@ -29,10 +30,9 @@ public class BiomeSavanna extends Biome return (WorldGenTree)(rand.rarity(5) ? field_150627_aC : this.worldGeneratorTrees); } - protected Biome createMutatedBiome(int p_180277_1_) + protected GenBiome createMutatedBiome(Biome base) { - Biome biomegenbase = new BiomeSavanna.Mutated(p_180277_1_, this); - biomegenbase.temperature = this.temperature == 28.0f ? 24.0f : 20.0f; + GenBiome biomegenbase = new BiomeSavanna.Mutated(base, this); biomegenbase.depth = this.depth * 0.5F + 0.3F; biomegenbase.scale = this.scale * 0.5F + 1.2F; return biomegenbase; @@ -55,9 +55,9 @@ public class BiomeSavanna extends Biome public static class Mutated extends BiomeMutated { - public Mutated(int p_i45382_1_, Biome p_i45382_2_) + public Mutated(Biome base, GenBiome p_i45382_2_) { - super(p_i45382_1_, p_i45382_2_); + super(base, p_i45382_2_); this.treesPerChunk = 2; this.flowersPerChunk = 2; this.grassPerChunk = 5; diff --git a/java/src/game/biome/BiomeSnow.java b/server/src/main/java/server/biome/BiomeSnow.java similarity index 62% rename from java/src/game/biome/BiomeSnow.java rename to server/src/main/java/server/biome/BiomeSnow.java index 44767cf..ea236f2 100755 --- a/java/src/game/biome/BiomeSnow.java +++ b/server/src/main/java/server/biome/BiomeSnow.java @@ -1,24 +1,25 @@ -package game.biome; +package server.biome; -import game.init.Blocks; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.feature.WorldGenIcePath; -import game.worldgen.feature.WorldGenIceSpike; -import game.worldgen.tree.WorldGenTaiga2; -import game.worldgen.tree.WorldGenTree; +import common.biome.Biome; +import common.init.Blocks; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.feature.WorldGenIcePath; +import server.worldgen.feature.WorldGenIceSpike; +import server.worldgen.tree.WorldGenTaiga2; +import server.worldgen.tree.WorldGenTree; -public class BiomeSnow extends Biome +public class BiomeSnow extends GenBiome { private final WorldGenIceSpike spikeGen = new WorldGenIceSpike(); private final WorldGenIcePath pathGen = new WorldGenIcePath(4); private final boolean spiky; - public BiomeSnow(int id, boolean spiky) + public BiomeSnow(Biome base, boolean spiky) { - super(id); + super(base); this.spiky = spiky; if(spiky) this.topBlock = Blocks.snow.getState(); @@ -54,9 +55,9 @@ public class BiomeSnow extends Biome return new WorldGenTaiga2(false); } - protected Biome createMutatedBiome(int p_180277_1_) + protected GenBiome createMutatedBiome(Biome base) { - Biome biomegenbase = (new BiomeSnow(p_180277_1_, true)).setColor(13828095).setBiomeName(this.name + "Spikes", this.display + " + Spitzen").enableColdBeach().setTemperature(-20.0f).setHumidity(50.0f).setScaling(this.depth + 0.1F, this.scale + 0.1F); + GenBiome biomegenbase = (new BiomeSnow(base, true)).enableColdBeach().setScaling(this.depth + 0.1F, this.scale + 0.1F); biomegenbase.depth = this.depth + 0.3F; biomegenbase.scale = this.scale + 0.4F; return biomegenbase; diff --git a/java/src/game/biome/BiomeSnowLand.java b/server/src/main/java/server/biome/BiomeSnowLand.java similarity index 54% rename from java/src/game/biome/BiomeSnowLand.java rename to server/src/main/java/server/biome/BiomeSnowLand.java index 8ad0d4a..37295ea 100755 --- a/java/src/game/biome/BiomeSnowLand.java +++ b/server/src/main/java/server/biome/BiomeSnowLand.java @@ -1,15 +1,16 @@ -package game.biome; +package server.biome; -import game.entity.animal.EntitySheep; -import game.entity.npc.EntitySpirit; -import game.init.Blocks; -import game.rng.WeightedList; +import common.biome.Biome; +import common.entity.animal.EntitySheep; +import common.entity.npc.EntitySpirit; +import common.init.Blocks; +import common.rng.WeightedList; -public class BiomeSnowLand extends Biome +public class BiomeSnowLand extends GenBiome { - public BiomeSnowLand(int id) + public BiomeSnowLand() { - super(id); + super(Biome.SNOWLAND); this.topBlock = Blocks.snow.getState(); this.fillerBlock = Blocks.snow.getState(); this.mushroomsPerChunk = -1; diff --git a/java/src/game/biome/BiomeSpace.java b/server/src/main/java/server/biome/BiomeSpace.java similarity index 65% rename from java/src/game/biome/BiomeSpace.java rename to server/src/main/java/server/biome/BiomeSpace.java index 67a3cf1..b83c9de 100755 --- a/java/src/game/biome/BiomeSpace.java +++ b/server/src/main/java/server/biome/BiomeSpace.java @@ -1,24 +1,25 @@ -package game.biome; +package server.biome; -import game.block.BlockDirt; -import game.init.Blocks; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; -import game.worldgen.feature.WorldGenAsteroid; +import common.biome.Biome; +import common.block.natural.BlockDirt; +import common.init.Blocks; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; +import server.worldgen.feature.WorldGenAsteroid; -public class BiomeSpace extends Biome +public class BiomeSpace extends GenBiome { protected FeatureGenerator asteroidGen1 = new WorldGenAsteroid(Blocks.stone.getState(), Blocks.rock.getState()); protected FeatureGenerator asteroidGen2 = new WorldGenAsteroid(Blocks.dirt.getState(), Blocks.dirt.getState().withProperty(BlockDirt.VARIANT, BlockDirt.DirtType.COARSE_DIRT)); - public BiomeSpace(int id) + public BiomeSpace() { - super(id); + super(Biome.SPACE); this.topBlock = Blocks.air.getState(); this.fillerBlock = Blocks.air.getState(); } diff --git a/java/src/game/biome/BiomeStoneBeach.java b/server/src/main/java/server/biome/BiomeStoneBeach.java similarity index 61% rename from java/src/game/biome/BiomeStoneBeach.java rename to server/src/main/java/server/biome/BiomeStoneBeach.java index 550a07b..47a4c5b 100755 --- a/java/src/game/biome/BiomeStoneBeach.java +++ b/server/src/main/java/server/biome/BiomeStoneBeach.java @@ -1,13 +1,14 @@ -package game.biome; +package server.biome; -import game.init.Blocks; -import game.rng.WeightedList; +import common.biome.Biome; +import common.init.Blocks; +import common.rng.WeightedList; -public class BiomeStoneBeach extends Biome +public class BiomeStoneBeach extends GenBiome { - public BiomeStoneBeach(int id) + public BiomeStoneBeach() { - super(id); + super(Biome.STONEBEACH); // this.mobs.clear(); this.topBlock = Blocks.stone.getState(); this.fillerBlock = Blocks.stone.getState(); diff --git a/java/src/game/biome/BiomeSwamp.java b/server/src/main/java/server/biome/BiomeSwamp.java similarity index 66% rename from java/src/game/biome/BiomeSwamp.java rename to server/src/main/java/server/biome/BiomeSwamp.java index c742d0a..9c3854d 100755 --- a/java/src/game/biome/BiomeSwamp.java +++ b/server/src/main/java/server/biome/BiomeSwamp.java @@ -1,22 +1,22 @@ -package game.biome; +package server.biome; -import game.block.BlockDirectional; -import game.block.BlockFlower; -import game.entity.npc.EntitySlime; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; -import game.worldgen.tree.WorldGenTree; +import common.biome.Biome; +import common.block.BlockDirectional; +import common.block.foliage.BlockFlower; +import common.entity.npc.EntitySlime; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; +import server.worldgen.tree.WorldGenTree; -public class BiomeSwamp extends Biome +public class BiomeSwamp extends GenBiome { - protected BiomeSwamp(int id) + protected BiomeSwamp() { - super(id); + super(Biome.SWAMPLAND); this.treesPerChunk = 2; this.flowersPerChunk = 1; this.deadBushPerChunk = 1; @@ -27,7 +27,6 @@ public class BiomeSwamp extends Biome this.sandPerChunk2 = 0; this.sandPerChunk = 0; this.grassPerChunk = 5; - this.waterColor = 0xe0ffae; this.mobs.add(new RngSpawn(EntitySlime.class, 1, 1, 1)); this.disableBeach(); } @@ -37,17 +36,6 @@ public class BiomeSwamp extends Biome return this.worldGeneratorSwamp; } - public int getGrassColorAtPos(BlockPos pos) - { - double d0 = GRASS_NOISE.generate((double)pos.getX() * 0.0225D, (double)pos.getZ() * 0.0225D); - return d0 < -0.1D ? 5011004 : 6975545; - } - - public int getFoliageColorAtPos(BlockPos pos) - { - return 6975545; - } - public BlockFlower.EnumFlowerType pickRandomFlower(Random rand, BlockPos pos) { return BlockFlower.EnumFlowerType.BLUE_ORCHID; @@ -64,7 +52,7 @@ public class BiomeSwamp extends Biome for (int k = chunkPrimerIn.height - 1; k >= 0; --k) { - if (chunkPrimerIn.get(j, k, i).getBlock().getMaterial() != Material.air) + if (chunkPrimerIn.get(j, k, i).getBlock() != Blocks.air) { if (k == 62 && chunkPrimerIn.get(j, k, i).getBlock() != Blocks.water) { diff --git a/java/src/game/biome/BiomeTaiga.java b/server/src/main/java/server/biome/BiomeTaiga.java similarity index 76% rename from java/src/game/biome/BiomeTaiga.java rename to server/src/main/java/server/biome/BiomeTaiga.java index f5b4b7e..97812ff 100755 --- a/java/src/game/biome/BiomeTaiga.java +++ b/server/src/main/java/server/biome/BiomeTaiga.java @@ -1,23 +1,24 @@ -package game.biome; +package server.biome; -import game.block.BlockDirt; -import game.block.BlockDoublePlant; -import game.block.BlockTallGrass; -import game.entity.animal.EntityWolf; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; -import game.worldgen.FeatureGenerator; -import game.worldgen.feature.WorldGenBlockBlob; -import game.worldgen.foliage.WorldGenTallGrass; -import game.worldgen.tree.WorldGenPine; -import game.worldgen.tree.WorldGenTaiga1; -import game.worldgen.tree.WorldGenTaiga2; -import game.worldgen.tree.WorldGenTree; +import common.biome.Biome; +import common.block.foliage.BlockDoublePlant; +import common.block.foliage.BlockTallGrass; +import common.block.natural.BlockDirt; +import common.entity.animal.EntityWolf; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; +import server.worldgen.FeatureGenerator; +import server.worldgen.feature.WorldGenBlockBlob; +import server.worldgen.foliage.WorldGenTallGrass; +import server.worldgen.tree.WorldGenPine; +import server.worldgen.tree.WorldGenTaiga1; +import server.worldgen.tree.WorldGenTaiga2; +import server.worldgen.tree.WorldGenTree; -public class BiomeTaiga extends Biome +public class BiomeTaiga extends GenBiome { private static final WorldGenTaiga1 field_150639_aC = new WorldGenTaiga1(); private static final WorldGenTaiga2 field_150640_aD = new WorldGenTaiga2(false); @@ -26,9 +27,9 @@ public class BiomeTaiga extends Biome private static final WorldGenBlockBlob field_150643_aG = new WorldGenBlockBlob(Blocks.mossy_cobblestone, 0); private int field_150644_aH; - public BiomeTaiga(int id, int p_i45385_2_) + public BiomeTaiga(Biome base, int p_i45385_2_) { - super(id); + super(base); this.field_150644_aH = p_i45385_2_; this.mobs.add(new RngSpawn(EntityWolf.class, 8, 4, 4)); this.treesPerChunk = 10; @@ -107,8 +108,8 @@ public class BiomeTaiga extends Biome this.generateBiomeTerrain(worldIn, rand, chunkPrimerIn, x, z, noiseVal); } - protected Biome createMutatedBiome(int p_180277_1_) + protected GenBiome createMutatedBiome(Biome base) { - return this.id == Biome.megaTaiga.id ? (new BiomeTaiga(p_180277_1_, 2)).setColor(5858897).setBiomeName("megaSpruceTaiga", "Hohe Fichtentaiga").setTemperature(-10.0f).setHumidity(80.0f).setScaling(this.depth, this.scale) : super.createMutatedBiome(p_180277_1_); + return this.base == Biome.MEGATAIGA ? (new BiomeTaiga(base, 2)).setScaling(this.depth, this.scale) : super.createMutatedBiome(base); } } diff --git a/java/src/game/biome/BiomeTian.java b/server/src/main/java/server/biome/BiomeTian.java similarity index 76% rename from java/src/game/biome/BiomeTian.java rename to server/src/main/java/server/biome/BiomeTian.java index 1382e11..021a972 100755 --- a/java/src/game/biome/BiomeTian.java +++ b/server/src/main/java/server/biome/BiomeTian.java @@ -1,23 +1,24 @@ -package game.biome; +package server.biome; -import game.block.BlockFlower; -import game.entity.animal.EntityBat; -import game.entity.animal.EntityMouse; -import game.entity.animal.EntityRabbit; -import game.entity.npc.EntityCultivator; -import game.init.Blocks; -import game.rng.Random; -import game.rng.WeightedList; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; -import game.worldgen.feature.WorldGenSpikes; -import game.worldgen.foliage.WorldGenMushroom; -import game.worldgen.tree.WorldGenBaseTree; -import game.worldgen.tree.WorldGenBigTree; -import game.worldgen.tree.WorldGenTree; +import common.biome.Biome; +import common.block.foliage.BlockFlower; +import common.entity.animal.EntityBat; +import common.entity.animal.EntityMouse; +import common.entity.animal.EntityRabbit; +import common.entity.npc.EntityCultivator; +import common.init.Blocks; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; +import server.worldgen.feature.WorldGenSpikes; +import server.worldgen.foliage.WorldGenMushroom; +import server.worldgen.tree.WorldGenBaseTree; +import server.worldgen.tree.WorldGenBigTree; +import server.worldgen.tree.WorldGenTree; -public class BiomeTian extends Biome +public class BiomeTian extends GenBiome { protected FeatureGenerator spikeGen = new WorldGenSpikes(Blocks.tian_soil, 128, 2, 3, Blocks.obsidian.getState(), true); protected FeatureGenerator mushroomBlueGen = new WorldGenMushroom(Blocks.blue_mushroom); @@ -29,9 +30,9 @@ public class BiomeTian extends Biome protected WorldGenTree treeGen4 = new WorldGenBigTree(false, Blocks.tian_log.getState(), Blocks.tian_leaves.getState()) .setHeightLimit(12, 15); - public BiomeTian(int id) + public BiomeTian() { - super(id); + super(Biome.TIAN); this.topBlock = Blocks.tian_soil.getState(); this.fillerBlock = Blocks.tian.getState(); this.mushroomsPerChunk = -1; diff --git a/java/src/game/biome/BiomeWater.java b/server/src/main/java/server/biome/BiomeWater.java similarity index 57% rename from java/src/game/biome/BiomeWater.java rename to server/src/main/java/server/biome/BiomeWater.java index 6c68df8..48c853b 100755 --- a/java/src/game/biome/BiomeWater.java +++ b/server/src/main/java/server/biome/BiomeWater.java @@ -1,13 +1,14 @@ -package game.biome; +package server.biome; -import game.entity.animal.EntitySquid; -import game.rng.WeightedList; +import common.biome.Biome; +import common.entity.animal.EntitySquid; +import common.rng.WeightedList; -public class BiomeWater extends Biome { +public class BiomeWater extends GenBiome { private final boolean river; - public BiomeWater(int id, boolean river) { - super(id); + public BiomeWater(Biome base, boolean river) { + super(base); this.river = river; this.disableBeach(); } diff --git a/server/src/main/java/server/biome/GenBiome.java b/server/src/main/java/server/biome/GenBiome.java new file mode 100755 index 0000000..cc3c27d --- /dev/null +++ b/server/src/main/java/server/biome/GenBiome.java @@ -0,0 +1,871 @@ +package server.biome; + +import common.biome.Biome; +import common.biome.IBiome; +import common.block.Block; +import common.block.BlockColored; +import common.block.Material; +import common.block.foliage.BlockFlower; +import common.block.foliage.BlockSapling; +import common.block.foliage.BlockTallGrass; +import common.block.natural.BlockSand; +import common.color.DyeColor; +import common.entity.animal.EntityBat; +import common.entity.animal.EntityChicken; +import common.entity.animal.EntityCow; +import common.entity.animal.EntityMouse; +import common.entity.animal.EntityPig; +import common.entity.animal.EntityRabbit; +import common.entity.animal.EntitySheep; +import common.entity.animal.EntitySquid; +import common.entity.npc.EntityArachnoid; +import common.entity.npc.EntityHaunter; +import common.entity.npc.EntityMage; +import common.entity.npc.EntitySlime; +import common.entity.npc.EntityUndead; +import common.entity.npc.EntityZombie; +import common.init.Blocks; +import common.init.WoodType; +import common.log.Log; +import common.rng.PerlinGen; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import common.world.AWorldServer; +import common.world.State; +import common.world.World; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; +import server.worldgen.FeatureGenerator; +import server.worldgen.feature.WorldGenClay; +import server.worldgen.feature.WorldGenClayExt; +import server.worldgen.feature.WorldGenSand; +import server.worldgen.foliage.FeatureDoublePlant; +import server.worldgen.foliage.WorldGenBigMushroom; +import server.worldgen.foliage.WorldGenCactus; +import server.worldgen.foliage.WorldGenDeadBush; +import server.worldgen.foliage.WorldGenFlowers; +import server.worldgen.foliage.WorldGenMushroom; +import server.worldgen.foliage.WorldGenPumpkin; +import server.worldgen.foliage.WorldGenReed; +import server.worldgen.foliage.WorldGenTallGrass; +import server.worldgen.foliage.WorldGenWaterlily; +import server.worldgen.tree.WorldGenBaseTree; +import server.worldgen.tree.WorldGenBigTree; +import server.worldgen.tree.WorldGenBirch; +import server.worldgen.tree.WorldGenDarkOak; +import server.worldgen.tree.WorldGenJungle; +import server.worldgen.tree.WorldGenPine; +import server.worldgen.tree.WorldGenSavanna; +import server.worldgen.tree.WorldGenSwamp; +import server.worldgen.tree.WorldGenTaiga2; +import server.worldgen.tree.WorldGenTree; + +public abstract class GenBiome implements IBiome { + public static final GenBiome[] BIOMES = new GenBiome[256]; + + public static final GenBiome none = (new BiomeNone()); + + public static final GenBiome plains = (new BiomePlains()); + public static final GenBiome desert = (new BiomeDesert(false)).setScaling(Scaling.PLAINS_LOW); + public static final GenBiome extremeHills = (new BiomeHills(Biome.EXTREMEHILLS, false)).setScaling(Scaling.HILLS_LARGE); + public static final GenBiome forest = (new BiomeForest(Biome.FOREST, 0)); + public static final GenBiome taiga = (new BiomeTaiga(Biome.TAIGA, 0)).setScaling(Scaling.PLAINS_MEDIUM); + public static final GenBiome swampland = (new BiomeSwamp()).setScaling(Scaling.SEA_POND); + public static final GenBiome river = (new BiomeWater(Biome.RIVER, true)).setScaling(Scaling.SEA_SHALLOW); + + public static final GenBiome exterminated = (new BiomeExterminated()); + public static final GenBiome space = (new BiomeSpace()); + + public static final GenBiome frozenSea = (new BiomeWater(Biome.FROZENSEA, false)).enableColdBeach().setScaling(Scaling.SEA_MEDIUM); + public static final GenBiome frozenRiver = (new BiomeWater(Biome.FROZENRIVER, true)).enableColdBeach().setScaling(Scaling.SEA_SHALLOW); + public static final GenBiome icePlains = (new BiomeSnow(Biome.ICEPLAINS, false)).enableColdBeach().setScaling(Scaling.PLAINS_LOW); + public static final GenBiome iceMountains = (new BiomeSnow(Biome.ICEMOUNTAINS, false)).enableColdBeach().setScaling(Scaling.HILLS_LOW); + public static final GenBiome mushroomPlains = (new BiomeMushroom()).setScaling(Scaling.PLAINS_VARYING); + public static final GenBiome blackened = (new BiomeBlackened()); + public static final GenBiome beach = (new BiomeBeach(false)).setScaling(Scaling.SEA_SHORE); + public static final GenBiome desertHills = (new BiomeDesert(true)).setScaling(Scaling.HILLS_LOW); + public static final GenBiome forestHills = (new BiomeForest(Biome.FORESTHILLS, 0)).setScaling(Scaling.HILLS_LOW); + public static final GenBiome taigaHills = (new BiomeTaiga(Biome.TAIGAHILLS, 0)).setScaling(Scaling.HILLS_LOW); + public static final GenBiome extremeHillsEdge = (new BiomeHills(Biome.EXTREMEHILLSEDGE, true)).setScaling(Scaling.HILLS_MEDIUM); + public static final GenBiome jungle = (new BiomeJungle(Biome.JUNGLE, false)); + public static final GenBiome jungleHills = (new BiomeJungle(Biome.JUNGLEHILLS, false)).setScaling(Scaling.HILLS_LOW); + public static final GenBiome jungleEdge = (new BiomeJungle(Biome.JUNGLEEDGE, true)); + public static final GenBiome sea = (new BiomeWater(Biome.SEA, false)).setScaling(Scaling.SEA_MEDIUM); + public static final GenBiome stoneBeach = (new BiomeStoneBeach()).setScaling(Scaling.SEA_VARYING); + public static final GenBiome coldBeach = (new BiomeBeach(true)).setScaling(Scaling.SEA_SHORE).enableColdBeach(); + public static final GenBiome birchForest = (new BiomeForest(Biome.BIRCHFOREST, 2)); + public static final GenBiome birchForestHills = (new BiomeForest(Biome.BIRCHFORESTHILLS, 2)).setScaling(Scaling.HILLS_LOW); + public static final GenBiome roofedForest = (new BiomeForest(Biome.ROOFEDFOREST, 3)); + public static final GenBiome coldTaiga = (new BiomeTaiga(Biome.COLDTAIGA, 0)).enableColdBeach().setScaling(Scaling.PLAINS_MEDIUM); + public static final GenBiome coldTaigaHills = (new BiomeTaiga(Biome.COLDTAIGAHILLS, 0)).enableColdBeach().setScaling(Scaling.HILLS_LOW); + public static final GenBiome megaTaiga = (new BiomeTaiga(Biome.MEGATAIGA, 1)).setScaling(Scaling.PLAINS_MEDIUM); + public static final GenBiome megaTaigaHills = (new BiomeTaiga(Biome.MEGATAIGAHILLS, 1)).setScaling(Scaling.HILLS_LOW); + public static final GenBiome extremeHillsPlus = (new BiomeHills(Biome.EXTREMEHILLSPLUS, true)).setScaling(Scaling.HILLS_LARGE); + public static final GenBiome savanna = (new BiomeSavanna(false)).setScaling(Scaling.PLAINS_LOW); + public static final GenBiome savannaPlateau = (new BiomeSavanna(true)).setScaling(Scaling.HILLS_PLATEAU); + + public static final GenBiome mesa = (new BiomeMesa(Biome.MESA, false, false)); + public static final GenBiome mesaPlateau_F = (new BiomeMesa(Biome.MESAPLATEAUF, false, true)).setScaling(Scaling.HILLS_PLATEAU); + public static final GenBiome mesaPlateau = (new BiomeMesa(Biome.MESAPLATEAU, false, false)).setScaling(Scaling.HILLS_PLATEAU); + + public static final GenBiome snowLand = (new BiomeSnowLand()).enableColdBeach(); + public static final GenBiome tian = (new BiomeTian()).setScaling(Scaling.VARYING_MEDIUM); + public static final GenBiome elvenForest = (new BiomeForest(Biome.ELVENFOREST, 4)); + public static final GenBiome upperHell = (new BiomeHell(Biome.UPPERHELL, 0)); + public static final GenBiome lowerHell = (new BiomeHell(Biome.LOWERHELL, 1)); + public static final GenBiome hellHills = (new BiomeHell(Biome.HELLHILLS, 1)).setScaling(Scaling.HILLS_LARGE); + public static final GenBiome soulPlains = (new BiomeHell(Biome.SOULPLAINS, 1)).setScaling(Scaling.SEA_POND); + public static final GenBiome ashLand = (new BiomeHell(Biome.ASHLAND, 2)).setScaling(Scaling.PLAINS_LOW); + public static final GenBiome moon = (new BiomeMoon()).setScaling(Scaling.PLAINS_LOW); + public static final GenBiome chaos = (new BiomeChaos()).setScaling(Scaling.VARYING_CHAOTIC); + + protected static final PerlinGen TREE_NOISE = new PerlinGen(new Random(726528729282625L), 8); + protected static final PerlinGen GRASS_NOISE = new PerlinGen(new Random(297363826225L), 1); + protected static final FeatureDoublePlant DOUBLE_PLANT_GEN = new FeatureDoublePlant(); + + public final Biome base; + + protected final WeightedList mobs = new WeightedList(); + protected final WorldGenBaseTree worldGeneratorTrees = new WorldGenBaseTree(false); + protected final WorldGenBigTree worldGeneratorBigTree = new WorldGenBigTree(false); + protected final WorldGenSwamp worldGeneratorSwamp = new WorldGenSwamp(); + private final FeatureGenerator clayGen = new WorldGenClay(4); + private final FeatureGenerator sandGen = new WorldGenSand(Blocks.sand, 7); + private final FeatureGenerator gravelAsSandGen = new WorldGenSand(Blocks.gravel, 6); + private final WorldGenFlowers yellowFlowerGen = new WorldGenFlowers(Blocks.flower, BlockFlower.EnumFlowerType.DANDELION); + private final FeatureGenerator mushroomBrownGen = new WorldGenMushroom(Blocks.brown_mushroom); + private final FeatureGenerator mushroomRedGen = new WorldGenMushroom(Blocks.red_mushroom); + private final FeatureGenerator bigMushroomGen = new WorldGenBigMushroom(); + private final FeatureGenerator reedGen = new WorldGenReed(); + private final FeatureGenerator cactusGen = new WorldGenCactus(); + private final FeatureGenerator waterlilyGen = new WorldGenWaterlily(); + private final FeatureGenerator clayGenExt = new WorldGenClayExt(32); + + public State topBlock = Blocks.grass.getState(); + public State fillerBlock = Blocks.dirt.getState(); + public float depth = Scaling.VARYING_LOW.depth; + public float scale = Scaling.VARYING_LOW.scale; + public boolean generateLakes = true; + public boolean generateLiquids = true; + public boolean allowColdBeach = false; + public boolean disallowBeach = false; + + protected int waterlilyPerChunk = 0; + protected int treesPerChunk = 0; + protected int flowersPerChunk = 2; + protected int grassPerChunk = 1; + protected int deadBushPerChunk = 0; + protected int mushroomsPerChunk = 0; + protected int reedsPerChunk = 0; + protected int cactiPerChunk = 0; + protected int sandPerChunk = 1; + protected int sandPerChunk2 = 3; + protected int clayPerChunk = 1; + protected int clayExtPerChunk = 0; // 10 + protected int bigMushroomsPerChunk = 0; + + public static GenBiome getBiome(int id) + { + if (id >= 0 && id < BIOMES.length) + { + return BIOMES[id]; + } + else + { + Log.TICK.warn("Biom-ID ist nicht im Bereich: " + id + ", verwende " + Biome.DEF_BIOME.id + " (" + Biome.DEF_BIOME.name + ")"); + return BIOMES[Biome.DEF_BIOME.id]; + } + } + + public static void setAsProvider() { + IBiome.setProvider(new IBiome.BiomeProvider() { + public final IBiome getBiome(Biome base) { + return BIOMES[base.id]; + } + }); + } + + static { + desert.createMutatedBiome(Biome.DESERTM); + forest.createMutatedBiome(Biome.FLOWERFOREST); + taiga.createMutatedBiome(Biome.TAIGAM); + swampland.createMutatedBiome(Biome.SWAMPLANDM); + icePlains.createMutatedBiome(Biome.ICEPLAINSSPIKES); + jungle.createMutatedBiome(Biome.JUNGLEM); + jungleEdge.createMutatedBiome(Biome.JUNGLEEDGEM); + coldTaiga.createMutatedBiome(Biome.COLDTAIGAM); + savanna.createMutatedBiome(Biome.SAVANNAM); + savannaPlateau.createMutatedBiome(Biome.SAVANNAPLATEAUM); + mesa.createMutatedBiome(Biome.MESABRYCE); + mesaPlateau_F.createMutatedBiome(Biome.MESAPLATEAUFM); + mesaPlateau.createMutatedBiome(Biome.MESAPLATEAUM); + birchForest.createMutatedBiome(Biome.BIRCHFORESTM); + birchForestHills.createMutatedBiome(Biome.BIRCHFORESTHILLSM); + roofedForest.createMutatedBiome(Biome.ROOFEDFORESTM); + megaTaiga.createMutatedBiome(Biome.MEGASPRUCETAIGA); + extremeHills.createMutatedBiome(Biome.EXTREMEHILLSM); + extremeHillsPlus.createMutatedBiome(Biome.EXTREMEHILLSPLUSM); + megaTaiga.createMutatedBiome(Biome.REDWOODTAIGAHILLSM); + } + + protected GenBiome(Biome base) { + BIOMES[base.id] = this; + this.base = base; + this.addMobs(this.mobs); + } + + protected void addMobs(WeightedList mobs) { + mobs.add(new RngSpawn(EntitySheep.class, 12, 4, 4)); + mobs.add(new RngSpawn(EntityRabbit.class, 10, 3, 10)); + mobs.add(new RngSpawn(EntityPig.class, 10, 4, 4)); + mobs.add(new RngSpawn(EntityChicken.class, 10, 4, 4)); + mobs.add(new RngSpawn(EntityCow.class, 8, 4, 4)); + mobs.add(new RngSpawn(EntityArachnoid.class, 100, 4, 4)); + mobs.add(new RngSpawn(EntityZombie.class, 100, 4, 4)); + mobs.add(new RngSpawn(EntityUndead.class, 100, 4, 4)); + mobs.add(new RngSpawn(EntityHaunter.class, 100, 4, 4)); + mobs.add(new RngSpawn(EntitySlime.class, 100, 4, 4)); +// mobs.add(new Biome.RngSpawn(EntityEnder....class, 10, 1, 4)); + mobs.add(new RngSpawn(EntityMage.class, 5, 1, 1)); + mobs.add(new RngSpawn(EntitySquid.class, 10, 4, 4)); + mobs.add(new RngSpawn(EntityBat.class, 10, 8, 8)); + mobs.add(new RngSpawn(EntityMouse.class, 10, 8, 8)); + } + + protected final GenBiome setScaling(Scaling scaling) + { + return this.setScaling(scaling.depth, scaling.scale); + } + + protected final GenBiome setScaling(float depth, float scale) + { + this.depth = depth; + this.scale = scale; + return this; + } + + public WorldGenTree genBigTreeChance(Random rand) + { + return rand.chance(10) ? this.worldGeneratorBigTree : this.worldGeneratorTrees; + } + + public WorldGenTree genBigTreeLegacy(Random rand, BlockPos pos) + { + int noise = (int)((TREE_NOISE.generate((double)pos.getX() * 0.5D, (double)pos.getZ() * 0.5D) / 8D + rand.doublev() * 4D + 4D) / 3D); + return (noise > 0 && rand.chance(noise)) || (this.base.isHighHumidity() && rand.chance(3)) ? this.worldGeneratorBigTree : + this.worldGeneratorTrees; + } + + public FeatureGenerator getRandomWorldGenForGrass(Random rand) + { + return new WorldGenTallGrass(BlockTallGrass.EnumType.GRASS); + } + + public BlockFlower.EnumFlowerType pickRandomFlower(Random rand, BlockPos pos) + { + return rand.rarity(3) ? BlockFlower.EnumFlowerType.DANDELION : BlockFlower.EnumFlowerType.ROSE; + } + + public State getFiller() { + return this.fillerBlock; + } + + public State getTop() { + return this.topBlock; + } + + protected GenBiome enableColdBeach() + { + this.allowColdBeach = true; + return this; + } + + protected GenBiome disableBeach() + { + this.disallowBeach = true; + return this; + } + + public WeightedList getMobs() + { + return this.mobs; + } + + public float getMobGenChance() + { + return 0.1F; + } + + public void decorate(WorldServer world, Random rand, BlockPos pos) + { + for (int i = 0; i < this.sandPerChunk2; ++i) + { + int j = rand.chOffset(); + int k = rand.chOffset(); + this.sandGen.generate(world, rand, world.getTopSolidOrLiquidBlock(pos.add(j, 0, k))); + } + + for (int i1 = 0; i1 < this.clayPerChunk; ++i1) + { + int l1 = rand.chOffset(); + int i6 = rand.chOffset(); + this.clayGen.generate(world, rand, world.getTopSolidOrLiquidBlock(pos.add(l1, 0, i6))); + } + + for (int j1 = 0; j1 < this.sandPerChunk; ++j1) + { + int i2 = rand.chOffset(); + int j6 = rand.chOffset(); + this.gravelAsSandGen.generate(world, rand, world.getTopSolidOrLiquidBlock(pos.add(i2, 0, j6))); + } + + for (int i1 = 0; i1 < this.clayExtPerChunk; ++i1) + { + int l1 = rand.chOffset(); + int i6 = rand.chOffset(); + this.clayGenExt.generate(world, rand, world.getTopSolidOrLiquidBlock(pos.add(l1, 0, i6))); + } + + int k1 = this.treesPerChunk; + + if (rand.chance(10)) + { + ++k1; + } + + for (int j2 = 0; j2 < k1; ++j2) + { + int k6 = rand.chOffset(); + int l = rand.chOffset(); + WorldGenTree treeGen = this.genBigTreeChance(rand); + treeGen.prepare(); + BlockPos blockpos = world.getHeight(pos.add(k6, 0, l)); + + if (treeGen.generate(world, rand, blockpos)) + { + treeGen.finish(world, rand, blockpos); + } + } + + for (int k2 = 0; k2 < this.bigMushroomsPerChunk; ++k2) + { + int l6 = rand.chOffset(); + int k10 = rand.chOffset(); + this.bigMushroomGen.generate(world, rand, world.getHeight(pos.add(l6, 0, k10))); + } + + for (int l2 = 0; l2 < this.flowersPerChunk; ++l2) + { + int i7 = rand.chOffset(); + int l10 = rand.chOffset(); + int j14 = world.getHeight(pos.add(i7, 0, l10)).getY() + 32; + + if (j14 > 0) + { + int k17 = rand.zrange(j14); + BlockPos blockpos1 = pos.add(i7, k17, l10); + BlockFlower.EnumFlowerType blockflower$enumflowertype = this.pickRandomFlower(rand, blockpos1); + BlockFlower blockflower = blockflower$enumflowertype.getBlockType().getBlock(); + + this.yellowFlowerGen.setGeneratedBlock(blockflower, blockflower$enumflowertype); + this.yellowFlowerGen.generate(world, rand, blockpos1); + } + } + + for (int i3 = 0; i3 < this.grassPerChunk; ++i3) + { + int j7 = rand.chOffset(); + int i11 = rand.chOffset(); + int k14 = world.getHeight(pos.add(j7, 0, i11)).getY() * 2; + + if (k14 > 0) + { + int l17 = rand.zrange(k14); + this.getRandomWorldGenForGrass(rand).generate(world, rand, pos.add(j7, l17, i11)); + } + } + + for (int j3 = 0; j3 < this.deadBushPerChunk; ++j3) + { + int k7 = rand.chOffset(); + int j11 = rand.chOffset(); + int l14 = world.getHeight(pos.add(k7, 0, j11)).getY() * 2; + + if (l14 > 0) + { + int i18 = rand.zrange(l14); + (new WorldGenDeadBush()).generate(world, rand, pos.add(k7, i18, j11)); + } + } + + for (int k3 = 0; k3 < this.waterlilyPerChunk; ++k3) + { + int l7 = rand.chOffset(); + int k11 = rand.chOffset(); + int i15 = world.getHeight(pos.add(l7, 0, k11)).getY() * 2; + + if (i15 > 0) + { + int j18 = rand.zrange(i15); + BlockPos blockpos4; + BlockPos blockpos7; + + for (blockpos4 = pos.add(l7, j18, k11); blockpos4.getY() > 0; blockpos4 = blockpos7) + { + blockpos7 = blockpos4.down(); + + if (!world.isAirBlock(blockpos7)) + { + break; + } + } + + this.waterlilyGen.generate(world, rand, blockpos4); + } + } + + for (int l3 = 0; l3 < this.mushroomsPerChunk; ++l3) + { + if (rand.chance(4)) + { + int i8 = rand.chOffset(); + int l11 = rand.chOffset(); + BlockPos blockpos2 = world.getHeight(pos.add(i8, 0, l11)); + this.mushroomBrownGen.generate(world, rand, blockpos2); + } + + if (rand.chance(8)) + { + int j8 = rand.chOffset(); + int i12 = rand.chOffset(); + int j15 = world.getHeight(pos.add(j8, 0, i12)).getY() * 2; + + if (j15 > 0) + { + int k18 = rand.zrange(j15); + BlockPos blockpos5 = pos.add(j8, k18, i12); + this.mushroomRedGen.generate(world, rand, blockpos5); + } + } + } + + if (this.mushroomsPerChunk != -1 && rand.chance(4)) + { + int i4 = rand.chOffset(); + int k8 = rand.chOffset(); + int j12 = world.getHeight(pos.add(i4, 0, k8)).getY() * 2; + + if (j12 > 0) + { + int k15 = rand.zrange(j12); + this.mushroomBrownGen.generate(world, rand, pos.add(i4, k15, k8)); + } + } + + if (this.mushroomsPerChunk != -1 && rand.chance(8)) + { + int j4 = rand.chOffset(); + int l8 = rand.chOffset(); + int k12 = world.getHeight(pos.add(j4, 0, l8)).getY() * 2; + + if (k12 > 0) + { + int l15 = rand.zrange(k12); + this.mushroomRedGen.generate(world, rand, pos.add(j4, l15, l8)); + } + } + + for (int k4 = 0; k4 < this.reedsPerChunk; ++k4) + { + int i9 = rand.chOffset(); + int l12 = rand.chOffset(); + int i16 = world.getHeight(pos.add(i9, 0, l12)).getY() * 2; + + if (i16 > 0) + { + int l18 = rand.zrange(i16); + this.reedGen.generate(world, rand, pos.add(i9, l18, l12)); + } + } + + for (int l4 = 0; l4 < 10; ++l4) + { + int j9 = rand.chOffset(); + int i13 = rand.chOffset(); + int j16 = world.getHeight(pos.add(j9, 0, i13)).getY() * 2; + + if (j16 > 0) + { + int i19 = rand.zrange(j16); + this.reedGen.generate(world, rand, pos.add(j9, i19, i13)); + } + } + + if (rand.chance(32)) + { + int i5 = rand.chOffset(); + int k9 = rand.chOffset(); + int j13 = world.getHeight(pos.add(i5, 0, k9)).getY() * 2; + + if (j13 > 0) + { + int k16 = rand.zrange(j13); + (new WorldGenPumpkin()).generate(world, rand, pos.add(i5, k16, k9)); + } + } + + for (int j5 = 0; j5 < this.cactiPerChunk; ++j5) + { + int l9 = rand.chOffset(); + int k13 = rand.chOffset(); + int l16 = world.getHeight(pos.add(l9, 0, k13)).getY() * 2; + + if (l16 > 0) + { + int j19 = rand.zrange(l16); + this.cactusGen.generate(world, rand, pos.add(l9, j19, k13)); + } + } + } + + public void genTerrainBlocks(WorldServer worldIn, Random rand, ChunkPrimer chunkPrimerIn, int x, int z, double noiseVal) + { + this.generateBiomeTerrain(worldIn, rand, chunkPrimerIn, x, z, noiseVal); + } + + /** + * Given x, z coordinates, we count down all the y positions starting at height - 1 and working our way down. When we hit a + * non-air block, we replace it with this.topBlock (default grass, descendants may set otherwise), and then a + * relatively shallow layer of blocks of type this.fillerBlock (default dirt). A random set of blocks below y == 5 + * (but always including y == 0) is replaced with bedrock in Chunk(...). + * + * If we don't hit non-air until somewhat below sea level, we top with gravel and fill down with stone. + * + * If this.fillerBlock is red sand, we replace some of that with red sandstone. + */ + public final void generateBiomeTerrain(WorldServer worldIn, Random rand, ChunkPrimer chunkPrimerIn, int x, int z, double noiseVal) + { + int i = worldIn.getSeaLevel(); + State worldState = worldIn.dimension.getFiller(); + Block worldBlock = worldState.getBlock(); + State worldAlt = worldIn.dimension.getAltFiller1(); + State liquid = worldIn.getSurfaceLiquid(); + boolean freeze = liquid.getBlock().getMaterial() == Material.WATER; + State iblockstate = this.topBlock; + State iblockstate1 = this.fillerBlock; + int j = -1; + int k = (int)(noiseVal / 3.0D + 3.0D + rand.doublev() * 0.25D); + int l = x & 15; + int i1 = z & 15; + BlockPos.MutableBlockPos blockpos$mutableblockpos = new BlockPos.MutableBlockPos(); + + for (int j1 = chunkPrimerIn.height - 1; j1 >= 0; --j1) + { + State iblockstate2 = chunkPrimerIn.get(i1, j1, l); + + if (iblockstate2.getBlock() == Blocks.air) + { + j = -1; + } + else if (iblockstate2.getBlock() == worldBlock) + { + if (j == -1) + { + if (k <= 0) + { + iblockstate = null; + iblockstate1 = worldState; + } + else if (j1 >= i - 4 && j1 <= i + 1) + { + iblockstate = this.topBlock; + iblockstate1 = this.fillerBlock; + } + + if (j1 < i && (iblockstate == null || iblockstate.getBlock() == Blocks.air)) + { + if (freeze && World.ABSOLUTE_ZERO + worldIn.getTempOffset() + this.base.getTemperature(blockpos$mutableblockpos.set(x, j1, z)) <= 0.0F) + { + iblockstate = Blocks.ice.getState(); + } + else + { + iblockstate = liquid; + } + } + + j = k; + + if (j1 >= i - 1) + { + chunkPrimerIn.set(i1, j1, l, iblockstate); + } + else if (j1 < i - 7 - k) + { + iblockstate = null; + iblockstate1 = worldState; + chunkPrimerIn.set(i1, j1, l, worldAlt); + } + else + { + chunkPrimerIn.set(i1, j1, l, iblockstate1); + } + } + else if (j > 0) + { + --j; + chunkPrimerIn.set(i1, j1, l, iblockstate1); + + if (j == 0 && iblockstate1.getBlock() == Blocks.sand) + { + j = rand.zrange(4) + Math.max(0, j1 - 63); + iblockstate1 = iblockstate1.getValue(BlockSand.VARIANT) == BlockSand.EnumType.RED_SAND ? Blocks.stained_hardened_clay.getState().withProperty(BlockColored.COLOR, DyeColor.ORANGE) : Blocks.sandstone.getState(); //TODO: check! + } + } + } + } + } + + public boolean generateBigMushroom(AWorldServer worldIn, BlockPos pos, State state, Random rand) + { + worldIn.setBlockToAir(pos); + FeatureGenerator worldgenerator = null; + + if (state.getBlock() == Blocks.brown_mushroom) + { + worldgenerator = new WorldGenBigMushroom(Blocks.brown_mushroom_block); + } + else if (state.getBlock() == Blocks.red_mushroom) + { + worldgenerator = new WorldGenBigMushroom(Blocks.red_mushroom_block); + } + + if (worldgenerator != null && worldgenerator.generate((WorldServer)worldIn, rand, pos)) + { + return true; + } + else + { + worldIn.setState(pos, state, 3); + return false; + } + } + + private boolean isTypeAt(World worldIn, BlockPos pos, WoodType type) + { + State iblockstate = worldIn.getState(pos); + return iblockstate.getBlock() instanceof BlockSapling && ((BlockSapling)iblockstate.getBlock()).getWoodType() == type; + } + + private boolean isSameSaplingTypeIn(World worldIn, BlockPos pos, int xOff, int yOff, WoodType type) + { + return this.isTypeAt(worldIn, pos.add(xOff, 0, yOff), type) && this.isTypeAt(worldIn, pos.add(xOff + 1, 0, yOff), type) && this.isTypeAt(worldIn, pos.add(xOff, 0, yOff + 1), type) && this.isTypeAt(worldIn, pos.add(xOff + 1, 0, yOff + 1), type); + } + + public void generateTree(AWorldServer worldIn, BlockPos pos, State state, Random rand) + { + WoodType type = state.getBlock() instanceof BlockSapling ? ((BlockSapling)state.getBlock()).getWoodType() : WoodType.OAK; + State log = type == WoodType.CHERRY ? Blocks.cherry_log.getState() : // .withProperty(BlockNewLog.VARIANT, BlockPlanks.EnumType.CHERRY) : + (type == WoodType.MAPLE ? Blocks.maple_log.getState() /* .withProperty(BlockNewLog.VARIANT, BlockPlanks.EnumType.MAPLE) */ : Blocks.oak_log.getState()); + State leaves = type == WoodType.CHERRY ? Blocks.cherry_leaves.getState() : + (type == WoodType.MAPLE ? Blocks.maple_leaves.getState() : Blocks.oak_leaves.getState()); + FeatureGenerator worldgenerator = (FeatureGenerator)(rand.chance(10) ? new WorldGenBigTree(true, log, leaves) : new WorldGenBaseTree(true, log, leaves)); + int i = 0; + int j = 0; + boolean flag = false; +// leaves = leaves.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen()); + + switch (type) + { + case SPRUCE: + label114: + for (i = 0; i >= -1; --i) + { + for (j = 0; j >= -1; --j) + { + if (this.isSameSaplingTypeIn(worldIn, pos, i, j, WoodType.SPRUCE)) + { + worldgenerator = new WorldGenPine(false, rand.chance()); + flag = true; + break label114; + } + } + } + + if (!flag) + { + j = 0; + i = 0; + worldgenerator = new WorldGenTaiga2(true); + } + + break; + + case BIRCH: + worldgenerator = new WorldGenBirch(true, false); + break; + + case TIAN: + worldgenerator = new WorldGenBigTree(true, Blocks.tian_log.getState(), Blocks.tian_leaves.getState()) + .setHeightLimit(6, 20); + break; + + case JUNGLE: + State iblockstate = Blocks.jungle_log.getState(); // .withProperty(BlockOldLog.VARIANT, BlockPlanks.EnumType.JUNGLE); + State iblockstate1 = Blocks.jungle_leaves.getState(); // .withProperty(BlockOldLeaf.VARIANT, BlockPlanks.EnumType.JUNGLE); // .withProperty(BlockLeaves.CHECK_DECAY, Boolean.valueOf(false)); + label269: + + for (i = 0; i >= -1; --i) + { + for (j = 0; j >= -1; --j) + { + if (this.isSameSaplingTypeIn(worldIn, pos, i, j, WoodType.JUNGLE)) + { + worldgenerator = new WorldGenJungle(true, 10, 20, iblockstate, iblockstate1); + flag = true; + break label269; + } + } + } + + if (!flag) + { + j = 0; + i = 0; + worldgenerator = new WorldGenBaseTree(true, rand.range(4, 10), iblockstate, iblockstate1, false); + } + + break; + + case ACACIA: + worldgenerator = new WorldGenSavanna(true); + break; + + case DARK_OAK: + label390: + for (i = 0; i >= -1; --i) + { + for (j = 0; j >= -1; --j) + { + if (this.isSameSaplingTypeIn(worldIn, pos, i, j, WoodType.DARK_OAK)) + { + worldgenerator = new WorldGenDarkOak(true); + flag = true; + break label390; + } + } + } + + if (!flag) + { + return; + } + + case OAK: + case CHERRY: + case MAPLE: + } + + State iblockstate2 = Blocks.air.getState(); + + if (flag) + { + worldIn.setState(pos.add(i, 0, j), iblockstate2, 4); + worldIn.setState(pos.add(i + 1, 0, j), iblockstate2, 4); + worldIn.setState(pos.add(i, 0, j + 1), iblockstate2, 4); + worldIn.setState(pos.add(i + 1, 0, j + 1), iblockstate2, 4); + } + else + { + worldIn.setState(pos, iblockstate2, 4); + } + + if (!worldgenerator.generate((WorldServer)worldIn, rand, pos.add(i, 0, j))) + { + if (flag) + { + worldIn.setState(pos.add(i, 0, j), state, 4); + worldIn.setState(pos.add(i + 1, 0, j), state, 4); + worldIn.setState(pos.add(i, 0, j + 1), state, 4); + worldIn.setState(pos.add(i + 1, 0, j + 1), state, 4); + } + else + { + worldIn.setState(pos, state, 4); + } + } + } + + public void growGrass(AWorldServer worldIn, BlockPos pos, State state, Random rand) + { + BlockPos blockpos = pos.up(); + + for (int i = 0; i < 128; ++i) + { + BlockPos blockpos1 = blockpos; + int j = 0; + + while (true) + { + if (j >= i / 16) + { + if (worldIn.getState(blockpos1).getBlock() == Blocks.air) + { + if (rand.chance(8)) + { + BlockFlower.EnumFlowerType blockflower$enumflowertype = BIOMES[worldIn.getBiomeGenForCoords(blockpos1).id].pickRandomFlower(rand, blockpos1); + BlockFlower blockflower = blockflower$enumflowertype.getBlockType().getBlock(); + State iblockstate = blockflower.getState().withProperty(blockflower.getTypeProperty(), blockflower$enumflowertype); + + if (blockflower.canBlockStay(worldIn, blockpos1, iblockstate)) + { + worldIn.setState(blockpos1, iblockstate, 3); + } + } + else + { + State iblockstate1 = Blocks.tallgrass.getState().withProperty(BlockTallGrass.TYPE, BlockTallGrass.EnumType.GRASS); + + if (Blocks.tallgrass.canBlockStay(worldIn, blockpos1, iblockstate1)) + { + worldIn.setState(blockpos1, iblockstate1, 3); + } + } + } + + break; + } + + blockpos1 = blockpos1.add(rand.zrange(3) - 1, (rand.zrange(3) - 1) * rand.zrange(3) / 2, rand.zrange(3) - 1); + + if (worldIn.getState(blockpos1.down()).getBlock() != Blocks.grass || worldIn.getState(blockpos1).getBlock().isNormalCube()) + { + break; + } + + ++j; + } + } + } + + protected GenBiome createMutatedBiome(Biome base) + { + return new BiomeMutated(base, this); + } + + public Class getBiomeClass() + { + return this.getClass(); + } + + public boolean isEqualTo(GenBiome biome) + { + return biome == this ? true : (biome == null ? false : this.getBiomeClass() == biome.getBiomeClass()); + } + + public Temperature getTempCategory() + { + return this.base.temperature < -12.0f ? Temperature.COLD : (this.base.temperature < 20.0f ? Temperature.MEDIUM : Temperature.WARM); + } +} diff --git a/java/src/game/biome/RngSpawn.java b/server/src/main/java/server/biome/RngSpawn.java similarity index 77% rename from java/src/game/biome/RngSpawn.java rename to server/src/main/java/server/biome/RngSpawn.java index 25ba373..140c20b 100644 --- a/java/src/game/biome/RngSpawn.java +++ b/server/src/main/java/server/biome/RngSpawn.java @@ -1,7 +1,7 @@ -package game.biome; +package server.biome; -import game.entity.types.EntityLiving; -import game.rng.RngItem; +import common.entity.types.EntityLiving; +import common.rng.RngItem; public class RngSpawn extends RngItem { public final Class type; diff --git a/java/src/game/biome/Scaling.java b/server/src/main/java/server/biome/Scaling.java similarity index 96% rename from java/src/game/biome/Scaling.java rename to server/src/main/java/server/biome/Scaling.java index 6629d78..1dadf62 100644 --- a/java/src/game/biome/Scaling.java +++ b/server/src/main/java/server/biome/Scaling.java @@ -1,4 +1,4 @@ -package game.biome; +package server.biome; public enum Scaling { VARYING_LOW(0.1F, 0.2F), diff --git a/java/src/game/biome/Temperature.java b/server/src/main/java/server/biome/Temperature.java similarity index 71% rename from java/src/game/biome/Temperature.java rename to server/src/main/java/server/biome/Temperature.java index b9acbf2..4eda435 100644 --- a/java/src/game/biome/Temperature.java +++ b/server/src/main/java/server/biome/Temperature.java @@ -1,4 +1,4 @@ -package game.biome; +package server.biome; public enum Temperature { SEA, COLD, MEDIUM, WARM; diff --git a/java/src/game/clipboard/BlockTransform.java b/server/src/main/java/server/clipboard/BlockTransform.java similarity index 99% rename from java/src/game/clipboard/BlockTransform.java rename to server/src/main/java/server/clipboard/BlockTransform.java index f17f475..94a5c87 100755 --- a/java/src/game/clipboard/BlockTransform.java +++ b/server/src/main/java/server/clipboard/BlockTransform.java @@ -1,4 +1,4 @@ -package game.clipboard; +package server.clipboard; public class BlockTransform { private double m00, m01, m02, m03; diff --git a/java/src/game/clipboard/ClipboardBlock.java b/server/src/main/java/server/clipboard/ClipboardBlock.java similarity index 54% rename from java/src/game/clipboard/ClipboardBlock.java rename to server/src/main/java/server/clipboard/ClipboardBlock.java index 546b2fa..aa73d4d 100755 --- a/java/src/game/clipboard/ClipboardBlock.java +++ b/server/src/main/java/server/clipboard/ClipboardBlock.java @@ -1,12 +1,12 @@ -package game.clipboard; +package server.clipboard; -import game.nbt.NBTTagCompound; -import game.tileentity.TileEntity; -import game.world.State; +import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.world.State; public class ClipboardBlock { private State state; - private NBTTagCompound nbt; + private TagObject data; public ClipboardBlock(State state) { this.state = state; @@ -14,9 +14,9 @@ public class ClipboardBlock { public ClipboardBlock(State data, TileEntity tile) { this(data); - NBTTagCompound tag = new NBTTagCompound(); - tile.writeToNBT(tag); - this.nbt = tag; + TagObject tag = new TagObject(); + tile.writeTags(tag); + this.data = tag; } public State getState() { @@ -27,7 +27,7 @@ public class ClipboardBlock { this.state = state; } - public NBTTagCompound getNbtData() { - return this.nbt; + public TagObject getData() { + return this.data; } } diff --git a/java/src/game/clipboard/ClipboardPlacer.java b/server/src/main/java/server/clipboard/ClipboardPlacer.java similarity index 92% rename from java/src/game/clipboard/ClipboardPlacer.java rename to server/src/main/java/server/clipboard/ClipboardPlacer.java index 02dd51b..f69acfa 100755 --- a/java/src/game/clipboard/ClipboardPlacer.java +++ b/server/src/main/java/server/clipboard/ClipboardPlacer.java @@ -1,4 +1,4 @@ -package game.clipboard; +package server.clipboard; import java.util.Deque; import java.util.HashMap; @@ -8,19 +8,17 @@ import java.util.List; import java.util.Map; import java.util.Set; -import game.collect.Lists; - -import game.block.Block; -import game.block.BlockDoor; -import game.block.BlockRailBase; -import game.block.ITileEntityProvider; -import game.init.Blocks; -import game.init.ReorderRegistry; -import game.inventory.IInventory; -import game.tileentity.TileEntity; -import game.world.BlockPos; -import game.world.Vec3i; -import game.world.WorldServer; +import common.block.Block; +import common.block.ITileEntityProvider; +import common.block.artificial.BlockDoor; +import common.block.tech.BlockRailBase; +import common.collect.Lists; +import common.init.Blocks; +import common.inventory.IInventory; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.Vec3i; +import server.world.WorldServer; public class ClipboardPlacer { private static class BlockEntry { @@ -43,8 +41,6 @@ public class ClipboardPlacer { } public void setBlock(BlockPos location, ClipboardBlock block) { - if(location.getY() < 0 || location.getY() > 511) - return; Block type = block.getState().getBlock(); if (ReorderRegistry.shouldPlaceLast(type)) { // Place torches, etc. last diff --git a/java/src/game/init/ReorderRegistry.java b/server/src/main/java/server/clipboard/ReorderRegistry.java similarity index 95% rename from java/src/game/init/ReorderRegistry.java rename to server/src/main/java/server/clipboard/ReorderRegistry.java index 9e35668..3040b08 100755 --- a/java/src/game/init/ReorderRegistry.java +++ b/server/src/main/java/server/clipboard/ReorderRegistry.java @@ -1,17 +1,20 @@ -package game.init; +package server.clipboard; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; -import game.block.Block; -import game.block.BlockBed; -import game.block.BlockDoor; -import game.color.DyeColor; -import game.world.Facing; -import game.world.State; -import game.world.Vec3i; +import common.block.Block; +import common.block.artificial.BlockBed; +import common.block.artificial.BlockDoor; +import common.color.DyeColor; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.WoodType; +import common.util.Facing; +import common.util.Vec3i; +import common.world.State; public abstract class ReorderRegistry { private static final Set PLACE_LAST = new HashSet(); @@ -33,7 +36,7 @@ public abstract class ReorderRegistry { return STATE_ATTACH.get(state); } - static void register() { + public static void register() { for(WoodType wood : WoodType.values()) { PLACE_LAST.add(BlockRegistry.getRegisteredBlock(wood.getName() + "_sapling")); } @@ -51,6 +54,8 @@ public abstract class ReorderRegistry { PLACE_LAST.add(Blocks.red_mushroom_block); PLACE_LAST.add(Blocks.torch); PLACE_LAST.add(Blocks.fire); + PLACE_LAST.add(Blocks.soul_fire); + PLACE_LAST.add(Blocks.black_fire); PLACE_LAST.add(Blocks.redstone); PLACE_LAST.add(Blocks.wheat); PLACE_LAST.add(Blocks.ladder); diff --git a/java/src/game/clipboard/Rotation.java b/server/src/main/java/server/clipboard/Rotation.java similarity index 97% rename from java/src/game/clipboard/Rotation.java rename to server/src/main/java/server/clipboard/Rotation.java index f70cb46..bf66507 100755 --- a/java/src/game/clipboard/Rotation.java +++ b/server/src/main/java/server/clipboard/Rotation.java @@ -1,4 +1,4 @@ -package game.clipboard; +package server.clipboard; import java.util.function.Predicate; diff --git a/java/src/game/init/RotationRegistry.java b/server/src/main/java/server/clipboard/RotationRegistry.java similarity index 79% rename from java/src/game/init/RotationRegistry.java rename to server/src/main/java/server/clipboard/RotationRegistry.java index 52c8bc2..6716e84 100755 --- a/java/src/game/init/RotationRegistry.java +++ b/server/src/main/java/server/clipboard/RotationRegistry.java @@ -1,38 +1,34 @@ -package game.init; +package server.clipboard; import java.util.HashMap; import java.util.List; import java.util.Map; - import java.util.function.Predicate; -import game.collect.Lists; -import game.collect.Maps; -import game.block.Block; -import game.block.BlockDoor; -import game.block.BlockLever; -import game.block.BlockLog; -import game.block.BlockPortal; -import game.block.BlockQuartz; -import game.block.BlockRail; -import game.block.BlockRailBase; -import game.block.BlockRailDetector; -import game.block.BlockRailPowered; -import game.block.BlockRotatedPillar; -import game.clipboard.Rotation; -import game.clipboard.RotationValue; -import game.clipboard.Vector; -import game.properties.IProperty; -import game.properties.PropertyDirection; -import game.world.Facing; -import game.world.State; -import game.world.Vec3i; +import common.block.Block; +import common.block.BlockRotatedPillar; +import common.block.artificial.BlockDoor; +import common.block.artificial.BlockPortal; +import common.block.artificial.BlockQuartz; +import common.block.foliage.BlockLog; +import common.block.tech.BlockLever; +import common.block.tech.BlockRail; +import common.block.tech.BlockRailBase; +import common.block.tech.BlockRailDetector; +import common.block.tech.BlockRailPowered; +import common.collect.Lists; +import common.collect.Maps; +import common.properties.IProperty; +import common.properties.PropertyDirection; +import common.util.Facing; +import common.util.Vec3i; +import common.world.State; public abstract class RotationRegistry { private static final Map MAP = new HashMap(); - static void register() { - for(Block block : game.init.BlockRegistry.REGISTRY) { + public static void register() { + for(Block block : common.init.BlockRegistry.REGISTRY) { for(IProperty prop : block.getPropertyMap()) { Predicate predicate = null; if(prop == BlockDoor.FACING) { @@ -114,9 +110,8 @@ public abstract class RotationRegistry { } } if(!values.isEmpty()) { - int legacyId = game.init.BlockRegistry.getIdFromBlock(block); Rotation state = new Rotation(values.toArray(new RotationValue[values.size()]), predicate); -// Log.CONFIG.debug("Block " + game.init.BlockRegistry.REGISTRY.getNameForObject(block) + "/" + legacyId + " mask = " + String.format("0x%x", mask)); +// Log.CONFIG.debug("Block " + game.init.BlockRegistry.getNameFromBlock(block) + "/" + legacyId + " mask = " + String.format("0x%x", mask)); // for(RotationValue value : values) { // Log.CONFIG.debug(" meta " + value.data + " -> " + value.direction.toString()); // } diff --git a/java/src/game/clipboard/RotationValue.java b/server/src/main/java/server/clipboard/RotationValue.java similarity index 95% rename from java/src/game/clipboard/RotationValue.java rename to server/src/main/java/server/clipboard/RotationValue.java index c6b6f88..29870cf 100755 --- a/java/src/game/clipboard/RotationValue.java +++ b/server/src/main/java/server/clipboard/RotationValue.java @@ -1,4 +1,4 @@ -package game.clipboard; +package server.clipboard; public class RotationValue { public final byte mask; diff --git a/java/src/game/clipboard/Vector.java b/server/src/main/java/server/clipboard/Vector.java similarity index 99% rename from java/src/game/clipboard/Vector.java rename to server/src/main/java/server/clipboard/Vector.java index 084cf12..ef94edd 100755 --- a/java/src/game/clipboard/Vector.java +++ b/server/src/main/java/server/clipboard/Vector.java @@ -1,4 +1,4 @@ -package game.clipboard; +package server.clipboard; public class Vector implements Comparable { public static final Vector ZERO = new Vector(0, 0, 0); diff --git a/java/src/game/command/ArgCombiner.java b/server/src/main/java/server/command/ArgCombiner.java similarity index 83% rename from java/src/game/command/ArgCombiner.java rename to server/src/main/java/server/command/ArgCombiner.java index b893697..166c11b 100644 --- a/java/src/game/command/ArgCombiner.java +++ b/server/src/main/java/server/command/ArgCombiner.java @@ -1,4 +1,4 @@ -package game.command; +package server.command; public interface ArgCombiner { Object combine(T[] values); diff --git a/server/src/main/java/server/command/Argument.java b/server/src/main/java/server/command/Argument.java new file mode 100644 index 0000000..d933fd0 --- /dev/null +++ b/server/src/main/java/server/command/Argument.java @@ -0,0 +1,6 @@ +package server.command; + +import java.util.Map; + +public record Argument(Parameter parameter, int position, String[] inputs, Map values) { +} diff --git a/java/src/game/command/ArgumentParser.java b/server/src/main/java/server/command/ArgumentParser.java similarity index 94% rename from java/src/game/command/ArgumentParser.java rename to server/src/main/java/server/command/ArgumentParser.java index d961f69..cf3b4b9 100644 --- a/java/src/game/command/ArgumentParser.java +++ b/server/src/main/java/server/command/ArgumentParser.java @@ -1,9 +1,9 @@ -package game.command; +package server.command; import java.util.Collection; import java.util.List; -import game.collect.Lists; +import common.collect.Lists; public abstract class ArgumentParser { public static String[][] splitString(String str) { @@ -88,7 +88,7 @@ public abstract class ArgumentParser { public abstract Object parse(CommandEnvironment env, String input); public abstract Object getDefault(CommandEnvironment env); public abstract Collection getCompletions(CommandEnvironment env); - public abstract Class getTypeClass(); + public abstract Class getTypeClass(boolean required); public final String getName() { return this.name; diff --git a/server/src/main/java/server/command/ArgumentSplitter.java b/server/src/main/java/server/command/ArgumentSplitter.java new file mode 100644 index 0000000..b6aaa59 --- /dev/null +++ b/server/src/main/java/server/command/ArgumentSplitter.java @@ -0,0 +1,224 @@ +package server.command; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import common.collect.Lists; +import common.collect.Maps; +import common.collect.Sets; + +public record ArgumentSplitter(Map arguments, String command, CommandEnvironment env) { + private static String joinArgs(Iterable iter) { + StringBuilder sb = new StringBuilder("'"); + for(T obj : iter) { + if(sb.length() > 1) + sb.append("', '"); + sb.append(String.valueOf(obj)); + } + return sb.append("'").toString(); + } + + public static ArgumentSplitter parseArgs(CommandEnvironment env, String str, String[] argv, CachedExecutable cached) { + boolean lenient = str == null; + Map parameters = cached.parameters(); + List positionals = Lists.newArrayList(cached.positionals()); + // String[] argv = ArgumentParser.splitString(str); + Map args = Maps.newHashMap(); + int ppos = 0; + boolean parse = true; + int length = lenient ? argv.length - 1 : argv.length; + for(int z = 1; z < length; z++) { + String arg = argv[z]; + Parameter param = null; + boolean pos = false; + if(parse && arg.equals("--")) { + parse = false; + continue; + } + else if(parse && (arg.startsWith("--") || (arg.startsWith("-") && arg.length() == 2 && (arg.charAt(1) < '0' || arg.charAt(1) > '9')))) { + param = parameters.get(arg.substring(arg.startsWith("--") ? 2 : 1)); + if(param != null && param.positional() && !args.containsKey(param.name())) { + for(int n = 0; n < positionals.size(); n++) { + if(param == positionals.get(n)) { + positionals.remove(n); + break; + } + } + } + } + else if(ppos < positionals.size()) { + param = positionals.get(ppos++); + pos = true; + } + else { + throw new RunException("Position %d: Parameter '%s' ist überflüssig", z, arg); + } + if(param == null) + throw new RunException("Position %d: Argument '%s' ist unbekannt", z, arg); + if(args.containsKey(param.name())) + throw new RunException("Position %d: Parameter '%s' mehrfach angegeben", z, param.name()); + int nargs = param.parsers().size(); +// if(!pos) +// z += 1; + if(z + (pos ? 0 : 1) + nargs > length) + if(lenient) + return new ArgumentSplitter(args, str, env); + else if(nargs == 1 && param.name().equals(param.parsers().get(0).getName())) + throw new RunException("Position %d: Argument '%s' benötigt einen Parameter", z, param.name()); + else + throw new RunException("Position %d: Argument '%s' benötigt %d Parameter (%s)", z, param.name(), nargs, + joinArgs(param.parsers())); + Map params = Maps.newHashMapWithExpectedSize(nargs); + String[] inputs = new String[nargs + (pos ? 0 : 1)]; + int apos = 0; + for(int n = pos ? 0 : 1; n < nargs + (pos ? 0 : 1); n++) { + String par = inputs[n] = argv[z + n]; + ArgumentParser parser = param.parsers().get(apos); + if(parse && (par.startsWith("--") || (par.startsWith("-") && par.length() == 2 && (par.charAt(1) < '0' || par.charAt(1) > '9')))) + if(nargs == 1 && param.name().equals(parser.getName())) + throw new RunException("Position %d: Argument '%s': '%s' als Parameter verwendet", z + n, param.name(), par); + else + throw new RunException("Position %d: Argument '%s': '%s' als Parameter '%s' (#%d) verwendet", z + n, + param.name(), par, parser.getName(), apos + 1); + try { + params.put(parser.getName(), parser.parse(env, par)); + } + catch(Throwable e) { + if(nargs == 1 && param.name().equals(parser.getName())) + throw new RunException(e, "Position %d: Argument '%s': Parameter konnte nicht interpretiert werden", z + n, + param.name()); + else + throw new RunException(e, "Position %d: Argument '%s': Parameter '%s' (#%d) konnte nicht interpretiert werden", z + n, + param.name(), parser.getName(), apos + 1); + } + apos += 1; + } + if(!pos) + inputs[0] = arg; + args.put(param.name(), new Argument(param, z, inputs, params)); + z += nargs - (pos ? 1 : 0); + } + if(lenient) + return new ArgumentSplitter(args, str, env); + for(Parameter param : parameters.values()) { + if(!args.containsKey(param.name())) { + if(param.neededIn(env)) + throw new RunException("Argument '%s' muss angegeben werden", param.name()); + else if(param.parsers().isEmpty()) + continue; + Map params = Maps.newHashMapWithExpectedSize(param.parsers().size()); + for(ArgumentParser parser : param.parsers()) { + params.put(parser.getName(), parser.getDefault(env)); + } + args.put(param.name(), new Argument(param, -1, null, params)); + } + } + return new ArgumentSplitter(args, str, env); + } + + private static Iterable getParam(CommandEnvironment env, String[] argv, CachedExecutable cached, String last) { + ArgumentSplitter parsed; + try { + parsed = parseArgs(env, null, argv, cached); + } + catch(Throwable t) { + parsed = new ArgumentSplitter(Maps.newHashMap(), null, env); + } + Map parameters = cached.parameters(); + List positionals = Lists.newArrayList(cached.positionals()); + Set args = Sets.newHashSet(); + Executable exec = cached.executable(); + int ppos = 0; + boolean parse = true; + for(int z = 1; z < argv.length; z++) { + String arg = argv[z]; + Parameter param = null; + boolean pos = false; + if(z == argv.length - 1) { + if(ppos < positionals.size()) { + param = positionals.get(ppos); + if(param.parsers().isEmpty()) // np + return null; + Iterable custom = exec.getCustomCompletions(env, env.getExecutor(), parsed, param.name(), param.parsers().get(0).getName(), last); + return custom != null ? custom : param.parsers().get(0).getCompletions(env); + } + else { + return null; + } + } + else if(parse && arg.equals("--")) { + parse = false; + continue; + } + else if(parse && (arg.startsWith("--") || (arg.startsWith("-") && arg.length() == 2 && (arg.charAt(1) < '0' || arg.charAt(1) > '9')))) { + param = parameters.get(arg.substring(arg.startsWith("--") ? 2 : 1)); + if(param != null && param.positional() && !args.contains(param.name())) { + for(int n = 0; n < positionals.size(); n++) { + if(param == positionals.get(n)) { + positionals.remove(n); + break; + } + } + } + } + else if(ppos < positionals.size()) { + param = positionals.get(ppos++); + pos = true; + } + else { + return null; + } + if(param == null || args.contains(param.name())) + return null; + int nargs = param.parsers().size(); +// if(z + (pos ? 0 : 1) + nargs > argv.length - 1) { +// return param.getParsers().get(argv.length - z).getCompletions(env); +// } + int apos = 0; + for(int n = pos ? 0 : 1; n < nargs + (pos ? 0 : 1); n++) { + if(z + n == argv.length - 1) { + Iterable custom = exec.getCustomCompletions(env, env.getExecutor(), parsed, param.name(), param.parsers().get(apos).getName(), last); + return custom != null ? custom : param.parsers().get(apos).getCompletions(env); + } + String par = argv[z + n]; + if(parse && (par.startsWith("--") || (par.startsWith("-") && par.length() == 2 && (par.charAt(1) < '0' || par.charAt(1) > '9')))) + return null; + apos += 1; + } + args.add(param.name()); + z += nargs - (pos ? 1 : 0); + } + return null; + } + + public static Iterable parseComplete(CommandEnvironment env, String[] argv, CachedExecutable cached, String last) { + Iterable comp = getParam(env, argv, cached, last); + if(comp == null /* || comp.length == 0 */ ) { + Set params = Sets.newTreeSet(); + boolean all = last.startsWith("--"); + for(String param : cached.parameters().keySet()) { + if(all || param.length() == 1) + params.add(param.length() == 1 ? "-" + param : ("--" + param)); + } + return params; + } + return comp; + } + + public boolean has(String name) { + return this.arguments.containsKey(name); + } + + public T get(String name, String par) { + Argument arg = this.arguments.get(name); + if(arg == null) + return null; + Object value = arg.values().get(par); + return value == null ? null : (T)value; + } + + public T get(String name) { + return this.get(name, name); + } +} diff --git a/java/src/game/command/BooleanParser.java b/server/src/main/java/server/command/BooleanParser.java similarity index 53% rename from java/src/game/command/BooleanParser.java rename to server/src/main/java/server/command/BooleanParser.java index 600435c..fc0935f 100644 --- a/java/src/game/command/BooleanParser.java +++ b/server/src/main/java/server/command/BooleanParser.java @@ -1,11 +1,11 @@ -package game.command; +package server.command; public class BooleanParser extends EnumParser { public BooleanParser(String name, Boolean def) { super(name, Boolean.class, def, true, false); } - public Class getTypeClass() { - return this.hasDefault() ? boolean.class : Boolean.class; + public Class getTypeClass(boolean required) { + return this.hasDefault() || required ? boolean.class : Boolean.class; } } diff --git a/server/src/main/java/server/command/CachedExecutable.java b/server/src/main/java/server/command/CachedExecutable.java new file mode 100644 index 0000000..031ecfe --- /dev/null +++ b/server/src/main/java/server/command/CachedExecutable.java @@ -0,0 +1,63 @@ +package server.command; + +import java.lang.reflect.Method; +import java.util.List; +import java.util.Map; + +import common.collect.Lists; +import common.collect.Maps; + +public record CachedExecutable(Executable executable, Map parameters, List positionals, Method method) { + public static CachedExecutable cacheExecutable(Executable executable) { + Map parameters = Maps.newTreeMap(); + Map params = executable.getParameters(); + parameters.putAll(params); + Parameter[] positions = new Parameter[parameters.size()]; + int pos = -1; + for(Parameter param : params.values()) { + if(param.positional()) { + positions[param.position()] = param; + pos = param.position() > pos ? param.position() : pos; + } + if(param.shorthand()) + parameters.put("" + param.shortName(), param); + } + List positionals = Lists.newArrayList(); + for(int z = 0; z <= pos; z++) { + if(positions[z] == null) + throw new NullPointerException("positions[" + z + "]"); + positionals.add(positions[z]); + } + List> classes = Lists.newArrayList(CommandEnvironment.class, Executor.class); + for(Parameter param : executable.getParamList()) { + ArgCombiner combiner = param.combiner(); + if(combiner != null) { + classes.add(combiner.getTypeClass()); + continue; + } + if(param.parsers().isEmpty()) { + classes.add(boolean.class); + continue; + } + for(ArgumentParser parser : param.parsers()) { + classes.add(parser.getTypeClass(param.required())); + } + } + Method method; + try { + method = executable.getClass().getDeclaredMethod("exec", classes.toArray(new Class[classes.size()])); + } + catch(NoSuchMethodException e) { + throw new RuntimeException(e); + } + return new CachedExecutable(executable, parameters, positionals, method); + } + + public String name() { + return this.executable.getName(); + } + + public String toString() { + return this.executable.getName(); + } +} diff --git a/java/src/game/command/ColorParser.java b/server/src/main/java/server/command/ColorParser.java similarity index 92% rename from java/src/game/command/ColorParser.java rename to server/src/main/java/server/command/ColorParser.java index d8db5ff..0a3e49c 100644 --- a/java/src/game/command/ColorParser.java +++ b/server/src/main/java/server/command/ColorParser.java @@ -1,6 +1,6 @@ -package game.command; +package server.command; -import game.color.DyeColor; +import common.color.DyeColor; public class ColorParser extends IntParser { public ColorParser(String name, Integer def, Object ... completions) { diff --git a/java/src/game/command/Command.java b/server/src/main/java/server/command/Command.java similarity index 64% rename from java/src/game/command/Command.java rename to server/src/main/java/server/command/Command.java index cfb029e..25e0cb5 100644 --- a/java/src/game/command/Command.java +++ b/server/src/main/java/server/command/Command.java @@ -1,16 +1,18 @@ -package game.command; +package server.command; import java.lang.reflect.Array; import java.util.Collection; import java.util.List; import java.util.Map; -import game.collect.Lists; -import game.collect.Maps; - -import game.command.DoubleParser.DefType; -import game.world.Vec3; -import game.world.World; +import common.collect.Lists; +import common.collect.Maps; +import common.util.BlockPos; +import common.util.CharValidator; +import common.util.Vec3; +import common.world.World; +import server.command.DoubleParser.DefType; +import server.command.IntParser.CoordType; public abstract class Command implements Executable { private final String name; @@ -29,6 +31,11 @@ public abstract class Command implements Executable { return this; } + protected Command setParamsRequired() { + this.parReq = true; + return this; + } + protected Command addParameter(String name, ArgCombiner combiner, ArgumentParser ... parsers) { Parameter param = new Parameter(name, (char)0, this.parPos++, this.parReq, Lists.newArrayList(parsers), combiner); this.parameters.put(name, param); @@ -37,7 +44,7 @@ public abstract class Command implements Executable { } protected Command addParameter(String name, char shortName, ArgCombiner combiner, ArgumentParser ... parsers) { - Parameter param = new Parameter(name, shortName, -1, false, Lists.newArrayList(parsers), combiner); + Parameter param = new Parameter(name, shortName, -1, this.parReq, Lists.newArrayList(parsers), combiner); this.parameters.put(name, param); this.argList.add(param); return this; @@ -74,10 +81,29 @@ public abstract class Command implements Executable { } }, new DoubleParser("x", defaulted ? DefType.X : null, (double)(-World.MAX_SIZE), (double)World.MAX_SIZE, centered), - new DoubleParser("y", defaulted ? DefType.Y : null, 0.0, (double)World.HEIGHT, false), + new DoubleParser("y", defaulted ? DefType.Y : null, (double)(-World.MAX_SIZE_Y), (double)World.MAX_SIZE_Y, false), new DoubleParser("z", defaulted ? DefType.Z : null, (double)(-World.MAX_SIZE), (double)World.MAX_SIZE, centered)); } + protected Command addBlockPos(String name, boolean defaulted) { + return this.addParameter(name, new ArgCombiner() { + public BlockPos combine(Integer[] values) { + return new BlockPos(values[0], values[1], values[2]); + } + + public Class getTypeClass() { + return BlockPos.class; + } + + public Class getInputClass() { + return Integer.class; + } + }, + new IntParser("x", defaulted ? CoordType.X : null, -World.MAX_SIZE, World.MAX_SIZE), + new IntParser("y", defaulted ? CoordType.Y : null, -World.MAX_SIZE_Y, World.MAX_SIZE_Y), + new IntParser("z", defaulted ? CoordType.Z : null, -World.MAX_SIZE, World.MAX_SIZE)); + } + protected Command addWorld(String name, boolean defaulted) { return this.addParameter(new WorldParser(name, false, defaulted)); } @@ -154,36 +180,60 @@ public abstract class Command implements Executable { return this.addParameter(shortName, new TagParser(name, null)); } - protected Command addPlayer(String name, boolean defaulted) { - return this.addParameter(new PlayerParser(name, defaulted)); + protected Command addUser(String name, boolean defaulted, UserPolicy policy) { + return this.addParameter(new UserParser(name, defaulted, policy)); } - protected Command addPlayerEntity(String name, boolean defaulted) { - return this.addParameter(new PlayerEntityParser(name, defaulted)); + protected Command addPlayer(String name, boolean defaulted, UserPolicy policy) { + return this.addParameter(new PlayerParser(name, defaulted, policy)); } - protected Command addEntity(String name, boolean defaulted) { - return this.addParameter(new EntityParser(name, defaulted, false)); + protected Command addPlayerList(String name, boolean defaulted, UserPolicy policy) { + return this.addParameter(new PlayerListParser(name, defaulted, policy)); } - protected Command addEntity(String name, char shortName, boolean defaulted) { - return this.addParameter(shortName, new EntityParser(name, defaulted, false)); + protected Command addPlayerEntity(String name, boolean defaulted, UserPolicy policy) { + return this.addParameter(new PlayerEntityParser(name, defaulted, policy)); } - protected Command addEntityList(String name, boolean defaulted) { - return this.addParameter(new EntityListParser(name, defaulted, false)); + protected Command addPlayerItem(String name, boolean defaulted, UserPolicy policy) { + return this.addParameter(new PlayerItemParser(name, defaulted, policy)); } - protected Command addEntityList(String name, char shortName, boolean defaulted) { - return this.addParameter(shortName, new EntityListParser(name, defaulted, false)); + protected Command addPlayerItem(String name, char shortName, boolean defaulted, UserPolicy policy) { + return this.addParameter(shortName, new PlayerItemParser(name, defaulted, policy)); } - protected Command addLivingEntity(String name, boolean defaulted) { - return this.addParameter(new EntityParser(name, defaulted, true)); + protected Command addPlayerEntityList(String name, boolean defaulted, UserPolicy policy) { + return this.addParameter(new PlayerEntityListParser(name, defaulted, policy)); } - protected Command addLivingEntityList(String name, boolean defaulted) { - return this.addParameter(new EntityListParser(name, defaulted, true)); + protected Command addPlayerEntityList(String name, char shortName, boolean defaulted, UserPolicy policy) { + return this.addParameter(shortName, new PlayerEntityListParser(name, defaulted, policy)); + } + + protected Command addEntity(String name, boolean defaulted, UserPolicy policy) { + return this.addParameter(new EntityParser(name, defaulted, false, policy)); + } + + protected Command addEntity(String name, char shortName, boolean defaulted, UserPolicy policy) { + return this.addParameter(shortName, new EntityParser(name, defaulted, false, policy)); + } + + protected Command addEntityList(String name, boolean defaulted, UserPolicy policy) { + return this.addParameter(new EntityListParser(name, defaulted, false, policy)); + } + + protected Command addEntityList(String name, char shortName, boolean defaulted, UserPolicy policy) { + return this.addParameter(shortName, new EntityListParser(name, defaulted, false, policy)); + } + + protected Command addLivingEntity(String name, boolean defaulted, UserPolicy policy) { + return this.addParameter(new EntityParser(name, defaulted, true, policy)); + } + + protected Command addLivingEntityList(String name, boolean defaulted, UserPolicy policy) { + return this.addParameter(new EntityListParser(name, defaulted, true, policy)); } protected Command addString(String name, boolean allowEmpty, Object ... completions) { @@ -193,6 +243,18 @@ public abstract class Command implements Executable { protected Command addString(String name, boolean allowEmpty, StringCompleter completer) { return this.addParameter(new StringParser(name, null, allowEmpty, null, null, null, completer)); } + + protected Command addString(String name, String def, boolean allowEmpty, Object ... completions) { + return this.addParameter(new StringParser(name, def, allowEmpty, null, null, null, completions)); + } + + protected Command addString(String name, String def, boolean allowEmpty, StringCompleter completer) { + return this.addParameter(new StringParser(name, def, allowEmpty, null, null, null, completer)); + } + + protected Command addString(String name, boolean allowEmpty, Integer min, Integer max, CharValidator validator) { + return this.addParameter(new StringParser(name, null, allowEmpty, min, max, validator)); + } public Map getParameters() { return this.parameters; diff --git a/java/src/game/command/CommandEnvironment.java b/server/src/main/java/server/command/CommandEnvironment.java similarity index 63% rename from java/src/game/command/CommandEnvironment.java rename to server/src/main/java/server/command/CommandEnvironment.java index 458a2c2..4fa070c 100644 --- a/java/src/game/command/CommandEnvironment.java +++ b/server/src/main/java/server/command/CommandEnvironment.java @@ -1,4 +1,4 @@ -package game.command; +package server.command; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; @@ -6,14 +6,15 @@ import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; +import java.util.regex.Pattern; -import game.collect.Lists; -import game.collect.Maps; -import game.collect.Sets; -import game.Server; -import game.color.TextColor; -import game.command.commands.*; -import game.log.Log; +import common.collect.Lists; +import common.collect.Maps; +import common.collect.Sets; +import common.color.TextColor; +import common.log.Log; +import server.Server; +import server.command.commands.*; public class CommandEnvironment { private final Server server; @@ -32,10 +33,10 @@ public class CommandEnvironment { public void registerExecutable(Executable executable) { CachedExecutable cached = CachedExecutable.cacheExecutable(executable); - if(this.executables.containsKey(cached.getName())) - throw new IllegalStateException("Befehl " + cached.getName() + " ist bereits registriert"); - this.executables.put(cached.getName(), cached); - this.registerReplacer(cached.getName(), new Function() { + if(this.executables.containsKey(cached.name())) + throw new IllegalStateException("Befehl " + cached.name() + " ist bereits registriert"); + this.executables.put(cached.name(), cached); + this.registerReplacer(cached.name(), new Function() { public String apply(String str) { Object o; try { @@ -54,14 +55,14 @@ public class CommandEnvironment { public void registerReplacer(String var, Function function) { if(this.builtins.contains(var)) throw new IllegalStateException("Variable " + var + " ist bereits registriert"); - this.replacers.add(new PatternReplacer(var, true, function)); + this.replacers.add(new PatternReplacer(Pattern.compile("\\$\\((" + Pattern.quote(var) + "[^\\)]*)\\)"), function)); this.builtins.add(var); } public void registerVariable(String var, Variable variable) { if(this.builtins.contains(var)) throw new IllegalStateException("Variable " + var + " ist bereits registriert"); - this.replacers.add(new PatternReplacer(var, false, new Function() { + this.replacers.add(new PatternReplacer(Pattern.compile("\\$\\((" + Pattern.quote(var) + ")\\)"), new Function() { public String apply(String ign) { return variable.get(); } @@ -84,7 +85,7 @@ public class CommandEnvironment { private String substitute(String str) { StringBuffer sb = new StringBuffer(str); for(PatternReplacer replacer : this.replacers) { - replacer.replaceVar(sb); + replacer.replace(sb); } return sb.toString(); } @@ -114,12 +115,12 @@ public class CommandEnvironment { } ArgumentSplitter args = ArgumentSplitter.parseArgs(this, cmd, argv, cached); List params = Lists.newArrayList(this, this.currentExecutor); - for(Parameter param : cached.getExecutable().getParamList()) { - ArgCombiner combiner = param.getCombiner(); + for(Parameter param : cached.executable().getParamList()) { + ArgCombiner combiner = param.combiner(); if(combiner != null) { - Object[] data = (Object[])Array.newInstance(combiner.getInputClass(), param.getParsers().size()); + Object[] data = (Object[])Array.newInstance(combiner.getInputClass(), param.parsers().size()); for(int z = 0; z < data.length; z++) { - data[z] = args.getUnchecked(param.getName(), param.getParsers().get(z).getName()); + data[z] = args.get(param.name(), param.parsers().get(z).getName()); if(data[z] == null) { data = null; break; @@ -128,16 +129,16 @@ public class CommandEnvironment { params.add(data == null ? null : combiner.combine(data)); continue; } - if(param.getParsers().isEmpty()) { - params.add(args.hasArg(param.getName())); + if(param.parsers().isEmpty()) { + params.add(args.has(param.name())); continue; } - for(ArgumentParser parser : param.getParsers()) { - params.add(args.getUnchecked(param.getName(), parser.getName())); + for(ArgumentParser parser : param.parsers()) { + params.add(args.get(param.name(), parser.getName())); } } try { - o = cached.getMethod().invoke(cached.getExecutable(), params.toArray(new Object[params.size()])); + o = cached.method().invoke(cached.executable(), params.toArray(new Object[params.size()])); } catch(InvocationTargetException e) { if(e.getCause() instanceof RuntimeException) @@ -162,6 +163,7 @@ public class CommandEnvironment { } public void execute(String cmd, Executor exec) { + Executor prev = this.currentExecutor; this.currentExecutor = exec; try { this.execute(cmd, true); @@ -169,17 +171,17 @@ public class CommandEnvironment { catch(RunException e) { Throwable cause = e; do { - exec.logConsole(TextColor.RED + cause.getMessage()); + exec.log(TextColor.RED + cause.getMessage()); cause = cause.getCause(); } while(cause != null); } catch(Throwable t) { - exec.logConsole(TextColor.RED + "Fehler: %s", t.getMessage()); + exec.log(TextColor.RED + "Fehler: %s", t.getMessage()); Log.CONSOLE.error(t, "Fehler beim Ausführen von Befehl '%s'", cmd); } finally { - this.currentExecutor = null; + this.currentExecutor = prev; this.previousOutput = null; this.variables.clear(); } @@ -190,22 +192,18 @@ public class CommandEnvironment { List list = Lists.newArrayList(); try { String[][] cmds = ArgumentParser.splitString(cmd.endsWith(" ") ? cmd + "END" : cmd); - if(cmds.length == 0) - return list; - String[] argv = cmds[cmds.length - 1]; - if(argv.length == 0) - return list; - String param = cmd.endsWith(" ") ? "" : argv[argv.length - 1]; - Iterable comp; - if(argv.length > 1) { - int eq = argv[0].indexOf('='); - CachedExecutable cached = this.executables.get(eq >= 0 ? argv[0].substring(eq + 1) : argv[0]); - if(cached == null) - return list; - comp = ArgumentSplitter.parseComplete(this, argv, cached, param); - } - else { - comp = this.executables.keySet(); + Iterable comp = this.executables.keySet(); + String param = cmd; + if(cmds.length > 0 && cmds[cmds.length - 1].length > 0) { + String[] argv = cmds[cmds.length - 1]; + param = cmd.endsWith(" ") ? "" : argv[argv.length - 1]; + if(argv.length > 1) { + int eq = argv[0].indexOf('='); + CachedExecutable cached = this.executables.get(eq >= 0 ? argv[0].substring(eq + 1) : argv[0]); + if(cached == null) + return list; + comp = ArgumentSplitter.parseComplete(this, argv, cached, param); + } } for(String cmp : comp) { if(cmp.regionMatches(true, 0, param, 0, param.length())) @@ -214,7 +212,8 @@ public class CommandEnvironment { } catch(Throwable t) { list.clear(); - Log.CONSOLE.error(t, "Konnte Befehl '%s' nicht vervollständigen", cmd); + if(!(t instanceof RunException)) + Log.CONSOLE.error(t, "Konnte Befehl '%s' nicht vervollständigen", cmd); } finally { this.currentExecutor = null; @@ -223,22 +222,13 @@ public class CommandEnvironment { } public void registerDefaults() { - this.registerVariable("*", new Variable() { - public String get() { - return CommandEnvironment.this.currentExecutor.getExecId(); - } - }); - this.registerVariable("name", new Variable() { - public String get() { - return CommandEnvironment.this.currentExecutor.getExecName(); - } - }); this.registerVariable("!", new Variable() { public String get() { return CommandEnvironment.this.previousOutput == null ? null : CommandEnvironment.this.previousOutput.toString(); } }); + this.registerExecutable(new CommandHelp()); this.registerExecutable(new CommandSpawn()); this.registerExecutable(new CommandPotion()); this.registerExecutable(new CommandMilk()); @@ -254,7 +244,31 @@ public class CommandEnvironment { this.registerExecutable(new CommandWeather()); this.registerExecutable(new CommandKick()); this.registerExecutable(new CommandMessage()); - - this.registerExecutable(new CommandHelp(this)); + this.registerExecutable(new CommandShutdown()); + this.registerExecutable(new CommandPasswd()); + this.registerExecutable(new CommandPubkey()); + this.registerExecutable(new CommandPlayers()); + this.registerExecutable(new CommandUsers()); + this.registerExecutable(new CommandSave()); + this.registerExecutable(new CommandRegister()); + this.registerExecutable(new CommandRegkey()); + this.registerExecutable(new CommandFind()); + this.registerExecutable(new CommandBlock()); + this.registerExecutable(new CommandSeed()); + this.registerExecutable(new CommandSv()); + this.registerExecutable(new CommandClear()); + this.registerExecutable(new CommandEntity()); + this.registerExecutable(new CommandItem()); + this.registerExecutable(new CommandRunat()); + this.registerExecutable(new CommandRunas()); + this.registerExecutable(new CommandExp()); + this.registerExecutable(new CommandMagic()); + this.registerExecutable(new CommandGod()); + this.registerExecutable(new CommandNoclip()); + this.registerExecutable(new CommandRename()); + this.registerExecutable(new CommandRepair()); + this.registerExecutable(new CommandMore()); + this.registerExecutable(new CommandReturn()); + this.registerExecutable(new CommandDeathspot()); } } diff --git a/java/src/game/command/Completer.java b/server/src/main/java/server/command/Completer.java similarity index 86% rename from java/src/game/command/Completer.java rename to server/src/main/java/server/command/Completer.java index e09a484..3ec7b5c 100644 --- a/java/src/game/command/Completer.java +++ b/server/src/main/java/server/command/Completer.java @@ -1,4 +1,4 @@ -package game.command; +package server.command; import java.util.List; diff --git a/java/src/game/command/CompletingParser.java b/server/src/main/java/server/command/CompletingParser.java similarity index 75% rename from java/src/game/command/CompletingParser.java rename to server/src/main/java/server/command/CompletingParser.java index 247c740..154f7a4 100644 --- a/java/src/game/command/CompletingParser.java +++ b/server/src/main/java/server/command/CompletingParser.java @@ -1,9 +1,11 @@ -package game.command; +package server.command; import java.util.ArrayList; import java.util.Collection; import java.util.List; +import common.util.Identifyable; + public abstract class CompletingParser extends ArgumentParser { private final List defCompletions; @@ -11,7 +13,7 @@ public abstract class CompletingParser extends ArgumentParser { super(name); this.defCompletions = new ArrayList(completions.length); for(Object comp : completions) { - this.defCompletions.add(String.valueOf(comp)); + this.defCompletions.add(comp instanceof Identifyable id ? id.getName() : String.valueOf(comp)); } } diff --git a/java/src/game/command/DefaultingParser.java b/server/src/main/java/server/command/DefaultingParser.java similarity index 93% rename from java/src/game/command/DefaultingParser.java rename to server/src/main/java/server/command/DefaultingParser.java index 9accdaf..0b392c1 100644 --- a/java/src/game/command/DefaultingParser.java +++ b/server/src/main/java/server/command/DefaultingParser.java @@ -1,4 +1,4 @@ -package game.command; +package server.command; public abstract class DefaultingParser extends CompletingParser { private final Object def; diff --git a/java/src/game/command/DimensionParser.java b/server/src/main/java/server/command/DimensionParser.java similarity index 85% rename from java/src/game/command/DimensionParser.java rename to server/src/main/java/server/command/DimensionParser.java index f66ebf3..f941da9 100644 --- a/java/src/game/command/DimensionParser.java +++ b/server/src/main/java/server/command/DimensionParser.java @@ -1,10 +1,10 @@ -package game.command; +package server.command; import java.util.Collection; -import game.dimension.Dimension; -import game.init.UniverseRegistry; -import game.world.Position; +import common.dimension.Dimension; +import common.init.UniverseRegistry; +import common.util.Position; public class DimensionParser extends CompletingParser { private final boolean useSender; @@ -34,7 +34,7 @@ public class DimensionParser extends CompletingParser { if(!this.useSender) return null; Position pos = env.getExecutor().getExecPos(); - return pos == null ? null : UniverseRegistry.getDimension(pos.dim); + return pos == null ? null : UniverseRegistry.getDimension(pos.dim()); // if(dim == null) // throw new ScriptException("Unbekannte Dimension '%s'"); } @@ -43,7 +43,7 @@ public class DimensionParser extends CompletingParser { return UniverseRegistry.getWorldNames(); } - public Class getTypeClass() { + public Class getTypeClass(boolean required) { return Dimension.class; } } diff --git a/java/src/game/command/DoubleParser.java b/server/src/main/java/server/command/DoubleParser.java similarity index 73% rename from java/src/game/command/DoubleParser.java rename to server/src/main/java/server/command/DoubleParser.java index a629fa9..93a5a5c 100644 --- a/java/src/game/command/DoubleParser.java +++ b/server/src/main/java/server/command/DoubleParser.java @@ -1,10 +1,10 @@ -package game.command; +package server.command; import java.util.Collection; -import game.collect.Lists; -import game.world.BlockPos; -import game.world.Position; +import common.collect.Lists; +import common.util.BlockPos; +import common.util.Position; public class DoubleParser extends DefaultingParser { public static enum DefType { @@ -36,14 +36,21 @@ public class DoubleParser extends DefaultingParser { Double pre = this.defType != null && input.startsWith("~") ? this.getDefault(env) : null; input = pre != null ? input.substring(1) : input; double value; - try { - value = Double.parseDouble(input); + if(pre != null && input.isEmpty()) { + value = pre; } - catch(NumberFormatException e) { - throw new RunException("Ungültige Gleitkommazahl '%s'", input); + else { + try { + value = Double.parseDouble(input); + } + catch(NumberFormatException e) { + throw new RunException("Ungültige Gleitkommazahl '%s'", input); + } + if(this.center && pre == null && input.indexOf('.') < 0) + value += 0.5; + else if(pre != null) + value = pre + value; } - if(this.center && pre == null && input.indexOf('.') < 0) - value += 0.5; if(this.min != null && value < this.min) if(this.max != null) throw new RunException("Die Zahl muss im Bereich %f .. %f liegen, habe %f", this.min, this.max, value); @@ -62,21 +69,21 @@ public class DoubleParser extends DefaultingParser { if(this.defType != null) switch(this.defType) { case X: - return pos == null ? null : pos.x; + return pos == null ? null : pos.x(); case Y: - return pos == null ? null : pos.y; + return pos == null ? null : pos.y(); case Z: - return pos == null ? null : pos.z; + return pos == null ? null : pos.z(); case YAW: - return pos == null ? null : (double)pos.yaw; + return pos == null ? null : (double)pos.yaw(); case PITCH: - return pos == null ? null : (double)pos.pitch; + return pos == null ? null : (double)pos.pitch(); } return (Double)super.getDefault(env); } - public Class getTypeClass() { - return this.hasDefault() ? double.class : Double.class; + public Class getTypeClass(boolean required) { + return this.hasDefault() || required ? double.class : Double.class; } public Collection getCompletions(CommandEnvironment env) { diff --git a/java/src/game/command/EntityListParser.java b/server/src/main/java/server/command/EntityListParser.java similarity index 71% rename from java/src/game/command/EntityListParser.java rename to server/src/main/java/server/command/EntityListParser.java index b21f17b..1238856 100644 --- a/java/src/game/command/EntityListParser.java +++ b/server/src/main/java/server/command/EntityListParser.java @@ -1,50 +1,54 @@ -package game.command; +package server.command; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; -import game.collect.Lists; -import game.collect.Sets; -import game.entity.Entity; -import game.entity.EntityType; -import game.entity.types.EntityLiving; -import game.init.EntityRegistry; -import game.network.Player; -import game.world.WorldServer; +import common.collect.Lists; +import common.collect.Sets; +import common.entity.Entity; +import common.entity.EntityType; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.EntityRegistry; +import server.network.Player; +import server.world.WorldServer; public class EntityListParser extends EntityParser { - public EntityListParser(String name, boolean useSender, boolean livingOnly) { - super(name, useSender, livingOnly); + public EntityListParser(String name, boolean useSender, boolean livingOnly, UserPolicy policy) { + super(name, useSender, livingOnly, policy); } public Object parse(CommandEnvironment env, String input) { if(input.equals("**")) { List list = Lists.newArrayList(); + boolean found = false; for(WorldServer world : env.getServer().getWorlds()) { - if(this.livingOnly) { - for(Entity ent : world.getEntities()) { - if(ent instanceof EntityLiving) + for(Entity ent : world.getEntities()) { + if(!this.livingOnly || ent instanceof EntityLiving) { + found = true; + if(!(ent instanceof EntityNPC) || !((EntityNPC)ent).isPlayer() || this.policy.applies(env, env.getExecutor(), (Player)((EntityNPC)ent).connection)) list.add(ent); } } - else { - list.addAll(world.getEntities()); - } } if(list.isEmpty()) - throw new RunException(this.livingOnly ? "Keine lebendigen Objekte gefunden" : "Keine Objekte gefunden"); + throw new RunException(this.livingOnly ? "Keine " + (found ? "erlaubten" : "lebendigen") + " Objekte gefunden" : "Keine " + (found ? "erlaubten " : "") + "Objekte gefunden"); return list; } else if(input.equals("*")) { List list = Lists.newArrayList(); + boolean found = false; for(Player plr : env.getServer().getPlayers()) { - if(plr.getPresentEntity() != null) - list.add(plr.getPresentEntity()); + if(plr.getPresentEntity() != null) { + found = true; + if(this.policy.applies(env, env.getExecutor(), plr)) + list.add(plr.getPresentEntity()); + } } if(list.isEmpty()) - throw new RunException("Keine Spieler gefunden"); + throw new RunException("Keine " + (found ? "erlaubten " : "") + "Spieler gefunden"); return list; } Set> classes = Sets.newHashSet(); @@ -95,18 +99,22 @@ public class EntityListParser extends EntityParser { } List filtered = Lists.newArrayList(entities); boolean negateOnly = (living == null && player == null && types.isEmpty() && classes.isEmpty() && entities.isEmpty()); + boolean found = false; for(WorldServer world : env.getServer().getWorlds()) { for(Entity ent : world.getEntities()) { if((!this.livingOnly || ent instanceof EntityLiving) && (negateOnly || (living != null && types.isEmpty() && classes.isEmpty() && living == (ent instanceof EntityLiving)) || (player != null && types.isEmpty() && classes.isEmpty() && player == ent.isPlayer()) || types.contains(ent.getType()) || classes.contains(ent.getClass())) && (living == null || living == (ent instanceof EntityLiving)) && (player == null || player == ent.isPlayer()) && - !ntypes.contains(ent.getType()) && !nclasses.contains(ent.getClass()) && !nentities.contains(ent) && !entities.contains(ent)) - filtered.add(ent); + !ntypes.contains(ent.getType()) && !nclasses.contains(ent.getClass()) && !nentities.contains(ent) && !entities.contains(ent)) { + found = true; + if(!(ent instanceof EntityNPC) || !((EntityNPC)ent).isPlayer() || this.policy.applies(env, env.getExecutor(), (Player)((EntityNPC)ent).connection)) + filtered.add(ent); + } } } if(filtered.isEmpty()) - throw new RunException("Keine Objekte gefunden"); + throw new RunException("Keine " + (found ? "erlaubten " : "") + "Objekte gefunden"); return filtered; } @@ -117,7 +125,8 @@ public class EntityListParser extends EntityParser { public Collection getCompletions(CommandEnvironment env) { Collection comp = super.getCompletions(env); - comp.add("*"); + if(this.policy != UserPolicy.NO_PLAYERS) + comp.add("*"); for(Class clazz : EntityRegistry.getAllClasses()) { if(!this.livingOnly || EntityLiving.class.isAssignableFrom(clazz)) comp.add(EntityRegistry.getEntityString(clazz)); @@ -125,11 +134,13 @@ public class EntityListParser extends EntityParser { for(EntityType type : EntityType.values()) { comp.add(type.getName()); } - Collections.addAll(comp, "Player", "Living", "**"); + if(this.policy != UserPolicy.NO_PLAYERS) + comp.add("Player"); + Collections.addAll(comp, "Living", "**"); return comp; } - public Class getTypeClass() { + public Class getTypeClass(boolean required) { return List.class; } } diff --git a/java/src/game/command/EntityParser.java b/server/src/main/java/server/command/EntityParser.java similarity index 64% rename from java/src/game/command/EntityParser.java rename to server/src/main/java/server/command/EntityParser.java index ef53831..193c640 100644 --- a/java/src/game/command/EntityParser.java +++ b/server/src/main/java/server/command/EntityParser.java @@ -1,18 +1,20 @@ -package game.command; +package server.command; import java.util.Collection; import java.util.List; -import game.collect.Lists; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.world.WorldServer; +import common.collect.Lists; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import server.network.Player; +import server.world.WorldServer; public class EntityParser extends PlayerEntityParser { protected final boolean livingOnly; - public EntityParser(String name, boolean useSender, boolean livingOnly) { - super(name, useSender); + public EntityParser(String name, boolean useSender, boolean livingOnly, UserPolicy policy) { + super(name, useSender, policy); this.livingOnly = livingOnly; } @@ -32,6 +34,8 @@ public class EntityParser extends PlayerEntityParser { break; } } + if(entity instanceof EntityNPC && ((EntityNPC)entity).isPlayer() && !this.policy.applies(env, env.getExecutor(), (Player)((EntityNPC)entity).connection)) + throw new RunException(this.policy.getDenyMessage((Player)((EntityNPC)entity).connection)); } else { entity = (Entity)super.parse(env, input); @@ -49,12 +53,12 @@ public class EntityParser extends PlayerEntityParser { public Collection getCompletions(CommandEnvironment env) { Entity target = env.getExecutor().getPointedEntity(); - List comp = target == null || (this.livingOnly && !(target instanceof EntityLiving)) ? Lists.newArrayList() : Lists.newArrayList("#" + target.getId()); + List comp = target == null || (this.livingOnly && !(target instanceof EntityLiving)) || (target instanceof EntityNPC && ((EntityNPC)target).isPlayer() && !this.policy.applies(env, env.getExecutor(), (Player)((EntityNPC)target).connection)) ? Lists.newArrayList() : Lists.newArrayList("#" + target.getId()); comp.addAll(super.getCompletions(env)); return comp; } - public Class getTypeClass() { + public Class getTypeClass(boolean required) { return this.livingOnly ? EntityLiving.class : Entity.class; } } diff --git a/java/src/game/command/EnumParser.java b/server/src/main/java/server/command/EnumParser.java similarity index 77% rename from java/src/game/command/EnumParser.java rename to server/src/main/java/server/command/EnumParser.java index 356348d..2378fe8 100644 --- a/java/src/game/command/EnumParser.java +++ b/server/src/main/java/server/command/EnumParser.java @@ -1,8 +1,9 @@ -package game.command; +package server.command; import java.util.Map; -import game.collect.Maps; +import common.collect.Maps; +import common.util.Identifyable; public class EnumParser extends DefaultingParser { private final Class clazz; @@ -14,7 +15,7 @@ public class EnumParser extends DefaultingParser { for(T obj : iter) { if(sb.length() > 1) sb.append("', '"); - sb.append(String.valueOf(obj)); + sb.append(obj instanceof Identifyable id ? id.getName() : String.valueOf(obj)); } return sb.append("'").toString(); } @@ -24,7 +25,7 @@ public class EnumParser extends DefaultingParser { this.clazz = clazz; this.selections = selections; for(T o : selections) { - this.lookup.put(o.toString().toLowerCase(), o); + this.lookup.put(o instanceof Identifyable id ? id.getName() : o.toString().toLowerCase(), o); } } @@ -44,7 +45,7 @@ public class EnumParser extends DefaultingParser { return this.selections[id]; } - public Class getTypeClass() { + public Class getTypeClass(boolean required) { return this.clazz; } } diff --git a/server/src/main/java/server/command/Executable.java b/server/src/main/java/server/command/Executable.java new file mode 100644 index 0000000..13114d9 --- /dev/null +++ b/server/src/main/java/server/command/Executable.java @@ -0,0 +1,13 @@ +package server.command; + +import java.util.List; +import java.util.Map; + +public interface Executable { + Map getParameters(); + List getParamList(); + String getName(); + default Iterable getCustomCompletions(CommandEnvironment env, Executor exec, ArgumentSplitter parsed, String param, String parser, String arg) { + return null; + } +} diff --git a/server/src/main/java/server/command/Executor.java b/server/src/main/java/server/command/Executor.java new file mode 100644 index 0000000..e628987 --- /dev/null +++ b/server/src/main/java/server/command/Executor.java @@ -0,0 +1,31 @@ +package server.command; + +import common.entity.Entity; +import common.util.BlockPos; +import common.util.Position; + +public interface Executor { + void log(String msg); + Position getExecPos(); + void setExecPos(Position pos); + + default Entity getPointedEntity() { + return null; + } + + default BlockPos getPointedPosition() { + return null; + } + + default boolean isConsole() { + return false; + } + + default boolean isPlayer() { + return false; + } + + default void log(String fmt, Object ... args) { + this.log(String.format(fmt, args)); + } +} diff --git a/server/src/main/java/server/command/IntParser.java b/server/src/main/java/server/command/IntParser.java new file mode 100644 index 0000000..6db6b7e --- /dev/null +++ b/server/src/main/java/server/command/IntParser.java @@ -0,0 +1,97 @@ +package server.command; + +import java.util.Collection; + +import common.collect.Lists; +import common.util.BlockPos; +import common.util.ExtMath; +import common.util.Position; + +public class IntParser extends DefaultingParser { + public static enum CoordType { + X, Y, Z; + } + + private final CoordType defType; + private final Integer min; + private final Integer max; + private final boolean hex; + + public IntParser(String name, boolean hex, Integer def, Integer min, Integer max, Object ... completions) { + super(name, def, completions); + this.defType = null; + this.min = min; + this.max = max; + this.hex = hex; + } + + public IntParser(String name, CoordType type, Integer min, Integer max) { + super(name, null); + this.defType = type; + this.min = min; + this.max = max; + this.hex = false; + } + + public Integer parse(CommandEnvironment env, String input) { + Integer pre = this.defType != null && input.startsWith("~") ? this.getDefault(env) : null; + input = pre != null ? input.substring(1) : input; + int value; + if(pre != null && input.isEmpty()) { + value = pre; + } + else { + try { + value = Integer.parseInt(input, this.hex ? 16 : 10); + } + catch(NumberFormatException e) { + throw new RunException("Ungültige " + (this.hex ? "Hexadezimalzahl" : "Ganzzahl") + " '%s'", input); + } + if(pre != null) + value = pre + value; + } + if(this.min != null && value < this.min) + if(this.max != null) + throw new RunException("Die Zahl muss im Bereich %d .. %d liegen, habe %d", this.min, this.max, value); + else + throw new RunException("Die Zahl muss mindestens %d betragen, habe %d", this.min, value); + if(this.max != null && value > this.max) + if(this.min != null) + throw new RunException("Die Zahl muss im Bereich %d .. %d liegen, habe %d", this.min, this.max, value); + else + throw new RunException("Die Zahl darf höchstens %d betragen, habe %d", this.max, value); + return value; + } + + public Integer getDefault(CommandEnvironment env) { + Position pos = this.defType == null ? null : env.getExecutor().getExecPos(); + if(this.defType != null) + switch(this.defType) { + case X: + return pos == null ? null : ExtMath.floord(pos.x()); + case Y: + return pos == null ? null : ExtMath.floord(pos.y()); + case Z: + return pos == null ? null : ExtMath.floord(pos.z()); + } + return (Integer)super.getDefault(env); + } + + public Class getTypeClass(boolean required) { + return this.hasDefault() || required ? int.class : Integer.class; + } + + public Collection getCompletions(CommandEnvironment env) { + BlockPos pos = this.defType == null ? null : env.getExecutor().getPointedPosition(); + if(this.defType != null) + switch(this.defType) { + case X: + return pos == null ? null : Lists.newArrayList("" + pos.getX()); + case Y: + return pos == null ? null : Lists.newArrayList("" + pos.getY()); + case Z: + return pos == null ? null : Lists.newArrayList("" + pos.getZ()); + } + return super.getCompletions(env); + } +} diff --git a/java/src/game/command/LongParser.java b/server/src/main/java/server/command/LongParser.java similarity index 88% rename from java/src/game/command/LongParser.java rename to server/src/main/java/server/command/LongParser.java index e2452f2..ab7cf0e 100644 --- a/java/src/game/command/LongParser.java +++ b/server/src/main/java/server/command/LongParser.java @@ -1,4 +1,4 @@ -package game.command; +package server.command; public class LongParser extends DefaultingParser { private final Long min; @@ -31,7 +31,7 @@ public class LongParser extends DefaultingParser { return value; } - public Class getTypeClass() { - return this.hasDefault() ? long.class : Long.class; + public Class getTypeClass(boolean required) { + return this.hasDefault() || required ? long.class : Long.class; } } diff --git a/java/src/game/command/NonDefaultingParser.java b/server/src/main/java/server/command/NonDefaultingParser.java similarity index 90% rename from java/src/game/command/NonDefaultingParser.java rename to server/src/main/java/server/command/NonDefaultingParser.java index af97377..c06b105 100644 --- a/java/src/game/command/NonDefaultingParser.java +++ b/server/src/main/java/server/command/NonDefaultingParser.java @@ -1,4 +1,4 @@ -package game.command; +package server.command; public abstract class NonDefaultingParser extends CompletingParser { public NonDefaultingParser(String name, Object ... completions) { diff --git a/server/src/main/java/server/command/Parameter.java b/server/src/main/java/server/command/Parameter.java new file mode 100644 index 0000000..9c525ce --- /dev/null +++ b/server/src/main/java/server/command/Parameter.java @@ -0,0 +1,23 @@ +package server.command; + +import java.util.List; + +public record Parameter(String name, char shortName, int position, boolean required, List parsers, ArgCombiner combiner) { + public boolean positional() { + return this.position >= 0; + } + + public boolean shorthand() { + return this.shortName != 0; + } + + public boolean neededIn(CommandEnvironment env) { + if(!this.required) + return false; + for(ArgumentParser parser : this.parsers) { + if(parser.getDefault(env) == null) + return true; + } + return false; + } +} diff --git a/server/src/main/java/server/command/PatternReplacer.java b/server/src/main/java/server/command/PatternReplacer.java new file mode 100644 index 0000000..d209177 --- /dev/null +++ b/server/src/main/java/server/command/PatternReplacer.java @@ -0,0 +1,21 @@ +package server.command; + +import java.util.function.Function; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +public record PatternReplacer(Pattern pattern, Function function) { + public void replace(StringBuffer sb) { + String str = sb.toString(); + sb.delete(0, sb.length()); + Matcher matcher = this.pattern.matcher(str); + while(matcher.find()) { + String orig = matcher.group(1); + String rep = this.function.apply(orig); + if(rep == null) + throw new RunException("Variable '%s' konnte in diesem Kontext nicht ersetzt werden", orig); + matcher.appendReplacement(sb, rep); + } + matcher.appendTail(sb); + } +} diff --git a/java/src/game/command/PlayerEntityListParser.java b/server/src/main/java/server/command/PlayerEntityListParser.java similarity index 57% rename from java/src/game/command/PlayerEntityListParser.java rename to server/src/main/java/server/command/PlayerEntityListParser.java index 06335f6..cf0c39d 100644 --- a/java/src/game/command/PlayerEntityListParser.java +++ b/server/src/main/java/server/command/PlayerEntityListParser.java @@ -1,29 +1,33 @@ -package game.command; +package server.command; import java.util.Collection; import java.util.List; import java.util.Set; -import game.collect.Lists; -import game.collect.Sets; -import game.entity.Entity; -import game.entity.npc.EntityNPC; -import game.network.Player; +import common.collect.Lists; +import common.collect.Sets; +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import server.network.Player; public class PlayerEntityListParser extends PlayerEntityParser { - public PlayerEntityListParser(String name, boolean useSender) { - super(name, useSender); + public PlayerEntityListParser(String name, boolean useSender, UserPolicy policy) { + super(name, useSender, policy); } public Object parse(CommandEnvironment env, String input) { if(input.equals("*")) { List list = Lists.newArrayList(); + boolean found = false; for(Player plr : env.getServer().getPlayers()) { - if(plr.getPresentEntity() != null) - list.add(plr.getPresentEntity()); + if(plr.getPresentEntity() != null) { + found = true; + if(this.policy.applies(env, env.getExecutor(), plr)) + list.add(plr.getPresentEntity()); + } } if(list.isEmpty()) - throw new RunException("Keine Spieler gefunden"); + throw new RunException("Keine " + (found ? "erlaubten " : "") + "Spieler gefunden"); return list; } Set set = Sets.newHashSet(); @@ -41,12 +45,12 @@ public class PlayerEntityListParser extends PlayerEntityParser { } public Collection getCompletions(CommandEnvironment env) { - Collection comp = super.getCompletions(env); + Collection comp = Lists.newArrayList(super.getCompletions(env)); comp.add("*"); return comp; } - public Class getTypeClass() { + public Class getTypeClass(boolean required) { return List.class; } } diff --git a/java/src/game/command/PlayerEntityParser.java b/server/src/main/java/server/command/PlayerEntityParser.java similarity index 67% rename from java/src/game/command/PlayerEntityParser.java rename to server/src/main/java/server/command/PlayerEntityParser.java index 1239f06..2214ca4 100644 --- a/java/src/game/command/PlayerEntityParser.java +++ b/server/src/main/java/server/command/PlayerEntityParser.java @@ -1,11 +1,11 @@ -package game.command; +package server.command; -import game.entity.npc.EntityNPC; -import game.network.Player; +import common.entity.npc.EntityNPC; +import server.network.Player; public class PlayerEntityParser extends PlayerParser { - public PlayerEntityParser(String name, boolean useSender) { - super(name, useSender); + public PlayerEntityParser(String name, boolean useSender, UserPolicy policy) { + super(name, useSender, policy); } public Object parse(CommandEnvironment env, String input) { @@ -21,7 +21,7 @@ public class PlayerEntityParser extends PlayerParser { return net == null ? null : net.getPresentEntity(); } - public Class getTypeClass() { + public Class getTypeClass(boolean required) { return EntityNPC.class; } } diff --git a/server/src/main/java/server/command/PlayerItemParser.java b/server/src/main/java/server/command/PlayerItemParser.java new file mode 100644 index 0000000..6c77aa0 --- /dev/null +++ b/server/src/main/java/server/command/PlayerItemParser.java @@ -0,0 +1,27 @@ +package server.command; + +import common.entity.npc.EntityNPC; +import common.item.ItemStack; + +public class PlayerItemParser extends PlayerEntityParser { + public PlayerItemParser(String name, boolean useSender, UserPolicy policy) { + super(name, useSender, policy); + } + + public Object parse(CommandEnvironment env, String input) { + EntityNPC entity = (EntityNPC)super.parse(env, input); + ItemStack stack = entity.getHeldItem(); + if(stack == null) + throw new RunException("%s hält keinen Gegenstand in der Hand", entity.getCommandName()); + return stack; + } + + public Object getDefault(CommandEnvironment env) { + EntityNPC entity = (EntityNPC)super.getDefault(env); + return entity == null ? null : entity.getHeldItem(); + } + + public Class getTypeClass(boolean required) { + return ItemStack.class; + } +} diff --git a/java/src/game/command/PlayerListParser.java b/server/src/main/java/server/command/PlayerListParser.java similarity index 56% rename from java/src/game/command/PlayerListParser.java rename to server/src/main/java/server/command/PlayerListParser.java index a9a888f..1b8d6be 100644 --- a/java/src/game/command/PlayerListParser.java +++ b/server/src/main/java/server/command/PlayerListParser.java @@ -1,23 +1,27 @@ -package game.command; +package server.command; import java.util.Collection; import java.util.List; import java.util.Set; -import game.collect.Lists; -import game.collect.Sets; -import game.network.Player; +import common.collect.Filter; +import common.collect.Lists; +import common.collect.Sets; +import server.network.Player; public class PlayerListParser extends PlayerParser { - public PlayerListParser(String name, boolean useSender) { - super(name, useSender); + public PlayerListParser(String name, boolean useSender, UserPolicy policy) { + super(name, useSender, policy); } public Object parse(CommandEnvironment env, String input) { if(input.equals("*")) { if(env.getServer().getPlayers().isEmpty()) throw new RunException("Keine Spieler gefunden"); - return Lists.newArrayList(env.getServer().getPlayers()); + Collection filtered = Filter.filter(env.getServer().getPlayers(), player -> this.policy.applies(env, env.getExecutor(), player)); + if(filtered.isEmpty()) + throw new RunException("Keine erlaubten Spieler gefunden"); + return Lists.newArrayList(filtered); } Set set = Sets.newHashSet(); for(String tok : input.split(",", -1)) { @@ -34,12 +38,12 @@ public class PlayerListParser extends PlayerParser { } public Collection getCompletions(CommandEnvironment env) { - Collection comp = super.getCompletions(env); + Collection comp = Lists.newArrayList(super.getCompletions(env)); comp.add("*"); return comp; } - public Class getTypeClass() { + public Class getTypeClass(boolean required) { return List.class; } } diff --git a/server/src/main/java/server/command/PlayerParser.java b/server/src/main/java/server/command/PlayerParser.java new file mode 100644 index 0000000..f01f9b6 --- /dev/null +++ b/server/src/main/java/server/command/PlayerParser.java @@ -0,0 +1,38 @@ +package server.command; + +import java.util.Collection; + +import common.collect.Filter; +import server.network.Player; + +public class PlayerParser extends CompletingParser { + protected final boolean useSender; + protected final UserPolicy policy; + + public PlayerParser(String name, boolean useSender, UserPolicy policy) { + super(name); + this.useSender = useSender; + this.policy = policy; + } + + public Object parse(CommandEnvironment env, String input) { + Player net = env.getServer().getPlayer(input); + if(net == null) + throw new RunException("Spieler '%s' wurde nicht gefunden", input); + if(!this.policy.applies(env, env.getExecutor(), net)) + throw new RunException(this.policy.getDenyMessage(net)); + return net; + } + + public Object getDefault(CommandEnvironment env) { + return this.useSender && env.getExecutor().isPlayer() && this.policy.applies(env, env.getExecutor(), (Player)env.getExecutor()) ? (Player)env.getExecutor() : null; + } + + public Collection getCompletions(CommandEnvironment env) { + return Filter.filter(env.getServer().getAllPlayerNames(), user -> this.policy.applies(env, env.getExecutor(), env.getServer().getPlayer(user))); // add Lists.newArrayList if modifying! + } + + public Class getTypeClass(boolean required) { + return Player.class; + } +} diff --git a/java/src/game/command/RunException.java b/server/src/main/java/server/command/RunException.java similarity index 96% rename from java/src/game/command/RunException.java rename to server/src/main/java/server/command/RunException.java index ca97655..212af1c 100644 --- a/java/src/game/command/RunException.java +++ b/server/src/main/java/server/command/RunException.java @@ -1,4 +1,4 @@ -package game.command; +package server.command; public class RunException extends RuntimeException { public RunException(String desc) { diff --git a/java/src/game/command/StringCompleter.java b/server/src/main/java/server/command/StringCompleter.java similarity index 83% rename from java/src/game/command/StringCompleter.java rename to server/src/main/java/server/command/StringCompleter.java index 374bbb1..71cf5ce 100644 --- a/java/src/game/command/StringCompleter.java +++ b/server/src/main/java/server/command/StringCompleter.java @@ -1,4 +1,4 @@ -package game.command; +package server.command; import java.util.Collection; diff --git a/java/src/game/command/StringParser.java b/server/src/main/java/server/command/StringParser.java similarity index 95% rename from java/src/game/command/StringParser.java rename to server/src/main/java/server/command/StringParser.java index 1b3d636..5c2e35d 100644 --- a/java/src/game/command/StringParser.java +++ b/server/src/main/java/server/command/StringParser.java @@ -1,8 +1,8 @@ -package game.command; +package server.command; import java.util.Collection; -import game.util.CharValidator; +import common.util.CharValidator; public class StringParser extends DefaultingParser { private final boolean allowEmpty; @@ -53,7 +53,7 @@ public class StringParser extends DefaultingParser { return input; } - public Class getTypeClass() { + public Class getTypeClass(boolean required) { return String.class; } diff --git a/server/src/main/java/server/command/TagParser.java b/server/src/main/java/server/command/TagParser.java new file mode 100644 index 0000000..c24522f --- /dev/null +++ b/server/src/main/java/server/command/TagParser.java @@ -0,0 +1,24 @@ +package server.command; + +import common.tags.TagObject; + +public class TagParser extends DefaultingParser { + public TagParser(String name, TagObject def, Object ... completions) { + super(name, def, completions); + } + + public TagObject parse(CommandEnvironment env, String input) { + TagObject value; + try { + value = TagObject.parse(input); + } + catch(IllegalArgumentException e) { + throw new RunException(e, "Ungültiger Tag '%s'", input); + } + return value; + } + + public Class getTypeClass(boolean required) { + return TagObject.class; + } +} diff --git a/server/src/main/java/server/command/UserParser.java b/server/src/main/java/server/command/UserParser.java new file mode 100644 index 0000000..da291e9 --- /dev/null +++ b/server/src/main/java/server/command/UserParser.java @@ -0,0 +1,39 @@ +package server.command; + +import java.util.Collection; + +import common.collect.Filter; +import server.network.Player; +import server.network.User; + +public class UserParser extends CompletingParser { + protected final boolean useSender; + protected final UserPolicy policy; + + public UserParser(String name, boolean useSender, UserPolicy policy) { + super(name); + this.useSender = useSender; + this.policy = policy; + } + + public Object parse(CommandEnvironment env, String input) { + User user = env.getServer().getUser(input); + if(user == null) + throw new RunException("Nutzer '%s' wurde nicht gefunden", input); + if(!this.policy.applies(env, env.getExecutor(), user)) + throw new RunException(this.policy.getDenyMessage(user)); + return user; + } + + public Object getDefault(CommandEnvironment env) { + return this.useSender && env.getExecutor().isPlayer() && this.policy.applies(env, env.getExecutor(), (Player)env.getExecutor()) ? (Player)env.getExecutor() : null; + } + + public Collection getCompletions(CommandEnvironment env) { + return Filter.filter(env.getServer().getAllUserNames(), user -> this.policy.applies(env, env.getExecutor(), env.getServer().getUser(user))); // add Lists.newArrayList if modifying! + } + + public Class getTypeClass(boolean required) { + return User.class; + } +} diff --git a/server/src/main/java/server/command/UserPolicy.java b/server/src/main/java/server/command/UserPolicy.java new file mode 100644 index 0000000..d43890b --- /dev/null +++ b/server/src/main/java/server/command/UserPolicy.java @@ -0,0 +1,58 @@ +package server.command; + +import server.network.User; + +public enum UserPolicy { + EVERYONE("Wie haste denn das nu geschafft??!") { + public boolean applies(CommandEnvironment env, Executor exec, User user) { + return true; + } + }, + NO_PLAYERS("Objekt ist ein Spieler") { + public boolean applies(CommandEnvironment env, Executor exec, User user) { + return false; + } + }, + NON_ADMINS("Spieler ist ein Admin") { + public boolean applies(CommandEnvironment env, Executor exec, User user) { + return !user.isAdmin() || exec.isConsole(); + } + }, + NON_ADMINS_STRICT("Spieler ist ein Admin") { + public boolean applies(CommandEnvironment env, Executor exec, User user) { + return !user.isAdmin(); + } + }, + ADMINS("Spieler ist kein Admin") { + public boolean applies(CommandEnvironment env, Executor exec, User user) { + return user.isAdmin(); + } + }, + NOT_SELF("Diese Aktion kann nur an anderen Spielern ausgeführt werden") { + public boolean applies(CommandEnvironment env, Executor exec, User user) { + return user != exec; + } + }, + NON_ADMINS_NOT_SELF("Diese Aktion kann nur an anderen Spielern ohne Admin-Status ausgeführt werden") { + public boolean applies(CommandEnvironment env, Executor exec, User user) { + return (!user.isAdmin() || exec.isConsole()) && user != exec; + } + }, + NON_ADMINS_OR_SELF("Spieler ist ein Admin") { + public boolean applies(CommandEnvironment env, Executor exec, User user) { + return !user.isAdmin() || user == exec || exec.isConsole(); + } + }; + + private final String denyMessage; + + private UserPolicy(String denyMessage) { + this.denyMessage = denyMessage; + } + + public String getDenyMessage(User user) { + return String.format("%s: %s", user.getUser(), this.denyMessage); + } + + public abstract boolean applies(CommandEnvironment env, Executor exec, User user); +} diff --git a/java/src/game/command/Variable.java b/server/src/main/java/server/command/Variable.java similarity index 68% rename from java/src/game/command/Variable.java rename to server/src/main/java/server/command/Variable.java index 625aa39..46362ca 100644 --- a/java/src/game/command/Variable.java +++ b/server/src/main/java/server/command/Variable.java @@ -1,4 +1,4 @@ -package game.command; +package server.command; public interface Variable { public String get(); diff --git a/java/src/game/command/WorldParser.java b/server/src/main/java/server/command/WorldParser.java similarity index 87% rename from java/src/game/command/WorldParser.java rename to server/src/main/java/server/command/WorldParser.java index c2df3bf..520e2a0 100644 --- a/java/src/game/command/WorldParser.java +++ b/server/src/main/java/server/command/WorldParser.java @@ -1,12 +1,11 @@ -package game.command; +package server.command; import java.util.Collection; import java.util.List; -import game.collect.Lists; - -import game.dimension.Dimension; -import game.world.WorldServer; +import common.collect.Lists; +import common.dimension.Dimension; +import server.world.WorldServer; public class WorldParser extends DimensionParser { private final boolean loadedOnly; @@ -26,6 +25,8 @@ public class WorldParser extends DimensionParser { public WorldServer getDefault(CommandEnvironment env) { Dimension dim = (Dimension)super.getDefault(env); + if(dim == null) + return null; return this.loadedOnly ? env.getServer().getWorldNoLoad(dim.getDimensionId()) : env.getServer().getWorld(dim.getDimensionId()); // if(world == null) // throw new ScriptException("Dimension '%s' ist nicht geladen", dim.getFormattedName(false)); @@ -43,7 +44,7 @@ public class WorldParser extends DimensionParser { return super.getCompletions(env); } - public Class getTypeClass() { + public Class getTypeClass(boolean required) { return WorldServer.class; } } diff --git a/server/src/main/java/server/command/commands/CommandAdmin.java b/server/src/main/java/server/command/commands/CommandAdmin.java new file mode 100644 index 0000000..a5587c4 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandAdmin.java @@ -0,0 +1,23 @@ +package server.command.commands; + +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; +import server.network.Player; +import server.network.User; + +public class CommandAdmin extends Command { + public CommandAdmin() { + super("admin"); + + this.addUser("user", false, UserPolicy.NON_ADMINS_STRICT); + } + + public void exec(CommandEnvironment env, Executor exec, User user) { + user.setAdmin(true); + if(user.isOnline()) + ((Player)user).log("Du hast Administatorrechte von %s bekommen", exec.isPlayer() ? ((Player)exec).getUser() : "der Konsole"); + exec.log("%s ist jetzt ein Admin", user.getUser()); + } +} diff --git a/server/src/main/java/server/command/commands/CommandBlock.java b/server/src/main/java/server/command/commands/CommandBlock.java new file mode 100644 index 0000000..d0d3530 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandBlock.java @@ -0,0 +1,61 @@ +package server.command.commands; + +import java.util.Collection; +import common.init.BlockRegistry; +import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.world.State; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.command.StringCompleter; +import server.world.WorldServer; + +public class CommandBlock extends Command { + public CommandBlock() { + super("block"); + + this.addString("block", false, new StringCompleter() { + public Collection complete(CommandEnvironment env) { + return BlockRegistry.REGISTRY.getKeys(); + } + }); + this.addBlockPos("position", true); + this.addWorld("dim", true); + + this.setParamsOptional(); + this.addTag("tag", 't'); + } + + public Object exec(CommandEnvironment env, Executor exec, String block, BlockPos position, WorldServer world, TagObject tag) { + State state = BlockRegistry.getFromIdName(block, null); + if(state == null) + throw new RunException("Block '%s' existiert nicht", block); + boolean success = world.setState(position, state); + if(tag != null) { + TileEntity tile = world.getTileEntity(position); + if(tile != null) { + TagObject te = new TagObject(); + tile.writeTags(te); + tag.setString("id", te.getString("id")); + tag.setInt("x", position.getX()); + tag.setInt("y", position.getY()); + tag.setInt("z", position.getZ()); + te.merge(tag); + TileEntity newTile = TileEntity.createAndLoadEntity(te); + if(newTile != null) { + world.removeTileEntity(position); + world.setTileEntity(position, newTile); + success = true; + } + } + } + if(success) + exec.log("%s bei %d, %d, %d in %s gesetzt", state.getBlock().getDisplay(), position.getX(), position.getY(), position.getZ(), world.dimension.getFormattedName(false)); + else + exec.log("Block wurde nicht verändert"); + return success; + } +} diff --git a/server/src/main/java/server/command/commands/CommandClear.java b/server/src/main/java/server/command/commands/CommandClear.java new file mode 100644 index 0000000..b221069 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandClear.java @@ -0,0 +1,40 @@ +package server.command.commands; + +import java.util.List; + +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; + +public class CommandClear extends Command { + public CommandClear() { + super("clear"); + + this.addLivingEntityList("entities", true, UserPolicy.NON_ADMINS_OR_SELF); + } + + public Object exec(CommandEnvironment env, Executor exec, List entities) { + int done = 0; + for(EntityLiving entity : entities) { + if(entity instanceof EntityNPC) { + if(entity.isPlayer()) { + ((EntityNPC)entity).inventory.clearItems(); + } + else { + ((EntityNPC)entity).getExtendedInventory().clear(); + for(int z = 0; z < 5; z++) { + ((EntityNPC)entity).setItem(z, null); + } + } + exec.log("Inventar von %s gelöscht", entity.getCommandName()); + done++; + } + } + if(done > 1) + exec.log("Inventar von %d Objekten gelöscht", done); + return done; + } +} diff --git a/server/src/main/java/server/command/commands/CommandDeathspot.java b/server/src/main/java/server/command/commands/CommandDeathspot.java new file mode 100644 index 0000000..dcdff13 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandDeathspot.java @@ -0,0 +1,35 @@ +package server.command.commands; + +import java.util.List; + +import common.entity.Entity; +import common.entity.npc.EntityNPC; +import common.init.UniverseRegistry; +import common.util.Position; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.command.UserPolicy; +import server.network.Player; + +public class CommandDeathspot extends Command { + public CommandDeathspot() { + super("deathspot"); + + this.addPlayerEntity("player", true, UserPolicy.NON_ADMINS_OR_SELF); + + this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); + } + + public Object exec(CommandEnvironment env, Executor exec, EntityNPC player, List entities) { + Position pos = ((Player)player.connection).getLastDeath(); + if(pos == null) + throw new RunException("%s hat keinen letzten Todespunkt", player.getCommandName()); + for(Entity entity : entities) { + entity.teleport(pos); + exec.log("%s zum Todespunkt von %s (%d, %d, %d in %s) teleportiert", entity.getCommandName(), player.getCommandName(), (int)pos.x(), (int)pos.y(), (int)pos.z(), UniverseRegistry.getDimension(pos.dim()).getFormattedName(false)); + } + return entities.size(); + } +} diff --git a/server/src/main/java/server/command/commands/CommandEntity.java b/server/src/main/java/server/command/commands/CommandEntity.java new file mode 100644 index 0000000..377c5aa --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandEntity.java @@ -0,0 +1,46 @@ +package server.command.commands; + +import java.util.List; + +import common.entity.Entity; +import common.tags.TagObject; +import common.util.BlockPos; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; + +public class CommandEntity extends Command { + public CommandEntity() { + super("entity"); + + this.addEntityList("entities", false, UserPolicy.NO_PLAYERS); + this.setParamsOptional(); + this.addTag("tag"); + } + + public Object exec(CommandEnvironment env, Executor exec, List entities, TagObject tag) { + int done = 0; + for(Entity entity : entities) { + if(entity.isEntityAlive()) { + BlockPos pos = entity.getPosition(); + TagObject etag = new TagObject(); + entity.writeTags(etag); + if(tag == null) { + exec.log("************************************************************"); + exec.log("Daten von %s bei %d, %d, %d in %s:", entity.getCommandName(), pos.getX(), pos.getY(), pos.getZ(), entity.worldObj.dimension.getFormattedName(false)); + exec.log(etag.format(4)); + } + else { + etag.merge(tag); + entity.readTags(etag); + exec.log("Daten von %s bei %d, %d, %d in %s geändert", entity.getCommandName(), pos.getX(), pos.getY(), pos.getZ(), entity.worldObj.dimension.getFormattedName(false)); + } + done++; + } + } + if(tag != null && done > 1) + exec.log("Daten von %d Objekten geändert", done); + return done; + } +} diff --git a/server/src/main/java/server/command/commands/CommandExp.java b/server/src/main/java/server/command/commands/CommandExp.java new file mode 100644 index 0000000..359ce85 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandExp.java @@ -0,0 +1,44 @@ +package server.command.commands; + +import java.util.List; + +import common.entity.npc.EntityNPC; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; + +public class CommandExp extends Command { + public CommandExp() { + super("exp"); + + this.setParamsOptional(); + this.addInt("points", 1, Integer.MAX_VALUE); + this.addFlag("reset", 'r'); + this.setParamsRequired(); + this.addPlayerEntityList("players", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); + } + + public void exec(CommandEnvironment env, Executor exec, Integer points, boolean reset, List players) { + for(EntityNPC player : players) { + if(points == null && !reset) { + exec.log("Erfahrung von %s: Level %d, %d/%d (%d Punkte)", player.getCommandName(), player.experienceLevel, (int)((float)player.xpBarCap() * player.experience), player.xpBarCap(), player.experienceTotal); + } + else if(reset) { + player.setExperience(points == null ? 0 : points); + exec.log("Erfahrung von %s " + (points == null ? "zurückgesetzt" : "auf %d Punkte gesetzt (Level %d)"), player.getCommandName(), player.experienceTotal, player.experienceLevel); + } + else { + int level = player.experienceLevel; + player.addExperience(points); + exec.log("%d Erfahrungspunkte an %s gegeben" + (player.experienceLevel != level ? ", ist jetzt Level %d" : ""), points, player.getCommandName(), player.experienceLevel); + } + } + if(players.size() > 1) { + if(reset) + exec.log("Erfahrung von %d Spielern " + (points == null ? "zurückgesetzt" : "auf %d Punkte gesetzt"), players.size(), points); + else if(points != null) + exec.log("%d Erfahrungspunkte an %d Spieler gegeben", points * players.size(), players.size()); + } + } +} diff --git a/server/src/main/java/server/command/commands/CommandFind.java b/server/src/main/java/server/command/commands/CommandFind.java new file mode 100644 index 0000000..99e8d27 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandFind.java @@ -0,0 +1,32 @@ +package server.command.commands; + +import java.util.List; + +import common.entity.Entity; +import common.util.BlockPos; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; + +public class CommandFind extends Command { + public CommandFind() { + super("find"); + + this.addEntityList("entities", false, UserPolicy.EVERYONE); + } + + public Object exec(CommandEnvironment env, Executor exec, List entities) { + int done = 0; + for(Entity entity : entities) { + if(entity.isEntityAlive()) { + BlockPos pos = entity.getPosition(); + exec.log("%s bei %d, %d, %d in %s gefunden", entity.getCommandName(), pos.getX(), pos.getY(), pos.getZ(), entity.worldObj.dimension.getFormattedName(false)); + done++; + } + } + if(done > 1) + exec.log("%d Objekte gefunden", done); + return done; + } +} diff --git a/server/src/main/java/server/command/commands/CommandGod.java b/server/src/main/java/server/command/commands/CommandGod.java new file mode 100644 index 0000000..ef5c51f --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandGod.java @@ -0,0 +1,35 @@ +package server.command.commands; + +import java.util.List; + +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.potion.Potion; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; + +public class CommandGod extends Command { + public CommandGod() { + super("god"); + + this.addPlayerEntityList("players", true, UserPolicy.NON_ADMINS_OR_SELF); + this.setParamsOptional(); + this.addFlag("remove", 'r'); + this.addFlag("quiet", 'q'); + } + + public void exec(CommandEnvironment env, Executor exec, List players, boolean remove, boolean quiet) { + remove = !remove && exec.isPlayer() && players.size() == 1 && players.get(0).connection == exec ? players.get(0).hasEffect(Potion.HASTE) && players.get(0).getEffect(Potion.HASTE).getAmplifier() == 255 : remove; + for(EntityNPC player : players) { + player.setGodMode(!remove); + if(!quiet) + player.connection.addFeed(!remove ? (TextColor.GREEN + "Statuseffekte wurden hinzugefügt") : (TextColor.RED + "Statuseffekte wurden entfernt")); + if(quiet || player.connection != exec) + exec.log("Statuseffekte " + (!remove ? "an %s gegeben" : "von %s entfernt"), player.getCommandName()); + } + if(players.size() > 1) + exec.log("Statuseffekte " + (!remove ? "an %d Spieler gegeben" : "von %d Spielern entfernt"), players.size()); + } +} diff --git a/server/src/main/java/server/command/commands/CommandHelp.java b/server/src/main/java/server/command/commands/CommandHelp.java new file mode 100644 index 0000000..8f21e7f --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandHelp.java @@ -0,0 +1,71 @@ +package server.command.commands; + +import java.util.Collection; +import java.util.List; +import java.util.Map.Entry; +import java.util.function.Function; + +import common.collect.Lists; +import common.util.Util; +import server.command.ArgumentParser; +import server.command.CachedExecutable; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.Parameter; +import server.command.RunException; +import server.command.StringCompleter; + +public class CommandHelp extends Command { + public CommandHelp() { + super("help"); + + this.setParamsOptional(); + this.addString("command", false, new StringCompleter() { + public Collection complete(CommandEnvironment env) { + return env.getExecutables().keySet(); + } + }); + } + + private void formatCommand(CommandEnvironment env, Executor exec, CachedExecutable cmd) { + List list = Lists.newArrayList(); + for(Entry entry : cmd.parameters().entrySet()) { + Parameter param = entry.getValue(); + boolean required = param.neededIn(env); + if(entry.getKey().length() == 1 && !param.positional() && param.shorthand()) { + list.add((required ? "<" : "[") + "-" + param.shortName() + (param.parsers().isEmpty() ? " (" + param.name() + ")" : (param.parsers().size() == 1 && + param.parsers().get(0).getName().equals(param.name()) ? " <" + param.name() + ">" : + " (" + param.name() + ")" + Util.buildLines(" ", new Function() { + public String apply(ArgumentParser parser) { + return "<" + parser.getName() + ">"; + } + }, param.parsers()))) + (required ? ">" : "]")); + } + } + for(Parameter param : cmd.positionals()) { + boolean required = param.neededIn(env); + list.add((required ? "<" : "[") + (param.parsers().size() == 1 && + param.parsers().get(0).getName().equals(param.name()) ? param.name() : + "(" + param.name() + ") " + Util.buildLines(" ", new Function() { + public String apply(ArgumentParser parser) { + return "<" + parser.getName() + ">"; + } + }, param.parsers())) + (required ? ">" : "]")); + } + exec.log("%s %s", cmd.name(), Util.buildLines(" ", list)); + } + + public void exec(CommandEnvironment env, Executor exec, String command) { + if(command == null) { + for(CachedExecutable cmd : env.getExecutables().values()) { + this.formatCommand(env, exec, cmd); + } + return; + } + CachedExecutable cmd = env.getExecutables().get(command); + if(cmd == null) + throw new RunException("Befehl '%s' ist nicht bekannt", command); + this.formatCommand(env, exec, cmd); + } +} diff --git a/server/src/main/java/server/command/commands/CommandItem.java b/server/src/main/java/server/command/commands/CommandItem.java new file mode 100644 index 0000000..00797d0 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandItem.java @@ -0,0 +1,63 @@ +package server.command.commands; + +import java.util.Collection; +import java.util.List; + +import common.entity.npc.EntityNPC; +import common.init.ItemRegistry; +import common.item.ItemStack; +import common.tags.TagObject; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.command.StringCompleter; +import server.command.UserPolicy; + +public class CommandItem extends Command { + public CommandItem() { + super("item"); + + this.addString("item", false, new StringCompleter() { + public Collection complete(CommandEnvironment env) { + return ItemRegistry.REGISTRY.getKeys(); + } + }); + this.setParamsOptional(); + this.addInt("amount", 1, ItemStack.MAX_SIZE, 1); + this.addTag("tag", 't'); + this.setParamsRequired(); + this.addPlayerEntityList("players", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); + } + + public Object exec(CommandEnvironment env, Executor exec, String item, int amount, TagObject tag, List players) { + ItemStack stack = ItemRegistry.getFromIdName(item, null); + if(stack == null) + throw new RunException("Gegenstand '%s' existiert nicht", item); + stack.setTagCompound(tag); + int done = 0; + int given = 0; + for(EntityNPC player : players) { + int total = amount; + while(total > 0) { + int added = Math.min(total, stack.getMaxStackSize()); + ItemStack st = stack.copy(); + st.size = added; + player.inventory.addItemStackToInventory(st); + added -= st.size; + if(added <= 0) + break; + total -= added; + } + total = amount - total; + if(total <= 0) + continue; + exec.log("%d * %s zum Inventar von %s hinzugefügt", total, stack.getDisplayName(), player.getCommandName()); + done++; + given += total; + } + if(done > 1) + exec.log("%d * %s an %d Spieler verteilt", given, stack.getDisplayName(), done); + return given; + } +} diff --git a/server/src/main/java/server/command/commands/CommandKick.java b/server/src/main/java/server/command/commands/CommandKick.java new file mode 100644 index 0000000..1b88406 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandKick.java @@ -0,0 +1,26 @@ +package server.command.commands; + +import java.util.List; + +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; +import server.network.Player; + +public class CommandKick extends Command { + public CommandKick() { + super("kick"); + + this.addPlayerList("player", false, UserPolicy.NON_ADMINS_NOT_SELF); + this.setParamsOptional(); + this.addString("message", "Du wurdest vom Server geworfen", false); + } + + public void exec(CommandEnvironment env, Executor exec, List players, String message) { + for(Player player : players) { + player.disconnect(message); + exec.log("%s wurde vom Server geworfen", player.getUser()); + } + } +} diff --git a/server/src/main/java/server/command/commands/CommandMagic.java b/server/src/main/java/server/command/commands/CommandMagic.java new file mode 100644 index 0000000..6c1df47 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandMagic.java @@ -0,0 +1,51 @@ +package server.command.commands; + +import java.util.Map.Entry; + +import common.enchantment.Enchantment; +import common.enchantment.EnchantmentHelper; +import common.item.ItemStack; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.command.UserPolicy; + +public class CommandMagic extends Command { + public CommandMagic() { + super("magic"); + + this.addEnum("enchantment", Enchantment.class, Enchantment.values()); + this.setParamsOptional(); + this.addInt("level", 1, 32767); + this.addFlag("remove", 'r'); + this.addFlag("force", 'f'); + this.setParamsRequired(); + this.addPlayerItem("player", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); + } + + public void exec(CommandEnvironment env, Executor exec, Enchantment ench, Integer level, boolean remove, boolean force, ItemStack stack) { + if(remove) { + int current = EnchantmentHelper.getEnchantmentLevel(ench, stack); + if(current == 0) + throw new RunException("%s hat die Verzauberung %s nicht", stack.getDisplayName(), ench.getDisplay()); + stack.removeEnchantment(ench); + exec.log("Verzauberung %s wurde von %s entfernt", ench.getFormattedName(current), stack.getDisplayName()); + return; + } + level = level == null ? ench.getMaxLevel() : level; + if(!force) { + if(level > ench.getMaxLevel()) + throw new RunException("Level %d ist zu hoch für %s, maximal %d erlaubt", level, ench.getDisplay(), ench.getMaxLevel()); + if(!ench.canApply(stack)) + throw new RunException("Verzauberung %s kann nicht auf %s verwendet werden", ench.getDisplay(), stack.getDisplayName()); + for(Entry id : EnchantmentHelper.getEnchantments(stack).entrySet()) { + if(id.getKey() != ench && !ench.canApplyTogether(id.getKey())) + throw new RunException("Verzauberung %s kann nicht zusammen mit %s verwendet werden", ench.getDisplay(), id.getKey().getFormattedName(id.getValue())); + } + } + stack.removeEnchantment(ench); + stack.addEnchantment(ench, level); + exec.log("Verzauberung %s wurde zu %s hinzugefügt", ench.getFormattedName(level), stack.getDisplayName()); + } +} diff --git a/java/src/game/command/commands/CommandMessage.java b/server/src/main/java/server/command/commands/CommandMessage.java similarity index 67% rename from java/src/game/command/commands/CommandMessage.java rename to server/src/main/java/server/command/commands/CommandMessage.java index ecd6702..8209267 100644 --- a/java/src/game/command/commands/CommandMessage.java +++ b/server/src/main/java/server/command/commands/CommandMessage.java @@ -1,9 +1,9 @@ -package game.command.commands; +package server.command.commands; -import game.command.CommandEnvironment; -import game.command.Command; -import game.command.Executor; -import game.packet.SPacketMessage; +import common.packet.SPacketMessage; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; public class CommandMessage extends Command { public CommandMessage() { @@ -11,6 +11,7 @@ public class CommandMessage extends Command { this.addString("message", false); + this.setParamsOptional(); this.addEnum("type", 't', SPacketMessage.Type.CHAT, SPacketMessage.Type.class, SPacketMessage.Type.values()); } diff --git a/java/src/game/command/commands/CommandMilk.java b/server/src/main/java/server/command/commands/CommandMilk.java similarity index 54% rename from java/src/game/command/commands/CommandMilk.java rename to server/src/main/java/server/command/commands/CommandMilk.java index 66c6769..6cc2883 100644 --- a/java/src/game/command/commands/CommandMilk.java +++ b/server/src/main/java/server/command/commands/CommandMilk.java @@ -1,18 +1,20 @@ -package game.command.commands; +package server.command.commands; import java.util.List; -import game.collect.Lists; -import game.command.CommandEnvironment; -import game.command.Command; -import game.command.Executor; -import game.entity.types.EntityLiving; -import game.potion.Potion; + +import common.collect.Lists; +import common.entity.types.EntityLiving; +import common.potion.Potion; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; public class CommandMilk extends Command { public CommandMilk() { super("milk"); - this.addLivingEntityList("entities", true); + this.addLivingEntityList("entities", true, UserPolicy.NON_ADMINS_OR_SELF); this.setParamsOptional(); List potions = Lists.newArrayList(); for(Potion potion : Potion.values()) { @@ -28,18 +30,19 @@ public class CommandMilk extends Command { int done = 0; for(EntityLiving entity : entities) { if(type != null && entity.hasEffect(type)) { + int amplifier = entity.getEffect(type).getAmplifier(); entity.removeEffect(type); - exec.logConsole("%s von %s entfernt", type.getDisplay(), entity.getCommandName()); + exec.log("%s von %s entfernt", type.getDisplay(amplifier), entity.getCommandName()); done++; } else if(type == null && !entity.getEffects().isEmpty()) { entity.clearEffects(negative); - exec.logConsole("Alle Effekte von %s entfernt", entity.getCommandName()); + exec.log("Alle Effekte von %s entfernt", entity.getCommandName()); done++; } } if(done > 1) - exec.logConsole(type == null ? "Alle Effekte von %d Objekten entfernt" : "%d Effekte entfernt", entities.size()); + exec.log(type == null ? "Alle Effekte von %d Objekten entfernt" : "%d Effekte entfernt", entities.size()); return done; } } diff --git a/server/src/main/java/server/command/commands/CommandMore.java b/server/src/main/java/server/command/commands/CommandMore.java new file mode 100644 index 0000000..05c72b1 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandMore.java @@ -0,0 +1,55 @@ +package server.command.commands; + +import java.util.List; + +import common.entity.npc.EntityNPC; +import common.item.ItemStack; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; + +public class CommandMore extends Command { + public CommandMore() { + super("more"); + + this.setParamsOptional(); + this.addFlag("all", 'a'); + this.setParamsRequired(); + this.addPlayerEntityList("players", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); + } + + private int addItems(ItemStack stack) { + int diff = stack.getMaxStackSize() - stack.size; + stack.size = stack.getMaxStackSize(); + return diff; + } + + public void exec(CommandEnvironment env, Executor exec, boolean all, List players) { + int done = 0; + int added = 0; + for(EntityNPC player : players) { + int add = 0; + if(all) { + for(ItemStack item : player.inventory.mainInventory) { + if(item != null) + add += this.addItems(item); + } + for(ItemStack item : player.inventory.armorInventory) { + if(item != null) + add += this.addItems(item); + } + } + else if(player.getHeldItem() != null) { + add += this.addItems(player.getHeldItem()); + } + if(add > 0) { + exec.log("%d " + (add == 1 ? "Gegenstand" : "Gegenstände") + " wurde" + (add == 1 ? "" : "n") + " dem Inventar von %s hinzugefügt", add, player.getCommandName()); + done++; + } + added += add; + } + if(done > 1) + exec.log("%d Gegenstände wurden dem Inventar von %d Spielern hinzugefügt", added, done); + } +} diff --git a/server/src/main/java/server/command/commands/CommandNoclip.java b/server/src/main/java/server/command/commands/CommandNoclip.java new file mode 100644 index 0000000..46edf72 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandNoclip.java @@ -0,0 +1,38 @@ +package server.command.commands; + +import java.util.List; + +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; + +public class CommandNoclip extends Command { + public CommandNoclip() { + super("noclip"); + + this.addPlayerEntityList("players", true, UserPolicy.NON_ADMINS_OR_SELF); + this.setParamsOptional(); + this.addFlag("remove", 'r'); + this.addFlag("quiet", 'q'); + } + + public void exec(CommandEnvironment env, Executor exec, List players, boolean remove, boolean quiet) { + int done = 0; + remove = !remove && exec.isPlayer() && players.size() == 1 && players.get(0).connection == exec ? players.get(0).noclip : remove; + for(EntityNPC player : players) { + if(player.noclip == !remove) + continue; + player.setNoclip(!remove); + if(!quiet) + player.connection.addFeed((!remove ? TextColor.GREEN : TextColor.RED) + "NoClip wurde " + (!remove ? "eingeschaltet" : "ausgeschaltet")); + if(quiet || player.connection != exec) + exec.log("NoClip für %s " + (!remove ? "eingeschaltet" : "ausgeschaltet"), player.getCommandName()); + done++; + } + if(done > 1) + exec.log("NoClip von %d Spielern " + (!remove ? "eingeschaltet" : "ausgeschaltet"), done); + } +} diff --git a/java/src/game/command/commands/CommandOfflinetp.java b/server/src/main/java/server/command/commands/CommandOfflinetp.java similarity index 53% rename from java/src/game/command/commands/CommandOfflinetp.java rename to server/src/main/java/server/command/commands/CommandOfflinetp.java index a7340b7..55a3dba 100644 --- a/java/src/game/command/commands/CommandOfflinetp.java +++ b/server/src/main/java/server/command/commands/CommandOfflinetp.java @@ -1,17 +1,18 @@ -package game.command.commands; +package server.command.commands; import java.util.Collection; import java.util.List; -import game.command.CommandEnvironment; -import game.collect.Lists; -import game.command.Command; -import game.command.Executor; -import game.command.RunException; -import game.command.StringCompleter; -import game.entity.Entity; -import game.init.UniverseRegistry; -import game.network.Player; -import game.world.Position; + +import common.entity.Entity; +import common.init.UniverseRegistry; +import common.util.Position; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.command.StringCompleter; +import server.command.UserPolicy; +import server.network.Player; public class CommandOfflinetp extends Command { public CommandOfflinetp() { @@ -19,11 +20,11 @@ public class CommandOfflinetp extends Command { this.addString("user", false, new StringCompleter() { public Collection complete(CommandEnvironment env) { - return Lists.newArrayList(env.getServer().getUsers()); + return env.getServer().getPlayerFilenames(); } }); - this.addEntityList("entities", 'e', true); + this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); } public Object exec(CommandEnvironment env, Executor exec, String user, List entities) { @@ -33,7 +34,7 @@ public class CommandOfflinetp extends Command { throw new RunException("Spieler '%s' konnte nicht gefunden werden", user); for(Entity entity : entities) { entity.teleport(pos); - exec.logConsole("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x, (int)pos.y, (int)pos.z, UniverseRegistry.getDimension(pos.dim).getFormattedName(false)); + exec.log("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x(), (int)pos.y(), (int)pos.z(), UniverseRegistry.getDimension(pos.dim()).getFormattedName(false)); } return entities.size(); } diff --git a/server/src/main/java/server/command/commands/CommandPasswd.java b/server/src/main/java/server/command/commands/CommandPasswd.java new file mode 100644 index 0000000..6b3085b --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandPasswd.java @@ -0,0 +1,80 @@ +package server.command.commands; + +import java.security.MessageDigest; + +import common.color.TextColor; +import common.network.IPlayer; +import common.util.EncryptUtil; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.command.UserPolicy; +import server.network.Player; +import server.network.User; +import server.util.Form; +import server.vars.SVars; + +public class CommandPasswd extends Command { + public CommandPasswd() { + super("passwd"); + + this.addUser("user", true, UserPolicy.NON_ADMINS_OR_SELF); + this.setParamsOptional(); + this.addString("password", false); + } + + public void exec(CommandEnvironment env, Executor exec, User user, String password) { + if(exec.isPlayer()) { + if(password != null) + throw new RunException("Bei Verwendung als Spieler darf kein Passwort angegeben werden"); + if(user.getPubkey() != null && user == exec) + throw new RunException("Es darf kein Pubkey vorhanden sein, um diesen Befehl an sich selbst anzuwenden"); + if(user.getPasswordHash() == null && user == exec) + throw new RunException("Es muss ein Passwort vorhanden sein, um diesen Befehl an sich selbst anzuwenden"); + ((Player)exec).displayForm(new Form() { + private Field checkField; + private Field passwordField; + private Field confirmField; + + protected void init() { + this.checkField = user != exec ? null : this.addPassword("Aktuelles Passwort", 0, IPlayer.MAX_PASS_LENGTH, ""); + this.passwordField = this.addPassword("Neues Passwort", SVars.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); + this.confirmField = this.addPassword("Passwort bestätigen", SVars.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); + } + + public String getTitle() { + return "Passwort für " + user.getUser() + " ändern"; + } + + protected void accept() { + User plr = env.getServer().getUser(user.getUser()); + if(!((Player)exec).isAdmin() || plr == null || (plr.isAdmin() && plr != exec) || (plr.getPasswordHash() == null && plr == exec) || (plr.getPubkey() != null && plr == exec)) { + exec.log(TextColor.DRED + "Ein Fehler ist aufgetreten"); + return; + } + if(this.checkField != null && !MessageDigest.isEqual(EncryptUtil.hashPassword(this.checkField.get(), plr.getPasswordHash().second()), plr.getPasswordHash().first())) { + exec.log(TextColor.RED + "Falsches Passwort eingegeben"); + return; + } + if(!this.passwordField.get().equals(this.confirmField.get())) { + exec.log(TextColor.RED + "Passwörter stimmen nicht überein"); + return; + } + plr.setPasswordHash(EncryptUtil.hashPassword(this.passwordField.get())); + plr.setPubkey(null); + exec.log(TextColor.GREEN + "Passwort" + (plr != exec ? " für %s" : "") + " gesetzt", plr.getUser()); + } + }); + } + else if(exec.isConsole()) { + if(password == null) + throw new RunException("Bei Verwendung in der Konsole muss ein Passwort angegeben werden"); + if(password.length() < 8) + throw new RunException("Das Passwort ist zu kurz, mindestens 8 Zeichen sind erforderlich"); + user.setPasswordHash(EncryptUtil.hashPassword(password)); + user.setPubkey(null); + exec.log(TextColor.GREEN + "Passwort für %s gesetzt", user.getUser()); + } + } +} diff --git a/server/src/main/java/server/command/commands/CommandPlayers.java b/server/src/main/java/server/command/commands/CommandPlayers.java new file mode 100644 index 0000000..fe2bcb9 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandPlayers.java @@ -0,0 +1,33 @@ +package server.command.commands; + +import java.util.List; + +import common.color.TextColor; +import common.entity.npc.EntityNPC; +import common.util.ExtMath; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.network.Player; + +public class CommandPlayers extends Command { + public CommandPlayers() { + super("players"); + + this.setParamsOptional(); + this.addFlag("coords", 'c'); + } + + public void exec(CommandEnvironment env, Executor exec, boolean coords) { + List players = env.getServer().getPlayers(); + if(players.isEmpty()) { + exec.log(TextColor.DGRAY + "Es sind keine Spieler online"); + return; + } + exec.log(TextColor.GREEN + "Es " + (players.size() == 1 ? "ist" : "sind") + " " + TextColor.YELLOW + "%d" + TextColor.GREEN + " Spieler online", players.size()); + for(Player player : players) { + EntityNPC entity = player.getPresentEntity(); + exec.log("%s%s" + TextColor.GRAY + ": '%s" + TextColor.GRAY + "'" + (coords ? " [" + TextColor.ORANGE + "%s @ %d, %d, %d" + TextColor.GRAY + "]" : ""), player.isAdmin() ? TextColor.RED : TextColor.NEON, player.getUser(), entity == null ? TextColor.DGRAY + "<->" : TextColor.ACID + entity.getCommandName(), entity == null ? null : entity.worldObj.dimension.getFormattedName(false), entity == null ? null : ExtMath.floord(entity.posX), entity == null ? null : ExtMath.floord(entity.posY), entity == null ? null : ExtMath.floord(entity.posZ)); + } + } +} diff --git a/java/src/game/command/commands/CommandPotion.java b/server/src/main/java/server/command/commands/CommandPotion.java similarity index 62% rename from java/src/game/command/commands/CommandPotion.java rename to server/src/main/java/server/command/commands/CommandPotion.java index edf0d5a..87bf9da 100644 --- a/java/src/game/command/commands/CommandPotion.java +++ b/server/src/main/java/server/command/commands/CommandPotion.java @@ -1,18 +1,20 @@ -package game.command.commands; +package server.command.commands; import java.util.List; -import game.command.CommandEnvironment; -import game.command.Command; -import game.command.Executor; -import game.entity.types.EntityLiving; -import game.potion.Potion; -import game.potion.PotionEffect; + +import common.entity.types.EntityLiving; +import common.potion.Potion; +import common.potion.PotionEffect; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; public class CommandPotion extends Command { public CommandPotion() { super("potion"); - this.addLivingEntityList("entities", true); + this.addLivingEntityList("entities", true, UserPolicy.NON_ADMINS_OR_SELF); this.addEnum("type", Potion.class, Potion.values()); this.setParamsOptional(); this.addInt("duration", 0, 1000000, 1000000); @@ -26,7 +28,7 @@ public class CommandPotion extends Command { public Object exec(CommandEnvironment env, Executor exec, List entities, Potion type, int duration, int strength, boolean particles, boolean ambient, boolean keep) { int done = 0; for(EntityLiving entity : entities) { - if(entity.isPotionApplicable(type)) { + if(entity.isPotionApplicable(type, strength - 1)) { if(type.isInstant()) { type.onImpact(null, null, entity, strength - 1, 1.0); } @@ -37,14 +39,14 @@ public class CommandPotion extends Command { entity.addEffect(effect); } if(type.isInstant() || duration == 0) - exec.logConsole("%d * %s an %s gegeben", strength, type.getDisplay(), entity.getCommandName()); + exec.log("%s an %s gegeben", type.getDisplay(strength - 1), entity.getCommandName()); else - exec.logConsole("%d * %s für %d Sekunden an %s gegeben", strength, type.getDisplay(), duration, entity.getCommandName()); + exec.log("%s für %d Sekunden an %s gegeben", type.getDisplay(strength - 1), duration, entity.getCommandName()); done++; } } if(done > 1) - exec.logConsole("%d Effekte vergeben", done); + exec.log("%d Effekte vergeben", done); return done; } } diff --git a/server/src/main/java/server/command/commands/CommandPubkey.java b/server/src/main/java/server/command/commands/CommandPubkey.java new file mode 100644 index 0000000..74384ab --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandPubkey.java @@ -0,0 +1,87 @@ +package server.command.commands; + +import java.security.MessageDigest; +import java.security.PublicKey; + +import common.color.TextColor; +import common.network.IPlayer; +import common.util.EncryptUtil; +import common.util.Pair; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.command.UserPolicy; +import server.network.Player; +import server.network.User; +import server.util.Form; + +public class CommandPubkey extends Command { + public CommandPubkey() { + super("pubkey"); + + this.addUser("user", true, UserPolicy.NON_ADMINS_OR_SELF); + this.setParamsOptional(); + this.addString("keySpec", false); + this.addString("keyData", false); + this.addString("keyHash", false); + this.addString("keyName", false); + } + + public void exec(CommandEnvironment env, Executor exec, User user, String keySpec, String keyData, String keyHash, String keyName) { + if(exec.isPlayer()) { + if(keySpec != null || keyData != null || keyHash != null || keyName != null) + throw new RunException("Bei Verwendung als Spieler darf kein Schlüssel angegeben werden"); + ((Player)exec).displayForm(new Form() { + private Field checkField; + private Field keyField; + + protected void init() { + this.checkField = user.getPasswordHash() == null || user != exec ? null : this.addPassword("Aktuelles Passwort", 0, IPlayer.MAX_PASS_LENGTH, ""); + this.keyField = this.addField("Neuer Pubkey", 1, 960, ""); + } + + public String getTitle() { + return "Schlüssel für " + user.getUser() + " ändern"; + } + + protected void accept() { + User plr = env.getServer().getUser(user.getUser()); + if(!((Player)exec).isAdmin() || plr == null || (plr.isAdmin() && plr != exec)) { + exec.log(TextColor.DRED + "Ein Fehler ist aufgetreten"); + return; + } + if(this.checkField != null && plr.getPasswordHash() != null && !MessageDigest.isEqual(EncryptUtil.hashPassword(this.checkField.get(), plr.getPasswordHash().second()), plr.getPasswordHash().first())) { + exec.log(TextColor.RED + "Falsches Passwort eingegeben"); + return; + } + Pair key; + try { + key = EncryptUtil.parseArmoredPubkey(this.keyField.get()); + } + catch(IllegalArgumentException e) { + exec.log(TextColor.RED + "Ungültiger Schlüssel"); + return; + } + plr.setPasswordHash(null); + plr.setPubkey(key.first()); + exec.log(TextColor.GREEN + "Schlüssel" + (plr != exec ? " für %s" : "") + " gesetzt", plr.getUser()); + } + }); + } + else if(exec.isConsole()) { + if(keySpec == null || keyData == null || keyHash == null) + throw new RunException("Bei Verwendung in der Konsole muss ein Schlüssel angegeben werden"); + Pair key; + try { + key = EncryptUtil.parseArmoredPubkey(keySpec + " " + keyData + " " + keyHash + (keyName == null ? null : " " + keyName)); + } + catch(IllegalArgumentException e) { + throw new RunException(e, "Ungültiger Schlüssel"); + } + user.setPasswordHash(null); + user.setPubkey(key.first()); + exec.log(TextColor.GREEN + "Schlüssel für %s gesetzt", user.getUser()); + } + } +} diff --git a/server/src/main/java/server/command/commands/CommandRegister.java b/server/src/main/java/server/command/commands/CommandRegister.java new file mode 100644 index 0000000..5e315f5 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandRegister.java @@ -0,0 +1,75 @@ +package server.command.commands; + +import common.color.TextColor; +import common.network.IPlayer; +import common.util.EncryptUtil; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.network.Player; +import server.network.User; +import server.util.Form; +import server.vars.SVars; + +public class CommandRegister extends Command { + public CommandRegister() { + super("register"); + + this.addString("username", false, null, IPlayer.MAX_USER_LENGTH, IPlayer.VALID_USER); + this.setParamsOptional(); + this.addString("password", false); + this.addFlag("admin", 'a'); + } + + public void exec(CommandEnvironment env, Executor exec, String username, String password, boolean admin) { + if(env.getServer().getUser(username) != null) + throw new RunException("Ein Spieler mit diesem Nutzernamen ist bereits registriert"); + if(env.getServer().loadPlayerData(username) != null) + throw new RunException("Ein Spieler mit diesem Nutzernamen hat bereits Spielerdaten, ist aber nicht registriert"); + if(exec.isPlayer()) { + if(password != null) + throw new RunException("Bei Verwendung als Spieler darf kein Passwort angegeben werden"); + ((Player)exec).displayForm(new Form() { + private Field passwordField; + private Field confirmField; + + protected void init() { + this.passwordField = this.addPassword("Passwort", SVars.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); + this.confirmField = this.addPassword("Passwort bestätigen", SVars.minPassLength, IPlayer.MAX_PASS_LENGTH, ""); + } + + public String getTitle() { + return "Spieler " + username + " registrieren"; + } + + protected void accept() { + if(!((Player)exec).isAdmin() || env.getServer().getUser(username) != null || env.getServer().loadPlayerData(username) != null) { + exec.log(TextColor.DRED + "Ein Fehler ist aufgetreten"); + return; + } + if(!this.passwordField.get().equals(this.confirmField.get())) { + exec.log(TextColor.RED + "Passwörter stimmen nicht überein"); + return; + } + User user = new User(username); + user.setPasswordHash(EncryptUtil.hashPassword(this.passwordField.get())); + user.setAdmin(admin); + env.getServer().addUser(user); + exec.log(TextColor.GREEN + "Spieler %s registriert", username); + } + }); + } + else if(exec.isConsole()) { + if(password == null) + throw new RunException("Bei Verwendung in der Konsole muss ein Passwort angegeben werden"); + if(password.length() < 8) + throw new RunException("Das Passwort ist zu kurz, mindestens 8 Zeichen sind erforderlich"); + User user = new User(username); + user.setPasswordHash(EncryptUtil.hashPassword(password)); + user.setAdmin(admin); + env.getServer().addUser(user); + exec.log(TextColor.GREEN + "Spieler %s registriert", username); + } + } +} diff --git a/server/src/main/java/server/command/commands/CommandRegkey.java b/server/src/main/java/server/command/commands/CommandRegkey.java new file mode 100644 index 0000000..451c0b3 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandRegkey.java @@ -0,0 +1,87 @@ +package server.command.commands; + +import java.security.PublicKey; + +import common.color.TextColor; +import common.network.IPlayer; +import common.util.EncryptUtil; +import common.util.Pair; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.network.Player; +import server.network.User; +import server.util.Form; + +public class CommandRegkey extends Command { + public CommandRegkey() { + super("regkey"); + + this.addString("username", false, null, IPlayer.MAX_USER_LENGTH, IPlayer.VALID_USER); + this.setParamsOptional(); + this.addString("keySpec", false); + this.addString("keyData", false); + this.addString("keyHash", false); + this.addString("keyName", false); + this.addFlag("admin", 'a'); + } + + public void exec(CommandEnvironment env, Executor exec, String username, String keySpec, String keyData, String keyHash, String keyName, boolean admin) { + if(env.getServer().getUser(username) != null) + throw new RunException("Ein Spieler mit diesem Nutzernamen ist bereits registriert"); + if(env.getServer().loadPlayerData(username) != null) + throw new RunException("Ein Spieler mit diesem Nutzernamen hat bereits Spielerdaten, ist aber nicht registriert"); + if(exec.isPlayer()) { + if(keySpec != null || keyData != null || keyHash != null || keyName != null) + throw new RunException("Bei Verwendung als Spieler darf kein Schlüssel angegeben werden"); + ((Player)exec).displayForm(new Form() { + private Field keyField; + + protected void init() { + this.keyField = this.addField("Pubkey", 1, 960, ""); + } + + public String getTitle() { + return "Spieler " + username + " registrieren"; + } + + protected void accept() { + if(!((Player)exec).isAdmin() || env.getServer().getUser(username) != null || env.getServer().loadPlayerData(username) != null) { + exec.log(TextColor.DRED + "Ein Fehler ist aufgetreten"); + return; + } + Pair key; + try { + key = EncryptUtil.parseArmoredPubkey(this.keyField.get()); + } + catch(IllegalArgumentException e) { + exec.log(TextColor.RED + "Ungültiger Schlüssel"); + return; + } + User user = new User(username); + user.setPubkey(key.first()); + user.setAdmin(admin); + env.getServer().addUser(user); + exec.log(TextColor.GREEN + "Spieler %s registriert", username); + } + }); + } + else if(exec.isConsole()) { + if(keySpec == null || keyData == null || keyHash == null) + throw new RunException("Bei Verwendung in der Konsole muss ein Schlüssel angegeben werden"); + Pair key; + try { + key = EncryptUtil.parseArmoredPubkey(keySpec + " " + keyData + " " + keyHash + (keyName == null ? null : " " + keyName)); + } + catch(IllegalArgumentException e) { + throw new RunException(e, "Ungültiger Schlüssel"); + } + User user = new User(username); + user.setPubkey(key.first()); + user.setAdmin(admin); + env.getServer().addUser(user); + exec.log(TextColor.GREEN + "Spieler %s registriert", username); + } + } +} diff --git a/java/src/game/command/commands/CommandRemove.java b/server/src/main/java/server/command/commands/CommandRemove.java similarity index 51% rename from java/src/game/command/commands/CommandRemove.java rename to server/src/main/java/server/command/commands/CommandRemove.java index 314dcc6..56044bc 100644 --- a/java/src/game/command/commands/CommandRemove.java +++ b/server/src/main/java/server/command/commands/CommandRemove.java @@ -1,17 +1,20 @@ -package game.command.commands; +package server.command.commands; import java.util.List; -import game.command.CommandEnvironment; -import game.command.Command; -import game.command.Executor; -import game.entity.Entity; + +import common.entity.Entity; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; public class CommandRemove extends Command { public CommandRemove() { super("remove"); - this.addEntityList("entities", true); - + this.addEntityList("entities", true, UserPolicy.NON_ADMINS_OR_SELF); + + this.setParamsOptional(); this.addFlag("kill", 'k'); } @@ -23,12 +26,12 @@ public class CommandRemove extends Command { entity.kill(); else entity.setDead(); - exec.logConsole(kill ? "%s getötet" : "%s entfernt", entity.getCommandName()); + exec.log(kill ? "%s getötet" : "%s entfernt", entity.getCommandName()); done++; } } if(done > 1) - exec.logConsole(kill ? "%d Objekte getötet" : "%d Objekte entfernt", done); + exec.log(kill ? "%d Objekte getötet" : "%d Objekte entfernt", done); return done; } } diff --git a/server/src/main/java/server/command/commands/CommandRename.java b/server/src/main/java/server/command/commands/CommandRename.java new file mode 100644 index 0000000..e4c38cc --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandRename.java @@ -0,0 +1,28 @@ +package server.command.commands; + +import common.item.ItemStack; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; + +public class CommandRename extends Command { + public CommandRename() { + super("rename"); + + this.setParamsOptional(); + this.addString("name", false, 1, 30, null); + this.setParamsRequired(); + this.addPlayerItem("player", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); + } + + public void exec(CommandEnvironment env, Executor exec, String name, ItemStack stack) { + String prev = stack.getDisplayName(); + if(name == null) + stack.clearCustomName(); + else + stack.setStackDisplayName(name); + if(!prev.equals(stack.getDisplayName())) + exec.log("Gegenstand '%s' wurde zu '%s' umbenannt", prev, stack.getDisplayName()); + } +} diff --git a/server/src/main/java/server/command/commands/CommandRepair.java b/server/src/main/java/server/command/commands/CommandRepair.java new file mode 100644 index 0000000..23abc7b --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandRepair.java @@ -0,0 +1,62 @@ +package server.command.commands; + +import java.util.List; + +import common.entity.npc.EntityNPC; +import common.item.ItemStack; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; + +public class CommandRepair extends Command { + public CommandRepair() { + super("repair"); + + this.setParamsOptional(); + this.addFlag("all", 'a'); + this.setParamsRequired(); + this.addPlayerEntityList("players", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); + } + + private boolean fixItem(ItemStack stack) { + boolean flag = false; + if(stack.getRepairCost() != 0) { + stack.setRepairCost(0); + flag = true; + } + if(stack.getItem().getMaxDamage() > 0 && stack.getItemDamage() != 0) { + stack.setItemDamage(0); + flag = true; + } + return flag; + } + + public void exec(CommandEnvironment env, Executor exec, boolean all, List players) { + int done = 0; + int repaired = 0; + for(EntityNPC player : players) { + int rep = 0; + if(all) { + for(ItemStack item : player.inventory.mainInventory) { + if(item != null && this.fixItem(item)) + rep++; + } + for(ItemStack item : player.inventory.armorInventory) { + if(item != null && this.fixItem(item)) + rep++; + } + } + else if(player.getHeldItem() != null && this.fixItem(player.getHeldItem())) { + rep++; + } + if(rep > 0) { + exec.log("%d " + (rep == 1 ? "Gegenstand" : "Gegenstände") + " im Inventar von %s wurde" + (rep == 1 ? "" : "n") + " repariert", rep, player.getCommandName()); + done++; + } + repaired += rep; + } + if(done > 1) + exec.log("%d Gegenstände im Inventar von %d Spielern wurden repariert", repaired, done); + } +} diff --git a/server/src/main/java/server/command/commands/CommandReturn.java b/server/src/main/java/server/command/commands/CommandReturn.java new file mode 100644 index 0000000..4f99203 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandReturn.java @@ -0,0 +1,33 @@ +package server.command.commands; + +import java.util.List; + +import common.entity.npc.EntityNPC; +import common.init.UniverseRegistry; +import common.util.Position; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; +import server.network.Player; + +public class CommandReturn extends Command { + public CommandReturn() { + super("return"); + + this.addPlayerEntityList("players", 'p', true, UserPolicy.NON_ADMINS_OR_SELF); + } + + public Object exec(CommandEnvironment env, Executor exec, List players) { + int done = 0; + for(EntityNPC player : players) { + Position pos = ((Player)player.connection).getLastTeleport(); + if(pos != null) { + player.teleport(pos); + exec.log("%s zum letzten Punkt (%d, %d, %d in %s) teleportiert", player.getCommandName(), (int)pos.x(), (int)pos.y(), (int)pos.z(), UniverseRegistry.getDimension(pos.dim()).getFormattedName(false)); + done++; + } + } + return done; + } +} diff --git a/server/src/main/java/server/command/commands/CommandRevoke.java b/server/src/main/java/server/command/commands/CommandRevoke.java new file mode 100644 index 0000000..cea782a --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandRevoke.java @@ -0,0 +1,26 @@ +package server.command.commands; + +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.command.UserPolicy; +import server.network.Player; +import server.network.User; + +public class CommandRevoke extends Command { + public CommandRevoke() { + super("revoke"); + + this.addUser("user", false, UserPolicy.ADMINS); + } + + public void exec(CommandEnvironment env, Executor exec, User user) { + if(!exec.isConsole()) + throw new RunException("Dieser Befehl kann nur der Konsole ausgeführt werden"); + user.setAdmin(false); + if(user.isOnline()) + ((Player)user).log("Der Host hat deine Administatorrechte entfernt"); + exec.log("%s ist jetzt kein Admin mehr", user.getUser()); + } +} diff --git a/server/src/main/java/server/command/commands/CommandRunas.java b/server/src/main/java/server/command/commands/CommandRunas.java new file mode 100644 index 0000000..caae85b --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandRunas.java @@ -0,0 +1,26 @@ +package server.command.commands; + +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; +import server.network.Player; + +public class CommandRunas extends Command { + public CommandRunas() { + super("~"); + + this.addPlayer("player", false, UserPolicy.NON_ADMINS_NOT_SELF); + this.addString("command", false); + } + + public void exec(CommandEnvironment env, Executor exec, Player player, String command) { + try { + player.setForcedExec(exec); + env.execute(command, player); + } + finally { + player.setForcedExec(null); + } + } +} diff --git a/server/src/main/java/server/command/commands/CommandRunat.java b/server/src/main/java/server/command/commands/CommandRunat.java new file mode 100644 index 0000000..0acbeb9 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandRunat.java @@ -0,0 +1,37 @@ +package server.command.commands; + +import java.util.List; + +import common.entity.Entity; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; + +public class CommandRunat extends Command { + public CommandRunat() { + super("@"); + + this.addEntityList("entities", false, UserPolicy.NON_ADMINS_NOT_SELF); + this.addString("command", false); + } + + public Object exec(CommandEnvironment env, Executor exec, List entities, String command) { + int done = 0; + for(Entity entity : entities) { + if(entity.isEntityAlive()) { + try { + exec.setExecPos(entity.getPos()); + env.execute(command, exec); + } + finally { + exec.setExecPos(null); + } + done++; + } + } + if(done > 1) + exec.log("Befehl bei %d Objekten ausgeführt", done); + return done; + } +} diff --git a/server/src/main/java/server/command/commands/CommandSave.java b/server/src/main/java/server/command/commands/CommandSave.java new file mode 100644 index 0000000..36e9b02 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandSave.java @@ -0,0 +1,36 @@ +package server.command.commands; + +import common.color.TextColor; +import common.packet.SPacketMessage; +import common.packet.SPacketMessage.Type; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.world.Region; + +public class CommandSave extends Command { + public CommandSave() { + super("save"); + + this.setParamsOptional(); + this.addFlag("message", 'm'); + this.addFlag("flush", 'f'); + } + + public void exec(CommandEnvironment env, Executor exec, boolean message, boolean flush) { + if(message) + env.getServer().sendPacket(new SPacketMessage(TextColor.RED + "Speichere Serverdaten, der Server könnte kurz einfrieren", Type.FEED)); + exec.log(TextColor.ORANGE + "Speichere Spielerdaten ..."); + env.getServer().saveAllPlayerData(true); + exec.log(TextColor.ORANGE + "Speichere Weltdaten ..."); + env.getServer().saveAllWorlds(true); + env.getServer().resetSaveTimer(); + if(flush) { + exec.log(TextColor.ORANGE + "Beende E/A ..."); + Region.finishWrite(); + } + exec.log(TextColor.DGREEN + "Alle Serverdaten wurden gespeichert"); + if(message) + env.getServer().sendPacket(new SPacketMessage(TextColor.GREEN + "Die Serverdaten wurden gespeichert", Type.FEED)); + } +} diff --git a/server/src/main/java/server/command/commands/CommandSeed.java b/server/src/main/java/server/command/commands/CommandSeed.java new file mode 100644 index 0000000..1879edc --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandSeed.java @@ -0,0 +1,24 @@ +package server.command.commands; + +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.world.WorldServer; + +public class CommandSeed extends Command { + public CommandSeed() { + super("seed"); + + this.addWorld("dim", true); + + this.setParamsOptional(); + this.addFlag("dump", 'd'); + } + + public Object exec(CommandEnvironment env, Executor exec, WorldServer world, boolean dump) { + if(dump) + exec.log("Daten: %s", world.dimension.dumpTags().format(4)); + exec.log("Startwert von %s: %d", world.dimension.getFormattedName(false), world.dimension.getSeed()); + return world.dimension.getSeed(); + } +} diff --git a/server/src/main/java/server/command/commands/CommandShutdown.java b/server/src/main/java/server/command/commands/CommandShutdown.java new file mode 100644 index 0000000..5872df3 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandShutdown.java @@ -0,0 +1,18 @@ +package server.command.commands; + +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; + +public class CommandShutdown extends Command { + public CommandShutdown() { + super("shutdown"); + + this.setParamsOptional(); + this.addString("message", "Server beendet", false); + } + + public void exec(CommandEnvironment env, Executor exec, String message) { + env.getServer().shutdown(message); + } +} diff --git a/java/src/game/command/commands/CommandSpawn.java b/server/src/main/java/server/command/commands/CommandSpawn.java similarity index 51% rename from java/src/game/command/commands/CommandSpawn.java rename to server/src/main/java/server/command/commands/CommandSpawn.java index aff6b20..dbb77ad 100644 --- a/java/src/game/command/commands/CommandSpawn.java +++ b/server/src/main/java/server/command/commands/CommandSpawn.java @@ -1,23 +1,22 @@ -package game.command.commands; +package server.command.commands; import java.util.List; import java.util.Set; -import game.collect.Lists; -import game.collect.Sets; - -import game.command.CommandEnvironment; -import game.command.RunException; -import game.command.Command; -import game.command.Executor; -import game.entity.Entity; -import game.entity.types.EntityLiving; -import game.init.EntityRegistry; -import game.nbt.NBTTagCompound; -import game.network.Player; -import game.util.Util; -import game.world.Vec3; -import game.world.WorldServer; +import common.collect.Lists; +import common.collect.Sets; +import common.entity.Entity; +import common.entity.types.EntityLiving; +import common.init.EntityRegistry; +import common.tags.TagObject; +import common.util.Util; +import common.util.Vec3; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.network.Player; +import server.world.WorldServer; public class CommandSpawn extends Command { public CommandSpawn() { @@ -29,9 +28,9 @@ public class CommandSpawn extends Command { } names.add("Lightning"); this.addEnum("type", String.class, names); - this.setParamsOptional(); this.addVector("position", true, true); this.addWorld("dim", true); + this.setParamsOptional(); this.addTag("tag"); this.addFlag("noinit", 'n'); @@ -39,13 +38,13 @@ public class CommandSpawn extends Command { this.addTag("postTag", 'p'); } - public Object exec(CommandEnvironment env, Executor exec, String type, Vec3 pos, WorldServer world, NBTTagCompound tag, boolean noinit, int count, NBTTagCompound postTag) { + public Object exec(CommandEnvironment env, Executor exec, String type, Vec3 pos, WorldServer world, TagObject tag, boolean noinit, int count, TagObject postTag) { if(type.equalsIgnoreCase("Lightning")) { for(int z = 0; z < count; z++) { int color = 0xffffff; - if(tag != null && tag.hasKey("color", 3)) - color = tag.getInteger("color"); - else if(tag != null && tag.hasKey("color", 8)) { + if(tag != null && tag.hasInt("color")) + color = tag.getInt("color"); + else if(tag != null && tag.hasString("color")) { try { color = Integer.parseUnsignedInt(tag.getString("color"), 16); } @@ -53,10 +52,10 @@ public class CommandSpawn extends Command { } } world.strikeLightning(pos.xCoord, pos.yCoord, pos.zCoord, color, - tag != null && tag.hasKey("damage", 3) ? tag.getInteger("damage") : 0, tag != null && tag.hasKey("fire", 1) && tag.getBoolean("fire"), - exec instanceof Player && tag != null && tag.hasKey("summoned", 1) && tag.getBoolean("summoned") ? ((Player)exec).getPresentEntity() : null); + tag != null && tag.hasInt("damage") ? tag.getInt("damage") : 0, tag != null && tag.hasBool("fire") && tag.getBool("fire"), + exec.isPlayer() && tag != null && tag.hasBool("summoned") && tag.getBool("summoned") ? ((Player)exec).getPresentEntity() : null); } - exec.logConsole("%sBlitz bei %d, %d, %d in %s erschaffen", count == 1 ? "" : (count + "x "), (int)pos.xCoord, (int)pos.yCoord, (int)pos.zCoord, world.dimension.getFormattedName(false)); + exec.log("%sBlitz bei %d, %d, %d in %s erschaffen", count == 1 ? "" : (count + "x "), (int)pos.xCoord, (int)pos.yCoord, (int)pos.zCoord, world.dimension.getFormattedName(false)); return null; } else { @@ -67,23 +66,23 @@ public class CommandSpawn extends Command { throw new RunException("Objekt konnte nicht erzeugt werden"); entity.setLocationAndAngles(pos.xCoord, pos.yCoord, pos.zCoord, world.rand.floatv() * 360.0f, 0.0f); if(tag != null) { - NBTTagCompound ent = new NBTTagCompound(); - entity.writeToNBT(ent); + TagObject ent = new TagObject(); + entity.writeTags(ent); ent.merge(tag); - entity.readFromNBT(ent); + entity.readTags(ent); } if(!noinit && (entity instanceof EntityLiving)) ((EntityLiving)entity).onInitialSpawn(null); world.spawnEntityInWorld(entity); if(postTag != null) { - NBTTagCompound ent = new NBTTagCompound(); - entity.writeToNBT(ent); + TagObject ent = new TagObject(); + entity.writeTags(ent); ent.merge(postTag); - entity.readFromNBT(ent); + entity.readTags(ent); } spawned.add("#" + entity.getId()); } - exec.logConsole("%s%s bei %d, %d, %d in %s erschaffen", count == 1 ? "" : (count + "x "), EntityRegistry.getEntityName(type), (int)pos.xCoord, (int)pos.yCoord, (int)pos.zCoord, world.dimension.getFormattedName(false)); + exec.log("%s%s bei %d, %d, %d in %s erschaffen", count == 1 ? "" : (count + "x "), EntityRegistry.getEntityName(type), (int)pos.xCoord, (int)pos.yCoord, (int)pos.zCoord, world.dimension.getFormattedName(false)); return Util.buildLines(",", spawned); } } diff --git a/server/src/main/java/server/command/commands/CommandSv.java b/server/src/main/java/server/command/commands/CommandSv.java new file mode 100644 index 0000000..a6acbbf --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandSv.java @@ -0,0 +1,100 @@ +package server.command.commands; + +import java.util.Collection; +import java.util.Map.Entry; + +import common.collect.Lists; +import common.color.TextColor; +import server.command.ArgumentSplitter; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.command.StringCompleter; +import server.vars.SVar; +import server.vars.ValueType; + +public class CommandSv extends Command { + public CommandSv() { + super("sv"); + + this.setParamsOptional(); + this.addString("variable", false, new StringCompleter() { + public Collection complete(CommandEnvironment env) { + return env.getServer().getVariables().keySet(); + } + }); + this.addString("value", true); + } + + public Iterable getCustomCompletions(CommandEnvironment env, Executor exec, ArgumentSplitter parsed, String param, String parser, String arg) { + if(param.equals("value") && parsed.has("variable")) { + SVar sv = env.getServer().getVariables().get(parsed.get("variable")); + if(sv != null && sv.type == ValueType.BOOLEAN) + return Boolean.parseBoolean(sv.get()) ? Lists.newArrayList("false", "true") : Lists.newArrayList("true", "false"); + else if(sv != null && !sv.noDef && (sv.type == ValueType.INTEGER || sv.type == ValueType.FLOAT)) + return Lists.newArrayList(sv.def); + } + return null; + } + + private String formatVariable(String name, SVar sv, String separator, boolean censor) { + String value = sv.get(); + StringBuilder sb = new StringBuilder(TextColor.YELLOW + name + TextColor.GRAY + " " + separator + " "); + if(sv.noDef && sv.def.equals(value)) + sb.append(TextColor.DGRAY + "[ - ]"); + else if(censor && name.equals("password") && !value.isEmpty()) + sb.append(TextColor.NEON + "'****'"); + else if(sv.type == ValueType.STRING) + sb.append(TextColor.NEON + "'" + value + "'"); + else + sb.append(((sv.type == ValueType.BOOLEAN ? (value.equals("true") ? TextColor.GREEN : TextColor.RED) : TextColor.BLUE)) + value); + if(!sv.def.equals(value)) + sb.append(TextColor.GRAY + " (" + (sv.noDef ? TextColor.DGRAY + "[ - ]" : TextColor.BROWN + sv.def) + TextColor.GRAY + ")"); + return sb.toString(); + } + + public Object exec(CommandEnvironment env, Executor exec, String variable, String value) { + if(variable == null) { + if(value != null) + throw new RunException("Kann keinen Wert ohne eine Variable angeben"); + for(Entry entry : env.getServer().getVariables().entrySet()) { + exec.log(this.formatVariable(entry.getKey(), entry.getValue(), "=", true)); + } + exec.log(TextColor.GREEN + "SVARs insgesamt registriert: %d", env.getServer().getVariables().size()); + return null; + } + SVar sv = env.getServer().getVariables().get(variable); + if(sv == null) + throw new RunException("Variable '%s' existiert nicht", variable); + if(value != null) { + if(sv.type == ValueType.BOOLEAN && !"true".equals(value) && !"false".equals(value)) { + if(value.equals("0") || value.equals("1")) + value = "" + value.equals("1"); + else if(value.equalsIgnoreCase("true") || value.equalsIgnoreCase("false")) + value = value.toLowerCase(); + else + throw new RunException("'%s' ist nicht 'true' (1) oder 'false' (0)", value); + } + else if(sv.type == ValueType.INTEGER) { + try { + Integer.parseInt(value); + } + catch(NumberFormatException e) { + throw new RunException(TextColor.DRED + "'%s' ist keine gültige Zahl", value); + } + } + else if(sv.type == ValueType.FLOAT) { + try { + Float.parseFloat(value); + } + catch(NumberFormatException e) { + throw new RunException(TextColor.DRED + "'%s' ist keine gültige Zahl", value); + } + } + sv.set(value, false, true); + } + exec.log(this.formatVariable(variable, sv, value == null ? "=" : "->", false)); + return sv.noDef && sv.def.equals(sv.get()) ? null : sv.get(); + } +} diff --git a/java/src/game/command/commands/CommandTele.java b/server/src/main/java/server/command/commands/CommandTele.java similarity index 56% rename from java/src/game/command/commands/CommandTele.java rename to server/src/main/java/server/command/commands/CommandTele.java index 5b918c1..8baf2f2 100644 --- a/java/src/game/command/commands/CommandTele.java +++ b/server/src/main/java/server/command/commands/CommandTele.java @@ -1,30 +1,33 @@ -package game.command.commands; +package server.command.commands; import java.util.List; -import game.command.CommandEnvironment; -import game.dimension.Dimension; -import game.command.Command; -import game.command.Executor; -import game.entity.Entity; -import game.world.Vec3; + +import common.dimension.Dimension; +import common.entity.Entity; +import common.util.Vec3; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; public class CommandTele extends Command { public CommandTele() { super("tele"); this.addVector("position", false, true); - this.setParamsOptional(); this.addDimension("dim", true); + this.setParamsOptional(); this.addDouble("yaw", -180.0, 180.0); this.addDouble("pitch", -89.0, 89.0); - this.addEntityList("entities", 'e', true); + this.setParamsRequired(); + this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); } public Object exec(CommandEnvironment env, Executor exec, Vec3 position, Dimension dim, Double yaw, Double pitch, List entities) { for(Entity entity : entities) { entity.teleport(position.xCoord, position.yCoord, position.zCoord, yaw == null ? entity.rotYaw : yaw.floatValue(), pitch == null ? entity.rotPitch : pitch.floatValue(), dim.getDimensionId()); - exec.logConsole("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)position.xCoord, (int)position.yCoord, (int)position.zCoord, dim.getFormattedName(false)); + exec.log("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)position.xCoord, (int)position.yCoord, (int)position.zCoord, dim.getFormattedName(false)); } return entities.size(); } diff --git a/java/src/game/command/commands/CommandTime.java b/server/src/main/java/server/command/commands/CommandTime.java similarity index 84% rename from java/src/game/command/commands/CommandTime.java rename to server/src/main/java/server/command/commands/CommandTime.java index 0f31c8b..bcbbf59 100644 --- a/java/src/game/command/commands/CommandTime.java +++ b/server/src/main/java/server/command/commands/CommandTime.java @@ -1,20 +1,21 @@ -package game.command.commands; +package server.command.commands; -import game.command.CommandEnvironment; -import game.command.RunException; -import game.dimension.Dimension; -import game.command.Command; -import game.command.Executor; -import game.item.ItemSpaceNavigator; -import game.world.Position; -import game.world.WorldServer; +import common.dimension.Dimension; +import common.item.ItemSpaceNavigator; +import common.util.Position; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.world.WorldServer; public class CommandTime extends Command { public CommandTime() { super("time"); this.addString("time", false, "day", "night", "noon", "midnight", "sunrise", "sunset"); - + + this.setParamsOptional(); this.addFlag("absolute", 'a'); } @@ -69,7 +70,7 @@ public class CommandTime extends Command { public Object exec(CommandEnvironment env, Executor exec, String timeStr, boolean absolute) { Position pos = exec.getExecPos(); - WorldServer world = pos == null ? env.getServer().getSpace() : env.getServer().getWorld(pos.dim); + WorldServer world = pos == null ? env.getServer().getSpace() : env.getServer().getWorld(pos.dim()); long time = absolute ? 0L : world.getDayTime(); long fwd = parseDayTime(world.dimension, timeStr); if(fwd >= 0L) { @@ -89,7 +90,7 @@ public class CommandTime extends Command { dim.setDayTime(time); dim.resetWeather(); } - exec.logConsole("Zeit auf %s gesetzt", ItemSpaceNavigator.formatImperialTime(world, false)); + exec.log("Zeit auf %s gesetzt", ItemSpaceNavigator.formatImperialTime(world, false)); return time; } } diff --git a/server/src/main/java/server/command/commands/CommandTp.java b/server/src/main/java/server/command/commands/CommandTp.java new file mode 100644 index 0000000..cc4595b --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandTp.java @@ -0,0 +1,30 @@ +package server.command.commands; + +import java.util.List; + +import common.entity.Entity; +import common.init.UniverseRegistry; +import common.util.Position; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; + +public class CommandTp extends Command { + public CommandTp() { + super("tp"); + + this.addEntity("target", false, UserPolicy.NOT_SELF); + + this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); + } + + public Object exec(CommandEnvironment env, Executor exec, Entity target, List entities) { + Position pos = target.getPos(); + for(Entity entity : entities) { + entity.teleport(pos); + exec.log("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x(), (int)pos.y(), (int)pos.z(), UniverseRegistry.getDimension(pos.dim()).getFormattedName(false)); + } + return entities.size(); + } +} diff --git a/server/src/main/java/server/command/commands/CommandUsers.java b/server/src/main/java/server/command/commands/CommandUsers.java new file mode 100644 index 0000000..74da5a0 --- /dev/null +++ b/server/src/main/java/server/command/commands/CommandUsers.java @@ -0,0 +1,26 @@ +package server.command.commands; + +import java.util.Collection; +import common.color.TextColor; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.network.User; + +public class CommandUsers extends Command { + public CommandUsers() { + super("users"); + } + + public void exec(CommandEnvironment env, Executor exec) { + Collection users = env.getServer().getUsers(); + if(users.isEmpty()) { + exec.log(TextColor.DGRAY + "Es sind keine Spieler registriert"); + return; + } + exec.log(TextColor.GREEN + "Es " + (users.size() == 1 ? "ist" : "sind") + " " + TextColor.YELLOW + "%d" + TextColor.GREEN + " Spieler registriert", users.size()); + for(User user : users) { + exec.log("%s%s" + TextColor.GRAY + ": %s" + TextColor.GRAY + ", %s", user.isAdmin() ? TextColor.RED : TextColor.NEON, user.getUser(), user.isOnline() ? TextColor.DGREEN + "Online" : TextColor.DGRAY + "Offline", user.getPubkey() != null ? TextColor.YELLOW + "Pubkey" : (user.getPasswordHash() != null ? TextColor.MAGENTA + "Passwort" : TextColor.BLACK + "Kein Login")); + } + } +} diff --git a/java/src/game/command/commands/CommandWarp.java b/server/src/main/java/server/command/commands/CommandWarp.java similarity index 67% rename from java/src/game/command/commands/CommandWarp.java rename to server/src/main/java/server/command/commands/CommandWarp.java index 8f102ef..85bc447 100644 --- a/java/src/game/command/commands/CommandWarp.java +++ b/server/src/main/java/server/command/commands/CommandWarp.java @@ -1,15 +1,17 @@ -package game.command.commands; +package server.command.commands; import java.util.Collection; import java.util.List; -import game.command.CommandEnvironment; -import game.command.Command; -import game.command.Executor; -import game.command.RunException; -import game.command.StringCompleter; -import game.entity.Entity; -import game.init.UniverseRegistry; -import game.world.Position; + +import common.entity.Entity; +import common.init.UniverseRegistry; +import common.util.Position; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.command.StringCompleter; +import server.command.UserPolicy; public class CommandWarp extends Command { public CommandWarp() { @@ -23,7 +25,7 @@ public class CommandWarp extends Command { } }); - this.addEntityList("entities", 'e', true); + this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); } public Object exec(CommandEnvironment env, Executor exec, String warp, List entities) { @@ -41,12 +43,12 @@ public class CommandWarp extends Command { pos = env.getServer().getWarps().get(warp); if(pos == null) throw new RunException("Warp '%s' existiert nicht", warp); - else if(env.getServer().getWorld(pos.dim) == null) - throw new RunException("Warp '%s' hat kein Level (%s)", warp, pos.dim); + else if(env.getServer().getWorld(pos.dim()) == null) + throw new RunException("Warp '%s' hat kein Level (%s)", warp, pos.dim()); // } for(Entity entity : entities) { entity.teleport(pos); - exec.logConsole("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x, (int)pos.y, (int)pos.z, UniverseRegistry.getDimension(pos.dim).getFormattedName(false)); + exec.log("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), (int)pos.x(), (int)pos.y(), (int)pos.z(), UniverseRegistry.getDimension(pos.dim()).getFormattedName(false)); } return entities.size(); } diff --git a/java/src/game/command/commands/CommandWeather.java b/server/src/main/java/server/command/commands/CommandWeather.java similarity index 67% rename from java/src/game/command/commands/CommandWeather.java rename to server/src/main/java/server/command/commands/CommandWeather.java index 30b7ab8..25313c6 100644 --- a/java/src/game/command/commands/CommandWeather.java +++ b/server/src/main/java/server/command/commands/CommandWeather.java @@ -1,20 +1,20 @@ -package game.command.commands; +package server.command.commands; -import game.command.CommandEnvironment; -import game.command.RunException; -import game.command.Command; -import game.command.Executor; -import game.world.Weather; -import game.world.WorldServer; +import common.world.Weather; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.RunException; +import server.world.WorldServer; public class CommandWeather extends Command { public CommandWeather() { super("weather"); this.addEnum("weather", Weather.class, Weather.values()); - this.setParamsOptional(); this.addWorld("dim", true); - + + this.setParamsOptional(); this.addFlag("transition", 't'); } @@ -26,6 +26,6 @@ public class CommandWeather extends Command { world.setWeather(weather); if(!transition) world.resetWeather(); - exec.logConsole("Wetter in %s zu %s geändert", world.dimension.getFormattedName(false), weather.getDisplay()); + exec.log("Wetter in %s zu %s geändert", world.dimension.getFormattedName(false), weather.getDisplay()); } } diff --git a/java/src/game/command/commands/CommandWorld.java b/server/src/main/java/server/command/commands/CommandWorld.java similarity index 66% rename from java/src/game/command/commands/CommandWorld.java rename to server/src/main/java/server/command/commands/CommandWorld.java index a673dca..316fc18 100644 --- a/java/src/game/command/commands/CommandWorld.java +++ b/server/src/main/java/server/command/commands/CommandWorld.java @@ -1,20 +1,22 @@ -package game.command.commands; +package server.command.commands; import java.util.List; -import game.command.CommandEnvironment; -import game.command.Command; -import game.command.Executor; -import game.entity.Entity; -import game.world.BlockPos; -import game.world.WorldServer; + +import common.entity.Entity; +import common.util.BlockPos; +import server.command.Command; +import server.command.CommandEnvironment; +import server.command.Executor; +import server.command.UserPolicy; +import server.world.WorldServer; public class CommandWorld extends Command { public CommandWorld() { super("world"); - this.addWorld("dim", true); + this.addWorld("dim", false); - this.addEntityList("entities", 'e', true); + this.addEntityList("entities", 'e', true, UserPolicy.NON_ADMINS_OR_SELF); } public Object exec(CommandEnvironment env, Executor exec, WorldServer world, List entities) { @@ -31,7 +33,7 @@ public class CommandWorld extends Command { pos = pos.up(); } entity.teleport(pos, world.dimension.getDimensionId()); - exec.logConsole("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), pos.getX(), pos.getY(), pos.getZ(), world.dimension.getFormattedName(false)); + exec.log("%s nach %d, %d, %d in %s teleportiert", entity.getCommandName(), pos.getX(), pos.getY(), pos.getZ(), world.dimension.getFormattedName(false)); } return entities.size(); } diff --git a/java/src/game/network/HandshakeHandler.java b/server/src/main/java/server/network/HandshakeHandler.java similarity index 50% rename from java/src/game/network/HandshakeHandler.java rename to server/src/main/java/server/network/HandshakeHandler.java index dee4f5b..fb42a35 100755 --- a/java/src/game/network/HandshakeHandler.java +++ b/server/src/main/java/server/network/HandshakeHandler.java @@ -1,11 +1,14 @@ -package game.network; +package server.network; -import game.Server; -import game.init.Config; -import game.packet.HPacketHandshake; -import game.packet.RPacketDisconnect; +import common.network.IHandshakeHandler; +import common.network.NetConnection; +import common.network.PacketRegistry; +import common.packet.HPacketHandshake; +import common.packet.RPacketDisconnect; +import common.util.Util; +import server.Server; -public class HandshakeHandler extends NetHandler +public class HandshakeHandler implements IHandshakeHandler { private final Server server; private final NetConnection networkManager; @@ -27,19 +30,21 @@ public class HandshakeHandler extends NetHandler return; } this.networkManager.setConnectionState(PacketRegistry.LOGIN); - if (packetIn.getProtocolVersion() != Config.PROTOCOL) + if (packetIn.getProtocolVersion() != Util.PROTOCOL) { String comp; - if(packetIn.getProtocolVersion() < Config.PROTOCOL) - comp = "Der Server nutzt eine neuere Version: " + Config.VERSION; + if(packetIn.getProtocolVersion() < Util.PROTOCOL) + comp = "Der Server nutzt eine neuere Version: " + Util.VERSION; else - comp = "Der Server nutzt eine ältere Version: " + Config.VERSION; + comp = "Der Server nutzt eine ältere Version: " + Util.VERSION; this.networkManager.sendPacket(new RPacketDisconnect(comp)); this.networkManager.closeChannel(comp); } else { - this.networkManager.setNetHandler(new LoginHandler(this.server, this.networkManager)); + LoginHandler handler = new LoginHandler(this.server, this.networkManager); + this.networkManager.setNetHandler(handler); + handler.sendLoginPacket(); } } } diff --git a/server/src/main/java/server/network/LoginHandler.java b/server/src/main/java/server/network/LoginHandler.java new file mode 100755 index 0000000..10653ff --- /dev/null +++ b/server/src/main/java/server/network/LoginHandler.java @@ -0,0 +1,229 @@ +package server.network; + +import java.security.KeyPair; +import java.security.MessageDigest; +import java.security.PublicKey; +import java.security.SecureRandom; +import common.color.TextColor; +import common.log.Log; +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; +import common.network.ILoginHandler; +import common.network.IPlayer; +import common.network.NetConnection; +import common.packet.LPacketChallenge; +import common.packet.LPacketPassword; +import common.packet.LPacketPubkey; +import common.packet.LPacketResponse; +import common.packet.LPacketStartEncrypt; +import common.packet.RPacketChallenge; +import common.packet.RPacketDisconnect; +import common.packet.RPacketRequestEncrypt; +import common.packet.RPacketResponse; +import common.packet.RPacketServerConfig; +import common.util.EncryptUtil; +import server.Server; +import server.vars.SVars; + +public class LoginHandler implements ILoginHandler +{ + private static enum LoginState { + INIT, ENCRYPT, PROOF, PASSWORD, CHALLENGE, AUTHENTICATED, ACCEPTED; + } + + private static final SecureRandom TOKEN_RNG = new SecureRandom(); + + private final Server server; + public final NetConnection netManager; + private final KeyPair tempKeys; + + private LoginState state = LoginState.INIT; + private int timer; + private String loginUser; + private String loginPass; + private byte[] loginToken; + private PublicKey loginKey; + + public LoginHandler(Server server, NetConnection netManager) + { + this.netManager = netManager; + this.server = server; + this.tempKeys = EncryptUtil.createDHKeypair(); + } + + public void closeConnection(String reason) + { + try + { + Log.NETWORK.info("Trenne " + this.getConnectionInfo()); + this.netManager.sendPacket(new RPacketDisconnect(reason)); + this.netManager.closeChannel(reason); + } + catch (Exception exception) + { + Log.NETWORK.error(exception, "Fehler beim Trennen des Spielers beim Login"); + } + } + + public void onDisconnect(String reason) + { + Log.NETWORK.info(this.getConnectionInfo() + " wurde beim Login getrennt: " + TextColor.stripCodes(reason)); + } + + public String getConnectionInfo() + { + return this.loginUser != null ? (this.loginUser + " (" + this.netManager.getCutAddress() + + ")") : this.netManager.getCutAddress(); + } + + public void update() + { + if(this.state == LoginState.AUTHENTICATED) + this.tryAdvance(); + if(this.timer++ == 600) + this.closeConnection("Anmeldung dauerte zu lange"); + } + + private void tryAdvance() { + String kick = this.checkPlayer(); + if(kick != null) { + this.closeConnection(kick); + return; + } + this.server.addPlayer(this.netManager, this.loginUser); + this.state = LoginState.ACCEPTED; + } + + private String checkPlayer() { + if(this.server.getPlayer(this.loginUser) != null) + return "Nutzername '" + this.loginUser + "' ist bereits vergeben"; + User user = this.server.getUser(this.loginUser); + if(SVars.authenticate) { + if(user == null) { + if(!SVars.register) + return "Anmeldung neuer Accounts ist auf diesem Server deaktiviert (Whitelisted)"; + if(SVars.playerLimit > 0 && this.server.getPlayers().size() >= SVars.playerLimit) + return String.format("Der Server ist voll (%d/%d)!", this.server.getPlayers().size(), SVars.playerLimit); + if(this.loginKey != null) { + this.server.addUser(user = new User(this.loginUser)); + user.setPubkey(this.loginKey); + Log.NETWORK.info(this.loginUser + " registrierte sich mit Pubkey"); + } + else { + if(this.loginPass == null || this.loginPass.length() == 0) + return "Ein neues Passwort ist erforderlich um diesen Server zu betreten (mindestens " + SVars.minPassLength + " Zeichen)"; + if(this.loginPass.length() < SVars.minPassLength) + return "Passwort ist zu kurz, mindestens " + SVars.minPassLength + " Zeichen"; + this.server.addUser(user = new User(this.loginUser)); + user.setPasswordHash(EncryptUtil.hashPassword(this.loginPass)); + Log.NETWORK.info(this.loginUser + " registrierte sich mit Passwort"); + } + } + else if((user.getPasswordHash() == null && user.getPubkey() == null) || (user.getPubkey() != null ? !user.getPubkey().equals(this.loginKey) : + (this.loginPass == null || !MessageDigest.isEqual(EncryptUtil.hashPassword(this.loginPass, user.getPasswordHash().second()), user.getPasswordHash().first())))) { + return this.loginKey != null ? "Falscher Pubkey" : "Falsches Passwort"; + } + else { + Log.NETWORK.info(this.loginUser + " loggte sich mit " + (this.loginKey != null ? "Pubkey" : "Passwort") + " ein"); + } + } + if(SVars.playerLimit > 0 && this.server.getPlayers().size() >= SVars.playerLimit && (user == null || !user.isAdmin())) + return String.format("Der Server ist voll (%d/%d)!", this.server.getPlayers().size(), SVars.playerLimit); + return null; + } + + public void sendLoginPacket() { + if(this.state != LoginState.INIT) + throw new IllegalStateException("Unerwartetes Handshake-Paket"); + if(SVars.encrypt) { + this.state = LoginState.ENCRYPT; + this.netManager.sendPacket(new RPacketRequestEncrypt(this.server.getPublicKey(), this.tempKeys.getPublic())); + } + else { + this.state = LoginState.PASSWORD; + this.netManager.sendPacket(new RPacketServerConfig(SVars.accessRequired, SVars.authenticate, SVars.authenticate && SVars.passwordAuth, false)); + } + } + + public void processEncryption(LPacketStartEncrypt packet) { + if(this.state != LoginState.ENCRYPT) + throw new IllegalStateException("Unerwartetes Verschlüsselungs-Paket"); + this.netManager.startEncryption(EncryptUtil.makeKeyAgreement(this.tempKeys.getPrivate(), packet.getKey())); + this.state = LoginState.PROOF; + } + + public void processChallenge(LPacketChallenge packet) { + if(this.state != LoginState.PROOF) + throw new IllegalStateException("Unerwartetes Anforderungs-Paket"); + this.state = LoginState.PASSWORD; + this.netManager.sendPacket(new RPacketResponse(this.server.getPrivateKey(), packet.getToken()), new GenericFutureListener < Future > () { + public void operationComplete(Future u) throws Exception { + LoginHandler.this.netManager.sendPacket(new RPacketServerConfig(SVars.accessRequired, SVars.authenticate, SVars.authenticate && SVars.passwordAuth, + SVars.authenticate && SVars.pubkeyAuth)); + } + }); + } + + private boolean checkAccess(String access) { + if(SVars.accessRequired) { + if(SVars.password.length() < 8) { + this.closeConnection("Es ist kein Zugangspasswort für diesen Server konfiguriert"); + return false; + } + if(!SVars.password.equals(access)) { + this.closeConnection("Falsches Zugangspasswort"); + return false; + } + } + return true; + } + + public void processPassword(LPacketPassword packet) { + if(this.state != LoginState.PASSWORD) + throw new IllegalStateException("Unerwartetes Passwort-Paket"); + this.loginUser = packet.getUser(); + if(this.loginUser.isEmpty() || !IPlayer.isValidUser(this.loginUser)) + throw new IllegalStateException("Ungültiger Nutzername!"); + if(!SVars.passwordAuth && SVars.authenticate) { + this.closeConnection("Dieser Server " + (SVars.pubkeyAuth && SVars.encrypt ? "benötigt einen öffentlichen Schlüssel zur Authentifizierung" : "hat keine Authentifizierungsmethode konfiguriert")); + return; + } + if(!this.checkAccess(packet.getAccess())) + return; + if(SVars.authenticate) + this.loginPass = packet.getPassword(); + this.state = LoginState.AUTHENTICATED; + } + + public void processPubkey(LPacketPubkey packet) { + if(this.state != LoginState.PASSWORD) + throw new IllegalStateException("Unerwartetes Pubkey-Paket"); + this.loginUser = packet.getUser(); + if(this.loginUser.isEmpty() || !IPlayer.isValidUser(this.loginUser)) + throw new IllegalStateException("Ungültiger Nutzername!"); + if((!SVars.pubkeyAuth || !SVars.encrypt) && SVars.authenticate) { + this.closeConnection("Dieser Server " + (SVars.passwordAuth ? "benötigt ein Passwort zur Authentifizierung" : "hat keine Authentifizierungsmethode konfiguriert")); + return; + } + if(!this.checkAccess(packet.getAccess())) + return; + if(SVars.authenticate) { + this.loginKey = packet.getKey(); + this.loginToken = new byte[32]; + TOKEN_RNG.nextBytes(this.loginToken); + this.netManager.sendPacket(new RPacketChallenge(this.loginToken)); + this.state = LoginState.CHALLENGE; + } + else { + this.state = LoginState.AUTHENTICATED; + } + } + + public void processResponse(LPacketResponse packet) { + if(this.state != LoginState.CHALLENGE) + throw new IllegalStateException("Unerwartetes Beweis-Paket"); + if(!packet.verifyToken(this.loginKey, this.loginToken)) + throw new IllegalStateException("Fehlerhaftes Beweis-Token"); + this.state = LoginState.AUTHENTICATED; + } +} diff --git a/java/src/game/network/Player.java b/server/src/main/java/server/network/Player.java similarity index 78% rename from java/src/game/network/Player.java rename to server/src/main/java/server/network/Player.java index 8a19a68..5299582 100755 --- a/java/src/game/network/Player.java +++ b/server/src/main/java/server/network/Player.java @@ -1,139 +1,141 @@ -package game.network; +package server.network; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; -import java.util.Map.Entry; import java.util.Set; - import java.util.function.Predicate; -import game.collect.Lists; -import game.future.Futures; -import game.Server; -import game.block.Block; -import game.block.BlockFence; -import game.block.BlockFenceGate; -import game.block.BlockWall; -import game.clipboard.BlockTransform; -import game.clipboard.ClipboardBlock; -import game.clipboard.ClipboardPlacer; -import game.clipboard.Rotation; -import game.clipboard.RotationValue; -import game.clipboard.Vector; -import game.color.TextColor; -import game.command.Executor; -import game.dimension.Dimension; -import game.entity.Entity; -import game.entity.animal.EntityHorse; -import game.entity.item.EntityItem; -import game.entity.item.EntityXp; -import game.entity.npc.Alignment; -import game.entity.npc.EntityHuman; -import game.entity.npc.EntityNPC; -import game.entity.npc.PlayerCharacter; -import game.entity.projectile.EntityArrow; -import game.entity.types.EntityLiving; -import game.init.BlockRegistry; -import game.init.Config; -import game.init.Config.ValueType; -import game.init.EntityRegistry; -import game.init.Items; -import game.init.RotationRegistry; -import game.init.SoundEvent; -import game.init.UniverseRegistry; -import game.inventory.Container; -import game.inventory.ContainerChest; -import game.inventory.ContainerHorseInventory; -import game.inventory.ContainerMerchant; -import game.inventory.ICrafting; -import game.inventory.IInventory; -import game.inventory.InventoryPlayer; -import game.inventory.Slot; -import game.inventory.SlotCrafting; -import game.item.ItemArmor; -import game.item.ItemControl; -import game.item.ItemStack; -import game.log.Log; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.nbt.NBTTagString; -import game.packet.CPacketAction; -import game.packet.CPacketAction.Action; -import game.packet.CPacketBook; -import game.packet.CPacketBreak; -import game.packet.CPacketCheat; -import game.packet.CPacketClick; -import game.packet.CPacketComplete; -import game.packet.CPacketInput; -import game.packet.CPacketKeepAlive; -import game.packet.CPacketMessage; -import game.packet.CPacketPlace; -import game.packet.CPacketPlayer; -import game.packet.CPacketSign; -import game.packet.CPacketSkin; -import game.packet.S18PacketEntityTeleport; -import game.packet.S1APacketEntityStatus; -import game.packet.S1BPacketEntityAttach; -import game.packet.S1DPacketEntityEffect; -import game.packet.S1EPacketRemoveEntityEffect; -import game.packet.S29PacketSoundEffect; -import game.packet.S2DPacketOpenWindow; -import game.packet.S2EPacketCloseWindow; -import game.packet.S2FPacketSetSlot; -import game.packet.S30PacketWindowItems; -import game.packet.S31PacketWindowProperty; -import game.packet.S32PacketConfirmTransaction; -import game.packet.S36PacketSignEditorOpen; -import game.packet.S39PacketPlayerAbilities; -import game.packet.S3APacketTabComplete; -import game.packet.SPacketAnimation; -import game.packet.SPacketBlockChange; -import game.packet.SPacketCharacterList; -import game.packet.SPacketChunkData; -import game.packet.SPacketDestroyEntities; -import game.packet.SPacketDisconnect; -import game.packet.SPacketKeepAlive; -import game.packet.SPacketLoading; -import game.packet.SPacketMapChunkBulk; -import game.packet.SPacketMessage; -import game.packet.SPacketMessage.Type; -import game.packet.SPacketPlayerPosLook; -import game.packet.SPacketServerTick; -import game.packet.SPacketSetExperience; -import game.packet.SPacketSkin; -import game.packet.SPacketTrades; -import game.packet.SPacketUpdateHealth; -import game.potion.Potion; -import game.potion.PotionEffect; -import game.tileentity.IInteractionObject; -import game.tileentity.ILockableContainer; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityMachine; -import game.tileentity.TileEntitySign; -import game.util.CharValidator; -import game.util.ExtMath; -import game.village.MerchantRecipeList; -import game.world.BlockPos; -import game.world.BoundingBox; -import game.world.Chunk; -import game.world.ChunkPos; -import game.world.Facing; -import game.world.IntHashMap; -import game.world.PortalType; -import game.world.Position; -import game.world.Region; -import game.world.State; -import game.world.Vec3i; -import game.world.World; -import game.world.WorldPos; -import game.world.WorldServer; -import io.netty.util.concurrent.Future; -import io.netty.util.concurrent.GenericFutureListener; +import common.block.Block; +import common.block.artificial.BlockFence; +import common.block.artificial.BlockFenceGate; +import common.block.artificial.BlockWall; +import common.collect.Lists; +import common.color.TextColor; +import common.dimension.Dimension; +import common.entity.Entity; +import common.entity.animal.EntityHorse; +import common.entity.item.EntityItem; +import common.entity.item.EntityXp; +import common.entity.npc.Alignment; +import common.entity.npc.EntityHuman; +import common.entity.npc.EntityNPC; +import common.entity.npc.PlayerCharacter; +import common.entity.projectile.EntityArrow; +import common.entity.types.EntityLiving; +import common.future.Futures; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.EntityRegistry; +import common.init.Items; +import common.init.SoundEvent; +import common.init.UniverseRegistry; +import common.inventory.Container; +import common.inventory.ContainerChest; +import common.inventory.ContainerEnchantment; +import common.inventory.ContainerEntityInventory; +import common.inventory.ContainerMerchant; +import common.inventory.ICrafting; +import common.inventory.IInventory; +import common.inventory.InventoryPlayer; +import common.inventory.Slot; +import common.inventory.SlotCrafting; +import common.item.ItemArmor; +import common.item.ItemControl; +import common.item.ItemStack; +import common.log.Log; +import common.net.util.concurrent.Future; +import common.net.util.concurrent.GenericFutureListener; +import common.network.IPlayer; +import common.network.NetConnection; +import common.network.NetHandler; +import common.network.Packet; +import common.packet.CPacketAction; +import common.packet.CPacketBreak; +import common.packet.CPacketCheat; +import common.packet.CPacketClick; +import common.packet.CPacketComplete; +import common.packet.CPacketForm; +import common.packet.CPacketInput; +import common.packet.CPacketKeepAlive; +import common.packet.CPacketMessage; +import common.packet.CPacketPlace; +import common.packet.CPacketPlayer; +import common.packet.CPacketSign; +import common.packet.CPacketSkin; +import common.packet.SPacketEntityTeleport; +import common.packet.SPacketEntityStatus; +import common.packet.SPacketEntityAttach; +import common.packet.SPacketEntityEffect; +import common.packet.SPacketRemoveEntityEffect; +import common.packet.SPacketSoundEffect; +import common.packet.SPacketOpenWindow; +import common.packet.SPacketCloseWindow; +import common.packet.SPacketSetSlot; +import common.packet.SPacketWindowItems; +import common.packet.SPacketWindowProperty; +import common.packet.SPacketConfirmTransaction; +import common.packet.SPacketSignEditorOpen; +import common.packet.SPacketPlayerAbilities; +import common.packet.SPacketTabComplete; +import common.packet.SPacketAnimation; +import common.packet.SPacketBlockChange; +import common.packet.SPacketCharacterList; +import common.packet.SPacketChunkData; +import common.packet.SPacketDestroyEntities; +import common.packet.SPacketDisconnect; +import common.packet.SPacketDisplayForm; +import common.packet.SPacketKeepAlive; +import common.packet.SPacketLoading; +import common.packet.SPacketMapChunkBulk; +import common.packet.SPacketMessage; +import common.packet.SPacketPlayerPosLook; +import common.packet.SPacketServerTick; +import common.packet.SPacketSetExperience; +import common.packet.SPacketSkin; +import common.packet.SPacketTrades; +import common.packet.SPacketUpdateHealth; +import common.packet.CPacketAction.Action; +import common.packet.SPacketMessage.Type; +import common.potion.Potion; +import common.potion.PotionEffect; +import common.tags.TagObject; +import common.tileentity.IInteractionObject; +import common.tileentity.ILockableContainer; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityDevice; +import common.tileentity.TileEntitySign; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ChunkPos; +import common.util.ExtMath; +import common.util.Facing; +import common.util.IntHashMap; +import common.util.PortalType; +import common.util.Position; +import common.util.Vec3i; +import common.util.WorldPos; +import common.village.MerchantRecipeList; +import common.world.BlockArray; +import common.world.State; +import common.world.World; +import server.Server; +import server.clipboard.BlockTransform; +import server.clipboard.ClipboardBlock; +import server.clipboard.ClipboardPlacer; +import server.clipboard.Rotation; +import server.clipboard.RotationRegistry; +import server.clipboard.RotationValue; +import server.clipboard.Vector; +import server.command.Executor; +import server.util.Form; +import server.vars.SVars; +import server.world.ChunkServer; +import server.world.Region; +import server.world.WorldServer; -public class Player extends NetHandler implements ICrafting, Executor +public class Player extends User implements ICrafting, Executor, IPlayer { private static enum EditAction { SELECT("Auswahlmodus"), COPYPASTE("Kopiermodus"), TRANSFORM("Drehmodus"); @@ -145,32 +147,10 @@ public class Player extends NetHandler implements ICrafting, Executor } } - public static class UserValidator implements CharValidator { - public boolean valid(char ch) { - return (ch >= 'a' && ch <= 'z') || (ch >= '0' && ch <= '9') || ch == '_' || ch == '-'; - } - } - - public static class NickValidator implements CharValidator { - public boolean valid(char ch) { - return (ch <= 0xff && Character.isLetterOrDigit(ch)) || (ch >= 32 && ch < 126); - } - } - - public static final int MAX_USER_LENGTH = 16; - public static final int MAX_NICK_LENGTH = 32; - public static final int MAX_PASS_LENGTH = 64; - public static final int MAX_CMD_LENGTH = 1024; - public static final int MAX_INFO_LENGTH = 4096; - - public static final CharValidator VALID_USER = new UserValidator(); - public static final CharValidator VALID_NICK = new NickValidator(); - private final NetConnection connection; private final Server server; - private final String user; private final IntHashMap transactions = new IntHashMap(); - private final List characters = Lists.newArrayList(); + private final List characters = Lists.newArrayList(); private EntityNPC entity; private int tickTime; @@ -184,11 +164,9 @@ public class Player extends NetHandler implements ICrafting, Executor private double lastPosZ; private boolean hasMoved = true; private boolean charEditor = true; + private Form form; - private boolean admin; private int ping; - private boolean deleted; - private String password; private boolean profiling; private int selectionDim = Integer.MIN_VALUE; @@ -210,35 +188,31 @@ public class Player extends NetHandler implements ICrafting, Executor private int initialBlockDamage; private int durabilityRemainingOnBlock = -1; - public boolean isChangingQuantityOnly; + private boolean isChangingQuantityOnly; private int respawnTimer; - public double managedPosX; - public double managedPosZ; + private double managedPosX; + private double managedPosZ; private float combinedHealth = Float.MIN_VALUE; private float lastHealth = -1.0E8F; private int lastExperience = -99999999; private int currentWindowId; + private int currentFormId; private int pointedEntity; private BlockPos pointedPosition; - public final List loadedChunks = new LinkedList(); + private final List loadedChunks = new LinkedList(); private final List destroyedItemsNetCache = new LinkedList(); -// private final Set statsQueue = Sets.newHashSet(); -// private final Map stats = Maps.newConcurrentMap(); - public static boolean isValidUser(String user) { - return VALID_USER.valid(user); - } + private Position forcedPos; + private Executor forcedExec; + private Position deathPos; + private Position teleportPos; - public static boolean isValidNick(String user) { - return VALID_NICK.valid(user); - } - - public Player(Server server, NetConnection connection, String user) + public Player(Server server, NetConnection connection, String user) { - this.user = user; + super(user); this.server = server; this.connection = connection; // this.local = connection.isLocalChannel(); @@ -276,7 +250,7 @@ public class Player extends NetHandler implements ICrafting, Executor this.pingKey = (int)this.lastPingTime; this.sendPacket(new SPacketKeepAlive(this.pingKey)); } - if(this.admin && this.profiling) + if(this.isAdmin() && this.profiling) this.sendPacket(new SPacketServerTick((int)this.server.getLastTick())); if(this.respawnTimer > 0) { if(--this.respawnTimer == 0) { @@ -285,6 +259,10 @@ public class Player extends NetHandler implements ICrafting, Executor } } + public boolean isOnline() { + return true; + } + public void displayLoading(String message) { this.sendPacket(new SPacketLoading(message)); } @@ -298,13 +276,14 @@ public class Player extends NetHandler implements ICrafting, Executor } public void onEntityDeath() { + this.deathPos = this.entity.getPos(); this.entity.sendDeathMessage(); - if (!Config.keepInventory && Config.playerDrop) + if (!SVars.keepInventory && SVars.playerDrop) { this.entity.inventory.dropAllItems(); } - if(Config.skullDrop) { + if(SVars.skullDrop) { ItemStack stack = new ItemStack(Items.skull, 1, 0); this.entity.dropItem(stack, true, false); } @@ -329,8 +308,8 @@ public class Player extends NetHandler implements ICrafting, Executor // this.removeStat(StatRegistry.timeSinceDeathStat); this.entity.resetCombat(); - if(Config.respawnTime > 0) - this.respawnTimer = ExtMath.clampi(Config.respawnTime, 2, 20); + if(SVars.respawnTime > 0) + this.respawnTimer = ExtMath.clampi(SVars.respawnTime, 2, 20); } public boolean isInEditor() { @@ -344,10 +323,6 @@ public class Player extends NetHandler implements ICrafting, Executor public EntityNPC getEntity() { return this.entity; } - - public String getUser() { - return this.user; - } // public boolean isLocal() { // return this.local; @@ -356,22 +331,6 @@ public class Player extends NetHandler implements ICrafting, Executor public int getLatency() { return this.ping; } - - public boolean isAdmin() { - return this.admin; // || this.local; - } - - public boolean getAdmin() { - return this.admin; - } - - public void setPassword(String pass) { - this.password = pass; - } - - public String getPassword() { - return this.password; - } @@ -419,7 +378,7 @@ public class Player extends NetHandler implements ICrafting, Executor BlockPos blockpos = new BlockPos(i, j, k); Block block = this.entity.worldObj.getState(blockpos).getBlock(); - if (block.getMaterial() == Material.air) + if (block == Blocks.air) { Block block1 = this.entity.worldObj.getState(blockpos.down()).getBlock(); @@ -437,6 +396,11 @@ public class Player extends NetHandler implements ICrafting, Executor { this.currentWindowId = this.currentWindowId % 100 + 1; } + + private void getNextFormId() + { + this.currentFormId = this.currentFormId % 100 + 1; + } public void displayTradeGui(EntityNPC npc) { @@ -446,7 +410,7 @@ public class Player extends NetHandler implements ICrafting, Executor this.entity.openContainer.onCraftGuiOpened(this); IInventory iinventory = ((ContainerMerchant)this.entity.openContainer).getMerchantInventory(); String ichatcomponent = npc.getName(); - this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "trade", ichatcomponent, iinventory.getSizeInventory())); + this.sendPacket(new SPacketOpenWindow(this.currentWindowId, "trade", ichatcomponent, iinventory.getSizeInventory())); MerchantRecipeList merchantrecipelist = npc.getTrades(this.entity); if (merchantrecipelist != null) @@ -462,7 +426,7 @@ public class Player extends NetHandler implements ICrafting, Executor { if (!this.isChangingQuantityOnly) { - this.sendPacket(new S2FPacketSetSlot(-1, -1, this.entity.inventory.getItemStack())); + this.sendPacket(new SPacketSetSlot(-1, -1, this.entity.inventory.getItemStack())); } } @@ -498,25 +462,19 @@ public class Player extends NetHandler implements ICrafting, Executor public void clonePlayer(EntityNPC oldPlayer) { - if(Config.keepInventory) + this.lastExperience = -1; + this.lastHealth = -1.0F; + if(SVars.keepInventory) this.entity.inventory.copyInventory(oldPlayer.inventory); this.entity.experienceLevel = oldPlayer.experienceLevel; this.entity.experienceTotal = oldPlayer.experienceTotal; this.entity.experience = oldPlayer.experience; - this.entity.setXPSeed(oldPlayer.getXPSeed()); + this.entity.setEnchSeed(oldPlayer.getEnchSeed()); this.entity.setWarpChest(oldPlayer.getWarpChest()); -// this.entity.getDataWatcher().updateObject(10, Integer.valueOf(oldPlayer.getDataWatcher().getWatchableObjectInt(10))); - this.lastExperience = -1; - this.lastHealth = -1.0F; -// this.destroyedItemsNetCache.addAll(oldPlayer.connection.destroyedItemsNetCache); this.entity.setSkin(oldPlayer.getSkin()); - this.entity.getDataWatcher().updateObject(29, oldPlayer.getDataWatcher().getWatchableObjectFloat(29)); -// this.entity.getDataWatcher().updateObject(11, oldPlayer.getDataWatcher().getWatchableObjectByte(11)); - this.entity.getDataWatcher().updateObject(1, oldPlayer.getDataWatcher().getWatchableObjectString(1)); - this.entity.getDataWatcher().updateObject(18, oldPlayer.getDataWatcher().getWatchableObjectByte(18)); + this.entity.setHeight(oldPlayer.getHeight()); + this.entity.setCustomNameTag(oldPlayer.getCustomNameTag()); this.entity.setAlignment(oldPlayer.getAlignment()); -// this.stats.putAll(oldPlayer.stats); -// this.statsQueue.addAll(oldPlayer.statsQueue); } public void removeEntity(Entity p_152339_1_) @@ -570,7 +528,7 @@ public class Player extends NetHandler implements ICrafting, Executor { if (this.entity != null) { - this.sendPacket(new S39PacketPlayerAbilities(this.entity)); + this.sendPacket(new SPacketPlayerAbilities(this.entity)); this.entity.updateEffectMeta(); } } @@ -607,6 +565,10 @@ public class Player extends NetHandler implements ICrafting, Executor this.sendPacket(new SPacketMessage(String.format(format, args), Type.HOTBAR)); } + private WorldServer getEntityWorld() { + return (WorldServer)this.entity.getServerWorld(); + } + public void sendPickupMessage(Entity entity, int amount) { if(entity instanceof EntityItem) if(amount == 1) @@ -622,58 +584,34 @@ public class Player extends NetHandler implements ICrafting, Executor } public void sendThrowMessage(ItemStack stack) { - if(stack.stackSize == 1) + if(stack.size == 1) this.addFeed(TextColor.DRED + "* %s weg geworfen", stack.getColoredName(TextColor.DRED)); else - this.addFeed(TextColor.DRED + "* %d %s weg geworfen", stack.stackSize, + this.addFeed(TextColor.DRED + "* %d %s weg geworfen", stack.size, stack.getColoredName(TextColor.DRED)); } - public void readFromNBT(NBTTagCompound tag) { - this.admin = tag.getBoolean("admin"); - if(tag.hasKey("password", 8)) - this.password = tag.getString("password"); - this.selected = tag.getInteger("selected"); - NBTTagList list = tag.getTagList("characters", 10); - for(int z = 0; z < list.tagCount(); z++) { - this.characters.add(list.getCompoundTagAt(z)); + public void readTags(TagObject tag) { + this.selected = tag.getInt("selected"); + List list = tag.getList("characters"); + for(int z = 0; z < list.size(); z++) { + this.characters.add(list.get(z)); } this.selected = Math.min(this.selected, this.characters.size() - 1); this.charEditor = this.selected < 0; -// this.stats.clear(); -// if(tag.hasKey("Stats", 10)) { -// NBTTagCompound stats = tag.getCompoundTag("Stats"); -// for(String key : stats.getKeySet()) { -// StatBase stat = StatRegistry.getStat(key); -// if(stat == null) { -// Log.warn("Ungültige Statistik: Statistik '" + key + "' ist unbekannt"); -// continue; -// } -// this.stats.put(stat, stats.getInteger(key)); -// } -// } } - public void writeToNBT(NBTTagCompound tag) { - if(this.admin) - tag.setBoolean("admin", this.admin); - if(this.password != null) - tag.setString("password", this.password); + public void writeTags(TagObject tag) { if(!this.characters.isEmpty()) { - tag.setInteger("selected", this.selected); - NBTTagList list = new NBTTagList(); - for(NBTTagCompound etag : this.characters) { - list.appendTag(etag); + tag.setInt("selected", this.selected); + List list = Lists.newArrayList(); + for(TagObject etag : this.characters) { + list.add(etag); } - tag.setTag("characters", list); + tag.setList("characters", list); } -// NBTTagCompound stats = new NBTTagCompound(); -// for(Entry entry : this.stats.entrySet()) { -// stats.setInteger(entry.getKey().statId, entry.getValue()); -// } -// tag.setTag("Stats", stats); } @@ -700,6 +638,7 @@ public class Player extends NetHandler implements ICrafting, Executor } public void teleport(double x, double y, double z, float yaw, float pitch, int dimension) { + this.teleportPos = this.entity.getPos(); x = ExtMath.clampd(x, -World.MAX_SIZE + 1, World.MAX_SIZE - 1); z = ExtMath.clampd(z, -World.MAX_SIZE + 1, World.MAX_SIZE - 1); // this.setLastTeleport(this.getLocation()); @@ -720,20 +659,20 @@ public class Player extends NetHandler implements ICrafting, Executor public void mountEntity(Entity entityIn) { - this.sendPacket(new S1BPacketEntityAttach(0, this.entity, this.entity.vehicle)); + this.sendPacket(new SPacketEntityAttach(0, this.entity, this.entity.vehicle)); this.setPlayerLocation(this.entity.posX, this.entity.posY, this.entity.posZ, this.entity.rotYaw, this.entity.rotPitch); } public void openEditSign(TileEntitySign signTile) { signTile.setPlayer(this.entity); - this.sendPacket(new S36PacketSignEditorOpen(signTile.getPos())); + this.sendPacket(new SPacketSignEditorOpen(signTile.getPos())); } public void displayGui(IInteractionObject guiOwner) { this.getNextWindowId(); - this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, guiOwner.getGuiID(), guiOwner.getCommandName())); + this.sendPacket(new SPacketOpenWindow(this.currentWindowId, guiOwner.getGuiID(), guiOwner.getCommandName())); this.entity.openContainer = guiOwner.createContainer(this.entity.inventory, this.entity); this.entity.openContainer.windowId = this.currentWindowId; this.entity.openContainer.onCraftGuiOpened(this); @@ -753,27 +692,27 @@ public class Player extends NetHandler implements ICrafting, Executor if (ilockablecontainer.isLocked() && !this.entity.canOpen(ilockablecontainer.getLockCode())) // && !this.isSpectator()) { this.addHotbar(TextColor.RED + "%s ist verschlossen!", chestInventory.getCommandName()); - this.sendPacket(new S29PacketSoundEffect(SoundEvent.DOOR, this.entity.posX, this.entity.posY, this.entity.posZ, 1.0F)); + this.sendPacket(new SPacketSoundEffect(SoundEvent.DOOR, this.entity.posX, this.entity.posY, this.entity.posZ, 1.0F)); return; } } this.getNextWindowId(); - if (chestInventory instanceof TileEntityMachine) + if (chestInventory instanceof TileEntityDevice) { - this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "machine_" + ((IInteractionObject)chestInventory).getGuiID(), chestInventory.getCommandName(), chestInventory.getSizeInventory(), - ((TileEntityMachine)chestInventory).getPos())); + this.sendPacket(new SPacketOpenWindow(this.currentWindowId, "tile", chestInventory.getCommandName(), chestInventory.getSizeInventory(), + ((TileEntityDevice)chestInventory).getPos())); this.entity.openContainer = ((IInteractionObject)chestInventory).createContainer(this.entity.inventory, this.entity); } else if (chestInventory instanceof IInteractionObject) { - this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, ((IInteractionObject)chestInventory).getGuiID(), chestInventory.getCommandName(), chestInventory.getSizeInventory())); + this.sendPacket(new SPacketOpenWindow(this.currentWindowId, ((IInteractionObject)chestInventory).getGuiID(), chestInventory.getCommandName(), chestInventory.getSizeInventory())); this.entity.openContainer = ((IInteractionObject)chestInventory).createContainer(this.entity.inventory, this.entity); } else { - this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "container", chestInventory.getCommandName(), chestInventory.getSizeInventory())); + this.sendPacket(new SPacketOpenWindow(this.currentWindowId, "container", chestInventory.getCommandName(), chestInventory.getSizeInventory())); this.entity.openContainer = new ContainerChest(this.entity.inventory, chestInventory, this.entity); } @@ -781,7 +720,7 @@ public class Player extends NetHandler implements ICrafting, Executor this.entity.openContainer.onCraftGuiOpened(this); } - public void displayGUIHorse(EntityHorse horse, IInventory horseInventory) + public void displayEntityGui(Entity entity, IInventory inventory) { if (this.entity.openContainer != this.entity.inventoryContainer) { @@ -789,8 +728,8 @@ public class Player extends NetHandler implements ICrafting, Executor } this.getNextWindowId(); - this.sendPacket(new S2DPacketOpenWindow(this.currentWindowId, "EntityHorse", horseInventory.getCommandName(), horseInventory.getSizeInventory(), horse.getId())); - this.entity.openContainer = new ContainerHorseInventory(this.entity.inventory, horseInventory, horse, this.entity); + this.sendPacket(new SPacketOpenWindow(this.currentWindowId, "entity", inventory.getCommandName(), inventory.getSizeInventory(), entity.getId())); + this.entity.openContainer = new ContainerEntityInventory(this.entity.inventory, inventory, entity, this.entity); this.entity.openContainer.windowId = this.currentWindowId; this.entity.openContainer.onCraftGuiOpened(this); } @@ -807,7 +746,7 @@ public class Player extends NetHandler implements ICrafting, Executor public void closeScreen() { - this.sendPacket(new S2EPacketCloseWindow(this.entity.openContainer.windowId)); + this.sendPacket(new SPacketCloseWindow(this.entity.openContainer.windowId)); this.closeContainer(); } @@ -826,7 +765,7 @@ public class Player extends NetHandler implements ICrafting, Executor public void onItemUseFinish() { - this.sendPacket(new S1APacketEntityStatus(this.entity, (byte)9)); + this.sendPacket(new SPacketEntityStatus(this.entity, (byte)9)); } // /** @@ -844,17 +783,17 @@ public class Player extends NetHandler implements ICrafting, Executor public void onNewEffect(PotionEffect id) { - this.sendPacket(new S1DPacketEntityEffect(this.entity.getId(), id)); + this.sendPacket(new SPacketEntityEffect(this.entity.getId(), id)); } public void onChangedEffect(PotionEffect id, boolean added) { - this.sendPacket(new S1DPacketEntityEffect(this.entity.getId(), id)); + this.sendPacket(new SPacketEntityEffect(this.entity.getId(), id)); } public void onFinishedEffect(PotionEffect effect) { - this.sendPacket(new S1EPacketRemoveEntityEffect(this.entity.getId(), effect)); + this.sendPacket(new SPacketRemoveEntityEffect(this.entity.getId(), effect)); } public void setPositionAndUpdate(double x, double y, double z) @@ -864,22 +803,22 @@ public class Player extends NetHandler implements ICrafting, Executor public void onCriticalHit(Entity entityHit) { - this.entity.getServerWorld().sendToAllTrackingAndSelf(this.entity, new SPacketAnimation(entityHit, 4)); + this.getEntityWorld().sendToAllTrackingAndSelf(this.entity, new SPacketAnimation(entityHit, 4)); } public void onEnchantmentCritical(Entity entityHit) { - this.entity.getServerWorld().sendToAllTrackingAndSelf(this.entity, new SPacketAnimation(entityHit, 5)); + this.getEntityWorld().sendToAllTrackingAndSelf(this.entity, new SPacketAnimation(entityHit, 5)); } public void updateEffectMeta() { - this.entity.getServerWorld().updateTrackedPlayer(this.entity); + this.getEntityWorld().updateTrackedPlayer(this.entity); } public void playSound(SoundEvent name, float volume) { - this.server.sendNearExcept(this.entity, this.entity.posX, this.entity.posY, this.entity.posZ, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.entity.worldObj.dimension.getDimensionId(), new S29PacketSoundEffect(name, this.entity.posX, this.entity.posY, this.entity.posZ, volume)); + this.server.sendNearExcept(this.entity, this.entity.posX, this.entity.posY, this.entity.posZ, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.entity.worldObj.dimension.getDimensionId(), new SPacketSoundEffect(name, this.entity.posX, this.entity.posY, this.entity.posZ, volume)); } @@ -899,7 +838,7 @@ public class Player extends NetHandler implements ICrafting, Executor { if (!this.isChangingQuantityOnly) { - this.sendPacket(new S2FPacketSetSlot(containerToSend.windowId, slotInd, stack)); + this.sendPacket(new SPacketSetSlot(containerToSend.windowId, slotInd, stack)); } } } @@ -911,24 +850,115 @@ public class Player extends NetHandler implements ICrafting, Executor public void updateCraftingInventory(Container containerToSend, List itemsList) { - this.sendPacket(new S30PacketWindowItems(containerToSend.windowId, itemsList)); - this.sendPacket(new S2FPacketSetSlot(-1, -1, this.entity.inventory.getItemStack())); + this.sendPacket(new SPacketWindowItems(containerToSend.windowId, itemsList)); + this.sendPacket(new SPacketSetSlot(-1, -1, this.entity.inventory.getItemStack())); } public void sendProgressBarUpdate(Container containerIn, int varToUpdate, int newValue) { - this.sendPacket(new S31PacketWindowProperty(containerIn.windowId, varToUpdate, newValue)); + this.sendPacket(new SPacketWindowProperty(containerIn.windowId, varToUpdate, newValue)); } public void sendAllWindowProperties(Container p_175173_1_, IInventory p_175173_2_) { for (int i = 0; i < p_175173_2_.getFieldCount(); ++i) { - this.sendPacket(new S31PacketWindowProperty(p_175173_1_.windowId, i, p_175173_2_.getField(i))); + this.sendPacket(new SPacketWindowProperty(p_175173_1_.windowId, i, p_175173_2_.getField(i))); } } + + public static SPacketChunkData.Extracted getExtractedData(ChunkServer chunk, boolean biomes, boolean overworld, int[] extend) + { + Set aextendedblockstorage = chunk.getStorage(); + SPacketChunkData.Extracted s21packetchunkdata$extracted = new SPacketChunkData.Extracted(); + List list = Lists.newArrayList(); + + if(extend == null) { + for(BlockArray arr : aextendedblockstorage) { + if(arr != null && (!biomes || !arr.isEmpty())) + list.add(arr); + } + } + else { + for(int cy : extend) { + BlockArray arr = chunk.getArray(cy); + if(arr != null && (!biomes || !arr.isEmpty())) + list.add(arr); + } + } + extend = new int[list.size()]; + for(int z = 0; z < extend.length; z++) { + extend[z] = list.get(z).getY() >> 4; + } + + s21packetchunkdata$extracted.extend = extend; + s21packetchunkdata$extracted.data = new byte[SPacketChunkData.getSize(extend.length, overworld, biomes)]; + int j = 0; + + for (BlockArray extendedblockstorage1 : list) + { + char[] achar = extendedblockstorage1.getData(); + + for (char c0 : achar) + { + s21packetchunkdata$extracted.data[j++] = (byte)(c0 & 255); + s21packetchunkdata$extracted.data[j++] = (byte)(c0 >> 8 & 255); + } + } + + for (BlockArray extendedblockstorage2 : list) + { + j = copyTo(extendedblockstorage2.getBlocklight().getData(), s21packetchunkdata$extracted.data, j); + } + + if (overworld) + { + for (BlockArray extendedblockstorage3 : list) + { + j = copyTo(extendedblockstorage3.getSkylight().getData(), s21packetchunkdata$extracted.data, j); + } + } + + if (biomes) + { + copyTo(chunk.getBiomes(), s21packetchunkdata$extracted.data, j); + } + + return s21packetchunkdata$extracted; + } + + private static int copyTo(byte[] src, byte[] dest, int offset) + { + System.arraycopy(src, 0, dest, offset, src.length); + return offset + src.length; + } + + public static SPacketChunkData getPacket(ChunkServer chunkIn, boolean biomes, int[] extend, boolean sky) + { + return new SPacketChunkData(chunkIn.xPos, chunkIn.zPos, biomes, getExtractedData(chunkIn, biomes, sky, extend)); + } + + private static SPacketMapChunkBulk getPacket(List chunks, boolean sky) + { + int i = chunks.size(); + int[] xPositions = new int[i]; + int[] zPositions = new int[i]; + SPacketChunkData.Extracted[] chunksData = new SPacketChunkData.Extracted[i]; + + for (int j = 0; j < i; ++j) + { + ChunkServer chunk = chunks.get(j); + SPacketChunkData.Extracted s21packetchunkdata$extracted = getExtractedData(chunk, true, sky, null); + xPositions[j] = chunk.xPos; + zPositions[j] = chunk.zPos; + chunksData[j] = s21packetchunkdata$extracted; + } + + return new SPacketMapChunkBulk(xPositions, zPositions, chunksData, sky); + } + public void updateEntity() { @@ -965,7 +995,7 @@ public class Player extends NetHandler implements ICrafting, Executor if (!this.loadedChunks.isEmpty()) { - List list = Lists.newArrayList(); + List list = Lists.newArrayList(); Iterator iterator1 = this.loadedChunks.iterator(); List list1 = Lists.newArrayList(); @@ -979,12 +1009,12 @@ public class Player extends NetHandler implements ICrafting, Executor { if (this.entity.worldObj.isBlockLoaded(new BlockPos(chunkcoordintpair.x << 4, 0, chunkcoordintpair.z << 4))) { - Chunk chunk = this.entity.worldObj.getChunk(chunkcoordintpair.x, chunkcoordintpair.z); + ChunkServer chunk = this.getEntityWorld().getChunk(chunkcoordintpair.x, chunkcoordintpair.z); if (chunk.isPopulated()) { list.add(chunk); - list1.addAll(((WorldServer)this.entity.worldObj).getTileEntitiesIn(chunkcoordintpair.x * 16, 0, chunkcoordintpair.z * 16, chunkcoordintpair.x * 16 + 16, 512, chunkcoordintpair.z * 16 + 16)); + list1.addAll(((WorldServer)this.entity.worldObj).getTileEntitiesIn(chunkcoordintpair.x * 16, -World.MAX_SIZE_Y, chunkcoordintpair.z * 16, chunkcoordintpair.x * 16 + 16, World.MAX_SIZE_Y, chunkcoordintpair.z * 16 + 16)); iterator1.remove(); } } @@ -999,11 +1029,11 @@ public class Player extends NetHandler implements ICrafting, Executor { if (list.size() == 1) { - this.sendPacket(new SPacketChunkData((Chunk)list.get(0), true, 0xffffffff)); + this.sendPacket(getPacket(list.get(0), true, null, !this.entity.worldObj.dimension.hasNoLight())); } else { - this.sendPacket(new SPacketMapChunkBulk(list)); + this.sendPacket(getPacket(list, !this.entity.worldObj.dimension.hasNoLight())); } for (TileEntity tileentity : list1) @@ -1011,9 +1041,9 @@ public class Player extends NetHandler implements ICrafting, Executor this.sendTileEntityUpdate(tileentity); } - for (Chunk chunk1 : list) + for (ChunkServer chunk1 : list) { - this.entity.getServerWorld().updateChunksForPlayer(this.entity, chunk1); + this.getEntityWorld().updateChunksForPlayer(this.entity, chunk1); } } } @@ -1030,7 +1060,7 @@ public class Player extends NetHandler implements ICrafting, Executor int i = this.curblockDamage - this.initialBlockDamage; Block block = this.entity.worldObj.getState(this.removingPos).getBlock(); - if (block.getMaterial() == Material.air) + if (block == Blocks.air) { this.receivedFinishDiggingPacket = false; } @@ -1056,7 +1086,7 @@ public class Player extends NetHandler implements ICrafting, Executor { Block block1 = this.entity.worldObj.getState(this.startPos).getBlock(); - if (block1.getMaterial() == Material.air) + if (block1 == Blocks.air) { this.entity.worldObj.sendBlockBreakProgress(this.entity.getId(), this.startPos, -1); this.durabilityRemainingOnBlock = -1; @@ -1099,13 +1129,13 @@ public class Player extends NetHandler implements ICrafting, Executor this.initialDamage = this.curblockDamage; float f = 1.0F; - if (block.getMaterial() != Material.air) + if (block != Blocks.air) { block.onBlockClicked(this.entity.worldObj, pos, this.entity); f = block.getPlayerRelativeBlockHardness(this.entity, this.entity.worldObj, pos); } - if (block.getMaterial() != Material.air && f >= 1.0F) + if (block != Blocks.air && f >= 1.0F) { this.tryHarvestBlock(pos); } @@ -1127,7 +1157,7 @@ public class Player extends NetHandler implements ICrafting, Executor int i = this.curblockDamage - this.initialDamage; Block block = this.entity.worldObj.getState(pos).getBlock(); - if (block.getMaterial() != Material.air) + if (block != Blocks.air) { float f = block.getPlayerRelativeBlockHardness(this.entity, this.entity.worldObj, pos) * (float)(i + 1); @@ -1195,7 +1225,7 @@ public class Player extends NetHandler implements ICrafting, Executor { itemstack1.onBlockDestroyed(this.entity.worldObj, iblockstate.getBlock(), pos, this.entity); - if (itemstack1.stackSize == 0) + if (itemstack1.size == 0) { this.entity.destroyCurrentEquippedItem(); } @@ -1216,11 +1246,11 @@ public class Player extends NetHandler implements ICrafting, Executor // if(this.onPlayerInteract(false, null)) { // return true; // } - int i = stack.stackSize; + int i = stack.size; int j = stack.getMetadata(); ItemStack itemstack = stack.useItemRightClick(this.entity.worldObj, this.entity); - if (itemstack != stack || itemstack != null && (itemstack.stackSize != i || itemstack.getMaxItemUseDuration() > 0 || itemstack.getMetadata() != j)) + if (itemstack != stack || itemstack != null && (itemstack.size != i || itemstack.getMaxItemUseDuration() > 0 || itemstack.getMetadata() != j)) { this.entity.inventory.mainInventory[this.entity.inventory.currentItem] = itemstack; @@ -1234,7 +1264,7 @@ public class Player extends NetHandler implements ICrafting, Executor // } // } - if (itemstack.stackSize == 0) + if (itemstack.size == 0) { this.entity.inventory.mainInventory[this.entity.inventory.currentItem] = null; } @@ -1390,7 +1420,7 @@ public class Player extends NetHandler implements ICrafting, Executor int ny = this.clipboard[0].length; int nz = this.clipboard[0][0].length; BlockPos to = this.entity.getPosition(); - ClipboardPlacer placer = new ClipboardPlacer(this.entity.getServerWorld()); + ClipboardPlacer placer = new ClipboardPlacer(this.getEntityWorld()); BlockTransform transform = null; if(this.rotation != 0 || this.flipX || this.flipZ) { transform = new BlockTransform(); @@ -1475,7 +1505,7 @@ public class Player extends NetHandler implements ICrafting, Executor if(this.selectionDim == Integer.MIN_VALUE || this.selectionDim != this.entity.worldObj.dimension.getDimensionId() || this.selPos1 == null || this.selPos2 == null) return false; - WorldServer source = this.entity.getServerWorld(); + WorldServer source = this.getEntityWorld(); int mx = Math.min(this.selPos1.getX(), this.selPos2.getX()); int my = Math.min(this.selPos1.getY(), this.selPos2.getY()); int mz = Math.min(this.selPos1.getZ(), this.selPos2.getZ()); @@ -1534,18 +1564,19 @@ public class Player extends NetHandler implements ICrafting, Executor this.addHotbar(TextColor.YELLOW + (info.isEmpty() ? "Keine Drehung" : info)); } - public NBTTagCompound readCharacter() { + public TagObject readCharacter() { return this.characters.isEmpty() || this.selected < 0 ? null : this.characters.get(this.selected); } - public void writeCharacter(NBTTagCompound tag) { + public void writeCharacter(TagObject tag) { if(!this.characters.isEmpty() && this.selected >= 0) this.characters.set(this.selected, tag); } - public void disconnect() + public void disconnect(String message) { - this.connection.sendPacket(new SPacketDisconnect(), new GenericFutureListener < Future > () + Log.NETWORK.info("Trenne %s: %s", this.getUser(), message); + this.connection.sendPacket(new SPacketDisconnect(message), new GenericFutureListener < Future > () { public void operationComplete(Future p_operationComplete_1_) throws Exception { @@ -1564,33 +1595,32 @@ public class Player extends NetHandler implements ICrafting, Executor public void onDisconnect(String reason) { - Log.JNI.info(this.user + " wurde getrennt: " + TextColor.stripCodes(reason)); - this.server.sendPacket(new SPacketMessage(String.format("%s hat das Spiel verlassen", this.user), Type.FEED)); + Log.NETWORK.info(this.getUser() + " wurde getrennt: " + TextColor.stripCodes(reason)); + this.server.sendPacket(new SPacketMessage(String.format("%s hat das Spiel verlassen", this.getUser()), Type.FEED)); this.server.removePlayer(this); } - public PlayerCharacter getCharacterInfo(NBTTagCompound tag) { + public PlayerCharacter getCharacterInfo(TagObject tag) { String name = tag.getString("CustomName"); String info = tag.getString("Description"); if(info != null && info.isEmpty()) info = null; Alignment align = Alignment.getByName(tag.getString("Align")); - NBTTagList position = tag.getTagList("Pos", 6); - Dimension dimension = UniverseRegistry.getDimension(tag.getInteger("Dimension")); + Dimension dimension = UniverseRegistry.getDimension(tag.getInt("Dimension")); String dim = dimension == null ? "???" : dimension.getFormattedName(false); - BlockPos pos = new BlockPos(position.getDoubleAt(0), position.getDoubleAt(1), position.getDoubleAt(2)); + BlockPos pos = new BlockPos(tag.getDouble("PosX"), tag.getDouble("PosY"), tag.getDouble("PosZ")); String type = EntityRegistry.getEntityName(tag.getString("id")); - int level = tag.getInteger("XpLevel"); + int level = tag.getInt("XpLevel"); return new PlayerCharacter(name, info, align, dim, pos, type, level); } public void onConnect() { List chars = Lists.newArrayList(); - for(NBTTagCompound tag : this.characters) { + for(TagObject tag : this.characters) { chars.add(this.getCharacterInfo(tag)); } this.sendPacket(new SPacketCharacterList(this.selected, chars)); - this.server.sendPacket(new SPacketMessage(String.format("%s hat das Spiel betreten", this.user), Type.FEED)); + this.server.sendPacket(new SPacketMessage(String.format("%s hat das Spiel betreten", this.getUser()), Type.FEED)); } public void sendPacket(final Packet packet) @@ -1696,94 +1726,8 @@ public class Player extends NetHandler implements ICrafting, Executor return true; } - private boolean setVar(String line) { - if(!this.isAdmin()) - return false; - if(line.length() < 1) { - for(Entry entry : Config.VARS.entrySet()) { - Config.Value cvar = entry.getValue(); - String v = cvar.getValue(); - String comp = TextColor.YELLOW + entry.getKey() + TextColor.GRAY + " = "; - if(entry.getKey().equals("password") && !v.isEmpty()) - comp += TextColor.NEON + "'****'"; - else if(cvar.type == ValueType.STRING) - comp += TextColor.NEON + "'" + v + "'"; - else - comp += ((cvar.type == ValueType.BOOLEAN ? (v.equals("true") ? TextColor.GREEN : TextColor.RED) : TextColor.BLUE)) + v; - if(!cvar.def.equals(v)) { - comp += TextColor.GRAY + " (" + TextColor.BROWN + cvar.def + TextColor.GRAY + ")"; - } - this.addConsole(comp); - } - this.addConsole(TextColor.GREEN + "SVARs insgesamt registriert: %d", Config.VARS.size()); - return true; - } - line = line.trim(); - String[] args = /* line.isEmpty() ? new String[0] : */ line.split(" ", -1); - if(args.length == 1) { -// case 0: -// break; -// case 1: - Config.Value cfg = Config.VARS.get(args[0]); - if(cfg == null) - return false; - String v = cfg.getValue(); - String comp = TextColor.YELLOW + args[0] + TextColor.GRAY + " = "; - if(cfg.type == ValueType.STRING) - comp += TextColor.NEON + "'" + v + "'"; - else - comp += ((cfg.type == ValueType.BOOLEAN ? (v.equals("true") ? TextColor.GREEN : TextColor.RED) : TextColor.BLUE)) + v; - if(!cfg.def.equals(v)) - comp += TextColor.GRAY + " (" + TextColor.BROWN + cfg.def + TextColor.GRAY + ")"; - this.addConsole(comp); -// break; -// default: - } - else { - Config.Value cv = Config.VARS.get(args[0]); - if(cv == null) - return false; - String value = args[1]; - if(cv.type == ValueType.STRING && "\"\"".equals(value)) { - value = ""; - } -// else if(cv.type == ValueType.BOOLEAN && "toggle".equalsIgnoreCase(value)) { -// value = "" + !Boolean.parseBoolean(cv.getValue()); -// } -// else - if(cv.type == ValueType.BOOLEAN && !"true".equals(value) && !"false".equals(value)) { - if(!value.equalsIgnoreCase("true") && !value.equalsIgnoreCase("false")) { - this.addConsole(TextColor.DRED + "'%s' ist nicht 'true' oder 'false'", value); - return true; - } - value = value.toLowerCase(); - } - if(cv.type == ValueType.INTEGER) { - try { - Integer.parseInt(value); - } - catch(NumberFormatException e) { - this.addConsole(TextColor.DRED + "'%s' ist keine gültige Zahl", value); - return true; - } - } - else if(cv.type == ValueType.FLOAT) { - try { - Float.parseFloat(value); - } - catch(NumberFormatException e) { - this.addConsole(TextColor.DRED + "'%s' ist keine gültige Zahl", value); - return true; - } - } - Config.set(args[0], value, this.server); - this.addConsole(TextColor.YELLOW + "%s" + TextColor.GRAY + " -> " + ((cv.type == ValueType.BOOLEAN ? (cv.getValue().equals("true") ? TextColor.GREEN : TextColor.RED) : (cv.type == ValueType.STRING ? TextColor.NEON : TextColor.BLUE))) + "%s", args[0], cv.type == ValueType.STRING ? ("'" + cv.getValue() + "'") : cv.getValue()); - } - return true; - } - public void setAdmin(boolean admin) { - this.admin = admin; + super.setAdmin(admin); if(!this.isAdmin() && this.entity != null && this.entity.noclip) { this.entity.noclip = false; this.entity.flying &= this.entity.hasEffect(Potion.FLYING) || this.entity.canNaturallyFly(); @@ -1955,20 +1899,35 @@ public class Player extends NetHandler implements ICrafting, Executor // return Lists.newArrayList(); } - public void logConsole(String msg) { - this.addConsole(msg); + public void setForcedExec(Executor forced) { + this.forcedExec = forced; } - public String getExecId() { - return this.user; + public void setExecPos(Position pos) { + this.forcedPos = pos; } - public String getExecName() { - return this.entity != null ? this.entity.getCommandName() : this.user; + public void log(String msg) { + if(this.forcedExec != null) + this.forcedExec.log(TextColor.ACID + "Als " + TextColor.GREEN + "%s" + TextColor.DGRAY + ": " + TextColor.RESET + "%s", this.getUser(), msg); + else + this.addConsole(msg); } public Position getExecPos() { - return this.entity != null ? this.entity.getPos() : null; + return this.forcedPos != null ? this.forcedPos : (this.entity != null ? this.entity.getPos() : null); + } + + public Entity getPointedEntity() { + return this.pointedEntity != -1 && this.entity != null ? this.entity.worldObj.getEntityByID(this.pointedEntity) : null; + } + + public BlockPos getPointedPosition() { + return this.pointedPosition; + } + + public boolean isPlayer() { + return true; } public void processMessage(CPacketMessage packetIn) @@ -1988,8 +1947,7 @@ public class Player extends NetHandler implements ICrafting, Executor switch(type) { case COMMAND: - if(!this.setVar(msg)) - this.runCommand(msg); // this.addFeed(TextColor.RED + "Befehl wurde nicht gefunden"); + this.runCommand(msg); // this.addFeed(TextColor.RED + "Befehl wurde nicht gefunden"); break; case CHAT: @@ -1998,13 +1956,13 @@ public class Player extends NetHandler implements ICrafting, Executor break; case DISPLAY: - if(msg.isEmpty() || !isValidNick(msg) || msg.length() > MAX_NICK_LENGTH) + if(msg.isEmpty() || !IPlayer.isValidNick(msg) || msg.length() > IPlayer.MAX_NICK_LENGTH) throw new IllegalArgumentException("Ungültiger Anzeigename"); this.entity.setCustomNameTag(msg); break; case INFO: - if(msg.length() > MAX_INFO_LENGTH) + if(msg.length() > IPlayer.MAX_INFO_LENGTH) throw new IllegalArgumentException("Ungültige Beschreibung"); this.entity.setDescription(msg.isEmpty() ? null : msg); break; @@ -2019,63 +1977,21 @@ public class Player extends NetHandler implements ICrafting, Executor } } -// private Iterable getWarpList(char pre) { -// switch(pre) { -// case '+': -// return Lists.newArrayList(this.server.getUsers()); -// case '@': -// List warps = Lists.newArrayList("spawn"); -// for(String warp : this.server.getWarps().keySet()) { -// warps.add(warp); -// } -// return warps; -// case '*': -// return UniverseRegistry.getWorldNames(); -// } -// return Lists.newArrayList(); -// } - -// private static List getVarList() { -// List list = ; -// list.add("time"); -// return list; -// } - - private List getVarCompletion(String var) { - Config.Value v = Config.VARS.get(var); - if(v == null) - return Lists.newArrayList(); - if(v.type == ValueType.BOOLEAN) - return Boolean.parseBoolean(v.getValue()) ? Lists.newArrayList("false", "true") : Lists.newArrayList("true", "false"); - else if(v.type == ValueType.INTEGER || v.type == ValueType.FLOAT) - return Lists.newArrayList(v.def); - return Lists.newArrayList(); - } - public void processComplete(CPacketComplete packetIn) { NetHandler.checkThread(packetIn, this, this.server); if(this.charEditor || !this.isAdmin()) { - this.entity.connection.sendPacket(new S3APacketTabComplete(new String[0])); + this.entity.connection.sendPacket(new SPacketTabComplete(new String[0])); return; } this.pointedEntity = packetIn.getEntityId(); this.pointedPosition = packetIn.getPosition(); if(packetIn.getMessage().startsWith(" ")) { - this.entity.connection.sendPacket(new S3APacketTabComplete(new String[0])); + this.entity.connection.sendPacket(new SPacketTabComplete(new String[0])); return; } - List list = Lists.newArrayList(); - String s = packetIn.getMessage(); - String[] argv = s.split(" ", -1); - s = argv[argv.length - 1]; - Iterable res = argv.length == 1 ? Lists.newArrayList(Config.VARS.keySet()) : (argv.length == 2 ? getVarCompletion(argv[0]) : Lists.newArrayList()); - for(String s1 : res) { - if(s1.regionMatches(true, 0, s, 0, s.length())) - list.add(s1); - } - list.addAll(this.completeCommand(packetIn.getMessage())); - this.entity.connection.sendPacket(new S3APacketTabComplete(list.toArray(new String[list.size()]))); + List list = this.completeCommand(packetIn.getMessage()); + this.entity.connection.sendPacket(new SPacketTabComplete(list.toArray(new String[list.size()]))); } private static boolean isFinite(double value) { @@ -2098,7 +2014,7 @@ public class Player extends NetHandler implements ICrafting, Executor } else { - WorldServer worldserver = this.entity.getServerWorld(); // this.serverController.getWorld(this.playerEntity.dimension); + WorldServer worldserver = this.getEntityWorld(); // this.serverController.getWorld(this.playerEntity.dimension); // this.updated = true; double d0 = this.entity.posX; @@ -2148,14 +2064,14 @@ public class Player extends NetHandler implements ICrafting, Executor this.entity.vehicle.updateRiderPosition(); } - this.entity.getServerWorld().updateMountedMovingPlayer(this.entity); + this.getEntityWorld().updateMountedMovingPlayer(this.entity); if (this.entity.vehicle != null) { if (d3 > 4.0D) { Entity entity = this.entity.vehicle; - this.entity.connection.sendPacket(new S18PacketEntityTeleport(entity)); + this.entity.connection.sendPacket(new SPacketEntityTeleport(entity)); this.setPlayerLocation(this.entity.posX, this.entity.posY, this.entity.posZ, this.entity.rotYaw, this.entity.rotPitch); } @@ -2191,7 +2107,7 @@ public class Player extends NetHandler implements ICrafting, Executor float f1 = this.entity.rotYaw; float f2 = this.entity.rotPitch; - if (packetIn.isMoving() && packetIn.getPositionY() == -999.0D) + if (packetIn.isMoving() && packetIn.getPositionY() == -99999999.0D) { packetIn.setMoving(false); } @@ -2266,7 +2182,7 @@ public class Player extends NetHandler implements ICrafting, Executor } this.entity.setPositionAndRotation(d8, d9, d10, f1, f2); - this.entity.addMovementStat(this.entity.posX - d0, this.entity.posY - d1, this.entity.posZ - d2); + this.entity.addMovement(this.entity.posX - d0, this.entity.posY - d1, this.entity.posZ - d2); if (!this.entity.noClip) { @@ -2301,7 +2217,7 @@ public class Player extends NetHandler implements ICrafting, Executor // } this.entity.onGround = packetIn.isOnGround(); - this.entity.getServerWorld().updateMountedMovingPlayer(this.entity); + this.getEntityWorld().updateMountedMovingPlayer(this.entity); this.handleFalling(this.entity.posY - d7, packetIn.isOnGround()); } else if (this.tickTime - this.lastMoved > 20) @@ -2335,7 +2251,7 @@ public class Player extends NetHandler implements ICrafting, Executor NetHandler.checkThread(packetIn, this, this.server); if(this.charEditor) return; - WorldServer worldserver = this.entity.getServerWorld(); // this.serverController.getWorld(this.playerEntity.dimension); + WorldServer worldserver = this.getEntityWorld(); // this.serverController.getWorld(this.playerEntity.dimension); BlockPos blockpos = packetIn.getPosition(); switch (packetIn.getStatus()) @@ -2374,7 +2290,7 @@ public class Player extends NetHandler implements ICrafting, Executor { return; } - else if (blockpos.getY() >= World.HEIGHT) + else if (blockpos.getY() >= World.MAX_SIZE_Y) { return; } @@ -2402,7 +2318,7 @@ public class Player extends NetHandler implements ICrafting, Executor this.cancelDestroyingBlock(); } - if (worldserver.getState(blockpos).getBlock().getMaterial() != Material.air) + if (worldserver.getState(blockpos).getBlock() != Blocks.air) { this.sendPacket(new SPacketBlockChange(worldserver, blockpos)); } @@ -2421,7 +2337,7 @@ public class Player extends NetHandler implements ICrafting, Executor NetHandler.checkThread(packetIn, this, this.server); if(this.charEditor) return; - WorldServer worldserver = this.entity.getServerWorld(); // this.serverController.getWorld(this.playerEntity.dimension); + WorldServer worldserver = this.getEntityWorld(); // this.serverController.getWorld(this.playerEntity.dimension); ItemStack itemstack = this.entity.inventory.getCurrentItem(); boolean flag = false; BlockPos blockpos = packetIn.getPosition(); @@ -2438,7 +2354,7 @@ public class Player extends NetHandler implements ICrafting, Executor this.tryUseItem(itemstack); // } } - else if (blockpos.getY() < World.HEIGHT - 1 || enumfacing != Facing.UP && blockpos.getY() < World.HEIGHT) + else if (blockpos.getY() < World.MAX_SIZE_Y - 1 || enumfacing != Facing.UP && blockpos.getY() < World.MAX_SIZE_Y) { double max = this.entity.getReachDistance() + 3.0D; max *= max; @@ -2465,7 +2381,7 @@ public class Player extends NetHandler implements ICrafting, Executor itemstack = this.entity.inventory.getCurrentItem(); - if (itemstack != null && itemstack.stackSize == 0) + if (itemstack != null && itemstack.size == 0) { this.entity.inventory.mainInventory[this.entity.inventory.currentItem] = null; itemstack = null; @@ -2481,14 +2397,14 @@ public class Player extends NetHandler implements ICrafting, Executor if (!ItemStack.areItemStacksEqual(this.entity.inventory.getCurrentItem(), packetIn.getStack())) { - this.sendPacket(new S2FPacketSetSlot(this.entity.openContainer.windowId, slot.slotNumber, this.entity.inventory.getCurrentItem())); + this.sendPacket(new SPacketSetSlot(this.entity.openContainer.windowId, slot.slotNumber, this.entity.inventory.getCurrentItem())); } } } private void useEntity(int entityId, boolean interact) { - WorldServer worldserver = this.entity.getServerWorld(); // this.serverController.getWorld(this.playerEntity.dimension); + WorldServer worldserver = this.getEntityWorld(); // this.serverController.getWorld(this.playerEntity.dimension); Entity entity = worldserver.getEntityByID(entityId); if (entity != null) { @@ -2525,7 +2441,7 @@ public class Player extends NetHandler implements ICrafting, Executor NetHandler.checkThread(packetIn, this, this.server); CPacketAction.Action action = packetIn.getAction(); - if(this.charEditor != (action == Action.SET_ALIGN || action == Action.SET_SPECIES || action == Action.SET_CLASS || action == Action.SET_HEIGHT || action == Action.CLOSE_EDITOR)) // { + if(this.charEditor != (action == Action.SET_ALIGN || action == Action.SET_SPECIES || action == Action.SET_CLASS || action == Action.SET_HEIGHT || action == Action.CLOSE_EDITOR || action == Action.CANCEL_EDITOR)) // { // if(this.local && action == Action.CLOSE_EDITOR) // this.server.setDone(); return; @@ -2537,11 +2453,12 @@ public class Player extends NetHandler implements ICrafting, Executor this.charEditor = true; // if(this.local) // this.server.resetProgress(); - NBTTagCompound tag = this.server.swapPlayer(this, null, EntityHuman.class); + TagObject tag = this.server.swapPlayer(this, null, EntityHuman.class); if(!this.characters.isEmpty() && this.selected >= 0) this.characters.set(this.selected, tag); int last = this.selected; this.selected = -1; + this.teleportPos = this.deathPos = null; this.sendPacket(!this.characters.isEmpty() && last >= 0 ? new SPacketCharacterList(this.selected, last, this.getCharacterInfo(tag)) : new SPacketCharacterList(this.selected)); break; } @@ -2549,31 +2466,43 @@ public class Player extends NetHandler implements ICrafting, Executor case CLOSE_EDITOR: { this.charEditor = false; this.selected = this.characters.size(); - this.characters.add(new NBTTagCompound()); + this.characters.add(new TagObject()); WorldServer world = this.server.getWorld(packetIn.getAuxData()); world = world == null ? this.server.getSpace() : world; - WorldPos origin = new WorldPos(world.rand.range(-Config.originRadius, Config.originRadius), 64, world.rand.range(-Config.originRadius, Config.originRadius), + WorldPos origin = new WorldPos(world.rand.range(-SVars.originRadius, SVars.originRadius), 64, world.rand.range(-SVars.originRadius, SVars.originRadius), world.dimension.getDimensionId()); this.entity.setOrigin(origin); Position pos = this.server.getRandomSpawnPosition(origin); - if(Config.preload && /* this.local && */ this.server.getPlayers().size() == 1) - this.server.preload(world, (int)pos.x, (int)pos.z, this); this.entity.teleport(pos); + this.teleportPos = this.deathPos = null; this.sendPacket(new SPacketCharacterList(this.selected, this.selected, new PlayerCharacter(this.entity.getCustomNameTag(), this.entity.getDescription(), this.entity.getAlignment(), this.entity.worldObj.dimension.getFormattedName(false), this.entity.getPosition(), EntityRegistry.getEntityName(EntityRegistry.getEntityString(this.entity)), this.entity.experienceLevel))); // if(this.local) // this.server.setDone(); break; } + + case CANCEL_EDITOR: { + int index = packetIn.getAuxData(); + if(index >= this.characters.size() || index < 0) + return; + this.charEditor = false; + this.server.swapPlayer(this, this.characters.get(index), null); + this.selected = index; + this.teleportPos = this.deathPos = null; + this.sendPacket(new SPacketCharacterList(this.selected)); + break; + } case SELECT_CHARACTER: { int index = packetIn.getAuxData(); if(index == this.selected || index >= this.characters.size() || index < 0) return; - NBTTagCompound etag = this.server.swapPlayer(this, this.characters.get(index), null); + TagObject etag = this.server.swapPlayer(this, this.characters.get(index), null); if(!this.characters.isEmpty() && this.selected >= 0) this.characters.set(this.selected, etag); int last = this.selected; this.selected = index; + this.teleportPos = this.deathPos = null; this.sendPacket(!this.characters.isEmpty() && last >= 0 ? new SPacketCharacterList(this.selected, last, this.getCharacterInfo(etag)) : new SPacketCharacterList(this.selected)); break; } @@ -2669,7 +2598,7 @@ public class Player extends NetHandler implements ICrafting, Executor } catch (Exception e) { - Log.JNI.error(e, "Konnte Handel nicht wählen"); + Log.TICK.error(e, "Konnte Handel nicht wählen"); } break; @@ -2732,10 +2661,9 @@ public class Player extends NetHandler implements ICrafting, Executor break; case ENCHANT_ITEM: - if(this.entity.openContainer.windowId == (packetIn.getAuxData() & 255) && this.entity.openContainer.getCanCraft(this.entity)) // && !this.playerEntity.isSpectator()) - { - this.entity.openContainer.enchantItem(this.entity, (packetIn.getAuxData() >> 8) % 3); - this.entity.openContainer.detectAndSendChanges(); + if(this.entity.openContainer instanceof ContainerEnchantment ench && ench.windowId == (packetIn.getAuxData() & 255) && ench.getCanCraft(this.entity)) { + ench.enchantItem(this.entity, (packetIn.getAuxData() >> 8) % 3); + ench.detectAndSendChanges(); } break; @@ -2754,39 +2682,15 @@ public class Player extends NetHandler implements ICrafting, Executor case GOD: if(this.isAdmin()) { -// this.playerEntity.setCheat(!this.playerEntity.godmode); - this.entity.fallDistance = 0.0F; - if(this.entity.hasEffect(Potion.HASTE) && this.entity.getEffect(Potion.HASTE).getAmplifier() == 255) { - this.entity.removeEffect(Potion.HASTE); - this.entity.removeEffect(Potion.RESISTANCE); - this.entity.removeEffect(Potion.FIRE_RESISTANCE); - this.entity.removeEffect(Potion.FLYING); - this.entity.removeEffect(Potion.MANA); - this.addFeed(TextColor.RED + "Statuseffekte wurden entfernt"); - } - else { - this.entity.extinguish(); - this.entity.setHealth(this.entity.getMaxHealth()); - this.entity.setManaPoints(this.entity.getMaxMana()); - this.entity.clearEffects(false); - this.entity.addEffect(new PotionEffect(Potion.HASTE, Integer.MAX_VALUE, 255, false, false)); - this.entity.addEffect(new PotionEffect(Potion.RESISTANCE, Integer.MAX_VALUE, 255, false, false)); - this.entity.addEffect(new PotionEffect(Potion.FIRE_RESISTANCE, Integer.MAX_VALUE, 0, false, false)); - this.entity.addEffect(new PotionEffect(Potion.FLYING, Integer.MAX_VALUE, 0, false, false)); - this.entity.addEffect(new PotionEffect(Potion.MANA, Integer.MAX_VALUE, 255, false, false)); - this.addFeed(TextColor.GREEN + "Statuseffekte wurden hinzugefügt"); - } + boolean god = !this.entity.hasEffect(Potion.HASTE) || this.entity.getEffect(Potion.HASTE).getAmplifier() != 255; + this.entity.setGodMode(god); + this.addFeed(god ? (TextColor.GREEN + "Statuseffekte wurden hinzugefügt") : (TextColor.RED + "Statuseffekte wurden entfernt")); } break; case NOCLIP: if(this.isAdmin()) { - if(!this.entity.noclip) - this.entity.mountEntity(null); - this.entity.noclip ^= true; - this.entity.flying &= this.entity.hasEffect(Potion.FLYING) || this.entity.noclip || this.entity.canNaturallyFly(); - this.entity.fallDistance = 0.0F; - this.sendPlayerAbilities(); + this.entity.setNoclip(!this.entity.noclip); this.addFeed((this.entity.noclip ? TextColor.GREEN : TextColor.RED) + "NoClip ist jetzt " + (this.entity.noclip ? "eingeschaltet" : "ausgeschaltet")); } break; @@ -2818,8 +2722,8 @@ public class Player extends NetHandler implements ICrafting, Executor case REPAIR: if(this.isAdmin() && this.entity.getCurrentEquippedItem() != null) { ItemStack itemstack = this.entity.getCurrentEquippedItem(); - int diff = itemstack.getMaxStackSize() - itemstack.stackSize; - itemstack.stackSize = itemstack.getMaxStackSize(); + int diff = itemstack.getMaxStackSize() - itemstack.size; + itemstack.size = itemstack.getMaxStackSize(); itemstack.setRepairCost(0); if(itemstack.getItem().getMaxDamage() > 0) itemstack.setItemDamage(0); @@ -2899,12 +2803,12 @@ public class Player extends NetHandler implements ICrafting, Executor break; case START_PROFILING: - if(this.admin) + if(this.isAdmin()) this.profiling = true; break; case STOP_PROFILING: - if(this.admin) + if(this.isAdmin()) this.profiling = false; break; @@ -2946,7 +2850,7 @@ public class Player extends NetHandler implements ICrafting, Executor if (ItemStack.areItemStacksEqual(packetIn.getClickedItem(), itemstack)) { - this.entity.connection.sendPacket(new S32PacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true)); + this.entity.connection.sendPacket(new SPacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), true)); this.isChangingQuantityOnly = true; this.entity.openContainer.detectAndSendChanges(); this.updateHeldItem(); @@ -2955,7 +2859,7 @@ public class Player extends NetHandler implements ICrafting, Executor else { this.transactions.addKey(this.entity.openContainer.windowId, Short.valueOf(packetIn.getActionNumber())); - this.entity.connection.sendPacket(new S32PacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), false)); + this.entity.connection.sendPacket(new SPacketConfirmTransaction(packetIn.getWindowId(), packetIn.getActionNumber(), false)); this.entity.openContainer.setCanCraft(this.entity, false); List list1 = Lists.newArrayList(); @@ -2970,9 +2874,9 @@ public class Player extends NetHandler implements ICrafting, Executor } } - public void processCheat(CPacketCheat packetIn) + public void processCheat(CPacketCheat packet) { - NetHandler.checkThread(packetIn, this, this.server); + NetHandler.checkThread(packet, this, this.server); if(this.charEditor) return; @@ -2983,7 +2887,7 @@ public class Player extends NetHandler implements ICrafting, Executor // { // boolean drop = packetIn.getSlotId() < 0; // boolean changed = false; - ItemStack itemstack = packetIn.getStack(); + ItemStack itemstack = packet.getStack(); // if(itemstack != null && itemstack.getItem() == Items.barrier && !this.playerEntity.canUse(Permissions.BARRIER)) { // changed = true; // itemstack = null; @@ -2992,28 +2896,28 @@ public class Player extends NetHandler implements ICrafting, Executor // changed = true; // } - if (itemstack.hasTagCompound() && itemstack.getTagCompound().hasKey("BlockEntityTag")) + if (itemstack.hasTagCompound() && itemstack.getTagCompound().hasObject("BlockEntityTag")) { -// if(!itemstack.getTagCompound().hasKey("BlockEntityTag", 10)) { +// if(!itemstack.getTagCompound().hasTag("BlockEntityTag")) { // changed = true; // itemstack.setTagCompound(null); // } // else { - NBTTagCompound nbttagcompound = itemstack.getTagCompound().getCompoundTag("BlockEntityTag"); + TagObject tag = itemstack.getTagCompound().getObject("BlockEntityTag"); - if (nbttagcompound.hasKey("x") && nbttagcompound.hasKey("y") && nbttagcompound.hasKey("z")) + if (tag.hasInt("x") && tag.hasInt("y") && tag.hasInt("z")) { - BlockPos blockpos = new BlockPos(nbttagcompound.getInteger("x"), nbttagcompound.getInteger("y"), nbttagcompound.getInteger("z")); - TileEntity tileentity = this.entity.worldObj.getTileEntity(blockpos); + BlockPos pos = new BlockPos(tag.getInt("x"), tag.getInt("y"), tag.getInt("z")); + TileEntity te = this.entity.worldObj.getTileEntity(pos); - if (tileentity != null) + if (te != null) { - NBTTagCompound nbttagcompound1 = new NBTTagCompound(); - tileentity.writeToNBT(nbttagcompound1); - nbttagcompound1.removeTag("x"); - nbttagcompound1.removeTag("y"); - nbttagcompound1.removeTag("z"); - itemstack.setTagInfo("BlockEntityTag", nbttagcompound1); + TagObject tile = new TagObject(); + te.writeTags(tile); + tile.remove("x"); + tile.remove("y"); + tile.remove("z"); + itemstack.setTagInfo("BlockEntityTag", tile); } } // } @@ -3021,30 +2925,30 @@ public class Player extends NetHandler implements ICrafting, Executor // boolean validSlot = packetIn.getSlotId() >= 1 && packetIn.getSlotId() < 36 + InventoryPlayer.getHotbarSize(); boolean validItem = itemstack.getItem() != null; - boolean validData = itemstack.getMetadata() >= 0 && itemstack.stackSize <= itemstack.getMaxStackSize() && itemstack.stackSize > 0; // TODO: max + boolean validData = itemstack.getMetadata() >= 0 && itemstack.size <= itemstack.getMaxStackSize() && itemstack.size > 0; // TODO: max if (validItem && validData) { - int amount = itemstack.stackSize; - if(packetIn.getSlot() == -1) { + int amount = itemstack.size; + if(packet.getSlot() == -1) { this.entity.inventory.addItemStackToInventory(itemstack); - amount -= itemstack.stackSize; + amount -= itemstack.size; } - else if(packetIn.getSlot() >= 0 && packetIn.getSlot() < this.entity.inventory.getSizeInventory() && (packetIn.getSlot() < this.entity.inventory.mainInventory.length || (itemstack.getItem() instanceof ItemArmor && ((ItemArmor)itemstack.getItem()).armorType == packetIn.getSlot() - this.entity.inventory.mainInventory.length))) { - ItemStack old = this.entity.inventory.getStackInSlot(packetIn.getSlot()); + else if(packet.getSlot() >= 0 && packet.getSlot() < this.entity.inventory.getSizeInventory() && (packet.getSlot() < this.entity.inventory.mainInventory.length || (itemstack.getItem() instanceof ItemArmor && ((ItemArmor)itemstack.getItem()).armorType.getArmorSlot() == packet.getSlot() - this.entity.inventory.mainInventory.length))) { + ItemStack old = this.entity.inventory.getStackInSlot(packet.getSlot()); if(old != null) { if(ItemStack.areItemsEqual(itemstack, old) && ItemStack.areItemStackTagsEqual(itemstack, old)) { - itemstack.stackSize = Math.min(itemstack.getMaxStackSize(), old.stackSize + itemstack.stackSize); - amount = itemstack.stackSize - old.stackSize; + itemstack.size = Math.min(itemstack.getMaxStackSize(), old.size + itemstack.size); + amount = itemstack.size - old.size; } - else if(old.stackSize == 1) + else if(old.size == 1) this.addFeed(TextColor.DRED + "* %s zerstört", old.getColoredName(TextColor.DRED)); else - this.addFeed(TextColor.DRED + "* %d %s zerstört", old.stackSize, + this.addFeed(TextColor.DRED + "* %d %s zerstört", old.size, old.getColoredName(TextColor.DRED)); } - this.entity.inventory.setInventorySlotContents(packetIn.getSlot(), itemstack); + this.entity.inventory.setInventorySlotContents(packet.getSlot(), itemstack); } else { return; @@ -3068,7 +2972,7 @@ public class Player extends NetHandler implements ICrafting, Executor if(this.charEditor) return; - WorldServer worldserver = this.entity.getServerWorld(); // this.serverController.getWorld(this.playerEntity.dimension); + WorldServer worldserver = this.getEntityWorld(); // this.serverController.getWorld(this.playerEntity.dimension); BlockPos blockpos = packetIn.getPosition(); if (worldserver.isBlockLoaded(blockpos)) @@ -3105,6 +3009,7 @@ public class Player extends NetHandler implements ICrafting, Executor // this.signCommand = null; // } + tileentitysign.setPlayer(null); tileentitysign.markDirty(); worldserver.markBlockForUpdate(blockpos); } @@ -3143,40 +3048,47 @@ public class Player extends NetHandler implements ICrafting, Executor // this.lastSkinUpdate = System.currentTimeMillis(); } - public void processBook(CPacketBook packetIn) { - NetHandler.checkThread(packetIn, this, this.server); - if(this.charEditor) + public void processForm(CPacketForm packet) { + NetHandler.checkThread(packet, this, this.server); + if(this.charEditor || this.form == null || packet.getId() != this.currentFormId) return; - - String[] pages = packetIn.getPages(); -// if (!ItemWritableBook.isNBTValid(itemstack1.getTagCompound())) -// throw new IOException("Fehlerhafter Buch-Tag!"); - ItemStack itemstack = this.entity.inventory.getCurrentItem(); - if (itemstack != null && itemstack.getItem() == Items.writable_book) - { - if(pages.length == 0) { - if(itemstack.hasTagCompound()) { - itemstack.getTagCompound().removeTag("pages"); - if(itemstack.getTagCompound().hasNoTags()) - itemstack.setTagCompound(null); - } - } - else { - NBTTagList list = new NBTTagList(); - for(String page : pages) { - list.appendTag(new NBTTagString(page)); - } - itemstack.setTagInfo("pages", list); - } - } + this.form.accept(packet.getData()); + this.form = null; } - public Entity getPointedEntity() { - return this.pointedEntity != -1 && this.entity != null ? this.entity.worldObj.getEntityByID(this.pointedEntity) : null; + public void displayForm(Form form) { + this.form = form; + this.getNextFormId(); + this.sendPacket(new SPacketDisplayForm(this.currentFormId, form.getTitle(), form.getInputList())); + } + + public List getLoadedChunkList() { + return this.loadedChunks; + } + + public double getManagedX() { + return this.managedPosX; + } + + public double getManagedZ() { + return this.managedPosZ; + } + + public void setManagedPos(double x, double z) { + this.managedPosX = x; + this.managedPosZ = z; } - public BlockPos getPointedPosition() { - return this.pointedPosition; + public Position getLastTeleport() { + return this.teleportPos; + } + + public Position getLastDeath() { + return this.deathPos; + } + + public String getEntityName() { + return this.getPresentEntity() == null ? this.getUser() : this.getPresentEntity().getCommandName(); } // public void processCmdBlock(CPacketCmdBlock packetIn) { diff --git a/server/src/main/java/server/network/User.java b/server/src/main/java/server/network/User.java new file mode 100644 index 0000000..6b52716 --- /dev/null +++ b/server/src/main/java/server/network/User.java @@ -0,0 +1,121 @@ +package server.network; + +import java.io.File; +import java.security.PublicKey; +import java.util.Map; + +import common.log.Log; +import common.network.IPlayer; +import common.tags.TagObject; +import common.util.EncryptUtil; +import common.util.Pair; + +public class User { + private final String user; + private boolean admin; + private Pair password; + private PublicKey pubkey; + + public User(String user) { + this.user = user; + } + + public boolean isOnline() { + return false; + } + + public String getUser() { + return this.user; + } + + public void setAdmin(boolean admin) { + this.admin = admin; + } + + public boolean isAdmin() { + return this.admin; + } + + public void setPasswordHash(Pair hash) { + this.password = hash; + } + + public Pair getPasswordHash() { + return this.password; + } + + public void setPubkey(PublicKey key) { + this.pubkey = key; + } + + public PublicKey getPubkey() { + return this.pubkey; + } + + public void copyFrom(User user) { + this.admin = user.admin; + this.password = user.password; + this.pubkey = user.pubkey; + } + + public void readUserTags(TagObject tag) { + this.admin = tag.getBool("admin"); + if(tag.hasByteArray("passwordHash") && tag.hasByteArray("passwordSalt")) + this.password = new Pair(tag.getByteArray("passwordHash"), tag.getByteArray("passwordSalt")); + if(tag.hasByteArray("pubkey")) + this.pubkey = EncryptUtil.decodePublicKey(tag.getByteArray("pubkey")); + } + + public void writeUserTags(TagObject tag) { + if(this.admin) + tag.setBool("admin", this.admin); + if(this.password != null) { + tag.setByteArray("passwordHash", this.password.first()); + tag.setByteArray("passwordSalt", this.password.second()); + } + if(this.pubkey != null) + tag.setByteArray("pubkey", this.pubkey.getEncoded()); + } + + public static void saveDatabase(Map map) { + TagObject tag = new TagObject(); + for(User user : map.values()) { + TagObject data = new TagObject(); + user.writeUserTags(data); + tag.setObject(user.getUser(), data); + } + File nfile = new File("users.cdt.tmp"); + File lfile = new File("users.cdt"); + try { + TagObject.writeGZip(tag, nfile); + if(lfile.exists()) + lfile.delete(); + nfile.renameTo(lfile); + } + catch(Exception e) { + Log.IO.error(e, "Fehler beim Schreiben von " + nfile); + } + } + + public static void loadDatabase(Map map) { + File file = new File("users.cdt"); + if(!file.exists()) + file = new File("users.cdt.tmp"); + if(file.exists()) { + try { + TagObject tag = TagObject.readGZip(file); + for(String key : tag.keySet()) { + if(IPlayer.isValidUser(key) && tag.hasObject(key)) { + User user = new User(key); + user.readUserTags(tag.getObject(key)); + map.put(key, user); + } + } + } + catch(Exception e) { + Log.IO.error(e, "Fehler beim Lesen von " + file); + map.clear(); + } + } + } +} diff --git a/server/src/main/java/server/util/Form.java b/server/src/main/java/server/util/Form.java new file mode 100644 index 0000000..e96bee5 --- /dev/null +++ b/server/src/main/java/server/util/Form.java @@ -0,0 +1,185 @@ +package server.util; + +import java.util.List; + +import common.collect.Lists; +import common.util.Displayable; +import common.util.Triplet; + +public abstract class Form { + private abstract class FormElement { + protected final String name; + + protected FormElement(String name) { + this.name = name; + } + + protected abstract Object getInputData(); + protected abstract int getInputParameter(); + protected abstract boolean acceptValue(Object obj); + } + + protected class Toggle extends FormElement { + private boolean value; + + protected Toggle(String name, boolean value) { + super(name); + this.value = value; + } + + protected Object getInputData() { + return this.value; + } + + protected int getInputParameter() { + return 0; + } + + protected boolean acceptValue(Object obj) { + if(obj instanceof Boolean) + this.value = (Boolean)obj; + return obj instanceof Boolean; + } + + public boolean get() { + return this.value; + } + } + + protected class Switch extends FormElement { + private final T[] values; + private final int def; + + private T value; + + protected Switch(String name, T[] values, T value) { + super(name); + this.values = values; + this.value = value; + int def = 0; + for(int z = 0; z < values.length; z++) { + if(values[z] == value) { + def = z; + break; + } + } + this.def = def; + } + + protected Object getInputData() { + String[] strs = new String[this.values.length]; + for(int z = 0; z < strs.length; z++) { + strs[z] = this.values[z] instanceof Displayable ? ((Displayable)this.values[z]).getDisplay() : String.valueOf(this.values[z]); + } + return strs; + } + + protected int getInputParameter() { + return this.def; + } + + protected boolean acceptValue(Object obj) { + if(obj instanceof Integer && (Integer)obj >= 0 && (Integer)obj < this.values.length) { + this.value = this.values[(Integer)obj]; + return true; + } + return false; + } + + public T get() { + return this.value; + } + } + + protected class Field extends FormElement { + private final int minLength; + private final int maxLength; + private final boolean password; + + private String value; + + protected Field(String name, String value, int min, int max, boolean password) { + super(name); + this.value = value; + this.minLength = min; + this.maxLength = max; + this.password = password; + } + + protected Object getInputData() { + return this.value; + } + + protected int getInputParameter() { + return (this.password ? 0x80000000 : 0) | (this.minLength << 16) | this.maxLength; + } + + protected boolean acceptValue(Object obj) { + if(obj instanceof String && ((String)obj).length() >= this.minLength && ((String)obj).length() <= this.maxLength) { + this.value = (String)obj; + return true; + } + return false; + } + + public String get() { + return this.value; + } + } + + private final List inputs = Lists.newArrayList(); + + public Form() { + this.init(); + } + + private T add(T elem) { + this.inputs.add(elem); + return elem; + } + + protected Toggle addToggle(String name, boolean def) { + return this.add(new Toggle(name, def)); + } + + protected Switch addSwitch(String name, T def, T ... values) { + return this.add(new Switch(name, values, def)); + } + + protected Field addField(String name, int minLength, int maxLength, String def) { + return this.add(new Field(name, def, minLength, maxLength, false)); + } + + protected Field addPassword(String name, int minLength, int maxLength, String def) { + return this.add(new Field(name, def, minLength, maxLength, true)); + } + + public abstract String getTitle(); + protected abstract void init(); + protected abstract void accept(); + + protected void cancel() { + } + + public final Triplet[] getInputList() { + Triplet[] data = new Triplet[this.inputs.size()]; + for(int z = 0; z < data.length; z++) { + data[z] = new Triplet(this.inputs.get(z).name, this.inputs.get(z).getInputData(), this.inputs.get(z).getInputParameter()); + } + return data; + } + + public final void accept(Object[] data) { + if(data == null || data.length != this.inputs.size()) { + this.cancel(); + return; + } + for(int z = 0; z < data.length; z++) { + if(!this.inputs.get(z).acceptValue(data[z])) { + this.cancel(); + return; + } + } + this.accept(); + } +} diff --git a/server/src/main/java/server/vars/SVar.java b/server/src/main/java/server/vars/SVar.java new file mode 100644 index 0000000..deaa95a --- /dev/null +++ b/server/src/main/java/server/vars/SVar.java @@ -0,0 +1,84 @@ +package server.vars; + +import java.lang.reflect.Field; + +import common.util.ExtMath; +import common.util.Var; + +public class SVar { + public final ValueType type; + public final String def; + public final boolean noDef; + private final Field field; + private final float min; + private final float max; + + private Runnable callback; + + public SVar(Field field, Var value) { + this.type = field.getType() == int.class ? ValueType.INTEGER : (field.getType() == boolean.class ? ValueType.BOOLEAN : + (field.getType() == String.class ? ValueType.STRING : (field.getType() == float.class ? ValueType.FLOAT : null))); + if(this.type == null) + throw new IllegalArgumentException(value.name() + ": Unbekannter Variablen-Typ - " + field.getType()); + this.field = field; + this.def = this.get(); + this.noDef = value.nonDefault(); + this.min = (this.type == ValueType.INTEGER || this.type == ValueType.FLOAT) + ? value.min() : 0; + this.max = (this.type == ValueType.INTEGER || this.type == ValueType.FLOAT) + ? value.max() : (this.type == ValueType.BOOLEAN ? 1 : 0); + this.set(this.def, this.noDef, false); + } + + public String get() { + try { + return "" + this.field.get(null); + } + catch(IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); + } + } + + public void setCallback(Runnable callback) { + this.callback = callback; + } + + public void set(String value, boolean noClamp, boolean update) { + try { + switch(this.type) { + case STRING: + this.field.set(null, value); + break; + case BOOLEAN: + this.field.setBoolean(null, Boolean.parseBoolean(value)); + break; + case INTEGER: + int inum = 0; + try { + inum = Integer.parseInt(value); + } + catch(NumberFormatException e) { + } + this.field.setInt(null, noClamp ? inum : ExtMath.clampi(inum, (int)this.min, (int)this.max)); + break; + case FLOAT: + float fnum = 0.0f; + try { + fnum = Float.parseFloat(value); + } + catch(NumberFormatException e) { + } + if(!noClamp) + fnum = ExtMath.clampf(fnum, this.min, this.max); + int round = (int)(fnum * 1000.0f); + this.field.setFloat(null, (float)round / 1000.0f); + break; + } + } + catch(IllegalArgumentException | IllegalAccessException e) { + throw new RuntimeException(e); + } + if(update && this.callback != null) + this.callback.run(); + } +} \ No newline at end of file diff --git a/server/src/main/java/server/vars/SVars.java b/server/src/main/java/server/vars/SVars.java new file mode 100644 index 0000000..7d5a0f2 --- /dev/null +++ b/server/src/main/java/server/vars/SVars.java @@ -0,0 +1,101 @@ +package server.vars; + +import common.util.Var; +import common.vars.Vars; + +public abstract class SVars extends Vars { + @Var(name = "tickSpawning") + public static boolean tickSpawn = true; + @Var(name = "genSpawning") + public static boolean genSpawn = true; + @Var(name = "spawnVillagers") + public static boolean spawnVillager = true; + @Var(name = "spawnCagedVillagers") + public static boolean spawnCageMobs = true; + @Var(name = "spawnBridgeMages") + public static boolean spawnBridgeMobs = true; + @Var(name = "spawnMineshaftArachnoids") + public static boolean spawnMineshaftMobs = true; + @Var(name = "spawnStrongholdHaunters") + public static boolean spawnStrongholdMobs = true; + @Var(name = "spawnHutMages") + public static boolean spawnHutMage = true; + @Var(name = "daylightCycle") + public static boolean dayCycle = true; + @Var(name = "weatherChanges") + public static boolean weather = true; + @Var(name = "dropPlayerSkulls") + public static boolean skullDrop = true; + @Var(name = "checkRespawn") + public static boolean checkBed = true; + @Var(name = "registration") + public static boolean register = true; + @Var(name = "pubkeyAuthentication") + public static boolean pubkeyAuth = true; + @Var(name = "requireAccessPassword") + public static boolean accessRequired = true; + @Var(name = "encryption") + public static boolean encrypt = true; + @Var(name = "requireAuthentication") + public static boolean authenticate = true; + + @Var(name = "snowStacking") + public static boolean snowStack = false; + @Var(name = "passwordAuthentication") + public static boolean passwordAuth = false; + + @Var(name = "randomTickSpeed") + public static int randomTick = 3; + @Var(name = "weatherTickSpeed") + public static int weatherTick = 1; + @Var(name = "lightningChance") + public static int boltChance = 100000; + @Var(name = "igniteChance") + public static int igniteChance = 100; + @Var(name = "spawnRadius") + public static int spawnRadius = 10; + @Var(name = "originRadius", min = 0, max = 262144) + public static int originRadius = 16384; + @Var(name = "respawnTime") + public static int respawnTime = 0; + @Var(name = "spawnGroupCount") + public static int spawnGroups = 3; + @Var(name = "spawnGroupDistance") + public static int spawnGroupDist = 6; + @Var(name = "mobSpawnRadius") + public static int mobSpawnDist = 8; + @Var(name = "mobPlayerDistance") + public static int mobPlayerDist = 24; + @Var(name = "saveInterval") + public static int saveInterval = 900; + @Var(name = "maxPlayers") + public static int playerLimit = 0; + @Var(name = "compressAbove") + public static int compression = 256; + @Var(name = "timeFlow") + public static int timeFlow = 1; + @Var(name = "emptyTicks") + public static int unloadTicks = 1200; + @Var(name = "weatherChance") + public static int weatherChance = 48000; + @Var(name = "viewDistance", min = 2, max = 16) + public static int distance = 8; + @Var(name = "maxSpawns") + public static int maxMobs = 120; + @Var(name = "connectionTimeout", min = 10, max = 300) + public static int timeout = 30; + @Var(name = "passwordMinLength", min = 8, max = 32) + public static int minPassLength = 8; + @Var(name = "port", min = 1024, max = 32767, nonDefault = true) + public static int port = -1; + @Var(name = "spawnDungeonMobs") + public static int spawnDungeonMobs = 4; + + @Var(name = "gravity") + public static float gravity = 1.0f; + + @Var(name = "password", nonDefault = true) + public static String password = ""; + @Var(name = "baseSeed", nonDefault = true) + public static String seed = ""; +} diff --git a/server/src/main/java/server/vars/ValueType.java b/server/src/main/java/server/vars/ValueType.java new file mode 100644 index 0000000..6ed7cc6 --- /dev/null +++ b/server/src/main/java/server/vars/ValueType.java @@ -0,0 +1,5 @@ +package server.vars; + +public enum ValueType { + STRING, BOOLEAN, INTEGER, FLOAT; +} \ No newline at end of file diff --git a/java/src/game/village/VillageCollection.java b/server/src/main/java/server/village/VillageCollection.java similarity index 85% rename from java/src/game/village/VillageCollection.java rename to server/src/main/java/server/village/VillageCollection.java index e00e7b0..be459ab 100755 --- a/java/src/game/village/VillageCollection.java +++ b/server/src/main/java/server/village/VillageCollection.java @@ -1,18 +1,18 @@ -package game.village; +package server.village; import java.util.Iterator; import java.util.List; -import game.collect.Lists; - -import game.block.Block; -import game.block.BlockDoor; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.world.BlockPos; -import game.world.Facing; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.artificial.BlockDoor; +import common.collect.Lists; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.Facing; +import common.village.Village; +import common.village.VillageDoorInfo; +import server.world.WorldServer; public class VillageCollection { @@ -22,16 +22,16 @@ public class VillageCollection private int tickCounter; private boolean dirty; - public VillageCollection(NBTTagCompound nbt) { - if(nbt != null) { - this.tickCounter = nbt.getInteger("Tick"); - NBTTagList nbttaglist = nbt.getTagList("Villages", 10); + public VillageCollection(TagObject tag) { + if(tag != null) { + this.tickCounter = tag.getInt("Tick"); + List list = tag.getList("Villages"); - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < list.size(); ++i) { - NBTTagCompound nbttagcompound = nbttaglist.getCompoundTagAt(i); + TagObject obj = list.get(i); Village village = new Village(); - village.readVillageDataFromNBT(nbttagcompound); + village.readTags(obj); this.villageList.add(village); } } @@ -244,25 +244,25 @@ public class VillageCollection private boolean isWoodDoor(WorldServer world, BlockPos doorPos) { Block block = world.getState(doorPos).getBlock(); - return block instanceof BlockDoor ? block.getMaterial() == Material.wood : false; + return block instanceof BlockDoor ? block.getMaterial() == Material.WOOD : false; } - public NBTTagCompound writeToNBT() + public TagObject toTags() { - NBTTagCompound nbt = new NBTTagCompound(); - nbt.setInteger("Tick", this.tickCounter); - NBTTagList nbttaglist = new NBTTagList(); + TagObject tag = new TagObject(); + tag.setInt("Tick", this.tickCounter); + List list = Lists.newArrayList(); for (Village village : this.villageList) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - village.writeVillageDataToNBT(nbttagcompound); - nbttaglist.appendTag(nbttagcompound); + TagObject obj = new TagObject(); + village.writeTags(obj); + list.add(obj); } - nbt.setTag("Villages", nbttaglist); + tag.setList("Villages", list); this.dirty = false; - return nbt; + return tag; } public boolean isDirty() diff --git a/server/src/main/java/server/world/ChunkServer.java b/server/src/main/java/server/world/ChunkServer.java new file mode 100644 index 0000000..f30ccc3 --- /dev/null +++ b/server/src/main/java/server/world/ChunkServer.java @@ -0,0 +1,226 @@ +package server.world; + +import java.util.Map; +import java.util.Set; +import common.biome.Biome; +import common.block.Block; +import common.entity.Entity; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.log.Log; +import common.rng.Random; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.world.BlockArray; +import common.world.Chunk; +import common.world.State; +import common.world.World; +import server.worldgen.BiomeGenerator; + +public class ChunkServer extends Chunk { + private long lastSave; + private long inhabited; + + public ChunkServer(World world, int x, int z) { + super(world, x, z); + } + + public ChunkServer(World world, short[] data, int height, boolean base, boolean ceil, Random rand, Biome[] biomes, int x, int z) { + this(world, x, z); + boolean sky = !world.dimension.hasNoLight(); + for(int bx = 0; bx < 16; ++bx) { + for(int bz = 0; bz < 16; ++bz) { + for(int by = 0; by < height; ++by) { + State state = BlockRegistry.STATEMAP.getByValue(data[bx << 4 | bz | by << 8]); + if(state != null && state.getBlock() != Blocks.air) { + int y = by >> 4; + BlockArray arr = this.getArray(y); + if(arr == null) { + arr = new BlockArray(y << 4, sky, null); + this.setArray(arr); + } + arr.set(bx, by & 15, bz, state); + } + } + } + } + if(base) { + Block caves = world.dimension.getCaveFiller().getBlock(); + BlockArray arr = this.getArray(0); + if(arr == null) { + arr = new BlockArray(0, sky, null); + this.setArray(arr); + } + for(int bx = 0; bx < 16; ++bx) { + for(int bz = 0; bz < 16; ++bz) { + for(int by = 0; by < 5; ++by) { + if(by <= rand.zrange(5)) { + Block block = arr.get(bx, by, bz).getBlock(); + if(block == Blocks.air || block.getMaterial().isLiquid() || block == caves) + arr.set(bx, by, bz, this.filler); + } + } + } + } + } + if(ceil) { + int y = (height - 1) >> 4; + BlockArray arr = this.getArray(y); + if(arr == null) { + arr = new BlockArray(y << 4, sky, null); + this.setArray(arr); + } + y = (height - 5) >> 4; + arr = this.getArray(y); + if(arr == null) { + arr = new BlockArray(y << 4, sky, null); + this.setArray(arr); + } + for(int bx = 0; bx < 16; ++bx) { + for(int bz = 0; bz < 16; ++bz) { + for(int by = height - 1; by >= height - 5; --by) { + if(by >= (height - 1) - rand.zrange(5)) + this.getArray(by >> 4).set(bx, by & 15, bz, Blocks.air.getState()); + } + } + } + } + for(int n = 0; n < this.biomes.length; ++n) { + this.biomes[n] = (byte)biomes[n].id; + } + if(ceil) + this.resetRelight(); + else + this.genSkyLight(); + } + + public int getTopSegment() { + return this.top; + } + + public int getBottomSegment() { + return this.bottom; + } + + public Set getStorage() { + return this.blockList; + } + + public void addTileEntity(TileEntity tile) { + this.addTileEntity(tile.getPos(), tile); + + if(this.loaded) { + this.world.addTileEntity(tile); + } + } + + public void onChunkLoad() { + this.loaded = true; + this.world.addTileEntities(this.tiles.values()); + + for(int n = 0; n < this.entities.length; ++n) { + for(Entity entity : this.entities[n]) { + entity.onChunkLoad(); + } + + this.world.loadEntities(this.entities[n]); + } + } + + public boolean isDirty(long time) { + if(this.hasEntity && time != this.lastSave || this.modified) { + return true; + } + return this.modified; + } + + public void setStorage(BlockArray[] data) { + for(BlockArray arr : data) { + this.setArray(arr); + } + } + + public Biome getBiome(BlockPos pos, BiomeGenerator gen) { + int x = pos.getX() & 15; + int z = pos.getZ() & 15; + int o = this.biomes[z << 4 | x] & 255; + + if(o == 255) { + Biome biome = gen == null ? Biome.DEF_BIOME : gen.getBiomeGenerator(pos, Biome.DEF_BIOME); + o = biome.id; + this.biomes[z << 4 | x] = (byte)(o & 255); + } + + return Biome.getBiomeDef(o); + } + + public byte[] getBiomes() { + return this.biomes; + } + + public void setBiomes(byte[] biomes) { + if(this.biomes.length != biomes.length) { + Log.IO.warn("Konnte Biome des Chunks nicht setzen, Länge des Arrays ist " + biomes.length + " statt " + this.biomes.length); + } + else { + for(int n = 0; n < this.biomes.length; ++n) { + this.biomes[n] = biomes[n]; + } + } + } + + public int[] getHeights() { + return this.height; + } + + public void setHeights(int[] map) { + if(this.height.length != map.length) { + Log.IO.warn("Konnte Höhen des Chunks nicht setzen, Länge des Arrays ist " + map.length + " statt " + this.height.length); + } + else { + for(int n = 0; n < this.height.length; ++n) { + this.height[n] = map[n]; + } + } + } + + public Map getTiles() { + return this.tiles; + } + + public boolean isTerrainPopulated() { + return this.populated; + } + + public void setTerrainPopulated(boolean populated) { + this.populated = populated; + } + + public boolean isLightPopulated() { + return this.lightInit; + } + + public void setLightPopulated(boolean populated) { + this.lightInit = populated; + } + + public void setModified(boolean modified) { + this.modified = modified; + } + + public void setHasEntities(boolean entities) { + this.hasEntity = entities; + } + + public void setSaved(long time) { + this.lastSave = time; + } + + public long getInhabited() { + return this.inhabited; + } + + public void setInhabited(long time) { + this.inhabited = time; + } +} diff --git a/java/src/game/world/Converter.java b/server/src/main/java/server/world/Converter.java similarity index 70% rename from java/src/game/world/Converter.java rename to server/src/main/java/server/world/Converter.java index b7ff953..7b7bc10 100644 --- a/java/src/game/world/Converter.java +++ b/server/src/main/java/server/world/Converter.java @@ -1,96 +1,160 @@ -package game.world; +package server.world; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; +import java.io.DataInput; import java.io.DataInputStream; import java.io.File; +import java.io.FileInputStream; import java.io.FilenameFilter; import java.io.IOException; import java.io.RandomAccessFile; +import java.util.ArrayList; import java.util.Arrays; +import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; import java.util.zip.InflaterInputStream; -import game.collect.Maps; +import common.biome.Biome; +import common.block.Block; +import common.block.BlockColored; +import common.block.artificial.BlockCarpet; +import common.block.artificial.BlockFlowerPot; +import common.block.artificial.BlockQuartz; +import common.block.artificial.BlockSlab; +import common.block.artificial.BlockStainedGlass; +import common.block.artificial.BlockStainedGlassPane; +import common.block.artificial.BlockStoneBrick; +import common.block.artificial.BlockWall; +import common.block.foliage.BlockCactus; +import common.block.foliage.BlockFlower; +import common.block.foliage.BlockLeaves; +import common.block.foliage.BlockLog; +import common.block.foliage.BlockTallGrass; +import common.block.foliage.LeavesType; +import common.block.liquid.BlockLiquid; +import common.block.natural.BlockDirt; +import common.block.natural.BlockFire; +import common.block.natural.BlockRock; +import common.block.natural.BlockSand; +import common.block.natural.BlockSandStone; +import common.block.tech.BlockPistonBase; +import common.block.tech.BlockPistonHead; +import common.block.tech.BlockTNT; +import common.collect.Lists; +import common.collect.Maps; +import common.color.DyeColor; +import common.entity.Entity; +import common.entity.animal.EntityBat; +import common.entity.animal.EntityChicken; +import common.entity.animal.EntityCow; +import common.entity.animal.EntityHorse; +import common.entity.animal.EntityMooshroom; +import common.entity.animal.EntityOcelot; +import common.entity.animal.EntityPig; +import common.entity.animal.EntityRabbit; +import common.entity.animal.EntitySheep; +import common.entity.animal.EntitySquid; +import common.entity.animal.EntityWolf; +import common.entity.item.EntityBoat; +import common.entity.item.EntityMinecart; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.EntityRegistry; +import common.init.TileRegistry; +import common.log.Log; +import common.rng.Random; +import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityBanner; +import common.tileentity.TileEntityBeacon; +import common.tileentity.TileEntityChest; +import common.tileentity.TileEntityComparator; +import common.tileentity.TileEntityDaylightDetector; +import common.tileentity.TileEntityDispenser; +import common.tileentity.TileEntityDropper; +import common.tileentity.TileEntityEnchantmentTable; +import common.tileentity.TileEntityFurnace; +import common.tileentity.TileEntityHopper; +import common.tileentity.TileEntitySign; +import common.util.Facing; +import common.util.NibbleArray; +import common.world.State; +import common.world.Weather; +import server.Server; -import game.Game; -import game.biome.Biome; -import game.block.Block; -import game.block.BlockCactus; -import game.block.BlockCarpet; -import game.block.BlockColored; -import game.block.BlockDirt; -import game.block.BlockFire; -import game.block.BlockFlower; -import game.block.BlockFlowerPot; -import game.block.BlockLeaves; -import game.block.BlockLiquid; -import game.block.BlockLog; -import game.block.BlockPistonBase; -import game.block.BlockPistonHead; -import game.block.BlockQuartz; -import game.block.BlockRock; -import game.block.BlockSand; -import game.block.BlockSandStone; -import game.block.BlockSlab; -import game.block.BlockStainedGlass; -import game.block.BlockStainedGlassPane; -import game.block.BlockStoneBrick; -import game.block.BlockTNT; -import game.block.BlockTallGrass; -import game.block.BlockWall; -import game.block.LeavesType; -import game.color.DyeColor; -import game.entity.Entity; -import game.entity.animal.EntityBat; -import game.entity.animal.EntityChicken; -import game.entity.animal.EntityCow; -import game.entity.animal.EntityHorse; -import game.entity.animal.EntityMooshroom; -import game.entity.animal.EntityOcelot; -import game.entity.animal.EntityPig; -import game.entity.animal.EntityRabbit; -import game.entity.animal.EntitySheep; -import game.entity.animal.EntitySquid; -import game.entity.animal.EntityWolf; -import game.entity.item.EntityBoat; -import game.entity.item.EntityMinecart; -import game.gui.GuiConvert; -import game.gui.GuiLoading; -import game.gui.GuiLoading.Callback; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.Config; -import game.init.EntityRegistry; -import game.init.TileRegistry; -import game.init.UniverseRegistry; -import game.log.Log; -import game.nbt.NBTLoader; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityBanner; -import game.tileentity.TileEntityBeacon; -import game.tileentity.TileEntityChest; -import game.tileentity.TileEntityComparator; -import game.tileentity.TileEntityDaylightDetector; -import game.tileentity.TileEntityDispenser; -import game.tileentity.TileEntityDropper; -import game.tileentity.TileEntityEnchantmentTable; -import game.tileentity.TileEntityFurnace; -import game.tileentity.TileEntityHopper; -import game.tileentity.TileEntityMobSpawner; -import game.tileentity.TileEntityNote; -import game.tileentity.TileEntityPiston; -import game.tileentity.TileEntitySign; -import game.tileentity.TileEntitySkull; -import game.world.Region.FolderInfo; +public abstract class Converter { + private static class NbtTag { + private final Map map = Maps.newHashMap(); -public final class Converter { - public static enum SaveVersion { + private boolean has(String key, Class type) { + Object tag = this.map.get(key); + return tag != null && tag.getClass() == type; + } + + private List getList(String key, Class type) { + Object tag = this.map.get(key); + if(!(tag instanceof List)) + return Lists.newArrayList(); + List list = (List)tag; + return !list.isEmpty() && list.get(0).getClass() != type ? Lists.newArrayList() : list; + } + + public byte getByte(String key) { + return !this.has(key, Byte.class) ? 0 : (Byte)this.map.get(key); + } + + public int getInt(String key) { + return this.has(key, Integer.class) ? (Integer)this.map.get(key) : (this.has(key, Short.class) ? (Short)this.map.get(key) : this.getByte(key)); + } + + public String getString(String key) { + return !this.has(key, String.class) ? "" : (String)this.map.get(key); + } + + public byte[] getByteArray(String key) { + return !this.has(key, byte[].class) ? new byte[0] : (byte[])this.map.get(key); + } + + public int[] getIntArray(String key) { + return !this.has(key, int[].class) ? new int[0] : (int[])this.map.get(key); + } + + public NbtTag getTag(String key) { + return !this.has(key, NbtTag.class) ? new NbtTag() : (NbtTag)this.map.get(key); + } + + public float[] getFloatList(String key) { + List list = this.getList(key, Float.class); + float[] values = new float[list.size()]; + for(int z = 0; z < values.length; z++) { + values[z] = (Float)list.get(z); + } + return values; + } + + public double[] getDoubleList(String key) { + List list = this.getList(key, Double.class); + double[] values = new double[list.size()]; + for(int z = 0; z < values.length; z++) { + values[z] = (Double)list.get(z); + } + return values; + } + + public NbtTag[] getTagList(String key) { + List list = this.getList(key, NbtTag.class); + NbtTag[] values = new NbtTag[list.size()]; + for(int z = 0; z < values.length; z++) { + values[z] = (NbtTag)list.get(z); + } + return values; + } + } + + private static enum SaveVersion { ALPHA_1_0("Alpha 1.0 - Beta 1.2"), BETA_1_3("Beta 1.3 - Release 1.8.9"), RELEASE_1_9("Release 1.9 - Release 1.12.2"), @@ -106,12 +170,7 @@ public final class Converter { return this.name; } } - -// public static interface Callback { -// void postMessage(String msg); -// void postProgress(int progress); -// } - + private static class AnvilRegion { private final int[] offsets = new int[1024]; @@ -193,14 +252,10 @@ public final class Converter { State getState(int id, int data); } - private Converter() { - } - - private long postProgress(long start, int progress) { -// SKC.info("... " + progress + "%"); + private static long postProgress(long start, int progress) { if(System.currentTimeMillis() - start >= 500L) { start = System.currentTimeMillis(); - Log.JNI.info("... " + progress + "%"); + Log.IO.info("... " + progress + "%"); } return start; } @@ -209,16 +264,7 @@ public final class Converter { private static final Map ENTITY_MAP = Maps.newHashMap(); private static final Map TILE_MAP = Maps.newHashMap(); private static final char[] BLOCK_MAP = new char[65536]; -// private static final Map BLOCK_FUNCS = Maps.newHashMap(); private static final Map OLD_GAMERULES = Maps.newHashMap(); - - private String action; - private String task; - private String file; - private int totalRegions; - private int doneRegions; - private int totalChunks; - private int doneChunks; private static void mapEntity(Class clazz, String ... names) { String name = EntityRegistry.getEntityString(clazz); @@ -228,7 +274,7 @@ public final class Converter { } private static void mapTile(Class clazz, String ... names) { - String name = TileRegistry.classToNameMap.get(clazz); + String name = TileRegistry.CLASS_TO_NAME.get(clazz); for(String oldname : names) { TILE_MAP.put(oldname, name); } @@ -264,17 +310,6 @@ public final class Converter { } } -// private static void mapBlockDynamic(BlockFunction func, int id, int data) { -// BLOCK_MAP[(id << 4) | data] = (char)0x000f; -// BLOCK_FUNCS.put((char)((id << 4) | data), func); -// } -// -// private static void mapBlockDynamic(BlockFunction func, int id) { -// for(int z = 0; z < 16; z++) { -// mapBlockDynamic(func, id, z); -// } -// } - static { OLD_GAMERULES.put("doFireTick", "fireTick"); OLD_GAMERULES.put("mobGriefing", "mobGriefing"); @@ -284,7 +319,6 @@ public final class Converter { OLD_GAMERULES.put("doEntityDrops", "dropObjects"); OLD_GAMERULES.put("naturalRegeneration", "naturalRegeneration"); OLD_GAMERULES.put("doDaylightCycle", "daylightCycle"); -// OLD_GAMERULES.put("showDeathMessages", "deathMessages"); OLD_GAMERULES.put("keepInventory", "keepInventory"); OLD_GAMERULES.put("doWeatherCycle", "weatherChanges"); OLD_GAMERULES.put("randomTickSpeed", "randomTickSpeed"); @@ -308,16 +342,12 @@ public final class Converter { mapTile(TileEntityDispenser.class, "Trap", "dispenser"); mapTile(TileEntityDropper.class, "Dropper", "dropper"); mapTile(TileEntitySign.class, "Sign", "sign"); - mapTile(TileEntityMobSpawner.class, "MobSpawner", "mob_spawner"); - mapTile(TileEntityNote.class, "Music", "noteblock"); - mapTile(TileEntityPiston.class, "Piston", "piston"); + // mapTile(TileEntityPiston.class, "Piston", "piston"); mapTile(TileEntityEnchantmentTable.class, "EnchantTable", "enchanting_table"); mapTile(TileEntityBeacon.class, "Beacon", "beacon"); - mapTile(TileEntitySkull.class, "Skull", "skull"); mapTile(TileEntityDaylightDetector.class, "DLDetector", "daylight_detector"); mapTile(TileEntityHopper.class, "Hopper", "hopper"); mapTile(TileEntityComparator.class, "Comparator", "comparator"); -// mapTile(TileEntityFlowerPot.class, "FlowerPot", "flower_pot"); mapTile(TileEntityBanner.class, "Banner", "banner"); mapBlock(Blocks.stone.getState(), 1); @@ -456,7 +486,7 @@ public final class Converter { return Blocks.wool.getState().withProperty(BlockColored.COLOR, DyeColor.byMetadata(data)); } }, 35); - mapBlockData(Blocks.piston_extension, 36); + mapBlock(Blocks.stone, 36); // mapBlockData(Blocks.piston_extension, 36); mapBlock(Blocks.flower.getState().withProperty(Blocks.flower.getTypeProperty(), BlockFlower.EnumFlowerType.DANDELION), 37); mapBlock(Blocks.flower.getState().withProperty(Blocks.flower.getTypeProperty(), BlockFlower.EnumFlowerType.POPPY), 38); @@ -544,13 +574,13 @@ public final class Converter { return Blocks.fire.getState().withProperty(BlockFire.AGE, data); } }, 51); - mapBlock(Blocks.mob_spawner, 52); + mapBlock(Blocks.iron_bars, 52); mapBlockData(Blocks.oak_stairs, 53); mapBlockData(Blocks.chest, 54); mapBlockData(Blocks.redstone, 55); mapBlock(Blocks.diamond_ore, 56); mapBlock(Blocks.diamond_block, 57); - mapBlock(Blocks.crafting_table, 58); + mapBlock(Blocks.workbench, 58); mapBlockData(Blocks.wheat, 59); mapBlockData(Blocks.farmland, 60); mapBlockData(Blocks.furnace, 61); @@ -620,11 +650,6 @@ public final class Converter { mapBlockData(Blocks.stonebrick_stairs, 109); mapBlock(Blocks.mycelium, 110); mapBlockData(Blocks.waterlily, 111); -// mapBlockDynamic(new BlockFunction() { -// public IBlockState getState(int id, int data) { -// return Blocks.waterlily.getDefaultState().withProperty(BlockDirectional.FACING, Facing.randHorizontal(RANDOM)); -// } -// }, 111); mapBlock(Blocks.blood_brick, 112); mapBlockData(Blocks.blood_brick_fence, 113); mapBlockData(Blocks.blood_brick_stairs, 114); @@ -833,103 +858,76 @@ public final class Converter { return Blocks.stained_hardened_clay.getState().withProperty(BlockColored.COLOR, DyeColor.byMetadata(data)); } }, 252); - // 253, 254 mapBlock(Blocks.obsidian, 255); - -// addBlock(137, 49); // Command Block -// addBlock(166, 0); // Barrier -// addBlock(168, 98); // Prismarine -// // addBlock(169, 169); // Sea Lantern --> Lamp -// addBlock(179, 24); // Red Sandstone -// addBlock(180, 128); // Red Sandstone Stairs -// addBlock(181, 43, 1); // Red Sandstone Double Slab -// -// addBlock(198, 101); // End Rod -// addBlock(199, 102); // Chorus Plant -// addBlock(200, 102); // Chorus Flower -// addBlock(201, 155); // Purpur Block -// addBlock(203, 156); // Purpur Stairs -// addBlock(206, 98); // End Stone Bricks -// addBlock(207, 142); // Beetroot Block -// addBlock(208, 60); // Grass Path -// addBlock(209, 20); // End Gateway -// addBlock(210, 137); // Repeating Command Block -// addBlock(211, 137); // Chain Command Block -// addBlock(212, 79); // Frosted Ice -// addBlock(213, 87); // Magma Block -// addBlock(214, 100); // Nether Wart Block -// addBlock(215, 112); // Red Nether Brick -// addBlock(216, 155); // Bone Block -// addBlock(217, 20); // Structure Void -// addBlock(218, 158); // Observer -// addBlock(255, 49); // Structure Block -// addBlock(202, 155, 2); // Purpur Pillar -// addBlock(204, 43, 7); // Purpur Double Slab - -// if(block > 197 && adddata != null) -// adddata.set(cx, cy, cz, 0); -// if(block == 1 || block == 19) { // Stone, Sponge -// data.set(cx, cy, cz, 0); -// } -// else if(block == 29 || block == 33 || block == 34) { // Piston, Sticky Piston, Piston Head -// int dt = data.get(cx, cy, cz); -// if((dt & 7) == 6) -// data.set(cx, cy, cz, (dt & 8) | 1); -// } -// else if(block == 97) { // Monster Egg -// int dt = data.get(cx, cy, cz); -// switch(dt) { -// case 0: -// default: -// blocks[c] = (byte)1; -// data.set(cx, cy, cz, 0); -// break; -// case 1: -// blocks[c] = (byte)4; -// data.set(cx, cy, cz, 0); -// break; -// case 2: -// case 3: -// case 4: -// case 5: -// blocks[c] = (byte)98; -// data.set(cx, cy, cz, dt - 2); -// break; -// } -// } -// mapBlock(new BlockFunction() { -// public IBlockState getState(int id, int data) { -// return Blocks.waterlily.getDefaultState().withProperty(BlockDirectional.FACING, Facing.randHorizontal(RANDOM)); -// } -// }, 111); -// else if(block == 111) { // Water Lily -// data.set(cx, cy, cz, RANDOM.zrange(4)); -// } -// else if(block == 251 || block == 252) { // Concrete, Concrete Powder -// blocks[c] = (byte)159; -// } -// else if(block >= 235 && block <= 250) { // Glazed Terracotta -// blocks[c] = (byte)159; -// data.set(cx, cy, cz, block - 235); -// } -// else if(block >= 219 && block <= 234) { // Shulker Box -// blocks[c] = (byte)35; -// data.set(cx, cy, cz, block - 219); -// } -// else if(block == 205) { // Purpur Slab -// blocks[c] = (byte)44; -// data.set(cx, cy, cz, (data.get(cx, cy, cz) & 8) == 8 ? 15 : 7); -// } -// else if(block == 182) { // Red Sandstone Slab -// blocks[c] = (byte)44; -// data.set(cx, cy, cz, (data.get(cx, cy, cz) & 8) == 8 ? 9 : 1); -// } + } + + private static Object read(DataInput input, byte id) throws IOException { + switch(id) { + case 0: + return null; + case 1: + return input.readByte(); + case 2: + return input.readShort(); + case 3: + return input.readInt(); + case 4: + return input.readLong(); + case 5: + return input.readFloat(); + case 6: + return input.readDouble(); + case 7: { + int len = input.readInt(); + byte[] data = new byte[len]; + input.readFully(data); + return data; + } + case 8: + return input.readUTF(); + case 9: { + byte type = input.readByte(); + int len = input.readInt(); + if(type == 0 && len > 0) + throw new RuntimeException("Liste hat keinen Typ"); + List list = new ArrayList(len); + for(int z = 0; z < len; z++) { + list.add(read(input, type)); + } + return list; + } + case 10: { + NbtTag tag = new NbtTag(); + byte type; + while((type = input.readByte()) != 0) { + String key = input.readUTF(); + tag.map.put(key, read(input, type)); + } + return tag; + } + case 11: { + int len = input.readInt(); + int[] data = new int[len]; + for(int z = 0; z < len; z++) { + data[z] = input.readInt(); + } + return data; + } + default: + return null; + } + } + + private static NbtTag readTag(DataInputStream in) throws IOException { + if(in.readByte() != 10) + throw new IOException("Tag hat den falschen Typ"); + in.readUTF(); + return (NbtTag)read(in, (byte)10); } - private static void convertTile(NBTTagCompound ent) { - if("Sign".equals(ent.getString("id"))) { -// Log.debug("Konvertiere Schild bei " -// + ent.getInteger("x") + "," + ent.getInteger("y") + "," + ent.getInteger("z") + " ..."); + private static TagObject convertTile(NbtTag ent, String id) { + TagObject nent = new TagObject(); + if("Sign".equals(id)) { String[] signText = new String[4]; for(int i = 0; i < 4; ++i) { signText[i] = ent.getString("Text" + (i + 1)); @@ -939,15 +937,12 @@ public final class Converter { String[] old = new String[4]; for(int i = 0; i < 4; ++i) { old[i] = signText[i]; -// if(ChatFormat.hasLegacy(this.signText[i])) { - signText[i] = signText[i].indexOf('\u00A7') != -1 ? /* TextColor.replaceCodes( */ - signText[i].replaceAll("\u00A7[0-9a-fA-Fk-oK-O]", "") /* .replace("\u00A7", "$$")) */ : + signText[i] = signText[i].indexOf('\u00A7') != -1 ? + signText[i].replaceAll("\u00A7[0-9a-fA-Fk-oK-O]", "") : signText[i]; -// } if(signText[i].startsWith("{") && signText[i].endsWith("}")) { try { -// TextComponent comp = TextSerializer.toComponent(signText[i]); - signText[i] = ""; // comp.getFormattedText(); + signText[i] = ""; newComp++; } catch(Throwable e) { @@ -962,14 +957,15 @@ public final class Converter { if(newComp == 4 && (quotes & (1 << i)) != 0) { signText[i] = signText[i].substring(1, signText[i].length() - 1); } -// if(old[i] != signText[i]) { -// Log.debug("Zeile " + (i + 1) + ": '" + TextColor.stripCodes(signText[i]) + "'"); -// } } for(int i = 0; i < 4; ++i) { - ent.setString("Text" + (i + 1), signText[i]); + nent.setString("Text" + (i + 1), signText[i]); } } + else if("Comparator".equals(id)) { + nent.setInt("OutputSignal", ent.getInt("OutputSignal")); + } + return nent; } private static int getNibble(byte[] data, int x, int y, int z) { @@ -981,23 +977,22 @@ public final class Converter { int idx = name.indexOf(':'); return idx >= 0 ? name.substring(idx + 1) : name; // save compat } - - private static NBTTagCompound convertChunkData(NBTTagCompound tag, boolean legacy) { - tag = tag.getCompoundTag("Level"); + + private static TagObject convertChunkData(NbtTag tag, boolean legacy) { + TagObject ntag = new TagObject(); + tag = tag.getTag("Level"); if(legacy) { - if(tag.hasKey("LastUpdate", 3)) - tag.setLong("LastUpdate", (long)tag.getInteger("LastUpdate")); byte[] oldheight = tag.getByteArray("HeightMap"); int[] height = new int[oldheight.length]; for(int i = 0; i < oldheight.length; ++i) { height[i] = oldheight[i]; } - tag.setIntArray("HeightMap", height); + ntag.setIntArray("HeightMap", height); byte[] oldblks = tag.getByteArray("Blocks"); byte[] olddata = tag.getByteArray("Data"); byte[] oldsky = tag.getByteArray("SkyLight"); byte[] oldlight = tag.getByteArray("BlockLight"); - NBTTagList sections = new NBTTagList(); + List sections = Lists.newArrayList(); for(int n = 0; n < 8; ++n) { boolean empty = true; for(int x = 0; x < 16 && empty; ++x) { @@ -1029,63 +1024,80 @@ public final class Converter { } } } - NBTTagCompound section = new NBTTagCompound(); + TagObject section = new TagObject(); section.setByte("Y", (byte)(n & 255)); section.setByteArray("Blocks", blocks); section.setByteArray("Data", data.getData()); section.setByteArray("SkyLight", sky.getData()); section.setByteArray("BlockLight", light.getData()); - sections.appendTag(section); + sections.add(section); } } - tag.setTag("Sections", sections); + ntag.setList("Sections", sections); byte[] biomes = new byte[256]; Arrays.fill(biomes, (byte)(Biome.DEF_BIOME.id & 255)); - tag.setByteArray("Biomes", biomes); + ntag.setByteArray("Biomes", biomes); } - NBTTagList ents = tag.getTagList("Entities", 10); - NBTTagList entities = new NBTTagList(); - for(int z = 0; z < ents.tagCount(); z++) { - NBTTagCompound ent = ents.getCompoundTagAt(z); + else { + ntag.setIntArray("HeightMap", tag.getIntArray("HeightMap")); + } + + ntag.setBool("TerrainPopulated", true); + ntag.setBool("LightPopulated", tag.getByte("LightPopulated") != 0); + + NbtTag[] ents = tag.getTagList("Entities"); + List entities = Lists.newArrayList(); + for(NbtTag ent : ents) { + TagObject nent = new TagObject(); String mapped = ENTITY_MAP.get(trimColon(ent.getString("id"))); if(mapped != null) { - NBTTagList pos = ent.getTagList("Pos", 6); - NBTTagList motion = ent.getTagList("Motion", 6); - NBTTagList rotation = ent.getTagList("Rotation", 5); - boolean ground = ent.getBoolean("OnGround"); - ent.getKeySet().clear(); - ent.setTag("Pos", pos); - ent.setTag("Motion", motion); - ent.setTag("Rotation", rotation); - ent.setBoolean("OnGround", ground); - ent.setInteger("Dimension", 1); - ent.setString("id", mapped); - entities.appendTag(ent); + double[] pos = ent.getDoubleList("Pos"); + double[] motion = ent.getDoubleList("Motion"); + float[] rotation = ent.getFloatList("Rotation"); + if(pos.length != 3 || motion.length != 3 || rotation.length != 2) + continue; + boolean ground = ent.getByte("OnGround") != 0; + nent.setDouble("PosX", pos[0]); + nent.setDouble("PosY", pos[1]); + nent.setDouble("PosZ", pos[2]); + nent.setDouble("MotionX", motion[0]); + nent.setDouble("MotionY", motion[1]); + nent.setDouble("MotionZ", motion[2]); + nent.setFloat("Yaw", rotation[0]); + nent.setFloat("Pitch", rotation[1]); + nent.setBool("OnGround", ground); + nent.setInt("Dimension", 1); + nent.setString("id", mapped); + entities.add(nent); } } - tag.setTag("Entities", entities); + ntag.setList("Entities", entities); - ents = tag.getTagList("TileEntities", 10); - entities = new NBTTagList(); - for(int z = 0; z < ents.tagCount(); z++) { - NBTTagCompound ent = ents.getCompoundTagAt(z); + ents = tag.getTagList("TileEntities"); + entities = Lists.newArrayList(); + for(NbtTag ent : ents) { + TagObject nent = new TagObject(); String mapped = TILE_MAP.get(trimColon(ent.getString("id"))); if(mapped != null) { - ent.setString("id", mapped); - convertTile(ent); - entities.appendTag(ent); + nent = convertTile(ent, mapped); + nent.setString("id", mapped); + nent.setInt("x", ent.getInt("x")); + nent.setInt("y", ent.getInt("y")); + nent.setInt("z", ent.getInt("z")); + entities.add(nent); } } - tag.setTag("TileEntities", entities); + ntag.setList("TileEntities", entities); - tag.removeTag("TileTicks"); - - NBTTagList sects = tag.getTagList("Sections", 10); - for(int n = 0; n < sects.tagCount(); ++n) { - NBTTagCompound sect = sects.getCompoundTagAt(n); + NbtTag[] sects = tag.getTagList("Sections"); + entities = Lists.newArrayList(); + for(NbtTag sect : sects) { + TagObject nsect = new TagObject(); + nsect.setInt("Y", sect.getByte("Y")); byte[] blocks = sect.getByteArray("Blocks"); NibbleArray data = new NibbleArray(sect.getByteArray("Data")); - NibbleArray adddata = sect.hasKey("Add", 7) ? new NibbleArray(sect.getByteArray("Add")) : null; + byte[] add = sect.getByteArray("Add"); + NibbleArray adddata = add.length > 0 ? new NibbleArray(add) : null; for(int c = 0; c < blocks.length; ++c) { int cx = c & 15; int cy = c >> 8 & 15; @@ -1116,25 +1128,23 @@ public final class Converter { data.set(cx, cy, cz, cd & 15); } } - sect.setByteArray("Blocks", blocks); - sect.setByteArray("Data", data.getData()); + nsect.setByteArray("Blocks", blocks); + nsect.setByteArray("Data", data.getData()); if(adddata != null) - sect.setByteArray("Add", adddata.getData()); + nsect.setByteArray("Add", adddata.getData()); + entities.add(nsect); } - return tag; + ntag.setList("Sections", entities); + return ntag; } - private long convertChunks(File dir, File file, long start, int progress, int total) { + private static long convertChunks(File dir, File file, long start, int progress, int total) { String name = file.getName(); - this.file = name; - this.totalChunks = 1024; boolean legacy = name.endsWith(".mcr"); int rx, rz; String[] reg = name.split("\\."); if(reg.length != 4) { - Log.JNI.warn("Unbekannte Region " + file); - this.doneChunks = 0; - this.file = null; + Log.IO.warn("Unbekannte Region " + file); return start; } try { @@ -1142,9 +1152,7 @@ public final class Converter { rz = Integer.parseInt(reg[2]); } catch(NumberFormatException e) { - Log.JNI.warn("Unbekannte Region " + file); - this.doneChunks = 0; - this.file = null; + Log.IO.warn("Unbekannte Region " + file); return start; } try { @@ -1157,12 +1165,11 @@ public final class Converter { for(int bx = 0; bx < 4; bx++) { for(int bz = 0; bz < 4; bz++) { if(!oldreg.hasRegion(bx, bz)) { - this.doneChunks += 64; continue; } areas++; newreg = new Region(dir, rx * 4 + bx, rz * 4 + bz); - Log.JNI.info("Konvertiere " + file + " zu " + newreg.getFile() + " ..."); + Log.IO.info("Konvertiere " + file + " zu " + newreg.getFile() + " ..."); for(int nx = 0; nx < 8; nx++) { for(int nz = 0; nz < 8; nz++) { int x = bx << 3 | nx; @@ -1171,19 +1178,17 @@ public final class Converter { chunks++; DataInputStream in = oldreg.getInputStream(x, z); if(in == null) { - Log.JNI.warn("Konnte " + file.getPath() + "@" + x + "," + z + " nicht lesen"); - this.doneChunks += 1; + Log.IO.warn("Konnte " + file.getPath() + "@" + x + "," + z + " nicht lesen"); continue; } - NBTTagCompound tag = NBTLoader.read(in); + NbtTag tag = readTag(in); in.close(); - tag = convertChunkData(tag, legacy); + TagObject ntag = convertChunkData(tag, legacy); // DataOutputStream out = newreg.getOutputStream(nx, nz); // CompressedStreamTools.write(tag, out); // out.close(); - newreg.writeTag(nx, nz, tag); + newreg.writeTag(nx, nz, ntag); } - this.doneChunks += 1; } } newreg.close(false); @@ -1196,224 +1201,109 @@ public final class Converter { } } oldreg.close(); - Log.JNI.info(file + ": " + areas + " Regionen, " + chunks + " Chunks"); + Log.IO.info(file + ": " + areas + " Regionen, " + chunks + " Chunks"); } catch(IOException e) { e.printStackTrace(); } - this.doneChunks = 0; - this.file = null; return start; } - - public static FolderInfo convertMapFormat(File dir, boolean load) { + + public static boolean convert(Server server) { long cur = System.currentTimeMillis(); - if(load) - Log.JNI.info("Welt '" + dir + "' wird konvertiert"); - if(new File(dir, "level.nbt").exists()) { - if(load) - Log.JNI.error("Datei level.nbt existiert bereits"); - return null; - } - File ldat = new File(dir, "level.dat"); + if(new File("server.cdt").exists()) + return false; + File ldat = new File("level.dat"); if(!ldat.exists()) - ldat = new File(dir, "level.dat_old"); - if(!ldat.exists()) { - if(load) - Log.JNI.error("Datei level.dat und level.dat_old nicht gefunden"); - return null; - } - NBTTagCompound nbt; + ldat = new File("level.dat_old"); + if(!ldat.exists()) + return false; + Log.IO.info("Welt wird konvertiert"); + NbtTag tag; + DataInputStream in = null; try { - nbt = NBTLoader.readGZip(ldat); + in = new DataInputStream(new BufferedInputStream(new GZIPInputStream(new FileInputStream(ldat)))); + tag = readTag(in); } catch(Exception e) { - if(load) - Log.JNI.error(e, "Fehler beim Lesen von level.dat"); - return null; + Log.IO.error(e, "Fehler beim Lesen von level.dat"); + return false; } - nbt = nbt.getCompoundTag("Data"); - int version = nbt.getInteger("version"); - int data = nbt.getInteger("DataVersion"); -// nbt.setBoolean("incompatible", data >= 1400); + finally { + try { + if(in != null) + in.close(); + } + catch(IOException e) { + } + } + tag = tag.getTag("Data"); + int version = tag.getInt("version"); + int data = tag.getInt("DataVersion"); SaveVersion ver = data >= 1400 ? SaveVersion.RELEASE_1_13 : (data >= 100 ? SaveVersion.RELEASE_1_9 : (version == 19132 || version == 19133 ? SaveVersion.BETA_1_3 : (version == 0 ? SaveVersion.ALPHA_1_0 : null))); if(ver == null) { - if(load) - Log.IO.error("Version %d ist unbekannt", version); - return null; + Log.IO.error("Version %d ist unbekannt", version); + return false; } - long wtime = nbt.getLong(nbt.hasKey("DayTime", 99) ? "DayTime" : "Time") + World.START_TIME; - if(!load) - return new FolderInfo(wtime, nbt.getLong("LastPlayed"), ver, null); -// nbt.setString("verdesc", ver); -// NBTTagCompound nbt = getLegacyWorldInfo(dir); -// if(nbt == null) -// return false; - final Converter conv = new Converter(); - Game.getGame().displayGuiScreen(new GuiLoading("Konvertiere Welt ...", new Callback() { - public void poll(Game gm, GuiLoading gui) { - if(conv.totalRegions > 0) { - gui.setBar(conv.task, "Regionen", conv.totalRegions); - gui.setProgress(conv.doneRegions); - } - else { - gui.resetBar(); - } - if(conv.totalChunks > 0) { - gui.setSub(conv.file, "Chunks", conv.totalChunks); - gui.setSubProgress(conv.doneChunks); - } - else { - gui.resetSub(); - } - gui.setTask(conv.action); - } - })); - final NBTTagCompound tag = nbt; - new Thread(new Runnable() { - public void run() { - Log.IO.info("Version: %s", ver); - if(ver != SaveVersion.RELEASE_1_13) { - conv.action = "Suche nach Chunk-Daten"; - Log.JNI.info("Konvertiere Chunk-Daten von region/*.mca,*.mcr"); - File regionDir = new File(dir, "region"); - if(regionDir.exists()) { - File chunkDir = new File(new File(dir, "chunk"), "terra"); - Log.JNI.info("Konvertiere Welt nach '" + chunkDir + "' ..."); - Log.JNI.info("Durchsuche Ordner unter '" + regionDir + "' nach .mca- und .mcr-Dateien ..."); - File[] files = regionDir.listFiles(new FilenameFilter() { - public boolean accept(File file, String name) { - return name.endsWith(".mca") || name.endsWith(".mcr"); - } - }); - if(files.length == 0) { - Log.JNI.info("Keine .mca- oder .mcr-Dateien gefunden."); - } - else { - conv.task = "Konvertiere Chunkdaten"; - conv.totalRegions = files.length; - Log.JNI.info("Ingesamt wurden " + files.length + " .mca-Dateien und .mcr-Dateien gefunden, konvertiere ..."); - if(ver == SaveVersion.RELEASE_1_9) - Log.JNI.info("Konvertiere von neuerer Version, dies wird Blöcke entfernen ..."); - chunkDir.mkdirs(); - int progress = 0; - long time = System.currentTimeMillis(); - long start = conv.postProgress(time, 0); - for(File file : files) { - int percent = (int)Math.round(100.0D * (double)progress / (double)files.length); - Log.JNI.info("Konvertiere Chunk-Daten: " + file.getName() + " (" + progress + "/" + files.length + ")"); - start = conv.convertChunks(chunkDir, file, start, progress, files.length); - ++progress; - start = conv.postProgress(start, percent); - conv.doneRegions += 1; - } - time = System.currentTimeMillis() - time; - Log.JNI.info("Fertig. Konversion dauerte " + ((time / 60000L) > 0 ? ((time / 60000L) + " Minuten und ") : "") + ((time / 1000L) % 60L) + " Sekunden."); - } - } - } - else { - Log.JNI.warn("Konvertiere keine Chunk-Daten, da Version zu neu"); - } - conv.doneRegions = 0; - conv.task = null; - conv.action = "Konvertiere level.dat"; - Log.JNI.info("Konvertiere Daten von level.dat"); - Config.clear(); - UniverseRegistry.clear(); - if(tag.hasKey("GameRules", 10)) { - NBTTagCompound rules = tag.getCompoundTag("GameRules"); - for(Entry rule : OLD_GAMERULES.entrySet()) { - if(rules.hasKey(rule.getKey(), 8)) - Config.set(rule.getValue(), rules.getString(rule.getKey()), null); - } - } - // Config.setVar("noRespawn", "" + nbt.getBoolean("hardcore"), false); - // int id = nbt.getInteger("GameType"); - // Config.set("defaultNoCreative", "" + (id == 2 || id == 0), false); - Log.JNI.info("Speichere neue level.nbt ..."); - Region.saveWorldInfo(dir, wtime); -// if(tag.hasKey("Player", 10)) { -// conv.action = "Konvertiere Spielerdaten"; -// NBTTagCompound player = tag.getCompoundTag("Player"); -// NBTTagList pos = player.getTagList("Pos", 6); -// NBTTagList motion = player.getTagList("Motion", 6); -// NBTTagList rotation = player.getTagList("Rotation", 5); -// boolean ground = player.getBoolean("OnGround"); -// BlockPos spawn = null; -// // boolean force = player.getBoolean("OnGround"); -// // int mode = -1; -// // if(player.hasKey("playerGameType", 99)) { -// // mode = player.getInteger("playerGameType"); -// // mode = mode == 0 || mode == 2 ? 0 : (mode == 1 || mode == 3 ? 1 : -1); -// // } -// if(player.hasKey("SpawnX", 99) && player.hasKey("SpawnY", 99) && player.hasKey("SpawnZ", 99)) { -// spawn = new BlockPos(player.getInteger("SpawnX"), player.getInteger("SpawnY"), -// player.getInteger("SpawnZ")); -// // force = player.getBoolean("SpawnForced"); -// } -// player.getKeySet().clear(); -// player.setTag("Pos", pos); -// player.setTag("Motion", motion); -// player.setTag("Rotation", rotation); -// player.setBoolean("OnGround", ground); -// player.setInteger("Dimension", 1); -// player.setString("id", EntityRegistry.getEntityString(EntityHuman.class)); -// if(spawn != null) { -// player.setInteger("SpawnX", spawn.getX()); -// player.setInteger("SpawnY", spawn.getY()); -// player.setInteger("SpawnZ", spawn.getZ()); -// player.setInteger("SpawnDim", 1); -// // player.setBoolean("SpawnForced", force); -// } -// player.setInteger("OriginX", tag.getInteger("SpawnX")); -// player.setInteger("OriginY", tag.getInteger("SpawnY")); -// player.setInteger("OriginZ", tag.getInteger("SpawnZ")); -// player.setInteger("OriginDim", 1); -// player.setString("CustomName", user.substring(0, 1).toUpperCase() + user.substring(1)); -// NBTTagCompound plr = new NBTTagCompound(); -// plr.setInteger("selected", 0); -// NBTTagList list = new NBTTagList(); -// list.appendTag(player); -// plr.setTag("characters", list); -// // if(mode >= 0) -// // player.setBoolean("creative", mode == 1); -// Log.JNI.info("Speichere neue Spielerdaten " + user.toLowerCase() + ".nbt ..."); -// File pdat = new File(new File(dir, "players"), user.toLowerCase() + ".nbt"); -// try { -// pdat.getParentFile().mkdirs(); -// NBTLoader.writeGZip(plr, pdat); -// } -// catch(Exception e) { -// Log.JNI.error(e, "Fehler beim Schreiben von " + pdat); -// } -// } - Weather weather = tag.getBoolean("thundering") ? Weather.THUNDER : (tag.getBoolean("raining") ? Weather.RAIN : Weather.CLEAR); - if(weather != Weather.CLEAR) { - conv.action = "Konvertiere Dimensionsdaten"; - NBTTagCompound dataTag = new NBTTagCompound(); - dataTag.setString("Weather", weather.getName()); - Log.JNI.info("Speichere neue data.nbt ..."); - File dataFile = new File(new File(new File(dir, "chunk"), "terra"), "data.nbt"); - try { - NBTLoader.writeGZip(dataTag, dataFile); - } - catch(Exception e) { - Log.JNI.error(e, "Konnte Weltdaten nicht speichern"); - } - } - Log.IO.info("Welt '" + dir + "' wurde in %d Sekunden konvertiert", (System.currentTimeMillis() - cur) / 1000L); - Game.getGame().schedule(new Runnable() { - public void run() { - Game.getGame().displayGuiScreen(GuiConvert.INSTANCE); + Log.IO.info("Version: %s", ver); + if(ver != SaveVersion.RELEASE_1_13) { + Log.IO.info("Konvertiere Chunk-Daten von region/*.mca,*.mcr"); + File regionDir = new File("region"); + if(regionDir.exists()) { + File chunkDir = new File(new File("chunk"), "terra"); + Log.IO.info("Konvertiere Welt nach '" + chunkDir + "' ..."); + Log.IO.info("Durchsuche Ordner unter '" + regionDir + "' nach .mca- und .mcr-Dateien ..."); + File[] files = regionDir.listFiles(new FilenameFilter() { + public boolean accept(File file, String name) { + return name.endsWith(".mca") || name.endsWith(".mcr"); } }); + if(files.length == 0) { + Log.IO.info("Keine .mca- oder .mcr-Dateien gefunden."); + } + else { + Log.IO.info("Ingesamt wurden " + files.length + " .mca-Dateien und .mcr-Dateien gefunden, konvertiere ..."); + if(ver == SaveVersion.RELEASE_1_9) + Log.IO.info("Konvertiere von neuerer Version, dies wird Blöcke entfernen ..."); + chunkDir.mkdirs(); + int progress = 0; + long time = System.currentTimeMillis(); + long start = postProgress(time, 0); + for(File file : files) { + int percent = (int)Math.round(100.0D * (double)progress / (double)files.length); + Log.IO.info("Konvertiere Chunk-Daten: " + file.getName() + " (" + progress + "/" + files.length + ")"); + start = convertChunks(chunkDir, file, start, progress, files.length); + ++progress; + start = postProgress(start, percent); + } + time = System.currentTimeMillis() - time; + Log.IO.info("Fertig. Konversion dauerte " + ((time / 60000L) > 0 ? ((time / 60000L) + " Minuten und ") : "") + ((time / 1000L) % 60L) + " Sekunden."); + } } - }, "Converter Thread").start(); - return new FolderInfo(wtime, System.currentTimeMillis(), null, Config.VERSION); + } + else { + Log.IO.warn("Konvertiere keine Chunk-Daten, da Version zu neu"); + } + Log.IO.info("Konvertiere Daten von level.dat"); + NbtTag rules = tag.getTag("GameRules"); + for(Entry rule : OLD_GAMERULES.entrySet()) { + if(!rules.getString(rule.getKey()).isEmpty()) + server.getVariables().get(rule.getValue()).set(rules.getString(rule.getKey()), false, false); + } + Weather weather = tag.getByte("thundering") != 0 ? Weather.THUNDER : (tag.getByte("raining") != 0 ? Weather.RAIN : Weather.CLEAR); + if(weather != Weather.CLEAR) { + TagObject dataTag = new TagObject(); + dataTag.setString("Weather", weather.getName()); + Log.IO.info("Speichere neue data.cdt ..."); + File dataFile = new File(new File(new File("chunk"), "terra"), "data.cdt"); + try { + TagObject.writeGZip(dataTag, dataFile); + } + catch(Exception e) { + Log.IO.error(e, "Konnte Weltdaten nicht speichern"); + } + } + Log.IO.info("Welt wurde in %d Sekunden konvertiert", (System.currentTimeMillis() - cur) / 1000L); + return true; } - -// public static NBTTagCompound getLegacyWorldInfo(File worldDir) { -// return nbt; -// } } diff --git a/java/src/game/world/NextTickListEntry.java b/server/src/main/java/server/world/NextTickListEntry.java similarity index 87% rename from java/src/game/world/NextTickListEntry.java rename to server/src/main/java/server/world/NextTickListEntry.java index 4f15717..1f1878b 100755 --- a/java/src/game/world/NextTickListEntry.java +++ b/server/src/main/java/server/world/NextTickListEntry.java @@ -1,7 +1,7 @@ -package game.world; +package server.world; -import game.block.Block; -import game.init.BlockRegistry; +import common.block.Block; +import common.util.BlockPos; public class NextTickListEntry implements Comparable { @@ -61,11 +61,6 @@ public class NextTickListEntry implements Comparable return this.scheduledTime < p_compareTo_1_.scheduledTime ? -1 : (this.scheduledTime > p_compareTo_1_.scheduledTime ? 1 : (this.priority != p_compareTo_1_.priority ? this.priority - p_compareTo_1_.priority : (this.tickEntryID < p_compareTo_1_.tickEntryID ? -1 : (this.tickEntryID > p_compareTo_1_.tickEntryID ? 1 : 0)))); } - public String toString() - { - return BlockRegistry.getIdFromBlock(this.block) + ": " + this.position + ", " + this.scheduledTime + ", " + this.priority + ", " + this.tickEntryID; - } - public Block getBlock() { return this.block; diff --git a/java/src/game/world/Region.java b/server/src/main/java/server/world/Region.java similarity index 58% rename from java/src/game/world/Region.java rename to server/src/main/java/server/world/Region.java index bd7c25c..114c963 100755 --- a/java/src/game/world/Region.java +++ b/server/src/main/java/server/world/Region.java @@ -1,4 +1,4 @@ -package game.world; +package server.world; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; @@ -14,40 +14,26 @@ import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; -import game.collect.Lists; -import game.collect.Maps; - -import game.block.Block; -import game.entity.Entity; -import game.init.BlockRegistry; -import game.init.Config; -import game.init.EntityRegistry; -import game.init.UniverseRegistry; -import game.log.Log; -import game.nbt.NBTLoader; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.tileentity.TileEntity; -import game.world.Converter.SaveVersion; +import common.block.Block; +import common.collect.Lists; +import common.collect.Maps; +import common.entity.Entity; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.init.EntityRegistry; +import common.log.Log; +import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.NibbleArray; +import common.util.Util; +import common.world.BlockArray; public class Region { - public static class FolderInfo { - public final long time; - public final long lastPlayed; - public final SaveVersion legacy; - public final String version; - - public FolderInfo(long time, long lastPlayed, SaveVersion legacy, String version) { - this.time = time; - this.lastPlayed = lastPlayed; - this.legacy = legacy; - this.version = version; - } - } - private static class ChunkBuffer extends ByteArrayOutputStream { public ChunkBuffer() { super(8096); @@ -72,10 +58,7 @@ public class Region { private static final Map CACHE = Maps.newHashMap(); private static final List QUEUE = Collections.synchronizedList(Lists.newArrayList()); - -// public static long lastPlayed; -// public static int version; -// public static String owner; + private static volatile long queued; private static volatile long saved; private static volatile boolean waiting; @@ -95,10 +78,10 @@ public class Region { private boolean modified; public Region(File dir, int x, int z) { - File sdir = new File(dir, getRegionFolder(x << 3, z << 3)); + File sdir = new File(dir, Util.getRegionFolder(x << 3, z << 3)); if(!sdir.exists()) sdir.mkdirs(); - this.regFile = new File(sdir, getRegionName(x << 3, z << 3)); + this.regFile = new File(sdir, Util.getRegionName(x << 3, z << 3)); this.folder = dir; this.xPos = x; this.zPos = z; @@ -168,14 +151,14 @@ public class Region { // this.file.seek((long)(512 + (x + z * 8) * 8192)); int size = this.sizes[x + z * 8]; // this.file.readShort(); if(size > 8192 /* - 2 */ || size < 0) { - Log.JNI.warn("Chunk-Region-Datei " + this.regFile + " hat eine ungültige Größe bei " + x + ", " + z + ", überspringe"); + Log.IO.warn("Chunk-Region-Datei " + this.regFile + " hat eine ungültige Größe bei " + x + ", " + z + ", überspringe"); return null; } byte[] data; if(size == 0) { File expand = getExpansionFile(this.folder, this.xPos * 8 + x, this.zPos * 8 + z); if(!expand.exists()) { - Log.JNI.warn("Chunk-Erweiterungs-Datei " + expand + " ist nicht vorhanden oder nicht lesbar, überspringe"); + Log.IO.warn("Chunk-Erweiterungs-Datei " + expand + " ist nicht vorhanden oder nicht lesbar, überspringe"); return null; } in = new FileInputStream(expand); @@ -198,7 +181,7 @@ public class Region { else { int pos = this.positions[x + z * 8] << 8; if(pos + size > this.file.length() - 512L || pos < 0) { - Log.JNI.warn("Chunk-Region-Datei " + this.regFile + " hat eine ungültige Position bei " + x + ", " + z + ", überspringe"); + Log.IO.warn("Chunk-Region-Datei " + this.regFile + " hat eine ungültige Position bei " + x + ", " + z + ", überspringe"); return null; } this.file.seek(512L + (long)pos); @@ -215,7 +198,7 @@ public class Region { } catch(IOException e1) { } - Log.JNI.error(e, "Fehler beim lesen von Chunk-Region-Datei " + this.regFile + " bei " + x + ", " + z + ", überspringe"); + Log.IO.error(e, "Fehler beim lesen von Chunk-Region-Datei " + this.regFile + " bei " + x + ", " + z + ", überspringe"); return null; } } @@ -287,21 +270,14 @@ public class Region { return (long)this.timestamps[x + z * 8] * 10000L; } - public void writeTag(int x, int z, NBTTagCompound tag) throws IOException { + public void writeTag(int x, int z, TagObject tag) throws IOException { ChunkBuffer buf = new ChunkBuffer(); DataOutputStream out = new DataOutputStream(new DeflaterOutputStream(buf)); - NBTLoader.write(tag, out); + TagObject.write(tag, out); out.close(); this.write(x, z, buf.getData(), buf.size()); } -// public NBTTagCompound readTag(int x, int z) throws IOException { -// byte[] data = this.read(x, z); -// if(data == null) -// return null; -// return CompressedStreamTools.read(new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data))))); -// } - public File getFile() { return this.regFile; } @@ -318,7 +294,7 @@ public class Region { } private static File getExpansionFile(File dir, int x, int z) { - File sdir = new File(dir, getRegionFolder(x, z)); + File sdir = new File(dir, Util.getRegionFolder(x, z)); if(!sdir.exists()) sdir.mkdirs(); return new File(sdir, String.format("c.%c%X%c%X.chk", x < 0 ? 'n' : 'p', (x < 0) ? -x : x, z < 0 ? 'n' : 'p', (z < 0) ? -z : z)); @@ -364,58 +340,49 @@ public class Region { clearCache(true); } - public static /* synchronized */ NBTTagCompound readChunk(File dir, int x, int z) throws IOException { + public static /* synchronized */ TagObject readChunk(File dir, int x, int z) throws IOException { // return getRegionFile(dir, x >> 3, z >> 3).readTag(x & 7, z & 7); byte[] data = getRegionFile(dir, x >> 3, z >> 3).read(x & 7, z & 7); if(data == null) return null; - return NBTLoader.read(new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data))))); + return TagObject.read(new DataInputStream(new BufferedInputStream(new InflaterInputStream(new ByteArrayInputStream(data))))); } - public static /* synchronized */ void writeChunk(File dir, int x, int z, NBTTagCompound tag) throws IOException { + public static /* synchronized */ void writeChunk(File dir, int x, int z, TagObject tag) throws IOException { ChunkBuffer buf = new ChunkBuffer(); DataOutputStream out = new DataOutputStream(new DeflaterOutputStream(buf)); - NBTLoader.write(tag, out); + TagObject.write(tag, out); out.close(); getRegionFile(dir, x >> 3, z >> 3).write(x & 7, z & 7, buf.getData(), buf.size()); // getRegionFile(dir, x >> 3, z >> 3).writeTag(x & 7, z & 7, tag); } - public static String getRegionFolder(int x, int z) { - return String.format("%c%03X%c%03X", x < 0 ? 'n' : 'p', ((x < 0) ? -x : x) >> 9, z < 0 ? 'n' : 'p', ((z < 0) ? -z : z) >> 9); - } - - public static String getRegionName(int x, int z) { - return String.format("r.%c%X%c%X.rgn", x < 0 ? 'n' : 'p', ((x < 0) ? -x : x) >> 3, z < 0 ? 'n' : 'p', ((z < 0) ? -z : z) >> 3); - } - - public static Chunk readNbt(WorldServer world, int x, int z, NBTTagCompound tag) { -// if(!tag.hasKey("Level", 10)) { + public static ChunkServer readChunk(WorldServer world, int x, int z, TagObject tag) { +// if(!tag.hasTag("Level")) { // Log.error("Chunk-Datei bei " + x + "," + z + " hat keine Level-Daten, überspringe"); // return null; // } // tag = tag.getCompoundTag("Level"); - if(!tag.hasKey("Sections", 9)) { - Log.JNI.warn("Chunk-Datei bei " + x + "," + z + " hat keine Block-Daten, überspringe"); + if(!tag.hasList("Sections")) { + Log.IO.warn("Chunk-Datei bei " + x + "," + z + " hat keine Block-Daten, überspringe"); return null; } - Chunk chunk = new Chunk(world, x, z); + ChunkServer chunk = new ChunkServer(world, x, z); chunk.setHeights(tag.getIntArray("HeightMap")); - chunk.setTerrainPopulated(tag.getBoolean("TerrainPopulated")); - chunk.setLightPopulated(tag.getBoolean("LightPopulated")); + chunk.setTerrainPopulated(tag.getBool("TerrainPopulated")); + chunk.setLightPopulated(tag.getBool("LightPopulated")); chunk.setInhabited(tag.getLong("InhabitedTime")); - NBTTagList sects = tag.getTagList("Sections", 10); - int stor = 32; - BlockArray[] sections = new BlockArray[stor]; + List sects = tag.getList("Sections"); + BlockArray[] sections = new BlockArray[sects.size()]; boolean light = !world.dimension.hasNoLight(); - for(int n = 0; n < sects.tagCount(); ++n) { - NBTTagCompound sect = sects.getCompoundTagAt(n); - int y = sect.getByte("Y"); - BlockArray storage = new BlockArray(y << 4, light); + for(int n = 0; n < sects.size(); ++n) { + TagObject sect = sects.get(n); + int y = sect.getInt("Y"); + BlockArray storage = new BlockArray(y << 4, light, null); byte[] blocks = sect.getByteArray("Blocks"); NibbleArray data = new NibbleArray(sect.getByteArray("Data")); - NibbleArray adddata = sect.hasKey("Add", 7) ? new NibbleArray(sect.getByteArray("Add")) : null; + NibbleArray adddata = sect.hasByteArray("Add") ? new NibbleArray(sect.getByteArray("Add")) : null; char[] seg = new char[blocks.length]; for(int c = 0; c < seg.length; ++c) { @@ -434,29 +401,29 @@ public class Region { } storage.update(); - sections[y] = storage; + sections[n] = storage; } chunk.setStorage(sections); - if(tag.hasKey("Biomes", 7)) { + if(tag.hasByteArray("Biomes")) { chunk.setBiomes(tag.getByteArray("Biomes")); } - NBTTagList entities = tag.getTagList("Entities", 10); + List entities = tag.getList("Entities"); if(entities != null) { - for(int n = 0; n < entities.tagCount(); ++n) { - NBTTagCompound ent = entities.getCompoundTagAt(n); - Entity entity = EntityRegistry.createEntityFromNBT(ent, world); + for(int n = 0; n < entities.size(); ++n) { + TagObject ent = entities.get(n); + Entity entity = EntityRegistry.createFromTags(ent, world); chunk.setHasEntities(true); if(entity != null) { chunk.addEntity(entity); Entity rider = entity; - for(NBTTagCompound ride = ent; ride.hasKey("Riding", 10); ride = ride.getCompoundTag("Riding")) { - Entity pass = EntityRegistry.createEntityFromNBT(ride.getCompoundTag("Riding"), world); + for(TagObject ride = ent; ride.hasObject("Riding"); ride = ride.getObject("Riding")) { + Entity pass = EntityRegistry.createFromTags(ride.getObject("Riding"), world); if(pass != null) { chunk.addEntity(pass); @@ -469,11 +436,11 @@ public class Region { } } - NBTTagList tiles = tag.getTagList("TileEntities", 10); + List tiles = tag.getList("TileEntities"); if(tiles != null) { - for(int n = 0; n < tiles.tagCount(); ++n) { - NBTTagCompound tile = tiles.getCompoundTagAt(n); + for(int n = 0; n < tiles.size(); ++n) { + TagObject tile = tiles.get(n); TileEntity tileentity = TileEntity.createAndLoadEntity(tile); if(tileentity != null) { @@ -482,33 +449,25 @@ public class Region { } } - if(tag.hasKey("TileTicks", 9)) { - NBTTagList ticks = tag.getTagList("TileTicks", 10); + if(tag.hasList("TileTicks")) { + List ticks = tag.getList("TileTicks"); if(ticks != null) { int invalid = 0; - for(int n = 0; n < ticks.tagCount(); ++n) { - NBTTagCompound tick = ticks.getCompoundTagAt(n); - Block block; + for(int n = 0; n < ticks.size(); ++n) { + TagObject tick = ticks.get(n); + Block block = BlockRegistry.getRegisteredBlock(tick.getString("i")); - if(tick.hasKey("i", 8)) { - block = BlockRegistry.getByIdFallback(tick.getString("i")); - } - else { - block = BlockRegistry.getBlockById(tick.getInteger("i")); - } - - if(block != null) { // FIX - world.scheduleBlockUpdate(new BlockPos(tick.getInteger("x"), tick.getInteger("y"), tick.getInteger("z")), block, - tick.getInteger("t"), tick.getInteger("p")); + if(block != Blocks.air) { // FIX + world.scheduleBlockUpdate(new BlockPos(tick.getInt("x"), tick.getInt("y"), tick.getInt("z")), block, + tick.getInt("t"), tick.getInt("p")); } else if(invalid++ < 10) { - Log.JNI.warn("Unbekannter Block-Tick in Chunk " + x + "," + z + ": " + - (tick.hasKey("i", 8) ? ("'" + tick.getString("i") + "'") : ("#" + tick.getInteger("i")))); + Log.IO.warn("Unbekannter Block-Tick in Chunk " + x + "," + z + ": '" + tick.getString("i") + "'"); } } if(invalid > 10) { - Log.JNI.warn((invalid - 10) + " weitere ..."); + Log.IO.warn((invalid - 10) + " weitere ..."); } } } @@ -516,22 +475,22 @@ public class Region { return chunk; } - public static NBTTagCompound writeNbt(WorldServer world, Chunk chunk) { - NBTTagCompound tag = new NBTTagCompound(); + public static TagObject writeChunk(WorldServer world, ChunkServer chunk) { + TagObject tag = new TagObject(); // tag.setShort("V", (short)Config.PROTOCOL); tag.setLong("LastUpdate", world.getTime()); tag.setIntArray("HeightMap", chunk.getHeights()); - tag.setBoolean("TerrainPopulated", chunk.isTerrainPopulated()); - tag.setBoolean("LightPopulated", chunk.isLightPopulated()); + tag.setBool("TerrainPopulated", chunk.isTerrainPopulated()); + tag.setBool("LightPopulated", chunk.isLightPopulated()); tag.setLong("InhabitedTime", chunk.getInhabited()); - BlockArray[] sections = chunk.getStorage(); - NBTTagList sects = new NBTTagList(); + Set sections = chunk.getStorage(); + List sects = Lists.newArrayList(); boolean light = !world.dimension.hasNoLight(); for(BlockArray storage : sections) { if(storage != null) { - NBTTagCompound sect = new NBTTagCompound(); - sect.setByte("Y", (byte)(storage.getY() >> 4 & 511)); + TagObject sect = new TagObject(); + sect.setInt("Y", storage.getY() >> 4); byte[] blocks = new byte[storage.getData().length]; NibbleArray data = new NibbleArray(); NibbleArray adddata = null; @@ -570,55 +529,57 @@ public class Region { sect.setByteArray("SkyLight", new byte[storage.getBlocklight().getData().length]); } - sects.appendTag(sect); + sects.add(sect); } } - tag.setTag("Sections", sects); + tag.setList("Sections", sects); tag.setByteArray("Biomes", chunk.getBiomes()); chunk.setHasEntities(false); - NBTTagList entities = new NBTTagList(); + List entities = Lists.newArrayList(); for(int n = 0; n < chunk.getEntities().length; ++n) { for(Entity entity : chunk.getEntities()[n]) { - NBTTagCompound ent = new NBTTagCompound(); + TagObject ent = new TagObject(); - if(entity.writeToNBTOptional(ent)) { + if(entity.writeOptional(ent)) { chunk.setHasEntities(true); - entities.appendTag(ent); + entities.add(ent); } } } - tag.setTag("Entities", entities); - NBTTagList tiles = new NBTTagList(); + tag.setList("Entities", entities); + List tiles = Lists.newArrayList(); for(TileEntity tileentity : chunk.getTiles().values()) { - NBTTagCompound tile = new NBTTagCompound(); - tileentity.writeToNBT(tile); - tiles.appendTag(tile); + TagObject tile = new TagObject(); + tileentity.writeTags(tile); + tiles.add(tile); } - tag.setTag("TileEntities", tiles); + tag.setList("TileEntities", tiles); List tics = world.getPendingBlockUpdates(chunk); if(tics != null) { long time = world.getTime(); - NBTTagList ticks = new NBTTagList(); + List ticks = Lists.newArrayList(); for(NextTickListEntry tic : tics) { - NBTTagCompound tick = new NBTTagCompound(); - String res = BlockRegistry.REGISTRY.getNameForObject(tic.getBlock()); - tick.setString("i", res == null ? "" : res.toString()); - tick.setInteger("x", tic.position.getX()); - tick.setInteger("y", tic.position.getY()); - tick.setInteger("z", tic.position.getZ()); - tick.setInteger("t", (int)(tic.scheduledTime - time)); - tick.setInteger("p", tic.priority); - ticks.appendTag(tick); + if(tic.getBlock() == Blocks.air) + continue; + TagObject tick = new TagObject(); + String res = BlockRegistry.getNameFromBlock(tic.getBlock()); + tick.setString("i", res == null ? "" : res); + tick.setInt("x", tic.position.getX()); + tick.setInt("y", tic.position.getY()); + tick.setInt("z", tic.position.getZ()); + tick.setInt("t", (int)(tic.scheduledTime - time)); + tick.setInt("p", tic.priority); + ticks.add(tick); } - tag.setTag("TileTicks", ticks); + tag.setList("TileTicks", ticks); } return tag; @@ -662,93 +623,4 @@ public class Region { public static void killIO() { killed = true; } - - public static void saveWorldInfo(File worldDir, long time) { - NBTTagCompound data = new NBTTagCompound(); - data.setLong("Time", time); - data.setLong("LastAccess", System.currentTimeMillis()); - data.setString("Version", Config.VERSION); - NBTTagCompound cfg = new NBTTagCompound(); - for(String cvar : Config.VARS.keySet()) { - cfg.setString(cvar, Config.VARS.get(cvar).getValue()); -// Config.Value value = Config.VARS.get(cvar); -// switch(value.getType()) { -// case BOOLEAN: -// cfg.setString(cvar, "" + value.getBoolean()); -// break; -// case INTEGER: -// cfg.setString(cvar, "" + value.getInt()); -// break; -// case FLOAT: -// cfg.setString(cvar, "" + value.getFloat()); -// break; -// case STRING: -// cfg.setString(cvar, value.getString()); -// break; -// } - } - data.setTag("Config", cfg); - data.setTag("Universe", UniverseRegistry.saveNbt()); - if(worldDir != null) - worldDir.mkdirs(); - File nfile = new File(worldDir, "level.nbt.tmp"); - File lfile = new File(worldDir, "level.nbt"); - try { -// File ofile = new File(worldDir, "level.nbt_old"); - NBTLoader.writeGZip(data, nfile); -// if(ofile.exists()) -// ofile.delete(); -// lfile.renameTo(ofile); - if(lfile.exists()) - lfile.delete(); - nfile.renameTo(lfile); -// if(nfile.exists()) -// nfile.delete(); - } - catch(Exception e) { - Log.JNI.error(e, "Fehler beim Schreiben von " + nfile); - } - } - - public static FolderInfo loadWorldInfo(File worldDir) { - Config.clear(); - UniverseRegistry.clear(); - File file = new File(worldDir, "level.nbt"); - if(!file.exists()) - file = new File(worldDir, "level.nbt.tmp"); - if(file.exists()) { - try { - NBTTagCompound tag = NBTLoader.readGZip(file); - NBTTagCompound cfg = tag.getCompoundTag("Config"); - for(String key : cfg.getKeySet()) { - Config.set(key, cfg.getString(key), null); - } - UniverseRegistry.loadNbt(tag.getCompoundTag("Universe")); - // tag.getInteger("Version"); - long lastPlayed = tag.getLong("LastAccess"); - String version = tag.hasKey("Version", 8) ? tag.getString("Version") : null; - version = version != null && version.isEmpty() ? null : version; - long time = tag.hasKey("Time", 4) ? tag.getLong("Time") : World.START_TIME; - return new FolderInfo(time, lastPlayed, null, version); - } - catch(Exception e) { - Log.JNI.error(e, "Fehler beim Lesen von " + file); - } - } - return null; - } - -// public static void reloadWorldInfo(File worldDir) { -// File file = new File(worldDir, "level.nbt"); -// if(file.exists()) { -// Config.clear(); -// try { -// Config.readFromNbt(NBTLoader.readGZip(file).getCompoundTag("Config"), true); -// } -// catch(Exception e) { -// Log.error("Fehler beim Lesen von " + file, e); -// return; -// } -// } -// } } diff --git a/java/src/game/world/Spawner.java b/server/src/main/java/server/world/Spawner.java similarity index 85% rename from java/src/game/world/Spawner.java rename to server/src/main/java/server/world/Spawner.java index 739cdd4..06e5da6 100755 --- a/java/src/game/world/Spawner.java +++ b/server/src/main/java/server/world/Spawner.java @@ -1,20 +1,22 @@ -package game.world; +package server.world; import java.util.Set; -import game.collect.Sets; - -import game.biome.Biome; -import game.biome.RngSpawn; -import game.block.Block; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.entity.types.EntityWaterMob; -import game.init.Blocks; -import game.init.Config; -import game.rng.Random; -import game.rng.WeightedList; -import game.util.ExtMath; +import common.block.Block; +import common.collect.Sets; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.entity.types.EntityWaterMob; +import common.init.Blocks; +import common.rng.Random; +import common.rng.WeightedList; +import common.util.BlockPos; +import common.util.ChunkPos; +import common.util.ExtMath; +import common.world.World; +import server.biome.GenBiome; +import server.biome.RngSpawn; +import server.vars.SVars; public abstract class Spawner { private static final int MOB_COUNT_DIV = (int)Math.pow(17.0D, 2.0D); @@ -51,7 +53,7 @@ public abstract class Spawner { // } CHUNKS.clear(); int locs = 0; - int range = Math.max(Config.mobSpawnDist, 1); + int range = Math.max(SVars.mobSpawnDist, 1); for(EntityNPC player : world.players) { // if(Config.spectatorSpawning || !player.isSpectator()) { int x = ExtMath.floord(player.posX / 16.0D); @@ -73,33 +75,30 @@ public abstract class Spawner { } // boolean animals = (time % Math.max(Config.animalSpawnDelay, 1)) == 0; int spawned = 0; - int mobSpread = Math.max(Config.spawnGroupDist, 1); + int mobSpread = Math.max(SVars.spawnGroupDist, 1); // double spawnDist = (double)Config.mobSpawnDistance; - double playerDist = (double)Config.mobPlayerDist; + double playerDist = (double)SVars.mobPlayerDist; // BlockPos spawn = world.isPrimary() ? Server.getSpawnPoint() : null; // for(EnumCreatureType type : EnumCreatureType.values()) { // if((!type.isPeaceful() || peaceful) && (type.isPeaceful() || hostile) && (!type.isAnimal() || animals)) { int cur = world.countEntities(EntityLiving.class); - int max = Config.maxMobs * locs / MOB_COUNT_DIV; + int max = SVars.maxMobs * locs / MOB_COUNT_DIV; if(cur <= max) { typeLabel: for(ChunkPos coord : CHUNKS) { - Chunk chunk = world.getChunk(coord.x, coord.z); + ChunkServer chunk = world.getChunk(coord.x, coord.z); int x = coord.x * 16 + world.rand.zrange(16); int z = coord.z * 16 + world.rand.zrange(16); - int h = chunk.getHeight(new BlockPos(x, 0, z)) + 1; - if(h > 0) { - int m = h % 16; - h = m == 0 ? h : h + 16 - m; - } - h = h == 0 ? 16 : (h > 0 ? h : chunk.getTopSegment() + 16 - 1); - int y = world.rand.excl(h <= 8 ? 0 : 8, h); + int h = chunk.getTopSegment(); + if(h == Integer.MIN_VALUE) + continue; + int y = world.rand.range(chunk.getBottomSegment(), h + 16); BlockPos pos = new BlockPos(x, y, z); Block block = world.getState(pos).getBlock(); if(!block.isNormalCube()) { int group = 0; Object data = null; - for(int n = 0; n < Config.spawnGroups; ++n) { + for(int n = 0; n < SVars.spawnGroups; ++n) { int mx = x; int my = y; int mz = z; @@ -159,7 +158,7 @@ public abstract class Spawner { return spawned; } - public static void generate(WorldServer world, Biome biome, int x, int z, int sx, int sz, Random rand) { + public static void generate(WorldServer world, GenBiome biome, int x, int z, int sx, int sz, Random rand) { int iters = 0; while(rand.floatv() < biome.getMobGenChance()) { if(iters++ == 10) diff --git a/server/src/main/java/server/world/TickEvent.java b/server/src/main/java/server/world/TickEvent.java new file mode 100755 index 0000000..7759f94 --- /dev/null +++ b/server/src/main/java/server/world/TickEvent.java @@ -0,0 +1,13 @@ +package server.world; + +import common.block.Block; +import common.util.BlockPos; + +public record TickEvent(BlockPos position, Block block, int id, int parameter) { + public boolean equals(Object other) { + if(!(other instanceof TickEvent)) + return false; + TickEvent event = (TickEvent)other; + return this.position.equals(event.position) && this.id == event.id && this.parameter == event.parameter && this.block == event.block; + } +} diff --git a/java/src/game/world/WorldServer.java b/server/src/main/java/server/world/WorldServer.java similarity index 68% rename from java/src/game/world/WorldServer.java rename to server/src/main/java/server/world/WorldServer.java index 150ba5b..46db8b6 100755 --- a/java/src/game/world/WorldServer.java +++ b/server/src/main/java/server/world/WorldServer.java @@ -1,4 +1,4 @@ -package game.world; +package server.world; import java.io.File; import java.io.FileFilter; @@ -11,85 +11,109 @@ import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; - import java.util.function.Predicate; -import game.collect.Lists; -import game.collect.Maps; -import game.collect.Sets; -import game.Server; -import game.biome.Biome; -import game.biome.RngSpawn; -import game.block.Block; -import game.block.BlockDoor; -import game.block.BlockEventData; -import game.block.BlockFalling; -import game.block.BlockLiquid; -import game.block.BlockSnow; -import game.clipboard.ClipboardBlock; -import game.dimension.Dimension; -import game.entity.DamageSource; -import game.entity.Entity; -import game.entity.EntityTrackerEntry; -import game.entity.effect.EntityLightning; -import game.entity.npc.EntityNPC; -import game.entity.types.EntityLiving; -import game.init.Blocks; -import game.init.Config; -import game.init.SoundEvent; -import game.init.UniverseRegistry; -import game.item.ItemDoor; -import game.log.Log; -import game.material.Material; -import game.nbt.NBTLoader; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagInt; -import game.nbt.NBTTagList; -import game.network.Player; -import game.network.Packet; -import game.packet.S1APacketEntityStatus; -import game.packet.S27PacketExplosion; -import game.packet.S28PacketEffect; -import game.packet.S29PacketSoundEffect; -import game.packet.S2APacketParticles; -import game.packet.S2BPacketChangeGameState; -import game.packet.S2CPacketSpawnGlobalEntity; -import game.packet.SPacketBiomes; -import game.packet.SPacketBlockAction; -import game.packet.SPacketBlockBreakAnim; -import game.packet.SPacketBlockChange; -import game.packet.SPacketChunkData; -import game.packet.SPacketMultiBlockChange; -import game.renderer.particle.ParticleType; -import game.rng.Random; -import game.rng.WeightedList; -import game.tileentity.TileEntity; -import game.util.ExtMath; -import game.util.FileUtils; -import game.village.Village; -import game.village.VillageCollection; -import game.worldgen.BiomeGenSingle; -import game.worldgen.BiomeGenerator; -import game.worldgen.BlockReplacer; -import game.worldgen.ChunkGenerator; -import game.worldgen.ChunkPrimer; -import game.worldgen.FeatureDungeons; -import game.worldgen.FeatureLakes; -import game.worldgen.FeatureLiquids; -import game.worldgen.FeatureOres; -import game.worldgen.GeneratorDebug; -import game.worldgen.GeneratorDestroyed; -import game.worldgen.LootConstants; -import game.worldgen.caves.MapGenBigCaves; -import game.worldgen.caves.MapGenCaves; -import game.worldgen.caves.MapGenRavine; -import game.worldgen.structure.MapGenBridge; -import game.worldgen.structure.MapGenMineshaft; -import game.worldgen.structure.MapGenScatteredFeature; -import game.worldgen.structure.MapGenStronghold; -import game.worldgen.structure.MapGenVillage; +import common.biome.Biome; +import common.block.Block; +import common.block.BlockFalling; +import common.block.Material; +import common.block.artificial.BlockDoor; +import common.block.liquid.BlockLiquid; +import common.block.natural.BlockSnow; +import common.collect.Lists; +import common.collect.Maps; +import common.collect.Sets; +import common.dimension.Dimension; +import common.dimension.Dimension.GeneratorType; +import common.dimension.Lake; +import common.dimension.Liquid; +import common.dimension.Ore; +import common.entity.DamageSource; +import common.entity.Entity; +import common.entity.EntityTrackerEntry; +import common.entity.effect.EntityLightning; +import common.entity.npc.EntityNPC; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.SoundEvent; +import common.init.UniverseRegistry; +import common.item.ItemDoor; +import common.log.Log; +import common.model.ParticleType; +import common.network.IPlayer; +import common.network.Packet; +import common.packet.SPacketEntityStatus; +import common.packet.SPacketExplosion; +import common.packet.SPacketEffect; +import common.packet.SPacketSoundEffect; +import common.packet.SPacketParticles; +import common.packet.SPacketChangeGameState; +import common.packet.SPacketSpawnGlobalEntity; +import common.packet.SPacketBiome; +import common.packet.SPacketBlockAction; +import common.packet.SPacketBlockBreakAnim; +import common.packet.SPacketBlockChange; +import common.packet.SPacketMultiBlockChange; +import common.rng.Random; +import common.rng.WeightedList; +import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.util.BlockPos; +import common.util.BoundingBox; +import common.util.ChunkPos; +import common.util.ExtMath; +import common.util.IntHashMap; +import common.util.LongHashMap; +import common.util.PortalType; +import common.util.Position; +import common.util.Vec3; +import common.village.Village; +import common.world.BlockArray; +import common.world.Explosion; +import common.world.AWorldServer; +import common.world.LightType; +import common.world.State; +import common.world.Weather; +import common.world.World; +import server.Server; +import server.biome.GenBiome; +import server.biome.RngSpawn; +import server.clipboard.ClipboardBlock; +import server.network.Player; +import server.vars.SVars; +import server.village.VillageCollection; +import server.worldgen.BiomeGenLayered; +import server.worldgen.BiomeGenPerlin; +import server.worldgen.BiomeGenSingle; +import server.worldgen.BiomeGenerator; +import server.worldgen.BlockReplacer; +import server.worldgen.ChunkGenerator; +import server.worldgen.ChunkPrimer; +import server.worldgen.FeatureDungeons; +import server.worldgen.FeatureLakes; +import server.worldgen.FeatureLiquids; +import server.worldgen.FeatureOres; +import server.worldgen.GeneratorCavern; +import server.worldgen.GeneratorDestroyed; +import server.worldgen.GeneratorFlat; +import server.worldgen.GeneratorIsland; +import server.worldgen.GeneratorPerlin; +import server.worldgen.GeneratorSimple; +import server.worldgen.MobConstants; +import server.worldgen.ReplacerAltBiome; +import server.worldgen.ReplacerAltSurface; +import server.worldgen.ReplacerBiome; +import server.worldgen.ReplacerTopLayer; +import server.worldgen.caves.MapGenBigCaves; +import server.worldgen.caves.MapGenCaves; +import server.worldgen.caves.MapGenRavine; +import server.worldgen.structure.MapGenBridge; +import server.worldgen.structure.MapGenMineshaft; +import server.worldgen.structure.MapGenScatteredFeature; +import server.worldgen.structure.MapGenStronghold; +import server.worldgen.structure.MapGenVillage; -public final class WorldServer extends World { +public final class WorldServer extends AWorldServer { private static final int[][] XZ_DIRS = new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}; private final Server server; @@ -100,9 +124,9 @@ public final class WorldServer extends World { private final EventList[] queue = new EventList[] {new EventList(), new EventList()}; private final List ticksNow = Lists.newArrayList(); private final Set dropped = Collections.newSetFromMap(new ConcurrentHashMap()); - private final LongHashMap chunks = new LongHashMap(); - private final List loaded = Lists.newArrayList(); - private final Map toRemove = new ConcurrentHashMap(); + private final LongHashMap chunks = new LongHashMap(); + private final List loaded = Lists.newArrayList(); + private final Map toRemove = new ConcurrentHashMap(); private final Set pending = Collections.newSetFromMap(new ConcurrentHashMap()); private final LongHashMap loaders = new LongHashMap(); private final Set loaderList = Sets.newHashSet(); @@ -114,6 +138,7 @@ public final class WorldServer extends World { private final IntHashMap trackMap = new IntHashMap(); private final Map dataMap = Maps.newHashMap(); private final List dataList = Lists.newArrayList(); + private final List toTick = Lists.newArrayList(); private final Biome[] biomes = new Biome[256]; private MapGenCaves caveGen; @@ -130,8 +155,8 @@ public final class WorldServer extends World { private BlockReplacer replacer; private FeatureDungeons dungeons; private State liquid; - private State base; - private State ceil; + private boolean base; + private boolean ceil; private FeatureOres[] ores; private FeatureLakes[] lakes; private FeatureLiquids[] liquids; @@ -154,74 +179,156 @@ public final class WorldServer extends World { private int updateLCG = this.rand.intv(); private long prevUpdate; private long time; + + public static float clampGravity() { + return ExtMath.clampf(SVars.gravity, -10.0f, 10.0f); + } + + private BiomeGenerator createBiomeGenerator(Random rand) { + return this.dimension.getBiomeSize() > 0 ? new BiomeGenLayered(rand.longv(), this.dimension.getDefaultBiome(), this.dimension.isSemiFixed(), this.dimension.getBiomeSize(), this.dimension.getRiverSize(), + this.dimension.getSnowRarity(), this.dimension.getSeaRarity(), this.dimension.getAddBiomes() == null ? new Biome[0] : this.dimension.getAddBiomes(), this.dimension.getAddRarity(), + this.dimension.getHotBiomes() == null ? new Biome[] {this.dimension.getDefaultBiome()} : this.dimension.getHotBiomes(), + this.dimension.getMediumBiomes() == null ? new Biome[] {this.dimension.getDefaultBiome()} : this.dimension.getMediumBiomes(), + this.dimension.getColdBiomes() == null ? new Biome[] {this.dimension.getDefaultBiome()} : this.dimension.getColdBiomes(), + this.dimension.getFrostBiomes() == null ? new Biome[] {this.dimension.getDefaultBiome()} : this.dimension.getFrostBiomes()) : new BiomeGenSingle(this.dimension.getDefaultBiome()); + } + + private ChunkGenerator createChunkGenerator(Random rand) { + switch(this.dimension.getGeneratorType()) { + case FLAT: + return this.dimension.getLayers() == null ? new GeneratorFlat(this.dimension.getSeaLevel(), this.dimension.getFiller()) : new GeneratorFlat(this.dimension.getLayers()); + case PERLIN: + default: + return new GeneratorPerlin(rand, this.dimension.getFiller(), this.dimension.getLiquid(), this.dimension.getNoiseGen()); + case SIMPLE: + return new GeneratorSimple(rand, this.dimension.getFiller(), this.dimension.getLiquid(), + this.dimension.getBiomeSize() > 0 ? null : new BiomeGenPerlin(rand.longv())); + case ISLAND: + return new GeneratorIsland(rand, this.dimension.getFiller()); + case CAVERN: + return new GeneratorCavern(rand, this.dimension.getFiller(), this.dimension.getLiquid()); + case DESTROYED: + return new GeneratorDestroyed(this.dimension.getSeaLevel()); + } + } + + private BlockReplacer createBlockReplacer(Random rand) { + switch(this.dimension.getReplacerType()) { + case BIOMES: + default: + return new ReplacerBiome(rand); + case SIMPLE: + return new ReplacerAltBiome(rand, this.dimension.getFiller(), this.dimension.getLiquid(), this.dimension.getAlt2(), this.dimension.getAlt1()); + case ALTERNATE: + return new ReplacerAltSurface(rand, this.dimension.getFiller(), this.dimension.getAlt1(), this.dimension.getAlt2(), this.dimension.getLiquid()); + case TOPLAYER: + return new ReplacerTopLayer(this.dimension.getSurface(), this.dimension.getFiller().getBlock()); + case NONE: + return null; + } + } + + private FeatureDungeons createDungeonGenerator() { + return this.dimension.getDungeons() > 0 ? new FeatureDungeons(this.dimension.getDungeons()) : null; + } + + private MapGenCaves createCaveGenerator() { + return this.dimension.hasCaves() ? + (new MapGenCaves(this.dimension.getCaveFiller(), this.dimension.getFiller().getBlock(), this.dimension.getTop().getBlock(), + this.dimension.getSurface().getBlock(), this.dimension.getAlt1().getBlock())) : null; + } + + private MapGenRavine createRavineGenerator() { + return this.dimension.hasRavines() ? + (new MapGenRavine(this.dimension.getCaveFiller(), this.dimension.getFiller().getBlock(), + this.dimension.getTop().getBlock(), this.dimension.getSurface().getBlock())) : null; + } + + private MapGenBigCaves createBigCaveGenerator() { + return this.dimension.hasStrideCaves() ? + (new MapGenBigCaves(this.dimension.getFiller().getBlock(), + this.dimension.getTop().getBlock(), this.dimension.getSurface().getBlock())) : null; + } + + private FeatureOres[] createOres() { + if(this.dimension.getOres().isEmpty()) + return null; + FeatureOres[] gens = new FeatureOres[this.dimension.getOres().size()]; + for(int z = 0; z < gens.length; z++) { + Ore gen = this.dimension.getOres().get(z); + gens[z] = new FeatureOres(gen.state(), gen.count(), gen.more(), gen.size(), gen.min(), gen.max(), gen.dist()); + } + return gens; + } + + private FeatureLakes[] createLakes() { + if(this.dimension.getLakes().isEmpty()) + return null; + FeatureLakes[] gens = new FeatureLakes[this.dimension.getLakes().size()]; + for(int z = 0; z < gens.length; z++) { + Lake gen = this.dimension.getLakes().get(z); + gens[z] = new FeatureLakes(gen.state(), gen.filler(), gen.top(), gen.chance(), gen.minHeight(), gen.maxHeight(), gen.ratiod()); + } + return gens; + } + + private FeatureLiquids[] createLiquids() { + if(this.dimension.getLiquids().isEmpty()) + return null; + FeatureLiquids[] gens = new FeatureLiquids[this.dimension.getLiquids().size()]; + for(int z = 0; z < gens.length; z++) { + Liquid gen = this.dimension.getLiquids().get(z); + gens[z] = new FeatureLiquids(gen.state(), gen.chance(), gen.minHeight(), gen.maxHeight(), gen.lower()); + } + return gens; + } - public WorldServer(Server server, long dtime, Dimension dim, boolean debug) { - super(dim, false, debug); + public WorldServer(Server server, long dtime, Dimension dim) { + super(dim); this.server = server; // this.time = time; this.daytime = dtime; this.updateViewRadius(); this.chunkDir = new File(new File("chunk"), dim.getDimensionName()); - if(!debug) { - this.chunkDir.mkdirs(); - this.seed = this.rand.longv(); - this.dimension.setSeed(this.seed); - NBTTagCompound tag = null; - try { - File dat = new File(this.chunkDir, "data.nbt"); - if(dat.exists() && dat.isFile()) - tag = NBTLoader.readGZip(dat); - } - catch(Exception e) { - Log.JNI.error(e, "Konnte Weltdaten nicht laden"); - } - if(tag != null) { - this.exterminated = tag.getBoolean("Exterminated"); - this.time = tag.getLong("Time"); - if(tag.hasKey("Generator", 10)) { - this.dimension.fromNbt(tag.getCompoundTag("Generator")); - if(this.dimension.getType().weather && !this.exterminated) - this.weather = this.dimension.getWeather(); - this.seed = this.dimension.getSeed(); - } - if(this.dimension.getType().weather && !this.exterminated) - this.weather = Weather.getByName(tag.getString("Weather")); - if(this.weather == null) { - this.weather = this.dimension.getWeather(); -// this.dataModified = true; - } - // ... - } - if(this.exterminated) - this.weather = Weather.CLEAR; + this.chunkDir.mkdirs(); + if(!SVars.seed.isEmpty()) + this.rand.setSeed((long)SVars.seed.hashCode() ^ ~((long)dim.getDimensionName().hashCode())); + this.seed = this.rand.longv(); + this.dimension.setSeed(this.seed); + TagObject tag = null; + try { + File dat = new File(this.chunkDir, "data.cdt"); + if(dat.exists() && dat.isFile()) + tag = TagObject.readGZip(dat); } + catch(Exception e) { + Log.IO.error(e, "Konnte Weltdaten nicht laden"); + } + if(tag != null) { + this.exterminated = tag.getBool("Exterminated"); + this.time = tag.getLong("Time"); + if(tag.hasObject("Generator")) { + this.dimension.fromTags(tag.getObject("Generator")); + if(this.dimension.getType().weather && !this.exterminated) + this.weather = this.dimension.getWeather(); + this.seed = this.dimension.getSeed(); + } + if(this.dimension.getType().weather && !this.exterminated) + this.weather = Weather.getByName(tag.getString("Weather")); + if(this.weather == null) { + this.weather = this.dimension.getWeather(); +// this.dataModified = true; + } + // ... + } + else { + Log.TICK.info("Startwert für %s: %d" + (SVars.seed.isEmpty() ? "" : " von Basiswert '%s'"), this.dimension.getFormattedName(false), this.seed, SVars.seed); + } + if(this.exterminated) + this.weather = Weather.CLEAR; this.grng = new Random(this.seed); // GeneratorSettings settings = !debug && !this.exterminated ? dim.getSettings() : null; - if(debug) { - this.liquid = Blocks.air.getState(); - this.biomeGen = new BiomeGenSingle(Biome.none); - this.generator = new GeneratorDebug(); - this.replacer = null; - this.populate = false; - this.caveGen = null; - this.bigCaveGen = null; - this.ravineGen = null; - this.base = null; - this.ceil = null; - this.mobs = false; - this.snow = false; - this.strongholdGen = null; - this.villageGen = null; - this.mineshaftGen = null; - this.scatteredGen = null; - this.bridgeGen = null; - this.seaLevel = 0; - this.ores = null; - this.lakes = null; - this.liquids = null; - this.dungeons = null; - } - else if(this.exterminated) { + if(this.exterminated) { this.setExterminatedGen(); } // else if(settings != null) { @@ -280,15 +387,15 @@ public final class WorldServer extends World { // } else { this.liquid = this.dimension.getLiquid(); - this.biomeGen = this.dimension.createBiomeGenerator(this.grng); - this.generator = this.dimension.createChunkGenerator(this.grng); - this.replacer = this.dimension.createBlockReplacer(this.grng); + this.biomeGen = this.createBiomeGenerator(this.grng); + this.generator = this.createChunkGenerator(this.grng); + this.replacer = this.createBlockReplacer(this.grng); this.populate = this.dimension.hasPopulator(); - this.caveGen = this.dimension.createCaveGenerator(); - this.bigCaveGen = this.dimension.createBigCaveGenerator(); - this.ravineGen = this.dimension.createRavineGenerator(); - this.base = this.dimension.getWorldFloor(); - this.ceil = this.dimension.getWorldCeiling(); + this.caveGen = this.createCaveGenerator(); + this.bigCaveGen = this.createBigCaveGenerator(); + this.ravineGen = this.createRavineGenerator(); + this.base = this.dimension.getFiller().getBlock() != Blocks.air && this.dimension.getGeneratorType() != GeneratorType.FLAT; + this.ceil = this.dimension.hasWorldCeiling(); this.mobs = this.dimension.hasMobs(); this.snow = this.dimension.hasSnow(); this.strongholdGen = this.dimension.hasStrongholds() ? new MapGenStronghold() : null; @@ -297,77 +404,53 @@ public final class WorldServer extends World { this.scatteredGen = this.dimension.hasScattered() ? new MapGenScatteredFeature() : null; this.bridgeGen = this.dimension.hasFortresses() ? new MapGenBridge() : null; this.seaLevel = this.dimension.getSeaLevel(); - this.ores = this.dimension.getOres(); - this.lakes = this.dimension.getLakes(); - this.liquids = this.dimension.getLiquids(); - this.dungeons = this.dimension.createDungeonGenerator(); + this.ores = this.createOres(); + this.lakes = this.createLakes(); + this.liquids = this.createLiquids(); + this.dungeons = this.createDungeonGenerator(); } this.height = this.generator.getMaximumHeight(); // this.teleporter = new Teleporter(this); this.calculateInitialSkylight(); this.calculateInitialWeather(); this.updatePhysics(); - if(!debug) { - NBTTagCompound tag = null; + tag = null; + try { + File dat = new File(this.chunkDir, "loaders.cdt"); + if(dat.exists() && dat.isFile()) + tag = TagObject.readGZip(dat); + } + catch(Exception e) { + Log.IO.error(e, "Konnte Ladeliste nicht laden"); + } + if(tag != null && tag.hasList("Loaders")) { + List list = tag.getList("Loaders"); + for(int z = 0; z < list.size(); z++) { + TagObject pos = list.get(z); + this.addLoader(new BlockPos(pos.getInt("X"), pos.getInt("Y"), pos.getInt("Z"))); + } + this.loadersModified = false; + } + if(this.villageGen != null) { + tag = null; try { - File dat = new File(this.chunkDir, "loaders.nbt"); + File dat = new File(this.chunkDir, "villages.cdt"); if(dat.exists() && dat.isFile()) - tag = NBTLoader.readGZip(dat); + tag = TagObject.readGZip(dat); } catch(Exception e) { - Log.JNI.error(e, "Konnte Ladeliste nicht laden"); - } - if(tag != null && tag.hasKey("Loaders", 9)) { - NBTTagList list = tag.getTagList("Loaders", 10); - for(int z = 0; z < list.tagCount(); z++) { - NBTTagCompound pos = list.getCompoundTagAt(z); - this.addLoader(new BlockPos(pos.getInteger("X"), pos.getInteger("Y"), pos.getInteger("Z"))); - } - this.loadersModified = false; - } -// tag = null; -// try { -// File dat = new File(this.chunkDir, "warps.nbt"); -// if(dat.exists() && dat.isFile()) -// tag = NBTLoader.readGZip(dat); -// } -// catch(Exception e) { -// Log.warn("Konnte Warpliste nicht laden", e); -// } -// if(tag != null && tag.hasKey("Warps", 9)) { -// NBTTagList list = tag.getTagList("Warps", 10); -// for(int z = 0; z < list.tagCount(); z++) { -// NBTTagCompound pos = list.getCompoundTagAt(z); -// server.getWarps().put(pos.getString("Name"), new Position(pos.getDouble("X"), pos.getDouble("Y"), pos.getDouble("Z"), -// pos.getFloat("Yaw"), pos.getFloat("Pitch"), this.dimension.getDimensionId())); -// } -// this.warpsModified = false; -// } - if(this.villageGen != null) { - tag = null; - try { - File dat = new File(this.chunkDir, "villages.nbt"); - if(dat.exists() && dat.isFile()) - tag = NBTLoader.readGZip(dat); - } - catch(Exception e) { - Log.JNI.error(e, "Konnte Dorfliste nicht laden"); - } - this.villageStorage = new VillageCollection(tag); + Log.IO.error(e, "Konnte Dorfliste nicht laden"); } + this.villageStorage = new VillageCollection(tag); } } - public static float clampGravity() { - return ExtMath.clampf(Config.gravity, -10.0f, 10.0f); - } - public Server getServer() { return this.server; } public void updatePhysics() { - this.setTimeFactor(Config.timeFlow); + this.setTimeFactor(SVars.timeFlow); this.setGravity(clampGravity()); } @@ -375,23 +458,21 @@ public final class WorldServer extends World { this.updateWeather(false); this.biomeGen.cleanupCache(); // this.profiler.start("mobSpawner"); - if(this.mobs && Config.mobs && Config.tickSpawn && !this.debug) { + if(this.mobs && SVars.mobs && SVars.tickSpawn) { Spawner.spawn(this); } // this.profiler.next("chunkSource"); - if(!this.debug) { - for(int i = 0; i < 100; ++i) { - if(!this.dropped.isEmpty()) { - Long v = (Long)this.dropped.iterator().next(); - Chunk chunk = (Chunk)this.chunks.getValueByKey(v.longValue()); - if(chunk != null) { - chunk.onChunkUnload(); - this.saveChunkData(chunk); - this.chunks.remove(v.longValue()); - this.loaded.remove(chunk); - } - this.dropped.remove(v); + for(int i = 0; i < 100; ++i) { + if(!this.dropped.isEmpty()) { + Long v = (Long)this.dropped.iterator().next(); + ChunkServer chunk = this.chunks.getValueByKey(v.longValue()); + if(chunk != null) { + chunk.onChunkUnload(); + this.saveChunkData(chunk); + this.chunks.remove(v.longValue()); + this.loaded.remove(chunk); } + this.dropped.remove(v); } } int light = this.calculateSkylightSubtracted(true); @@ -401,7 +482,7 @@ public final class WorldServer extends World { // this.info.tick(); this.time += 1L; // this.dataModified = true; - if(Config.dayCycle) // { + if(SVars.dayCycle) // { this.daytime += this.timeFactor; // if(this.dimension.getType().dayCycle) // this.season = this.getSeasonByTime(); @@ -468,10 +549,10 @@ public final class WorldServer extends World { Biome biome = this.getBiomeGenForCoords(pos); if(this.bridgeGen != null && (this.bridgeGen.isPresent(pos) || (this.bridgeGen.isPositionInStructure(this, pos) && this.getState(pos.down()).getBlock() == Blocks.blood_brick))) - return LootConstants.FORTRESS_MOBS; + return MobConstants.FORTRESS_MOBS; else if(this.scatteredGen != null && this.scatteredGen.hasMageHut(pos)) - return LootConstants.MAGEHUT_MOBS; - return biome.getMobs(); + return MobConstants.MAGEHUT_MOBS; + return GenBiome.BIOMES[biome.id].getMobs(); } public RngSpawn getSpawnListEntryForTypeAt(BlockPos pos) { @@ -500,117 +581,111 @@ public final class WorldServer extends World { } public void setItemData(String dataID, WorldSavedData worldSavedDataIn) { - if(!this.debug) - this.setData(dataID, worldSavedDataIn); + this.setData(dataID, worldSavedDataIn); } public WorldSavedData loadItemData(String dataID) { - return this.debug ? null : this.loadData(dataID); + return this.loadData(dataID); } protected void updateBlocks() { - this.setActivePlayerChunksAndCheckLight(Config.distance); + this.setActivePlayerChunksAndCheckLight(SVars.distance); - if(this.debug) { - for(ChunkPos chunkcoordintpair1 : this.active) { - this.getChunk(chunkcoordintpair1.x, chunkcoordintpair1.z).update(false); - } - } - else { - int i = 0; - int j = 0; + int i = 0; + int j = 0; - for(ChunkPos chunkcoordintpair : this.active) { - int k = chunkcoordintpair.x * 16; - int l = chunkcoordintpair.z * 16; + for(ChunkPos chunkcoordintpair : this.active) { + int k = chunkcoordintpair.x * 16; + int l = chunkcoordintpair.z * 16; // this.profiler.start("getChunk"); - Chunk chunk = this.getChunk(chunkcoordintpair.x, chunkcoordintpair.z); + ChunkServer chunk = this.getChunk(chunkcoordintpair.x, chunkcoordintpair.z); // this.profiler.next("moodSound"); // this.playMoodSound(k, l, chunk); // this.profiler.next("checkLight"); - chunk.enqueueRelight(); + chunk.enqueueRelight(); // this.profiler.next("tickChunk"); - chunk.update(false); + chunk.update(false); // this.profiler.next("thunder"); - int l2 = Config.boltChance; + int l2 = SVars.boltChance; - if(l2 > 0 && this.rand.zrange(l2) == 0 && this.isThundering()) { - this.updateLCG = this.updateLCG * 3 + 1013904223; - int i1 = this.updateLCG >> 2; - BlockPos blockpos = this.adjustPosToNearbyEntity(new BlockPos(k + (i1 & 15), 0, l + (i1 >> 8 & 15))); + if(l2 > 0 && this.rand.zrange(l2) == 0 && this.isThundering()) { + this.updateLCG = this.updateLCG * 3 + 1013904223; + int i1 = this.updateLCG >> 2; + BlockPos blockpos = this.adjustPosToNearbyEntity(new BlockPos(k + (i1 & 15), 0, l + (i1 >> 8 & 15))); - if(this.canStrikeAt(blockpos)) { - this.strikeLightning((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ(), 0x737380, 120, true, null); - } + if(this.canStrikeAt(blockpos)) { + this.strikeLightning((double)blockpos.getX(), (double)blockpos.getY(), (double)blockpos.getZ(), 0x737380, 120, true, null); } + } // this.profiler.next("iceandsnow"); - l2 = Config.weatherTick; + l2 = SVars.weatherTick; - for(int z = 0; z < l2; z++) { - if(this.rand.zrange(16) == 0) { - this.updateLCG = this.updateLCG * 3 + 1013904223; - int k2 = this.updateLCG >> 2; - BlockPos blockpos2 = this.getPrecipitationHeight(new BlockPos(k + (k2 & 15), 0, l + (k2 >> 8 & 15))); - BlockPos blockpos1 = blockpos2.down(); + for(int z = 0; z < l2; z++) { + if(this.rand.zrange(16) == 0) { + this.updateLCG = this.updateLCG * 3 + 1013904223; + int k2 = this.updateLCG >> 2; + BlockPos blockpos2 = this.getPrecipitationHeight(new BlockPos(k + (k2 & 15), 0, l + (k2 >> 8 & 15))); + BlockPos blockpos1 = blockpos2.down(); - if(this.canBlockFreeze(blockpos1, true)) { - this.setState(blockpos1, Blocks.ice.getState()); - } + if(this.canBlockFreeze(blockpos1, true)) { + this.setState(blockpos1, Blocks.ice.getState()); + } - if(this.snow && this.isRaining() && this.canSnowAt(blockpos2, true, Config.snowStack)) { - State layer = Config.snowStack ? this.getState(blockpos2) : null; - this.setState(blockpos2, Config.snowStack && layer.getBlock() == Blocks.snow_layer - ? (Blocks.snow_layer.getState().withProperty(BlockSnow.LAYERS, - Math.min(layer.getValue(BlockSnow.LAYERS) + 1, 2))) : Blocks.snow_layer.getState()); - } + if(this.snow && this.isRaining() && this.canSnowAt(blockpos2, true, SVars.snowStack)) { + State layer = SVars.snowStack ? this.getState(blockpos2) : null; + this.setState(blockpos2, SVars.snowStack && layer.getBlock() == Blocks.snow_layer + ? (Blocks.snow_layer.getState().withProperty(BlockSnow.LAYERS, + Math.min(layer.getValue(BlockSnow.LAYERS) + 1, 2))) : Blocks.snow_layer.getState()); + } - if(this.isRaining()) { // && this.getBiomeGenForCoords(blockpos1).canRain()) { - this.getState(blockpos1).getBlock().fillWithRain(this, blockpos1); - } + if(this.isRaining()) { // && this.getBiomeGenForCoords(blockpos1).canRain()) { + this.getState(blockpos1).getBlock().fillWithRain(this, blockpos1); + } - if(Config.igniteChance > 0 && Config.fire && !this.isRaining() && - this.rand.chance(this.hasDownfall() ? Math.max(1, Config.igniteChance / 3) : Config.igniteChance) - && this.canPlaceFireAt(blockpos2)) { - this.setState(blockpos2, Blocks.fire.getState()); - } + if(SVars.igniteChance > 0 && SVars.fire && !this.isRaining() && + this.rand.chance(this.hasDownfall() ? Math.max(1, SVars.igniteChance / 3) : SVars.igniteChance) + && this.canPlaceFireAt(blockpos2)) { + this.setState(blockpos2, Blocks.fire.getState()); } } + } // this.profiler.next("tickBlocks"); - l2 = Config.randomTick; + l2 = SVars.randomTick; - if(l2 > 0) { - for(BlockArray extendedblockstorage : chunk.getStorage()) { - if(extendedblockstorage != null && extendedblockstorage.isTicked()) { - for(int j1 = 0; j1 < l2; ++j1) { - this.updateLCG = this.updateLCG * 3 + 1013904223; - int k1 = this.updateLCG >> 2; - int l1 = k1 & 15; - int i2 = k1 >> 8 & 15; - int j2 = k1 >> 16 & 15; - ++j; - State iblockstate = extendedblockstorage.get(l1, j2, i2); - Block block = iblockstate.getBlock(); + if(l2 > 0) { + this.toTick.addAll(chunk.getStorage()); + for(BlockArray extendedblockstorage : this.toTick) { + if(extendedblockstorage != null && extendedblockstorage.isTicked()) { + for(int j1 = 0; j1 < l2; ++j1) { + this.updateLCG = this.updateLCG * 3 + 1013904223; + int k1 = this.updateLCG >> 2; + int l1 = k1 & 15; + int i2 = k1 >> 8 & 15; + int j2 = k1 >> 16 & 15; + ++j; + State iblockstate = extendedblockstorage.get(l1, j2, i2); + Block block = iblockstate.getBlock(); - if(block.getTickRandomly()) { - ++i; - block.randomTick(this, new BlockPos(l1 + k, j2 + extendedblockstorage.getY(), i2 + l), iblockstate, - this.rand); - } + if(block.getTickRandomly()) { + ++i; + block.randomTick(this, new BlockPos(l1 + k, j2 + extendedblockstorage.getY(), i2 + l), iblockstate, + this.rand); } } } } + this.toTick.clear(); + } // this.profiler.end(); - } } } private BlockPos adjustPosToNearbyEntity(BlockPos pos) { BlockPos blockpos = this.getPrecipitationHeight(pos); - BoundingBox axisalignedbb = (new BoundingBox(blockpos, new BlockPos(blockpos.getX(), World.HEIGHT, blockpos.getZ()))).expand(3.0D, + BoundingBox axisalignedbb = (new BoundingBox(blockpos, new BlockPos(blockpos.getX(), World.MAX_SIZE_Y, blockpos.getZ()))).expand(3.0D, 3.0D, 3.0D); List list = this.getEntitiesWithinAABB(EntityLiving.class, axisalignedbb, new Predicate() { public boolean test(EntityLiving p_apply_1_) { @@ -633,14 +708,14 @@ public final class WorldServer extends World { NextTickListEntry nextticklistentry = new NextTickListEntry(pos, blockIn); int i = 0; - if(this.updateForced && blockIn.getMaterial() != Material.air) { + if(this.updateForced && blockIn != Blocks.air) { if(blockIn.requiresUpdates()) { i = 8; if(this.isAreaLoaded(nextticklistentry.position.add(-i, -i, -i), nextticklistentry.position.add(i, i, i))) { State iblockstate = this.getState(nextticklistentry.position); - if(iblockstate.getBlock().getMaterial() != Material.air && iblockstate.getBlock() == nextticklistentry.getBlock()) { + if(iblockstate.getBlock() != Blocks.air && iblockstate.getBlock() == nextticklistentry.getBlock()) { iblockstate.getBlock().updateTick(this, nextticklistentry.position, iblockstate, this.rand); } } @@ -652,7 +727,7 @@ public final class WorldServer extends World { } if(this.isAreaLoaded(pos.add(-i, -i, -i), pos.add(i, i, i))) { - if(blockIn.getMaterial() != Material.air) { + if(blockIn != Blocks.air) { nextticklistentry.setScheduledTime((long)delay + this.time); nextticklistentry.setPriority(priority); } @@ -668,7 +743,7 @@ public final class WorldServer extends World { NextTickListEntry nextticklistentry = new NextTickListEntry(pos, blockIn); nextticklistentry.setPriority(priority); - if(blockIn.getMaterial() != Material.air) { + if(blockIn != Blocks.air) { nextticklistentry.setScheduledTime((long)delay + this.time); } @@ -680,7 +755,7 @@ public final class WorldServer extends World { public void updateEntities() { if(this.players.isEmpty()) { - if(this.emptyTicks++ >= Config.unloadTicks) { + if(this.emptyTicks++ >= SVars.unloadTicks) { return; } } @@ -696,68 +771,63 @@ public final class WorldServer extends World { } public boolean shouldUnload() { - return this.emptyTicks >= Config.unloadTicks && this.loaderList.isEmpty(); + return this.emptyTicks >= SVars.unloadTicks && this.loaderList.isEmpty(); } public boolean tickUpdates(boolean p_72955_1_) { - if(this.debug) { - return false; + int i = this.ticksNext.size(); + + if(i != this.ticks.size()) { + throw new IllegalStateException("TickNextTick list out of synch"); } else { - int i = this.ticksNext.size(); - - if(i != this.ticks.size()) { - throw new IllegalStateException("TickNextTick list out of synch"); + if(i > 1000) { + i = 1000; } - else { - if(i > 1000) { - i = 1000; - } // this.profiler.start("cleaning"); - for(int j = 0; j < i; ++j) { - NextTickListEntry nextticklistentry = (NextTickListEntry)this.ticksNext.first(); + for(int j = 0; j < i; ++j) { + NextTickListEntry nextticklistentry = (NextTickListEntry)this.ticksNext.first(); - if(!p_72955_1_ && nextticklistentry.scheduledTime > this.time) { - break; - } - - this.ticksNext.remove(nextticklistentry); - this.ticks.remove(nextticklistentry); - this.ticksNow.add(nextticklistentry); + if(!p_72955_1_ && nextticklistentry.scheduledTime > this.time) { + break; } + this.ticksNext.remove(nextticklistentry); + this.ticks.remove(nextticklistentry); + this.ticksNow.add(nextticklistentry); + } + // this.profiler.end(); // this.profiler.start("ticking"); - Iterator iterator = this.ticksNow.iterator(); + Iterator iterator = this.ticksNow.iterator(); - while(iterator.hasNext()) { - NextTickListEntry nextticklistentry1 = (NextTickListEntry)iterator.next(); - iterator.remove(); - int k = 0; + while(iterator.hasNext()) { + NextTickListEntry nextticklistentry1 = (NextTickListEntry)iterator.next(); + iterator.remove(); + int k = 0; - if(this.isAreaLoaded(nextticklistentry1.position.add(-k, -k, -k), nextticklistentry1.position.add(k, k, k))) { - State iblockstate = this.getState(nextticklistentry1.position); + if(this.isAreaLoaded(nextticklistentry1.position.add(-k, -k, -k), nextticklistentry1.position.add(k, k, k))) { + State iblockstate = this.getState(nextticklistentry1.position); - if(iblockstate.getBlock().getMaterial() != Material.air - && Block.isEqualTo(iblockstate.getBlock(), nextticklistentry1.getBlock())) { - iblockstate.getBlock().updateTick(this, nextticklistentry1.position, iblockstate, this.rand); - } - } - else { - this.scheduleUpdate(nextticklistentry1.position, nextticklistentry1.getBlock(), 0); + if(iblockstate.getBlock() != Blocks.air + && Block.isEqualTo(iblockstate.getBlock(), nextticklistentry1.getBlock())) { + iblockstate.getBlock().updateTick(this, nextticklistentry1.position, iblockstate, this.rand); } } + else { + this.scheduleUpdate(nextticklistentry1.position, nextticklistentry1.getBlock(), 0); + } + } // this.profiler.end(); - this.ticksNow.clear(); - return !this.ticksNext.isEmpty(); - } + this.ticksNow.clear(); + return !this.ticksNext.isEmpty(); } } - public List getPendingBlockUpdates(Chunk chunk) { + public List getPendingBlockUpdates(ChunkServer chunk) { int x1 = (chunk.xPos << 4) - 2; int x2 = x1 + 16 + 2; int z1 = (chunk.zPos << 4) - 2; @@ -799,33 +869,33 @@ public final class WorldServer extends World { } public static boolean needsLoading(Dimension dim) { - NBTTagCompound tag = null; + TagObject tag = null; try { - File dat = new File(new File(new File("chunk"), dim.getDimensionName()), "loaders.nbt"); + File dat = new File(new File(new File("chunk"), dim.getDimensionName()), "loaders.cdt"); if(dat.exists() && dat.isFile()) - tag = NBTLoader.readGZip(dat); + tag = TagObject.readGZip(dat); } catch(Exception e) { return false; } - return tag != null && tag.hasKey("Loaders", 9) && !tag.getTagList("Loaders", 10).hasNoTags(); + return tag != null && tag.hasList("Loaders") && !tag.getList("Loaders").isEmpty(); } public static void loadWarps(Dimension dim, Map warps) { - NBTTagCompound tag = null; + TagObject tag = null; try { - File dat = new File(new File(new File("chunk"), dim.getDimensionName()), "warps.nbt"); + File dat = new File(new File(new File("chunk"), dim.getDimensionName()), "warps.cdt"); if(dat.exists() && dat.isFile()) - tag = NBTLoader.readGZip(dat); + tag = TagObject.readGZip(dat); } catch(Exception e) { - Log.JNI.error(e, "Konnte Warpliste nicht laden"); + Log.IO.error(e, "Konnte Warpliste nicht laden"); return; } - if(tag != null && tag.hasKey("Warps", 9)) { - NBTTagList list = tag.getTagList("Warps", 10); - for(int z = 0; z < list.tagCount(); z++) { - NBTTagCompound pos = list.getCompoundTagAt(z); + if(tag != null && tag.hasList("Warps")) { + List list = tag.getList("Warps"); + for(int z = 0; z < list.size(); z++) { + TagObject pos = list.get(z); warps.put(pos.getString("Name"), new Position(pos.getDouble("X"), pos.getDouble("Y"), pos.getDouble("Z"), pos.getFloat("Yaw"), pos.getFloat("Pitch"), dim.getDimensionId())); } @@ -833,122 +903,144 @@ public final class WorldServer extends World { } public static void saveWarps(Map warps) { - Map map = Maps.newHashMap(); + Map> map = Maps.newHashMap(); for(Entry pos : warps.entrySet()) { - Dimension dim = UniverseRegistry.getDimension(pos.getValue().dim); + Dimension dim = UniverseRegistry.getDimension(pos.getValue().dim()); if(dim != null) { - NBTTagList list = map.get(pos.getValue().dim); + List list = map.get(pos.getValue().dim()); if(list == null) - map.put(pos.getValue().dim, list = new NBTTagList()); - NBTTagCompound warp = new NBTTagCompound(); + map.put(pos.getValue().dim(), list = Lists.newArrayList()); + TagObject warp = new TagObject(); warp.setString("Name", pos.getKey()); - warp.setDouble("X", pos.getValue().x); - warp.setDouble("Y", pos.getValue().y); - warp.setDouble("Z", pos.getValue().z); - warp.setFloat("Yaw", pos.getValue().yaw); - warp.setFloat("Pitch", pos.getValue().pitch); - list.appendTag(warp); + warp.setDouble("X", pos.getValue().x()); + warp.setDouble("Y", pos.getValue().y()); + warp.setDouble("Z", pos.getValue().z()); + warp.setFloat("Yaw", pos.getValue().yaw()); + warp.setFloat("Pitch", pos.getValue().pitch()); + list.add(warp); } } for(Dimension dim : UniverseRegistry.getDimensions()) { - NBTTagList list = map.get(dim.getDimensionId()); - File file = new File(new File(new File("chunk"), dim.getDimensionName()), "warps.nbt"); + List list = map.get(dim.getDimensionId()); + File file = new File(new File(new File("chunk"), dim.getDimensionName()), "warps.cdt"); if(list == null) { file.delete(); } else { - NBTTagCompound tag = new NBTTagCompound(); - tag.setTag("Warps", list); + TagObject tag = new TagObject(); + tag.setList("Warps", list); try { - NBTLoader.writeGZip(tag, file); + TagObject.writeGZip(tag, file); } catch(Exception e) { - Log.JNI.error(e, "Konnte Warpliste nicht speichern"); + Log.IO.error(e, "Konnte Warpliste nicht speichern"); } } } map.clear(); } + private static boolean deleteFiles(File[] files) { + if(files == null) { + Log.IO.warn("Konnte Ordner nicht löschen"); + return false; + } + + for(int i = 0; i < files.length; ++i) { + File file = files[i]; + Log.IO.info("Lösche " + file); + + if(file.isDirectory() && !deleteFiles(file.listFiles())) { + Log.IO.warn("Konnte Ordner " + file + " nicht löschen"); + return false; + } + + if(!file.delete()) { + Log.IO.warn("Konnte Datei " + file + " nicht löschen"); + return false; + } + } + + return true; + } + public void saveAllChunks() { - if(/* (force || !this.disableSaving) && */ !this.debug) { // if(this.primary) { // // } - if(this.loadersModified) { - this.loadersModified = false; - NBTTagCompound loaders = new NBTTagCompound(); - NBTTagList list = new NBTTagList(); - for(BlockPos pos : this.loaderList) { - NBTTagCompound loader = new NBTTagCompound(); - loader.setInteger("X", pos.getX()); - loader.setInteger("Y", pos.getY()); - loader.setInteger("Z", pos.getZ()); - list.appendTag(loader); + if(this.loadersModified) { + this.loadersModified = false; + TagObject loaders = new TagObject(); + List list = Lists.newArrayList(); + for(BlockPos pos : this.loaderList) { + TagObject loader = new TagObject(); + loader.setInt("X", pos.getX()); + loader.setInt("Y", pos.getY()); + loader.setInt("Z", pos.getZ()); + list.add(loader); + } + loaders.setList("Loaders", list); + File file = new File(this.chunkDir, "loaders.cdt"); + if(list.isEmpty()) { + file.delete(); + } + else { + try { + TagObject.writeGZip(loaders, file); } - loaders.setTag("Loaders", list); - File file = new File(this.chunkDir, "loaders.nbt"); - if(list.hasNoTags()) { - file.delete(); - } - else { - try { - NBTLoader.writeGZip(loaders, file); - } - catch(Exception e) { - Log.JNI.error(e, "Konnte Ladeliste nicht speichern"); - } + catch(Exception e) { + Log.IO.error(e, "Konnte Ladeliste nicht speichern"); } } + } // if(this.warpsModified) { // this.warpsModified = false; // } // if(this.dataModified) { // this.dataModified = false; - NBTTagCompound data = new NBTTagCompound(); + TagObject data = new TagObject(); // data.setLong("Seed", this.seed); - data.setTag("Generator", this.dimension.toNbt(true)); - data.setLong("Time", this.time); - data.setBoolean("Exterminated", this.exterminated); - data.setString("Weather", this.weather.getName()); - // ... - File file = new File(this.chunkDir, "data.nbt"); + data.setObject("Generator", this.dimension.toTags(true)); + data.setLong("Time", this.time); + data.setBool("Exterminated", this.exterminated); + data.setString("Weather", this.weather.getName()); + // ... + File file = new File(this.chunkDir, "data.cdt"); + try { + TagObject.writeGZip(data, file); + } + catch(Exception e) { + Log.IO.error(e, "Konnte Weltdaten nicht speichern"); + } +// } + for(int i = 0; i < this.dataList.size(); ++i) { + WorldSavedData wdata = this.dataList.get(i); + if(wdata.dirty) { + this.saveData(wdata); + wdata.dirty = false; + } + } + if(this.villageStorage != null && this.villageStorage.isDirty()) { + TagObject tag = this.villageStorage.toTags(); + File dat = new File(this.chunkDir, "villages.cdt"); try { - NBTLoader.writeGZip(data, file); + TagObject.writeGZip(tag, dat); } catch(Exception e) { - Log.JNI.error(e, "Konnte Weltdaten nicht speichern"); + Log.IO.error(e, "Konnte Dorfliste nicht speichern"); } -// } - for(int i = 0; i < this.dataList.size(); ++i) { - WorldSavedData wdata = this.dataList.get(i); - if(wdata.dirty) { - this.saveData(wdata); - wdata.dirty = false; - } + } + List list = Lists.newArrayList(this.loaded); + for(int n = 0; n < list.size(); ++n) { + ChunkServer chunk = list.get(n); + if(chunk.isDirty(this.time)) { + this.saveChunkData(chunk); + chunk.setModified(false); } - if(this.villageStorage != null && this.villageStorage.isDirty()) { - NBTTagCompound tag = this.villageStorage.writeToNBT(); - File dat = new File(this.chunkDir, "villages.nbt"); - try { - NBTLoader.writeGZip(tag, dat); - } - catch(Exception e) { - Log.JNI.error(e, "Konnte Dorfliste nicht speichern"); - } - } - List list = Lists.newArrayList(this.loaded); - for(int n = 0; n < list.size(); ++n) { - Chunk chunk = list.get(n); - if(chunk.isDirty(this.time)) { - this.saveChunkData(chunk); - chunk.setModified(false); - } - } - for(Chunk chunk : Lists.newArrayList(this.loaded)) { - if(chunk != null && !this.hasPlayerInstance(chunk.xPos, chunk.zPos)) { - this.dropChunk(chunk.xPos, chunk.zPos); - } + } + for(ChunkServer chunk : Lists.newArrayList(this.loaded)) { + if(chunk != null && !this.hasPlayerInstance(chunk.xPos, chunk.zPos)) { + this.dropChunk(chunk.xPos, chunk.zPos); } } } @@ -981,15 +1073,15 @@ public final class WorldServer extends World { EntityLightning entity = new EntityLightning(this, x, y, z, color, damage, fire, summoner); this.effects.add(entity); this.server.sendNear(entity.posX, entity.posY, entity.posZ, 512.0D, this.dimension.getDimensionId(), - new S2CPacketSpawnGlobalEntity(entity, 1, entity.color)); - if(fire && Config.fire) { + new SPacketSpawnGlobalEntity(entity, 1, entity.color)); + if(fire && SVars.fire) { BlockPos pos = new BlockPos(entity); if(this.isAreaLoaded(pos, 10)) { - if(this.getState(pos).getBlock().getMaterial() == Material.air && Blocks.fire.canPlaceBlockAt(this, pos)) + if(this.getState(pos).getBlock() == Blocks.air && Blocks.fire.canPlaceBlockAt(this, pos)) this.setState(pos, Blocks.fire.getState()); for(int n = 0; n < 4; n++) { BlockPos extra = pos.add(this.rand.range(-1, 1), this.rand.range(-1, 1), this.rand.range(-1, 1)); - if(this.getState(extra).getBlock().getMaterial() == Material.air && Blocks.fire.canPlaceBlockAt(this, extra)) + if(this.getState(extra).getBlock() == Blocks.air && Blocks.fire.canPlaceBlockAt(this, extra)) this.setState(extra, Blocks.fire.getState()); } } @@ -997,7 +1089,7 @@ public final class WorldServer extends World { } public void setEntityState(Entity entityIn, byte state) { - this.sendToAllTrackingAndSelf(entityIn, new S1APacketEntityStatus(entityIn, state)); + this.sendToAllTrackingAndSelf(entityIn, new SPacketEntityStatus(entityIn, state)); } public Explosion newExplosion(Entity entityIn, double x, double y, double z, float strength, boolean isFlaming, boolean isSmoking, boolean altSound) { @@ -1011,7 +1103,7 @@ public final class WorldServer extends World { for(EntityNPC entityplayer : this.players) { if(entityplayer.getDistanceSq(x, y, z) < 4096.0D) { - entityplayer.connection.sendPacket(new S27PacketExplosion(x, y, z, strength, explosion.getAffectedBlockPositions(), + entityplayer.connection.sendPacket(new SPacketExplosion(x, y, z, strength, explosion.getAffectedBlockPositions(), (Vec3)explosion.getPlayerKnockbackMap().get(entityplayer), altSound)); } } @@ -1020,9 +1112,9 @@ public final class WorldServer extends World { } public void addBlockEvent(BlockPos pos, Block blockIn, int eventID, int eventParam) { - BlockEventData blockeventdata = new BlockEventData(pos, blockIn, eventID, eventParam); + TickEvent blockeventdata = new TickEvent(pos, blockIn, eventID, eventParam); - for(BlockEventData blockeventdata1 : this.queue[this.blockEvtIdx]) { + for(TickEvent blockeventdata1 : this.queue[this.blockEvtIdx]) { if(blockeventdata1.equals(blockeventdata)) { return; } @@ -1036,12 +1128,12 @@ public final class WorldServer extends World { int i = this.blockEvtIdx; this.blockEvtIdx ^= 1; - for(BlockEventData blockeventdata : this.queue[i]) { + for(TickEvent blockeventdata : this.queue[i]) { if(this.fireBlockEvent(blockeventdata)) { - this.server.sendNear((double)blockeventdata.getPosition().getX(), (double)blockeventdata.getPosition().getY(), - (double)blockeventdata.getPosition().getZ(), 64.0D, this.dimension.getDimensionId(), - new SPacketBlockAction(blockeventdata.getPosition(), blockeventdata.getBlock(), blockeventdata.getEventID(), - blockeventdata.getEventParameter())); + this.server.sendNear((double)blockeventdata.position().getX(), (double)blockeventdata.position().getY(), + (double)blockeventdata.position().getZ(), 64.0D, this.dimension.getDimensionId(), + new SPacketBlockAction(blockeventdata.position(), blockeventdata.block(), blockeventdata.id(), + blockeventdata.parameter())); } } @@ -1049,10 +1141,10 @@ public final class WorldServer extends World { } } - private boolean fireBlockEvent(BlockEventData event) { - State iblockstate = this.getState(event.getPosition()); - return iblockstate.getBlock() == event.getBlock() - ? iblockstate.getBlock().onBlockEventReceived(this, event.getPosition(), iblockstate, event.getEventID(), event.getEventParameter()) + private boolean fireBlockEvent(TickEvent event) { + State iblockstate = this.getState(event.position()); + return iblockstate.getBlock() == event.block() + ? iblockstate.getBlock().onBlockEventReceived(this, event.position(), iblockstate, event.id(), event.parameter()) : false; } @@ -1064,7 +1156,7 @@ public final class WorldServer extends World { public void setWeather(Weather weather) { this.weather = weather; // this.dataModified = true; - this.server.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.SET_WEATHER, + this.server.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.SET_WEATHER, weather.getID()), this.dimension.getDimensionId()); } @@ -1091,9 +1183,9 @@ public final class WorldServer extends World { float prevRain = this.rain; float prevFog = this.fog; - if(Config.weather && Config.weatherChance > 0) { + if(SVars.weather && SVars.weatherChance > 0) { // int time = dim.getWeatherTime(); - if(this.rand.chance(Config.weatherChance)) { + if(this.rand.chance(SVars.weatherChance)) { Weather nweather = Weather.pick(this.getBaseTemperature(), this.rand); if(nweather != this.weather) { // dim.setWeatherTime(this.rand.zrange(Config.weatherFlow) + Config.weatherFlow); @@ -1136,15 +1228,15 @@ public final class WorldServer extends World { } if(prevRain != this.rain || force) { - this.server.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.RAIN_STRENGTH, this.rain), this.dimension.getDimensionId()); + this.server.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.RAIN_STRENGTH, this.rain), this.dimension.getDimensionId()); } if(prevDarkness != this.darkness || force) { - this.server.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.DARKNESS, this.darkness), this.dimension.getDimensionId()); + this.server.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.DARKNESS, this.darkness), this.dimension.getDimensionId()); } if(prevFog != this.fog || force) { - this.server.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.FOG_STRENGTH, this.fog), this.dimension.getDimensionId()); + this.server.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.FOG_STRENGTH, this.fog), this.dimension.getDimensionId()); } } @@ -1160,7 +1252,7 @@ public final class WorldServer extends World { } if(prevTemp != this.temp || force) { - this.server.sendPacket(new S2BPacketChangeGameState(S2BPacketChangeGameState.Action.TEMPERATURE, this.temp), this.dimension.getDimensionId()); + this.server.sendPacket(new SPacketChangeGameState(SPacketChangeGameState.Action.TEMPERATURE, this.temp), this.dimension.getDimensionId()); } } @@ -1176,7 +1268,7 @@ public final class WorldServer extends World { public void spawnParticle(ParticleType particleType, boolean longDistance, double xCoord, double yCoord, double zCoord, int numberOfParticles, double xOffset, double yOffset, double zOffset, double particleSpeed, int[] particleArguments) { - Packet packet = new S2APacketParticles(particleType, longDistance, (float)xCoord, (float)yCoord, (float)zCoord, (float)xOffset, + Packet packet = new SPacketParticles(particleType, longDistance, (float)xCoord, (float)yCoord, (float)zCoord, (float)xOffset, (float)yOffset, (float)zOffset, (float)particleSpeed, numberOfParticles, particleArguments); for(int i = 0; i < this.players.size(); ++i) { @@ -1191,14 +1283,18 @@ public final class WorldServer extends World { } protected boolean isLoaded(int x, int z, boolean allowEmpty) { - return this.chunkExists(x, z) && super.isLoaded(x, z, allowEmpty); + return this.chunkExists(x, z); } - public Chunk getChunk(int x, int z) { - Chunk chunk = this.chunks.getValueByKey(LongHashMap.packInt(x, z)); + public ChunkServer getChunk(int x, int z) { + ChunkServer chunk = this.chunks.getValueByKey(LongHashMap.packInt(x, z)); return chunk == null ? this.loadChunk(x, z) : chunk; } + public ChunkServer getChunk(BlockPos pos) { + return this.getChunk(pos.getX() >> 4, pos.getZ() >> 4); + } + private boolean chunkExists(int x, int z) { return this.chunks.containsItem(LongHashMap.packInt(x, z)); } @@ -1216,19 +1312,18 @@ public final class WorldServer extends World { } public void unloadAllChunks() { - for(Chunk chunk : this.loaded) { + for(ChunkServer chunk : this.loaded) { this.dropChunk(chunk.xPos, chunk.zPos); } } - public Chunk loadChunk(int x, int z) { + public ChunkServer loadChunk(int x, int z) { long id = LongHashMap.packInt(x, z); this.dropped.remove(Long.valueOf(id)); - Chunk chunk = (Chunk)this.chunks.getValueByKey(id); + ChunkServer chunk = this.chunks.getValueByKey(id); if(chunk == null) { - if(!this.debug) - chunk = this.loadChunkFromFile(x, z); + chunk = this.loadChunkFromFile(x, z); if(chunk == null) { chunk = this.generate(x, z); @@ -1243,10 +1338,10 @@ public final class WorldServer extends World { return chunk; } - private Chunk loadChunkFromFile(int x, int z) { + private ChunkServer loadChunkFromFile(int x, int z) { try { ChunkPos coord = new ChunkPos(x, z); - NBTTagCompound tag = this.toRemove.get(coord); + TagObject tag = this.toRemove.get(coord); if(tag == null) { tag = Region.readChunk(this.chunkDir, x, z); // DataInputStream in = ; @@ -1255,7 +1350,7 @@ public final class WorldServer extends World { } // tag = CompressedStreamTools.read(in); } - Chunk chunk = Region.readNbt(this, x, z, tag); + ChunkServer chunk = Region.readChunk(this, x, z, tag); if(chunk != null) { chunk.setSaved(this.time); if(this.mineshaftGen != null) { @@ -1277,32 +1372,24 @@ public final class WorldServer extends World { return chunk; } catch(Exception e) { - Log.JNI.error(e, "Konnte Chunk nicht laden"); + Log.IO.error(e, "Konnte Chunk nicht laden"); return null; } } - private void saveChunkData(Chunk chunk) { -// try { + private void saveChunkData(ChunkServer chunk) { chunk.setSaved(this.time); -// this.lock.check(); try { -// NBTTagCompound ltag = new NBTTagCompound(); -// tag.setTag("Level", ltag); - NBTTagCompound tag = Region.writeNbt(this, chunk); - ChunkPos coord = chunk.getPos(); + TagObject tag = Region.writeChunk(this, chunk); + ChunkPos coord = new ChunkPos(chunk.xPos, chunk.zPos); if(!this.pending.contains(coord)) { this.toRemove.put(coord, tag); } Region.queueIO(this); } catch(Exception e) { - Log.JNI.error(e, "Konnte Chunk nicht speichern"); + Log.IO.error(e, "Konnte Chunk nicht speichern"); } -// } -// catch(SaveException e) { -// Log.error("Konnte Chunk nicht speichern; bereits von einer anderen Instanz genutzt?", e); -// } } public boolean writeNextIO() { @@ -1317,7 +1404,7 @@ public final class WorldServer extends World { boolean flag; try { this.pending.add(coord); - NBTTagCompound tag = this.toRemove.remove(coord); + TagObject tag = this.toRemove.remove(coord); if(tag != null) { try { @@ -1327,7 +1414,7 @@ public final class WorldServer extends World { Region.writeChunk(this.chunkDir, coord.x, coord.z, tag); } catch(Exception e) { - Log.JNI.error(e, "Konnte Chunk nicht speichern"); + Log.IO.error(e, "Konnte Chunk nicht speichern"); } } flag = true; @@ -1399,14 +1486,14 @@ public final class WorldServer extends World { } private void populate(int x, int z) { - Chunk chunk = this.getChunk(x, z); + ChunkServer chunk = this.getChunk(x, z); if(!chunk.isTerrainPopulated()) { chunk.checkLight(); BlockFalling.fallInstantly = true; int bx = x * 16; int bz = z * 16; BlockPos pos = new BlockPos(bx, 0, bz); - Biome biome = this.getBiomeGenForCoords(pos.add(16, 0, 16)); + GenBiome biome = GenBiome.BIOMES[this.getBiomeGenForCoords(pos.add(16, 0, 16)).id]; this.grng.setSeed(this.seed); long sx = this.grng.longv() / 2L * 2L + 1L; long sz = this.grng.longv() / 2L * 2L + 1L; @@ -1449,7 +1536,7 @@ public final class WorldServer extends World { liquid.generate(this, this.grng, pos); } } - if(this.mobs && Config.mobs && Config.genSpawn) { + if(this.mobs && SVars.mobs && SVars.genSpawn) { Spawner.generate(this, biome, bx + 8, bz + 8, 16, 16, this.grng); } // if(this.snow) { @@ -1468,11 +1555,11 @@ public final class WorldServer extends World { } // } BlockFalling.fallInstantly = false; - chunk.setModified(); + chunk.setModified(true); } } - private Chunk generate(int x, int z) { + private ChunkServer generate(int x, int z) { this.grng.setSeed((long)x * 341873128712L + (long)z * 132897987541L); ChunkPrimer primer = new ChunkPrimer(this.height); this.generator.generateChunk(this, x, z, primer); @@ -1504,7 +1591,7 @@ public final class WorldServer extends World { if(this.scatteredGen != null) { this.scatteredGen.generate(this, x, z, primer); } - return new Chunk(this, primer, this.base, this.ceil, this.grng, this.biomes, x, z); + return new ChunkServer(this, primer.getData(), primer.height, this.base, this.ceil, this.grng, this.biomes, x, z); } public boolean isExterminated() { @@ -1512,8 +1599,6 @@ public final class WorldServer extends World { } public boolean exterminate() { - if(this.debug) - return true; if(this.exterminated) return false; this.setWeather(Weather.CLEAR); @@ -1527,11 +1612,11 @@ public final class WorldServer extends World { this.loaderList.clear(); for(Iterator> iter = this.server.getWarps().entrySet().iterator(); iter.hasNext();) { Entry pos = iter.next(); - if(pos.getValue().dim == this.dimension.getDimensionId()) + if(pos.getValue().dim() == this.dimension.getDimensionId()) iter.remove(); } Region.finishWrite(); - FileUtils.deleteFiles(this.chunkDir.listFiles(new FileFilter() { + deleteFiles(this.chunkDir.listFiles(new FileFilter() { public boolean accept(File file) { return file.isDirectory(); } @@ -1539,7 +1624,7 @@ public final class WorldServer extends World { this.exterminated = true; // this.dataModified = true; for(Long v : this.dropped) { - Chunk chunk = this.chunks.getValueByKey(v.longValue()); + ChunkServer chunk = this.chunks.getValueByKey(v.longValue()); if(chunk != null) { chunk.onChunkUnload(); this.chunks.remove(v.longValue()); @@ -1547,10 +1632,10 @@ public final class WorldServer extends World { } } this.dropped.clear(); - List loaded = Lists.newArrayList(this.loaded); + List loaded = Lists.newArrayList(this.loaded); this.loaded.clear(); this.setExterminatedGen(); - for(Chunk chunk : loaded) { + for(ChunkServer chunk : loaded) { long pos = LongHashMap.packInt(chunk.xPos, chunk.zPos); chunk.onChunkUnload(); this.chunks.remove(pos); @@ -1559,9 +1644,9 @@ public final class WorldServer extends World { this.loaded.add(chunk); chunk.onChunkLoad(); chunk.checkLight(); - chunk.setModified(); + chunk.setModified(true); } - for(Chunk chunk : this.loaded) { + for(ChunkServer chunk : this.loaded) { chunk.update(false); } this.entities.removeAll(this.unloaded); @@ -1583,15 +1668,15 @@ public final class WorldServer extends World { } for(EntityNPC player : this.players) { player.attackEntityFrom(DamageSource.causeExterminatusDamage(null), 5000); - Packet packet = new S2APacketParticles(ParticleType.EXPLOSION_HUGE, true, + Packet packet = new SPacketParticles(ParticleType.EXPLOSION_HUGE, true, (float)player.posX, (float)this.getSeaLevel() + 4.0f, (float)player.posZ, (float)128.0, (float)2.0, (float)128.0, (float)0.15, 1000, new int[0]); player.connection.sendPacket(packet); - packet = new S2APacketParticles(ParticleType.CLOUD, true, + packet = new SPacketParticles(ParticleType.CLOUD, true, (float)player.posX, (float)this.getSeaLevel() + 4.0f, (float)player.posZ, (float)128.0, (float)2.0, (float)128.0, (float)0.15, 1000, new int[0]); player.connection.sendPacket(packet); - packet = new S28PacketEffect(1025, new BlockPos(player.posX, (double)this.getSeaLevel() + 4.0, player.posZ), 0); + packet = new SPacketEffect(1025, new BlockPos(player.posX, (double)this.getSeaLevel() + 4.0, player.posZ), 0); player.connection.sendPacket(packet); } return true; @@ -1610,12 +1695,12 @@ public final class WorldServer extends World { this.scatteredGen = null; this.bridgeGen = null; this.generator = new GeneratorDestroyed(this.dimension.getSeaLevel()); - this.biomeGen = new BiomeGenSingle(Biome.exterminated); + this.biomeGen = new BiomeGenSingle(Biome.EXTERMINATED); this.replacer = null; this.populate = false; this.liquid = Blocks.air.getState(); - this.base = Blocks.air.getState(); - this.ceil = null; + this.base = false; + this.ceil = false; this.height = this.generator.getMaximumHeight(); this.seaLevel = this.dimension.getSeaLevel(); this.ores = null; @@ -1667,7 +1752,7 @@ public final class WorldServer extends World { public void playSound(SoundEvent sound, double x, double y, double z, float volume) { - this.server.sendNear(x, y, z, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.dimension.getDimensionId(), new S29PacketSoundEffect(sound, x, y, z, volume)); + this.server.sendNear(x, y, z, volume > 1.0F ? (double)(16.0F * volume) : 16.0D, this.dimension.getDimensionId(), new SPacketSoundEffect(sound, x, y, z, volume)); } public void markBlockRangeForRenderUpdate(int x1, int y1, int z1, int x2, int y2, int z2) @@ -1680,7 +1765,7 @@ public final class WorldServer extends World { public void playAuxSFX(EntityNPC player, int sfxType, BlockPos blockPosIn, int data) { - this.server.sendNearExcept(player, (double)blockPosIn.getX(), (double)blockPosIn.getY(), (double)blockPosIn.getZ(), 64.0D, this.dimension.getDimensionId(), new S28PacketEffect(sfxType, blockPosIn, data)); + this.server.sendNearExcept(player, (double)blockPosIn.getX(), (double)blockPosIn.getY(), (double)blockPosIn.getZ(), 64.0D, this.dimension.getDimensionId(), new SPacketEffect(sfxType, blockPosIn, data)); } // public void broadcastSound(int soundID, BlockPos pos, int data) @@ -1738,15 +1823,18 @@ public final class WorldServer extends World { return this.instances.getValueByKey(v) != null; } - public boolean updateBiomes(int chunkX, int chunkZ) { + public void setBiome(BlockPos pos, Biome biome) { + ChunkServer chunk = this.getChunk(pos); + if(chunk == null || !chunk.isLoaded()) + return; + chunk.getBiomes()[((pos.getZ() & 0xF) << 4 | pos.getX() & 0xF)] = (byte)biome.id; + chunk.setModified(true); + int chunkX = pos.getX() >> 4; + int chunkZ = pos.getZ() >> 4; long v = (long)chunkX + 2147483647L | (long)chunkZ + 2147483647L << 32; PlayerInstance ins = this.instances.getValueByKey(v); - if(ins == null) - return false; - Chunk chunk = this.getChunk(chunkX, chunkZ); - chunk.setModified(); - ins.sendToAllPlayersWatchingChunk(new SPacketBiomes(chunkX, chunkZ, chunk.getBiomes())); - return true; + if(ins != null) + ins.sendToAllPlayersWatchingChunk(new SPacketBiome(pos, biome)); } private PlayerInstance getPlayerInstance(int chunkX, int chunkZ, boolean create) { @@ -1775,8 +1863,7 @@ public final class WorldServer extends World { public void addPlayer(EntityNPC player) { int x = (int)player.posX >> 4; int z = (int)player.posZ >> 4; - player.connection.managedPosX = player.posX; - player.connection.managedPosZ = player.posZ; + player.connection.setManagedPos(player.posX, player.posZ); for(int cx = x - this.viewRadius; cx <= x + this.viewRadius; ++cx) { for(int cz = z - this.viewRadius; cz <= z + this.viewRadius; ++cz) { @@ -1789,7 +1876,7 @@ public final class WorldServer extends World { } private void filterChunkLoadQueue(EntityNPC player) { - List list = Lists.newArrayList(player.connection.loadedChunks); + List list = Lists.newArrayList(player.connection.getLoadedChunkList()); int p = 0; int r = this.viewRadius; int x = (int)player.posX >> 4; @@ -1797,10 +1884,10 @@ public final class WorldServer extends World { int cx = 0; int cz = 0; ChunkPos pos = this.getPlayerInstance(x, z, true).position; - player.connection.loadedChunks.clear(); + player.connection.getLoadedChunkList().clear(); if(list.contains(pos)) { - player.connection.loadedChunks.add(pos); + player.connection.getLoadedChunkList().add(pos); } for(int n = 1; n <= r * 2; ++n) { @@ -1813,7 +1900,7 @@ public final class WorldServer extends World { pos = this.getPlayerInstance(x + cx, z + cz, true).position; if(list.contains(pos)) { - player.connection.loadedChunks.add(pos); + player.connection.getLoadedChunkList().add(pos); } } } @@ -1827,14 +1914,14 @@ public final class WorldServer extends World { pos = this.getPlayerInstance(x + cx, z + cz, true).position; if(list.contains(pos)) { - player.connection.loadedChunks.add(pos); + player.connection.getLoadedChunkList().add(pos); } } } public void removePlayer(EntityNPC player) { - int x = (int)player.connection.managedPosX >> 4; - int z = (int)player.connection.managedPosZ >> 4; + int x = (int)player.connection.getManagedX() >> 4; + int z = (int)player.connection.getManagedZ() >> 4; for(int cx = x - this.viewRadius; cx <= x + this.viewRadius; ++cx) { for(int cz = z - this.viewRadius; cz <= z + this.viewRadius; ++cz) { @@ -1858,13 +1945,13 @@ public final class WorldServer extends World { public void updateMountedMovingPlayer(EntityNPC player) { int x = (int)player.posX >> 4; int z = (int)player.posZ >> 4; - double dx = player.connection.managedPosX - player.posX; - double dz = player.connection.managedPosZ - player.posZ; + double dx = player.connection.getManagedX() - player.posX; + double dz = player.connection.getManagedZ() - player.posZ; double dist = dx * dx + dz * dz; if(dist >= 64.0D) { - int px = (int)player.connection.managedPosX >> 4; - int pz = (int)player.connection.managedPosZ >> 4; + int px = (int)player.connection.getManagedX() >> 4; + int pz = (int)player.connection.getManagedZ() >> 4; int r = this.viewRadius; int mx = x - px; int mz = z - pz; @@ -1887,19 +1974,18 @@ public final class WorldServer extends World { } this.filterChunkLoadQueue(player); - player.connection.managedPosX = player.posX; - player.connection.managedPosZ = player.posZ; + player.connection.setManagedPos(player.posX, player.posZ); } } } public boolean isPlayerWatchingChunk(EntityNPC player, int chunkX, int chunkZ) { PlayerInstance inst = this.getPlayerInstance(chunkX, chunkZ, false); - return inst != null && inst.watching.contains(player) && !player.connection.loadedChunks.contains(inst.position); + return inst != null && inst.watching.contains(player) && !player.connection.getLoadedChunkList().contains(inst.position); } public void updateViewRadius() { - int radius = ExtMath.clampi(Config.distance, 3, 128); + int radius = ExtMath.clampi(SVars.distance, 3, 128); if(radius != this.viewRadius) { int diff = radius - this.viewRadius; @@ -1933,7 +2019,7 @@ public final class WorldServer extends World { this.viewRadius = radius; } - this.trackDistance = Config.distance * 16 - 16; + this.trackDistance = SVars.distance * 16 - 16; } public void trackEntity(Entity entityIn) { @@ -1968,7 +2054,7 @@ public final class WorldServer extends World { entitytrackerentry.updatePlayerEntities(this.players); } catch(Throwable throwable) { - Log.JNI.error((Throwable)throwable, (String)"Fange Objekt-Tracking-Fehler \"leise\" auf."); + Log.TICK.error((Throwable)throwable, (String)"Fange Objekt-Tracking-Fehler \"leise\" auf."); } } @@ -2044,7 +2130,7 @@ public final class WorldServer extends World { } } - public void updateChunksForPlayer(EntityNPC player, Chunk chunk) { + public void updateChunksForPlayer(EntityNPC player, ChunkServer chunk) { for(EntityTrackerEntry entitytrackerentry : this.tracked) { if(entitytrackerentry.trackedEntity != player && entitytrackerentry.trackedEntity.chunkCoordX == chunk.xPos && entitytrackerentry.trackedEntity.chunkCoordZ == chunk.zPos) { @@ -2057,7 +2143,7 @@ public final class WorldServer extends World { // int x = position.getBlockX(); // int y = position.getBlockY(); // int z = position.getBlockZ(); - Chunk chunk = this.getChunk(pos.getX() >> 4, pos.getZ() >> 4); + ChunkServer chunk = this.getChunk(pos.getX() >> 4, pos.getZ() >> 4); // BlockPos pos = new BlockPos(x, y, z); State old = chunk.getState(pos); State newState = block.getState(); @@ -2070,13 +2156,13 @@ public final class WorldServer extends World { State successState = chunk.setState(pos, newState); boolean successful = successState != null; if(successful) { - if(block.getNbtData() != null) { + if(block.getData() != null) { this.removeTileEntity(pos); - NBTTagCompound tag = block.getNbtData(); + TagObject tag = block.getData(); tag.setString("id", tag.getString("id")); - tag.setTag("x", new NBTTagInt(pos.getX())); - tag.setTag("y", new NBTTagInt(pos.getY())); - tag.setTag("z", new NBTTagInt(pos.getZ())); + tag.setInt("x", pos.getX()); + tag.setInt("y", pos.getY()); + tag.setInt("z", pos.getZ()); TileEntity tileEntity = TileEntity.createAndLoadEntity(tag); if(tileEntity != null) { this.setTileEntity(pos, tileEntity); @@ -2110,45 +2196,7 @@ public final class WorldServer extends World { return new ClipboardBlock(state); } } - -// public final EditBlock getLazyBlock(Vector position) { -// State state = this.getState(new BlockPos(position.getBlockX(), position.getBlockY(), position.getBlockZ())); -// return new LazyBlock(state, this, position); -// } - - public final boolean setBiome(BlockPos position, Biome biome) { - Chunk chunk = this.getChunk(position); - if((chunk != null) && (chunk.isLoaded())) { - chunk.getBiomes()[((position.getZ() & 0xF) << 4 | position.getX() & 0xF)] = (byte)biome.id; - return true; - } - return false; - } - public final void setBiomes(BlockPos start, BlockPos end, Biome biome) { - Set chunks = Sets.newHashSet(); - for(int x = start.getX(); x <= end.getX(); x++) { - for(int z = start.getZ(); z <= end.getZ(); z++) { - if(this.setBiome(new BlockPos(x, 0, z), biome)) - chunks.add(new ChunkPos(x >> 4, z >> 4)); - } - } - for(ChunkPos pos : chunks) { - this.updateBiomes(pos.x, pos.z); - } - chunks.clear(); - } - -// public final List getEntities(EditRegion region) { -// List entities = Lists.newArrayList(); -// for(Entity entity : this.entities) { -// if(region.contains(new Vector(entity.posX, entity.posY, entity.posZ))) { -// entities.add(entity); -// } -// } -// return entities; -// } - public final List getEntities() { List entities = Lists.newArrayList(); for(Entity entity : this.entities) { @@ -2235,10 +2283,10 @@ public final class WorldServer extends World { if(!this.canBurnAt(pos)) { return false; } - if(pos.getY() >= 0 && pos.getY() < 512) { + if(pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y) { Block block = this.getState(pos).getBlock(); - if(block.getMaterial() == Material.air && Blocks.fire.canPlaceBlockAt(this, pos)) { + if(block == Blocks.air && Blocks.fire.canPlaceBlockAt(this, pos)) { return true; } } @@ -2251,7 +2299,7 @@ public final class WorldServer extends World { return false; } else { - if(pos.getY() >= 0 && pos.getY() < 512 && this.getLightFor(LightType.BLOCK, pos) < 10) { + if(pos.getY() >= -World.MAX_SIZE_Y && pos.getY() < World.MAX_SIZE_Y && this.getLightFor(LightType.BLOCK, pos) < 10) { State iblockstate = this.getState(pos); Block block = iblockstate.getBlock(); @@ -2260,10 +2308,10 @@ public final class WorldServer extends World { return true; } - boolean flag = this.getState(pos.west()).getBlock().getMaterial() == Material.water && - this.getState(pos.east()).getBlock().getMaterial() == Material.water && - this.getState(pos.north()).getBlock().getMaterial() == Material.water && - this.getState(pos.south()).getBlock().getMaterial() == Material.water; + boolean flag = this.getState(pos.west()).getBlock().getMaterial() == Material.WATER && + this.getState(pos.east()).getBlock().getMaterial() == Material.WATER && + this.getState(pos.north()).getBlock().getMaterial() == Material.WATER && + this.getState(pos.south()).getBlock().getMaterial() == Material.WATER; if(!flag) { return true; @@ -2289,7 +2337,7 @@ public final class WorldServer extends World { for(int i2 = i1; i2 <= j1; ++i2) { Block block = this.getState(blockpos$mutableblockpos.set(k1, l1, i2)).getBlock(); - if(block.getMaterial() != Material.air) { + if(block != Blocks.air) { return true; } } @@ -2300,15 +2348,21 @@ public final class WorldServer extends World { } public BlockPos getTopSolidOrLiquidBlock(BlockPos pos) { - Chunk chunk = this.getChunk(pos); - BlockPos blockpos; + ChunkServer chunk = this.getChunk(pos); + int h = chunk.getTopSegment(); + if(h == Integer.MIN_VALUE) + return new BlockPos(pos.getX(), 0, pos.getZ()); + BlockPos blockpos = new BlockPos(pos.getX(), h + 16, pos.getZ()); BlockPos blockpos1; + h = chunk.getBottomSegment(); + if(blockpos.getY() - h > 512) + h = blockpos.getY() - 512; - for(blockpos = new BlockPos(pos.getX(), chunk.getTopSegment() + 16, pos.getZ()); blockpos.getY() >= 0; blockpos = blockpos1) { + for(; blockpos.getY() >= h; blockpos = blockpos1) { blockpos1 = blockpos.down(); Material material = chunk.getBlock(blockpos1).getMaterial(); - if(material.blocksMovement() && material != Material.leaves) { + if(material.blocksMovement() && material != Material.LEAVES) { break; } } @@ -2349,7 +2403,7 @@ public final class WorldServer extends World { } private File getSaveFile(String id) { - return new File(this.chunkDir, id.toLowerCase() + ".nbt"); + return new File(this.chunkDir, id.toLowerCase() + ".cdt"); } private WorldSavedData loadData(String id) { @@ -2359,16 +2413,7 @@ public final class WorldServer extends World { try { File file = this.getSaveFile(id); if(file.exists()) { -// try { - data = new WorldSavedData(id, NBTLoader.readGZip(file)); -// } -// catch(Exception re) { -// throw new RuntimeException("Konnte " + clazz.toString() + " nicht instanzieren", re); -// } -// FileInputStream in = new FileInputStream(file); -// NBTTagCompound tag = ; -// in.close(); -// data.readFromNBT(tag.getCompoundTag("data")); + data = new WorldSavedData(id, TagObject.readGZip(file)); } } catch(Exception e) { @@ -2392,13 +2437,7 @@ public final class WorldServer extends World { private void saveData(WorldSavedData data) { try { File file = this.getSaveFile(data.id); -// NBTTagCompound tag = new NBTTagCompound(); -// data.writeToNBT(tag); -// NBTTagCompound dtag = new NBTTagCompound(); -// dtag.setTag("data", tag); -// FileOutputStream out = new FileOutputStream(file); - NBTLoader.writeGZip(data.tag, file); -// out.close(); + TagObject.writeGZip(data.tag, file); } catch(Exception e) { e.printStackTrace(); @@ -2637,29 +2676,56 @@ public final class WorldServer extends World { // return true; } - private static class EventList extends ArrayList { + public List getAllPlayers() { + return (List)this.server.getPlayers(); + } + + public void placeInDimension(Entity entity, AWorldServer oldWorld, AWorldServer world, BlockPos pos, PortalType portal) { + this.server.placeInDimension(entity, (WorldServer)oldWorld, (WorldServer)world, pos, portal); + } + + public AWorldServer getOtherWorld(int dimension) { + return this.server.getWorld(dimension); + } + + public void markChunkDirty(BlockPos pos) { + if(this.isBlockLoaded(pos)) + this.getChunk(pos).setModified(true); + } + + private static class EventList extends ArrayList { private EventList() { } } public static class WorldSavedData { public final String id; - public final NBTTagCompound tag; + public final TagObject tag; public boolean dirty; - public WorldSavedData(String id, NBTTagCompound tag) { + public WorldSavedData(String id, TagObject tag) { this.id = id; this.tag = tag; } } + + private static SPacketMultiBlockChange getPacket(int amount, long[] list, ChunkServer chunk) { + ChunkPos pos = new ChunkPos(chunk.xPos, chunk.zPos); + SPacketMultiBlockChange.BlockUpdateData[] changes = new SPacketMultiBlockChange.BlockUpdateData[amount]; + for(int z = 0; z < changes.length; z++) { + changes[z] = new SPacketMultiBlockChange.BlockUpdateData(list[z], chunk.getState(SPacketMultiBlockChange.getPos(pos, list[z]))); + } + return new SPacketMultiBlockChange(pos, changes); + } private class PlayerInstance { private final List watching = Lists.newArrayList(); + private final Set extend = Sets.newHashSet(); + private final long[] changes = new long[64]; private final ChunkPos position; - private int[] changes = new int[64]; + private int updates; - private int sections; private long prevTime; private boolean biomes; @@ -2670,7 +2736,7 @@ public final class WorldServer extends World { public void addPlayer(EntityNPC player) { if(this.watching.contains(player)) { - Log.JNI.warn("Konnte Spieler nicht hinzufügen. #" + player.getId() + " ist bereits in Chunk " + this.position.x + ", " + Log.TICK.warn("Konnte Spieler nicht hinzufügen. #" + player.getId() + " ist bereits in Chunk " + this.position.x + ", " + this.position.z); } else { @@ -2679,20 +2745,20 @@ public final class WorldServer extends World { } this.watching.add(player); - player.connection.loadedChunks.add(this.position); + player.connection.getLoadedChunkList().add(this.position); } } public void removePlayer(EntityNPC player) { if(this.watching.contains(player)) { - Chunk chunk = WorldServer.this.getChunk(this.position.x, this.position.z); + ChunkServer chunk = WorldServer.this.getChunk(this.position.x, this.position.z); if(chunk.isPopulated()) { - player.connection.sendPacket(new SPacketChunkData(chunk, true, 0)); + player.connection.sendPacket(Player.getPacket(chunk, true, new int[0], !WorldServer.this.dimension.hasNoLight())); } this.watching.remove(player); - player.connection.loadedChunks.remove(this.position); + player.connection.getLoadedChunkList().remove(this.position); if(this.watching.isEmpty()) { long v = (long)this.position.x + 2147483647L | (long)this.position.z + 2147483647L << 32; @@ -2717,11 +2783,10 @@ public final class WorldServer extends World { if(this.updates == 0) WorldServer.this.toUpdate.add(this); this.updates = 64; - this.sections = 0xffffffff; this.biomes = true; } - private void increaseInhabitedTime(Chunk chunk) { + private void increaseInhabitedTime(ChunkServer chunk) { chunk.setInhabited(chunk.getInhabited() + WorldServer.this.time - this.prevTime); this.prevTime = WorldServer.this.time; } @@ -2731,10 +2796,10 @@ public final class WorldServer extends World { WorldServer.this.toUpdate.add(this); } - this.sections |= 1 << (y >> 4); + this.extend.add(y >> 4); if(this.updates < 64) { - int pos = x << 13 | z << 9 | y; + long pos = ((long)x & 4294967295L) << 36 | ((long)z & 4294967295L) << 32 | (y & 4294967295L); for(int i = 0; i < this.updates; ++i) { if(this.changes[i] == pos) { @@ -2750,7 +2815,7 @@ public final class WorldServer extends World { for(int z = 0; z < this.watching.size(); ++z) { EntityNPC player = this.watching.get(z); - if(!player.connection.loadedChunks.contains(this.position)) { + if(!player.connection.getLoadedChunkList().contains(this.position)) { player.connection.sendPacket(packet); } } @@ -2759,9 +2824,9 @@ public final class WorldServer extends World { public void onUpdate() { if(this.updates != 0) { if(this.updates == 1) { - int x = (this.changes[0] >> 13 & 15) + this.position.x * 16; - int y = this.changes[0] & 511; - int z = (this.changes[0] >> 9 & 15) + this.position.z * 16; + int x = (int)(this.changes[0] >> 36 & 15L) + this.position.x * 16; + int y = (int)(this.changes[0] & 4294967295L); + int z = (int)(this.changes[0] >> 32 & 15L) + this.position.z * 16; BlockPos pos = new BlockPos(x, y, z); this.sendToAllPlayersWatchingChunk(new SPacketBlockChange(WorldServer.this, pos)); @@ -2772,11 +2837,26 @@ public final class WorldServer extends World { else if(this.updates == 64) { int x = this.position.x * 16; int z = this.position.z * 16; - this.sendToAllPlayersWatchingChunk(new SPacketChunkData(WorldServer.this.getChunk(this.position.x, this.position.z), - this.biomes, this.sections)); + int[] extend = null; + if(!this.biomes) { + extend = new int[this.extend.size()]; + int n = 0; + for(Integer i : this.extend) { + extend[n++] = i; + } + } + this.sendToAllPlayersWatchingChunk(Player.getPacket(WorldServer.this.getChunk(this.position.x, this.position.z), + this.biomes, extend, !WorldServer.this.dimension.hasNoLight())); + + if(this.biomes) { + List list = WorldServer.this.getTileEntitiesIn(x, Integer.MIN_VALUE, z, x + 16, Integer.MAX_VALUE, z + 16); - for(int cy = 0; cy < 32; ++cy) { - if((this.sections & 1 << cy) != 0) { + for(int n = 0; n < list.size(); ++n) { + this.sendTileToAllPlayersWatchingChunk(list.get(n)); + } + } + else { + for(Integer cy : this.extend) { int y = cy << 4; List list = WorldServer.this.getTileEntitiesIn(x, y, z, x + 16, y + 16, z + 16); @@ -2787,13 +2867,13 @@ public final class WorldServer extends World { } } else { - this.sendToAllPlayersWatchingChunk(new SPacketMultiBlockChange(this.updates, this.changes, + this.sendToAllPlayersWatchingChunk(getPacket(this.updates, this.changes, WorldServer.this.getChunk(this.position.x, this.position.z))); for(int n = 0; n < this.updates; ++n) { - int x = (this.changes[n] >> 13 & 15) + this.position.x * 16; - int y = this.changes[n] & 511; - int z = (this.changes[n] >> 9 & 15) + this.position.z * 16; + int x = (int)(this.changes[n] >> 36 & 15L) + this.position.x * 16; + int y = (int)(this.changes[n] & 4294967295L); + int z = (int)(this.changes[n] >> 32 & 15L) + this.position.z * 16; BlockPos pos = new BlockPos(x, y, z); if(WorldServer.this.getState(pos).getBlock().hasTileEntity()) { @@ -2803,7 +2883,7 @@ public final class WorldServer extends World { } this.updates = 0; - this.sections = 0; + this.extend.clear(); this.biomes = false; } } diff --git a/java/src/game/worldgen/BiomeGenLayered.java b/server/src/main/java/server/worldgen/BiomeGenLayered.java similarity index 87% rename from java/src/game/worldgen/BiomeGenLayered.java rename to server/src/main/java/server/worldgen/BiomeGenLayered.java index 74f666d..7c03681 100755 --- a/java/src/game/worldgen/BiomeGenLayered.java +++ b/server/src/main/java/server/worldgen/BiomeGenLayered.java @@ -1,33 +1,32 @@ -package game.worldgen; +package server.worldgen; import java.util.List; import java.util.Set; -import game.collect.Lists; - -import game.biome.Biome; -import game.world.BlockPos; -import game.world.LongHashMap; -import game.worldgen.layer.GenLayer; -import game.worldgen.layer.GenLayerAddAreas; -import game.worldgen.layer.GenLayerAddExtra; -import game.worldgen.layer.GenLayerAddSea; -import game.worldgen.layer.GenLayerAddSnow; -import game.worldgen.layer.GenLayerBase; -import game.worldgen.layer.GenLayerBiome; -import game.worldgen.layer.GenLayerBiomeEdge; -import game.worldgen.layer.GenLayerEdge; -import game.worldgen.layer.GenLayerFuzzyZoom; -import game.worldgen.layer.GenLayerHills; -import game.worldgen.layer.GenLayerRemoveEmpty; -import game.worldgen.layer.GenLayerRiver; -import game.worldgen.layer.GenLayerRiverInit; -import game.worldgen.layer.GenLayerRiverMix; -import game.worldgen.layer.GenLayerShore; -import game.worldgen.layer.GenLayerSmooth; -import game.worldgen.layer.GenLayerVoronoiZoom; -import game.worldgen.layer.GenLayerZoom; -import game.worldgen.layer.IntCache; +import common.biome.Biome; +import common.collect.Lists; +import common.util.BlockPos; +import common.util.LongHashMap; +import server.worldgen.layer.GenLayer; +import server.worldgen.layer.GenLayerAddAreas; +import server.worldgen.layer.GenLayerAddExtra; +import server.worldgen.layer.GenLayerAddSea; +import server.worldgen.layer.GenLayerAddSnow; +import server.worldgen.layer.GenLayerBase; +import server.worldgen.layer.GenLayerBiome; +import server.worldgen.layer.GenLayerBiomeEdge; +import server.worldgen.layer.GenLayerEdge; +import server.worldgen.layer.GenLayerFuzzyZoom; +import server.worldgen.layer.GenLayerHills; +import server.worldgen.layer.GenLayerRemoveEmpty; +import server.worldgen.layer.GenLayerRiver; +import server.worldgen.layer.GenLayerRiverInit; +import server.worldgen.layer.GenLayerRiverMix; +import server.worldgen.layer.GenLayerShore; +import server.worldgen.layer.GenLayerSmooth; +import server.worldgen.layer.GenLayerVoronoiZoom; +import server.worldgen.layer.GenLayerZoom; +import server.worldgen.layer.IntCache; public class BiomeGenLayered implements BiomeGenerator { private class CacheBlock @@ -176,7 +175,7 @@ public class BiomeGenLayered implements BiomeGenerator { int[] aint = this.biomeIndexLayer.getInts(x, z, width, length); for(int i = 0; i < width * length; ++i) { - Biome biome = Biome.getBiome(aint[i], Biome.DEF_BIOME); + Biome biome = Biome.getBiomeDef(aint[i]); listToReuse[i] = (double)biome.getFactor(); } } @@ -192,7 +191,7 @@ public class BiomeGenLayered implements BiomeGenerator { int[] aint = this.biomeIndexLayer.getInts(xPos, zPos, sizeX, sizeZ); for(int i = 0; i < sizeX * sizeZ; ++i) { - Biome biome = Biome.getBiome(aint[i], Biome.DEF_BIOME); + Biome biome = Biome.getBiomeDef(aint[i]); factors[i] = (double)biome.getFactor(); } } @@ -204,7 +203,7 @@ public class BiomeGenLayered implements BiomeGenerator { int[] aint = this.genBiomes.getInts(x, z, width, height); for(int i = 0; i < width * height; ++i) { - biomes[i] = Biome.getBiome(aint[i], Biome.DEF_BIOME); + biomes[i] = Biome.getBiomeDef(aint[i]); } } @@ -223,7 +222,7 @@ public class BiomeGenLayered implements BiomeGenerator { int[] aint = this.biomeIndexLayer.getInts(x, z, width, length); for(int i = 0; i < width * length; ++i) { - listToReuse[i] = Biome.getBiome(aint[i], Biome.DEF_BIOME); + listToReuse[i] = Biome.getBiomeDef(aint[i]); } } } diff --git a/java/src/game/worldgen/BiomeGenPerlin.java b/server/src/main/java/server/worldgen/BiomeGenPerlin.java similarity index 93% rename from java/src/game/worldgen/BiomeGenPerlin.java rename to server/src/main/java/server/worldgen/BiomeGenPerlin.java index 4ff7756..3cde62c 100755 --- a/java/src/game/worldgen/BiomeGenPerlin.java +++ b/server/src/main/java/server/worldgen/BiomeGenPerlin.java @@ -1,7 +1,7 @@ -package game.worldgen; +package server.worldgen; -import game.rng.PerlinGenOld; -import game.rng.Random; +import common.rng.PerlinGenOld; +import common.rng.Random; public class BiomeGenPerlin { private final PerlinGenOld tempNoiseGen; diff --git a/java/src/game/worldgen/BiomeGenSingle.java b/server/src/main/java/server/worldgen/BiomeGenSingle.java similarity index 94% rename from java/src/game/worldgen/BiomeGenSingle.java rename to server/src/main/java/server/worldgen/BiomeGenSingle.java index 15462fc..cd5bade 100755 --- a/java/src/game/worldgen/BiomeGenSingle.java +++ b/server/src/main/java/server/worldgen/BiomeGenSingle.java @@ -1,10 +1,10 @@ -package game.worldgen; +package server.worldgen; import java.util.Arrays; import java.util.Set; -import game.biome.Biome; -import game.world.BlockPos; +import common.biome.Biome; +import common.util.BlockPos; public class BiomeGenSingle implements BiomeGenerator { private final Biome biome; diff --git a/java/src/game/worldgen/BiomeGenerator.java b/server/src/main/java/server/worldgen/BiomeGenerator.java similarity index 87% rename from java/src/game/worldgen/BiomeGenerator.java rename to server/src/main/java/server/worldgen/BiomeGenerator.java index 80f8d11..6d75568 100755 --- a/java/src/game/worldgen/BiomeGenerator.java +++ b/server/src/main/java/server/worldgen/BiomeGenerator.java @@ -1,9 +1,9 @@ -package game.worldgen; +package server.worldgen; import java.util.Set; -import game.biome.Biome; -import game.world.BlockPos; +import common.biome.Biome; +import common.util.BlockPos; public interface BiomeGenerator { public void genFactors(double[] factors, int xPos, int zPos, int sizeX, int sizeZ); diff --git a/java/src/game/worldgen/BlockReplacer.java b/server/src/main/java/server/worldgen/BlockReplacer.java similarity index 55% rename from java/src/game/worldgen/BlockReplacer.java rename to server/src/main/java/server/worldgen/BlockReplacer.java index 3ccc8f5..ab5cb4e 100755 --- a/java/src/game/worldgen/BlockReplacer.java +++ b/server/src/main/java/server/worldgen/BlockReplacer.java @@ -1,8 +1,8 @@ -package game.worldgen; +package server.worldgen; -import game.biome.Biome; -import game.rng.Random; -import game.world.WorldServer; +import common.biome.Biome; +import common.rng.Random; +import server.world.WorldServer; public interface BlockReplacer { public void replaceBlocks(WorldServer world, int x, int z, ChunkPrimer primer, Random rand, Biome[] biomes); diff --git a/java/src/game/worldgen/ChunkGenerator.java b/server/src/main/java/server/worldgen/ChunkGenerator.java similarity index 69% rename from java/src/game/worldgen/ChunkGenerator.java rename to server/src/main/java/server/worldgen/ChunkGenerator.java index d7d14ac..fd6f685 100755 --- a/java/src/game/worldgen/ChunkGenerator.java +++ b/server/src/main/java/server/worldgen/ChunkGenerator.java @@ -1,6 +1,6 @@ -package game.worldgen; +package server.worldgen; -import game.world.WorldServer; +import server.world.WorldServer; public interface ChunkGenerator { public void generateChunk(WorldServer world, int x, int z, ChunkPrimer primer); diff --git a/java/src/game/worldgen/ChunkPrimer.java b/server/src/main/java/server/worldgen/ChunkPrimer.java similarity index 75% rename from java/src/game/worldgen/ChunkPrimer.java rename to server/src/main/java/server/worldgen/ChunkPrimer.java index 2053420..7372177 100755 --- a/java/src/game/worldgen/ChunkPrimer.java +++ b/server/src/main/java/server/worldgen/ChunkPrimer.java @@ -1,8 +1,8 @@ -package game.worldgen; +package server.worldgen; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.world.State; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.world.State; public class ChunkPrimer { public final int height; @@ -12,6 +12,10 @@ public class ChunkPrimer { this.data = new short[Math.max(height, 256) * 256]; this.height = height; } + + public short[] getData() { + return this.data; + } public State get(int x, int y, int z) { State state = BlockRegistry.STATEMAP.getByValue(this.data[x << 4 | z | y << 8]); diff --git a/java/src/game/worldgen/FeatureDungeons.java b/server/src/main/java/server/worldgen/FeatureDungeons.java similarity index 75% rename from java/src/game/worldgen/FeatureDungeons.java rename to server/src/main/java/server/worldgen/FeatureDungeons.java index c63e856..719f09b 100755 --- a/java/src/game/worldgen/FeatureDungeons.java +++ b/server/src/main/java/server/worldgen/FeatureDungeons.java @@ -1,22 +1,28 @@ -package game.worldgen; +package server.worldgen; -import game.init.Blocks; -import game.init.Items; -import game.item.RngLoot; -import game.log.Log; -import game.material.Material; -import game.rng.Random; -import game.rng.WeightedList; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityChest; -import game.tileentity.TileEntityMobSpawner; -import game.world.BlockPos; -import game.world.Facing; -import game.world.WorldServer; +import java.lang.reflect.InvocationTargetException; + +import common.block.Material; +import common.entity.npc.EntityArachnoid; +import common.entity.npc.EntityUndead; +import common.entity.npc.EntityZombie; +import common.entity.types.EntityLiving; +import common.init.Blocks; +import common.init.Items; +import common.item.RngLoot; +import common.rng.Random; +import common.rng.WeightedList; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityChest; +import common.util.BlockPos; +import common.util.Facing; +import common.world.World; +import server.vars.SVars; +import server.world.WorldServer; public class FeatureDungeons { - private static final String[] SPAWNERTYPES = new String[] {"Undead", "Zombie", "Zombie", "Arachnoid"}; + private static final Class[] MOB_TYPES = new Class[] {EntityUndead.class, EntityZombie.class, EntityZombie.class, EntityArachnoid.class}; private final int chance; @@ -148,16 +154,15 @@ public class FeatureDungeons } } - worldIn.setState(position, Blocks.mob_spawner.getState(), 2); - TileEntity tileentity = worldIn.getTileEntity(position); - - if (tileentity instanceof TileEntityMobSpawner) - { - ((TileEntityMobSpawner)tileentity).setEntityName(this.pickMobSpawner(rand)); - } - else - { - Log.JNI.warn("Konnte kein Mob-Spawner-Objekt bei (" + position.getX() + ", " + position.getY() + ", " + position.getZ() + ") erstellen"); + if(SVars.mobs && SVars.spawnDungeonMobs > 0) { + for(int z = 0; z < SVars.spawnDungeonMobs; z++) { + EntityLiving entity = this.pickMobSpawner(rand, worldIn); + entity.setLocationAndAngles((double)position.getX() + rand.doublev(), (double)position.getY(), (double)position.getZ() + rand.doublev(), worldIn.rand.floatv() * 360.0F, 0.0F); + entity.onInitialSpawn(null); + worldIn.spawnEntityInWorld(entity); + if(rand.chance(5)) + break; + } } return true; @@ -168,11 +173,13 @@ public class FeatureDungeons } } - /** - * Randomly decides which spawner to use in a dungeon - */ - private String pickMobSpawner(Random p_76543_1_) + private EntityLiving pickMobSpawner(Random rand, WorldServer world) { - return SPAWNERTYPES[p_76543_1_.zrange(SPAWNERTYPES.length)]; + try { + return rand.pick(MOB_TYPES).getConstructor(World.class).newInstance(world); + } + catch(InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) { + throw new RuntimeException(e); + } } } diff --git a/java/src/game/worldgen/FeatureGenerator.java b/server/src/main/java/server/worldgen/FeatureGenerator.java similarity index 81% rename from java/src/game/worldgen/FeatureGenerator.java rename to server/src/main/java/server/worldgen/FeatureGenerator.java index 252d686..95f6331 100755 --- a/java/src/game/worldgen/FeatureGenerator.java +++ b/server/src/main/java/server/worldgen/FeatureGenerator.java @@ -1,9 +1,9 @@ -package game.worldgen; +package server.worldgen; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; public abstract class FeatureGenerator { diff --git a/java/src/game/worldgen/FeatureLakes.java b/server/src/main/java/server/worldgen/FeatureLakes.java similarity index 94% rename from java/src/game/worldgen/FeatureLakes.java rename to server/src/main/java/server/worldgen/FeatureLakes.java index dd1c3e5..2f6fa82 100755 --- a/java/src/game/worldgen/FeatureLakes.java +++ b/server/src/main/java/server/worldgen/FeatureLakes.java @@ -1,14 +1,14 @@ -package game.worldgen; +package server.worldgen; -import game.biome.Biome; -import game.block.Block; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.LightType; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.world.LightType; +import common.world.State; +import server.biome.GenBiome; +import server.world.WorldServer; public class FeatureLakes { @@ -163,7 +163,7 @@ public class FeatureLakes if (worldIn.getState(blockpos).getBlock() == replace && worldIn.getLightFor(LightType.SKY, position.add(i2, j4, j3)) > 0) { - Biome biomegenbase = worldIn.getBiomeGenForCoords(blockpos); + GenBiome biomegenbase = GenBiome.BIOMES[worldIn.getBiomeGenForCoords(blockpos).id]; if (biomegenbase.topBlock.getBlock() == Blocks.mycelium) { @@ -199,7 +199,7 @@ public class FeatureLakes } } - if (this.block.getMaterial() == Material.water) + if (this.block.getMaterial() == Material.WATER) { for (int k2 = 0; k2 < 16; ++k2) { diff --git a/java/src/game/worldgen/FeatureLiquids.java b/server/src/main/java/server/worldgen/FeatureLiquids.java similarity index 91% rename from java/src/game/worldgen/FeatureLiquids.java rename to server/src/main/java/server/worldgen/FeatureLiquids.java index 27c9abc..69f5871 100755 --- a/java/src/game/worldgen/FeatureLiquids.java +++ b/server/src/main/java/server/worldgen/FeatureLiquids.java @@ -1,11 +1,11 @@ -package game.worldgen; +package server.worldgen; -import game.block.Block; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; public class FeatureLiquids { @@ -66,7 +66,7 @@ public class FeatureLiquids { return false; } - else if (worldIn.getState(position).getBlock().getMaterial() != Material.air && worldIn.getState(position).getBlock() != replace) + else if (worldIn.getState(position).getBlock() != Blocks.air && worldIn.getState(position).getBlock() != replace) { return false; } diff --git a/java/src/game/worldgen/FeatureOres.java b/server/src/main/java/server/worldgen/FeatureOres.java similarity index 88% rename from java/src/game/worldgen/FeatureOres.java rename to server/src/main/java/server/worldgen/FeatureOres.java index 3383655..bd61fc6 100755 --- a/java/src/game/worldgen/FeatureOres.java +++ b/server/src/main/java/server/worldgen/FeatureOres.java @@ -1,11 +1,12 @@ -package game.worldgen; +package server.worldgen; -import game.block.Block; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.State; +import common.world.World; +import server.world.WorldServer; public class FeatureOres { @@ -41,18 +42,18 @@ public class FeatureOres this.oreBlock = state; this.distributed = dist; if(this.distributed) { - min = min < 0 ? 0 : (min > 511 ? 511 : min); - max = max < 0 ? 0 : (max > 512 ? 512 : max); - if(min + max > 511) { - max = 512 - min; + min = min < -World.MAX_SIZE_Y ? -World.MAX_SIZE_Y : (min > World.MAX_SIZE_Y - 1 ? World.MAX_SIZE_Y - 1 : min); + max = max < -World.MAX_SIZE_Y ? -World.MAX_SIZE_Y : (max > World.MAX_SIZE_Y ? World.MAX_SIZE_Y : max); + if(min + max > World.MAX_SIZE_Y - 1) { + max = World.MAX_SIZE_Y - min; } if(min - max < 0) { max = min; } } else { - min = min < 0 ? 0 : (min > 512 ? 512 : min); - max = max < 0 ? 0 : (max > 512 ? 512 : max); + min = min < -World.MAX_SIZE_Y ? -World.MAX_SIZE_Y : (min > World.MAX_SIZE_Y ? World.MAX_SIZE_Y : min); + max = max < -World.MAX_SIZE_Y ? -World.MAX_SIZE_Y : (max > World.MAX_SIZE_Y ? World.MAX_SIZE_Y : max); if (max < min) { int i = min; @@ -61,7 +62,7 @@ public class FeatureOres } else if (max == min) { - if (min < 511) + if (min < World.MAX_SIZE_Y - 1) { ++max; } diff --git a/java/src/game/worldgen/GeneratorCavern.java b/server/src/main/java/server/worldgen/GeneratorCavern.java similarity index 97% rename from java/src/game/worldgen/GeneratorCavern.java rename to server/src/main/java/server/worldgen/GeneratorCavern.java index adec0aa..12f221b 100755 --- a/java/src/game/worldgen/GeneratorCavern.java +++ b/server/src/main/java/server/worldgen/GeneratorCavern.java @@ -1,10 +1,10 @@ -package game.worldgen; +package server.worldgen; -import game.rng.OctaveGen; -import game.rng.Random; -import game.util.ExtMath; -import game.world.State; -import game.world.WorldServer; +import common.rng.OctaveGen; +import common.rng.Random; +import common.util.ExtMath; +import common.world.State; +import server.world.WorldServer; public class GeneratorCavern implements ChunkGenerator { diff --git a/java/src/game/worldgen/GeneratorDestroyed.java b/server/src/main/java/server/worldgen/GeneratorDestroyed.java similarity index 86% rename from java/src/game/worldgen/GeneratorDestroyed.java rename to server/src/main/java/server/worldgen/GeneratorDestroyed.java index 03ae28b..cfaf319 100755 --- a/java/src/game/worldgen/GeneratorDestroyed.java +++ b/server/src/main/java/server/worldgen/GeneratorDestroyed.java @@ -1,9 +1,9 @@ -package game.worldgen; +package server.worldgen; -import game.init.Blocks; -import game.rng.Random; -import game.world.State; -import game.world.WorldServer; +import common.init.Blocks; +import common.rng.Random; +import common.world.State; +import server.world.WorldServer; public class GeneratorDestroyed implements ChunkGenerator { diff --git a/java/src/game/worldgen/GeneratorFlat.java b/server/src/main/java/server/worldgen/GeneratorFlat.java similarity index 90% rename from java/src/game/worldgen/GeneratorFlat.java rename to server/src/main/java/server/worldgen/GeneratorFlat.java index 464e66a..668e651 100755 --- a/java/src/game/worldgen/GeneratorFlat.java +++ b/server/src/main/java/server/worldgen/GeneratorFlat.java @@ -1,9 +1,9 @@ -package game.worldgen; +package server.worldgen; import java.util.Arrays; -import game.world.State; -import game.world.WorldServer; +import common.world.State; +import server.world.WorldServer; public class GeneratorFlat implements ChunkGenerator { private final State[] layers; diff --git a/java/src/game/worldgen/GeneratorIsland.java b/server/src/main/java/server/worldgen/GeneratorIsland.java similarity index 97% rename from java/src/game/worldgen/GeneratorIsland.java rename to server/src/main/java/server/worldgen/GeneratorIsland.java index f202525..639b28e 100755 --- a/java/src/game/worldgen/GeneratorIsland.java +++ b/server/src/main/java/server/worldgen/GeneratorIsland.java @@ -1,10 +1,10 @@ -package game.worldgen; +package server.worldgen; -import game.rng.OctaveGen; -import game.rng.Random; -import game.util.ExtMath; -import game.world.State; -import game.world.WorldServer; +import common.rng.OctaveGen; +import common.rng.Random; +import common.util.ExtMath; +import common.world.State; +import server.world.WorldServer; public class GeneratorIsland implements ChunkGenerator { diff --git a/java/src/game/worldgen/GeneratorPerlin.java b/server/src/main/java/server/worldgen/GeneratorPerlin.java similarity index 95% rename from java/src/game/worldgen/GeneratorPerlin.java rename to server/src/main/java/server/worldgen/GeneratorPerlin.java index 2b4ff2d..e02d8ee 100755 --- a/java/src/game/worldgen/GeneratorPerlin.java +++ b/server/src/main/java/server/worldgen/GeneratorPerlin.java @@ -1,13 +1,14 @@ -package game.worldgen; +package server.worldgen; -import game.biome.Biome; -import game.dimension.Dimension; -import game.rng.NoiseGen; -import game.rng.OctaveGen; -import game.rng.Random; -import game.util.ExtMath; -import game.world.State; -import game.world.WorldServer; +import common.biome.Biome; +import common.dimension.Dimension; +import common.rng.NoiseGen; +import common.rng.OctaveGen; +import common.rng.Random; +import common.util.ExtMath; +import common.world.State; +import server.biome.GenBiome; +import server.world.WorldServer; public class GeneratorPerlin implements ChunkGenerator { @@ -196,13 +197,13 @@ public class GeneratorPerlin implements ChunkGenerator float min = 0.0F; float sum = 0.0F; int range = 2; - Biome biome = this.biomes[u + 2 + (v + 2) * 10]; + GenBiome biome = GenBiome.BIOMES[this.biomes[u + 2 + (v + 2) * 10].id]; for (int a = -range; a <= range; ++a) { for (int b = -range; b <= range; ++b) { - Biome biome2 = this.biomes[u + a + 2 + (v + b + 2) * 10]; + GenBiome biome2 = GenBiome.BIOMES[this.biomes[u + a + 2 + (v + b + 2) * 10].id]; float bmin = this.biomeDepthOffset + biome2.depth * this.biomeDepthWeight; float bmax = this.biomeScaleOffset + biome2.scale * this.biomeScaleWeight; diff --git a/java/src/game/worldgen/GeneratorSimple.java b/server/src/main/java/server/worldgen/GeneratorSimple.java similarity index 95% rename from java/src/game/worldgen/GeneratorSimple.java rename to server/src/main/java/server/worldgen/GeneratorSimple.java index deec5a5..0f84201 100755 --- a/java/src/game/worldgen/GeneratorSimple.java +++ b/server/src/main/java/server/worldgen/GeneratorSimple.java @@ -1,10 +1,10 @@ -package game.worldgen; +package server.worldgen; -import game.rng.NoiseGen; -import game.rng.OctaveGen; -import game.rng.Random; -import game.world.State; -import game.world.WorldServer; +import common.rng.NoiseGen; +import common.rng.OctaveGen; +import common.rng.Random; +import common.world.State; +import server.world.WorldServer; public class GeneratorSimple implements ChunkGenerator { diff --git a/java/src/game/worldgen/LootConstants.java b/server/src/main/java/server/worldgen/LootConstants.java similarity index 72% rename from java/src/game/worldgen/LootConstants.java rename to server/src/main/java/server/worldgen/LootConstants.java index 5eb0b1e..a26738f 100755 --- a/java/src/game/worldgen/LootConstants.java +++ b/server/src/main/java/server/worldgen/LootConstants.java @@ -1,40 +1,13 @@ -package game.worldgen; +package server.worldgen; -import game.biome.RngSpawn; -import game.color.DyeColor; -import game.entity.npc.EntityDarkMage; -import game.entity.npc.EntityMage; -import game.entity.npc.EntityMagma; -import game.entity.npc.EntityTiefling; -import game.entity.npc.EntityUndead; -import game.entity.projectile.RngFishable; -import game.init.Blocks; -import game.init.ItemRegistry; -import game.init.Items; -import game.item.ItemFishFood; -import game.item.ItemStack; -import game.item.RngLoot; -import game.rng.WeightedList; +import common.color.DyeColor; +import common.init.Blocks; +import common.init.ItemRegistry; +import common.init.Items; +import common.item.RngLoot; +import common.rng.WeightedList; public abstract class LootConstants { - public static final WeightedList FISHING_JUNK = new WeightedList( - (new RngFishable(new ItemStack(Items.leather_boots), 10)).setMaxDamagePercent(0.9F), new RngFishable(new ItemStack(Items.leather), 10), - new RngFishable(new ItemStack(Items.bone), 10), new RngFishable(new ItemStack(Items.potion), 10), - new RngFishable(new ItemStack(Items.string), 5), (new RngFishable(new ItemStack(Items.fishing_rod), 2)).setMaxDamagePercent(0.9F), - new RngFishable(new ItemStack(Items.bowl), 10), new RngFishable(new ItemStack(Items.stick), 5), - new RngFishable(new ItemStack(Items.dye, 10, DyeColor.BLACK.getDyeDamage()), 1), - new RngFishable(new ItemStack(Blocks.tripwire_hook), 10), new RngFishable(new ItemStack(Items.rotten_flesh), 10)); - public static final WeightedList FISHING_TREASURE = new WeightedList( - new RngFishable(new ItemStack(Blocks.waterlily), 1), new RngFishable(new ItemStack(Items.name_tag), 1), - new RngFishable(new ItemStack(Items.saddle), 1), - (new RngFishable(new ItemStack(Items.bow), 1)).setMaxDamagePercent(0.25F).setEnchantable(), - (new RngFishable(new ItemStack(Items.fishing_rod), 1)).setMaxDamagePercent(0.25F).setEnchantable(), - (new RngFishable(new ItemStack(Items.book), 1)).setEnchantable()); - public static final WeightedList FISH_TYPES = new WeightedList( - new RngFishable(new ItemStack(Items.fish, 1, ItemFishFood.FishType.COD.getMetadata()), 60), - new RngFishable(new ItemStack(Items.fish, 1, ItemFishFood.FishType.SALMON.getMetadata()), 25), - new RngFishable(new ItemStack(Items.fish, 1, ItemFishFood.FishType.CLOWNFISH.getMetadata()), 2), - new RngFishable(new ItemStack(Items.fish, 1, ItemFishFood.FishType.PUFFERFISH.getMetadata()), 13)); public static final WeightedList VILLAGE_BLACKSMITH = new WeightedList(new RngLoot(Items.diamond, 0, 1, 3, 3), new RngLoot(Items.iron_ingot, 0, 1, 5, 10), new RngLoot(Items.gold_ingot, 0, 1, 3, 5), new RngLoot(Items.bread, 0, 1, 3, 15), new RngLoot(Items.apple, 0, 1, 3, 15), new RngLoot(Items.iron_pickaxe, 0, 1, 1, 5), new RngLoot(Items.iron_sword, 0, 1, 1, 5), @@ -95,8 +68,4 @@ public abstract class LootConstants { new RngLoot(Items.wood_axe, 0, 1, 1, 5), new RngLoot(Items.stone_pickaxe, 0, 1, 1, 3), new RngLoot(Items.wood_pickaxe, 0, 1, 1, 5), new RngLoot(Items.apple, 0, 2, 3, 5), new RngLoot(Items.bread, 0, 2, 3, 3), new RngLoot(ItemRegistry.getItemFromBlock(Blocks.acacia_log), 0, 1, 3, 10)); - public static final WeightedList MAGEHUT_MOBS = new WeightedList(new RngSpawn(EntityMage.class, 1, 1, 1)); - public static final WeightedList FORTRESS_MOBS = new WeightedList(new RngSpawn(EntityDarkMage.class, 10, 2, 3), - new RngSpawn(EntityTiefling.class, 5, 4, 4), new RngSpawn(EntityUndead.class, 10, 4, 4), - new RngSpawn(EntityMagma.class, 3, 4, 4)); } diff --git a/server/src/main/java/server/worldgen/MobConstants.java b/server/src/main/java/server/worldgen/MobConstants.java new file mode 100644 index 0000000..38b9ab5 --- /dev/null +++ b/server/src/main/java/server/worldgen/MobConstants.java @@ -0,0 +1,16 @@ +package server.worldgen; + +import common.entity.npc.EntityDarkMage; +import common.entity.npc.EntityMage; +import common.entity.npc.EntityMagma; +import common.entity.npc.EntityTiefling; +import common.entity.npc.EntityUndead; +import common.rng.WeightedList; +import server.biome.RngSpawn; + +public abstract class MobConstants { + public static final WeightedList MAGEHUT_MOBS = new WeightedList(new RngSpawn(EntityMage.class, 1, 1, 1)); + public static final WeightedList FORTRESS_MOBS = new WeightedList(new RngSpawn(EntityDarkMage.class, 10, 2, 3), + new RngSpawn(EntityTiefling.class, 5, 4, 4), new RngSpawn(EntityUndead.class, 10, 4, 4), + new RngSpawn(EntityMagma.class, 3, 4, 4)); +} diff --git a/java/src/game/worldgen/ReplacerAltBiome.java b/server/src/main/java/server/worldgen/ReplacerAltBiome.java similarity index 91% rename from java/src/game/worldgen/ReplacerAltBiome.java rename to server/src/main/java/server/worldgen/ReplacerAltBiome.java index 45aa85a..8543e23 100755 --- a/java/src/game/worldgen/ReplacerAltBiome.java +++ b/server/src/main/java/server/worldgen/ReplacerAltBiome.java @@ -1,13 +1,14 @@ -package game.worldgen; +package server.worldgen; -import game.biome.Biome; -import game.block.Block; -import game.init.Blocks; -import game.rng.NoiseGen; -import game.rng.OctaveGen; -import game.rng.Random; -import game.world.State; -import game.world.WorldServer; +import common.biome.Biome; +import common.block.Block; +import common.init.Blocks; +import common.rng.NoiseGen; +import common.rng.OctaveGen; +import common.rng.Random; +import common.world.State; +import server.biome.GenBiome; +import server.world.WorldServer; public class ReplacerAltBiome implements BlockReplacer { @@ -57,7 +58,7 @@ public class ReplacerAltBiome implements BlockReplacer { for(int px = 0; px < 16; px++) { - Biome biome = biomes[pz * 16 + px]; + GenBiome biome = GenBiome.BIOMES[biomes[pz * 16 + px].id]; boolean alt2 = this.alt2Noise[pz + px * 16] + rand.doublev() * 0.20000000000000001D > 0.0D; boolean alt1 = this.alt1Noise[px + pz * 16] + rand.doublev() * 0.20000000000000001D > 3D; int excl = (int)(this.exclNoise[pz + px * 16] / 3D + 3D + rand.doublev() * 0.25D); diff --git a/java/src/game/worldgen/ReplacerAltSurface.java b/server/src/main/java/server/worldgen/ReplacerAltSurface.java similarity index 92% rename from java/src/game/worldgen/ReplacerAltSurface.java rename to server/src/main/java/server/worldgen/ReplacerAltSurface.java index 26f76b3..e3daac1 100755 --- a/java/src/game/worldgen/ReplacerAltSurface.java +++ b/server/src/main/java/server/worldgen/ReplacerAltSurface.java @@ -1,12 +1,12 @@ -package game.worldgen; +package server.worldgen; -import game.biome.Biome; -import game.block.Block; -import game.material.Material; -import game.rng.OctaveGen; -import game.rng.Random; -import game.world.State; -import game.world.WorldServer; +import common.biome.Biome; +import common.block.Block; +import common.init.Blocks; +import common.rng.OctaveGen; +import common.rng.Random; +import common.world.State; +import server.world.WorldServer; public class ReplacerAltSurface implements BlockReplacer { @@ -63,7 +63,7 @@ public class ReplacerAltSurface implements BlockReplacer // { State iblockstate2 = primer.get(k, j1, j); - if (iblockstate2.getBlock() != null && iblockstate2.getBlock().getMaterial() != Material.air) + if (iblockstate2.getBlock() != Blocks.air) { if (iblockstate2.getBlock() == this.fillerBlock) { @@ -92,7 +92,7 @@ public class ReplacerAltSurface implements BlockReplacer } } - if (j1 < i && (iblockstate == null || iblockstate.getBlock().getMaterial() == Material.air)) + if (j1 < i && (iblockstate == null || iblockstate.getBlock() == Blocks.air)) { iblockstate = this.liquid; } diff --git a/java/src/game/worldgen/ReplacerBiome.java b/server/src/main/java/server/worldgen/ReplacerBiome.java similarity index 75% rename from java/src/game/worldgen/ReplacerBiome.java rename to server/src/main/java/server/worldgen/ReplacerBiome.java index 74a8acb..894b8df 100755 --- a/java/src/game/worldgen/ReplacerBiome.java +++ b/server/src/main/java/server/worldgen/ReplacerBiome.java @@ -1,9 +1,10 @@ -package game.worldgen; +package server.worldgen; -import game.biome.Biome; -import game.rng.PerlinGen; -import game.rng.Random; -import game.world.WorldServer; +import common.biome.Biome; +import common.rng.PerlinGen; +import common.rng.Random; +import server.biome.GenBiome; +import server.world.WorldServer; public class ReplacerBiome implements BlockReplacer { @@ -24,7 +25,7 @@ public class ReplacerBiome implements BlockReplacer { for (int j = 0; j < 16; ++j) { - Biome biome = biomes[j + i * 16]; + GenBiome biome = GenBiome.BIOMES[biomes[j + i * 16].id]; biome.genTerrainBlocks(world, rand, primer, x * 16 + i, z * 16 + j, this.stoneNoise[j + i * 16]); } } diff --git a/java/src/game/worldgen/ReplacerTopLayer.java b/server/src/main/java/server/worldgen/ReplacerTopLayer.java similarity index 87% rename from java/src/game/worldgen/ReplacerTopLayer.java rename to server/src/main/java/server/worldgen/ReplacerTopLayer.java index ab62aa1..5f2a52c 100755 --- a/java/src/game/worldgen/ReplacerTopLayer.java +++ b/server/src/main/java/server/worldgen/ReplacerTopLayer.java @@ -1,12 +1,11 @@ -package game.worldgen; +package server.worldgen; -import game.biome.Biome; -import game.block.Block; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.State; -import game.world.WorldServer; +import common.biome.Biome; +import common.block.Block; +import common.init.Blocks; +import common.rng.Random; +import common.world.State; +import server.world.WorldServer; public class ReplacerTopLayer implements BlockReplacer { @@ -37,7 +36,7 @@ public class ReplacerTopLayer implements BlockReplacer { State iblockstate2 = primer.get(i, i1, j); - if (iblockstate2.getBlock().getMaterial() == Material.air) + if (iblockstate2.getBlock() == Blocks.air) { l = -1; } diff --git a/java/src/game/worldgen/caves/MapGenBase.java b/server/src/main/java/server/worldgen/caves/MapGenBase.java similarity index 90% rename from java/src/game/worldgen/caves/MapGenBase.java rename to server/src/main/java/server/worldgen/caves/MapGenBase.java index ecb6bec..a16f947 100755 --- a/java/src/game/worldgen/caves/MapGenBase.java +++ b/server/src/main/java/server/worldgen/caves/MapGenBase.java @@ -1,8 +1,8 @@ -package game.worldgen.caves; +package server.worldgen.caves; -import game.rng.Random; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; +import common.rng.Random; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; public class MapGenBase { diff --git a/java/src/game/worldgen/caves/MapGenBigCaves.java b/server/src/main/java/server/worldgen/caves/MapGenBigCaves.java similarity index 97% rename from java/src/game/worldgen/caves/MapGenBigCaves.java rename to server/src/main/java/server/worldgen/caves/MapGenBigCaves.java index a24947e..00cd451 100755 --- a/java/src/game/worldgen/caves/MapGenBigCaves.java +++ b/server/src/main/java/server/worldgen/caves/MapGenBigCaves.java @@ -1,12 +1,12 @@ -package game.worldgen.caves; +package server.worldgen.caves; -import game.block.Block; -import game.init.Blocks; -import game.rng.Random; -import game.util.ExtMath; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; +import common.block.Block; +import common.init.Blocks; +import common.rng.Random; +import common.util.ExtMath; +import common.world.State; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; public class MapGenBigCaves extends MapGenBase { diff --git a/java/src/game/worldgen/caves/MapGenCaves.java b/server/src/main/java/server/worldgen/caves/MapGenCaves.java similarity index 95% rename from java/src/game/worldgen/caves/MapGenCaves.java rename to server/src/main/java/server/worldgen/caves/MapGenCaves.java index c7fb66c..c3c67d4 100755 --- a/java/src/game/worldgen/caves/MapGenCaves.java +++ b/server/src/main/java/server/worldgen/caves/MapGenCaves.java @@ -1,16 +1,17 @@ -package game.worldgen.caves; +package server.worldgen.caves; -import game.block.Block; -import game.block.BlockColored; -import game.block.BlockSand; -import game.color.DyeColor; -import game.init.Blocks; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; +import common.block.Block; +import common.block.BlockColored; +import common.block.natural.BlockSand; +import common.color.DyeColor; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.State; +import server.biome.GenBiome; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; public class MapGenCaves extends MapGenBase { @@ -217,7 +218,7 @@ public class MapGenCaves extends MapGenBase if (flag1 && p_180702_5_.get(j3, j2 - 1, i2).getBlock() == this.top) { blockpos$mutableblockpos.set(j3 + p_180702_3_ * 16, 0, i2 + p_180702_4_ * 16); - p_180702_5_.set(j3, j2 - 1, i2, this.worldObj.getBiomeGenForCoords(blockpos$mutableblockpos).topBlock.getBlock().getState()); + p_180702_5_.set(j3, j2 - 1, i2, GenBiome.BIOMES[this.worldObj.getBiomeGenForCoords(blockpos$mutableblockpos).id].topBlock.getBlock().getState()); } } } diff --git a/java/src/game/worldgen/caves/MapGenRavine.java b/server/src/main/java/server/worldgen/caves/MapGenRavine.java similarity index 95% rename from java/src/game/worldgen/caves/MapGenRavine.java rename to server/src/main/java/server/worldgen/caves/MapGenRavine.java index a9e8958..8ac2336 100755 --- a/java/src/game/worldgen/caves/MapGenRavine.java +++ b/server/src/main/java/server/worldgen/caves/MapGenRavine.java @@ -1,13 +1,14 @@ -package game.worldgen.caves; +package server.worldgen.caves; -import game.block.Block; -import game.init.Blocks; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.ChunkPrimer; +import common.block.Block; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.State; +import server.biome.GenBiome; +import server.world.WorldServer; +import server.worldgen.ChunkPrimer; public class MapGenRavine extends MapGenBase { @@ -196,7 +197,7 @@ public class MapGenRavine extends MapGenBase if (flag && p_180707_5_.get(j3, j2 - 1, i2).getBlock() == this.top) { blockpos$mutableblockpos.set(j3 + p_180707_3_ * 16, 0, i2 + p_180707_4_ * 16); - p_180707_5_.set(j3, j2 - 1, i2, this.worldObj.getBiomeGenForCoords(blockpos$mutableblockpos).topBlock); + p_180707_5_.set(j3, j2 - 1, i2, GenBiome.BIOMES[this.worldObj.getBiomeGenForCoords(blockpos$mutableblockpos).id].topBlock); } } } diff --git a/java/src/game/worldgen/feature/WorldGenAbandonedChest.java b/server/src/main/java/server/worldgen/feature/WorldGenAbandonedChest.java similarity index 72% rename from java/src/game/worldgen/feature/WorldGenAbandonedChest.java rename to server/src/main/java/server/worldgen/feature/WorldGenAbandonedChest.java index 72bd27a..7e12f6b 100755 --- a/java/src/game/worldgen/feature/WorldGenAbandonedChest.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenAbandonedChest.java @@ -1,17 +1,17 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.block.Block; -import game.init.Blocks; -import game.item.RngLoot; -import game.material.Material; -import game.rng.Random; -import game.rng.WeightedList; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityChest; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; -import game.worldgen.LootConstants; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.item.RngLoot; +import common.rng.Random; +import common.rng.WeightedList; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityChest; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; +import server.worldgen.LootConstants; public class WorldGenAbandonedChest extends FeatureGenerator { @@ -33,7 +33,7 @@ public class WorldGenAbandonedChest extends FeatureGenerator public boolean generate(WorldServer worldIn, Random rand, BlockPos position) { Block block; - while (((block = worldIn.getState(position).getBlock()).getMaterial() == Material.air || block.getMaterial() == Material.leaves) && position.getY() > 1) + while (((block = worldIn.getState(position).getBlock()) == Blocks.air || block.getMaterial() == Material.LEAVES) && position.getY() > 1) { position = position.down(); } diff --git a/java/src/game/worldgen/feature/WorldGenAsteroid.java b/server/src/main/java/server/worldgen/feature/WorldGenAsteroid.java similarity index 91% rename from java/src/game/worldgen/feature/WorldGenAsteroid.java rename to server/src/main/java/server/worldgen/feature/WorldGenAsteroid.java index bf8d2fc..4444a4b 100755 --- a/java/src/game/worldgen/feature/WorldGenAsteroid.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenAsteroid.java @@ -1,10 +1,10 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenAsteroid extends FeatureGenerator { private final State[] blocks; diff --git a/java/src/game/worldgen/feature/WorldGenBlockBlob.java b/server/src/main/java/server/worldgen/feature/WorldGenBlockBlob.java similarity index 90% rename from java/src/game/worldgen/feature/WorldGenBlockBlob.java rename to server/src/main/java/server/worldgen/feature/WorldGenBlockBlob.java index c6eda23..bdc7467 100755 --- a/java/src/game/worldgen/feature/WorldGenBlockBlob.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenBlockBlob.java @@ -1,11 +1,11 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.block.Block; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Block; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenBlockBlob extends FeatureGenerator { diff --git a/java/src/game/worldgen/feature/WorldGenClay.java b/server/src/main/java/server/worldgen/feature/WorldGenClay.java similarity index 87% rename from java/src/game/worldgen/feature/WorldGenClay.java rename to server/src/main/java/server/worldgen/feature/WorldGenClay.java index 7f7fdce..e1b125a 100755 --- a/java/src/game/worldgen/feature/WorldGenClay.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenClay.java @@ -1,11 +1,11 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.block.Block; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Block; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenClay extends FeatureGenerator { diff --git a/java/src/game/worldgen/feature/WorldGenClayExt.java b/server/src/main/java/server/worldgen/feature/WorldGenClayExt.java similarity index 90% rename from java/src/game/worldgen/feature/WorldGenClayExt.java rename to server/src/main/java/server/worldgen/feature/WorldGenClayExt.java index 93b99bd..1f5c616 100755 --- a/java/src/game/worldgen/feature/WorldGenClayExt.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenClayExt.java @@ -1,11 +1,11 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.block.Block; -import game.init.Blocks; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.WorldServer; +import common.block.Block; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import server.world.WorldServer; public class WorldGenClayExt extends WorldGenClay { public WorldGenClayExt(int blocks) { diff --git a/java/src/game/worldgen/feature/WorldGenDesertWells.java b/server/src/main/java/server/worldgen/feature/WorldGenDesertWells.java similarity index 84% rename from java/src/game/worldgen/feature/WorldGenDesertWells.java rename to server/src/main/java/server/worldgen/feature/WorldGenDesertWells.java index 7dd67f9..90b0636 100755 --- a/java/src/game/worldgen/feature/WorldGenDesertWells.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenDesertWells.java @@ -1,21 +1,17 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.util.Predicates; - -import game.block.BlockSand; -import game.block.BlockSlab; -import game.init.Blocks; -import game.pattern.BlockStateHelper; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.artificial.BlockSlab; +import common.block.natural.BlockSand; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenDesertWells extends FeatureGenerator { - private static final BlockStateHelper field_175913_a = BlockStateHelper.forBlock(Blocks.sand).where(BlockSand.VARIANT, Predicates.equalTo(BlockSand.EnumType.SAND)); private final State field_175911_b = Blocks.sandstone_slab.getState().withProperty(BlockSlab.FACING, Facing.DOWN); private final State field_175912_c = Blocks.sandstone.getState(); private final State field_175910_d = Blocks.flowing_water.getState(); @@ -27,7 +23,8 @@ public class WorldGenDesertWells extends FeatureGenerator position = position.down(); } - if (!field_175913_a.test(worldIn.getState(position))) + State state = worldIn.getState(position); + if (state.getBlock() != Blocks.sand || state.getValue(BlockSand.VARIANT) != BlockSand.EnumType.SAND) { return false; } diff --git a/java/src/game/worldgen/feature/WorldGenFire.java b/server/src/main/java/server/worldgen/feature/WorldGenFire.java similarity index 75% rename from java/src/game/worldgen/feature/WorldGenFire.java rename to server/src/main/java/server/worldgen/feature/WorldGenFire.java index f878e76..2eb8728 100755 --- a/java/src/game/worldgen/feature/WorldGenFire.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenFire.java @@ -1,10 +1,10 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenFire extends FeatureGenerator { diff --git a/java/src/game/worldgen/feature/WorldGenGlowStone.java b/server/src/main/java/server/worldgen/feature/WorldGenGlowStone.java similarity index 80% rename from java/src/game/worldgen/feature/WorldGenGlowStone.java rename to server/src/main/java/server/worldgen/feature/WorldGenGlowStone.java index 9ec482f..951ece1 100755 --- a/java/src/game/worldgen/feature/WorldGenGlowStone.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenGlowStone.java @@ -1,12 +1,11 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenGlowStone extends FeatureGenerator { @@ -28,7 +27,7 @@ public class WorldGenGlowStone extends FeatureGenerator { BlockPos blockpos = position.add(rand.zrange(8) - rand.zrange(8), -rand.zrange(12), rand.zrange(8) - rand.zrange(8)); - if (worldIn.getState(blockpos).getBlock().getMaterial() == Material.air) + if (worldIn.getState(blockpos).getBlock() == Blocks.air) { int j = 0; diff --git a/java/src/game/worldgen/feature/WorldGenHellLava.java b/server/src/main/java/server/worldgen/feature/WorldGenHellLava.java similarity index 84% rename from java/src/game/worldgen/feature/WorldGenHellLava.java rename to server/src/main/java/server/worldgen/feature/WorldGenHellLava.java index 762423d..4d536bf 100755 --- a/java/src/game/worldgen/feature/WorldGenHellLava.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenHellLava.java @@ -1,12 +1,11 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.block.Block; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Block; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenHellLava extends FeatureGenerator { @@ -25,7 +24,7 @@ public class WorldGenHellLava extends FeatureGenerator { return false; } - else if (worldIn.getState(position).getBlock().getMaterial() != Material.air && worldIn.getState(position).getBlock() != Blocks.hellrock) + else if (worldIn.getState(position).getBlock() != Blocks.air && worldIn.getState(position).getBlock() != Blocks.hellrock) { return false; } diff --git a/java/src/game/worldgen/feature/WorldGenIcePath.java b/server/src/main/java/server/worldgen/feature/WorldGenIcePath.java similarity index 88% rename from java/src/game/worldgen/feature/WorldGenIcePath.java rename to server/src/main/java/server/worldgen/feature/WorldGenIcePath.java index 7012684..0f84e5c 100755 --- a/java/src/game/worldgen/feature/WorldGenIcePath.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenIcePath.java @@ -1,11 +1,11 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.block.Block; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Block; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenIcePath extends FeatureGenerator { diff --git a/java/src/game/worldgen/feature/WorldGenIceSpike.java b/server/src/main/java/server/worldgen/feature/WorldGenIceSpike.java similarity index 82% rename from java/src/game/worldgen/feature/WorldGenIceSpike.java rename to server/src/main/java/server/worldgen/feature/WorldGenIceSpike.java index 6e916f7..97d8efd 100755 --- a/java/src/game/worldgen/feature/WorldGenIceSpike.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenIceSpike.java @@ -1,13 +1,12 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.block.Block; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Block; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenIceSpike extends FeatureGenerator { @@ -50,7 +49,7 @@ public class WorldGenIceSpike extends FeatureGenerator { Block block = worldIn.getState(position.add(i1, k, j1)).getBlock(); - if (block.getMaterial() == Material.air || block == Blocks.dirt || block == Blocks.snow || block == Blocks.ice) + if (block == Blocks.air || block == Blocks.dirt || block == Blocks.snow || block == Blocks.ice) { this.setBlockAndNotifyAdequately(worldIn, position.add(i1, k, j1), Blocks.packed_ice.getState()); } @@ -59,7 +58,7 @@ public class WorldGenIceSpike extends FeatureGenerator { block = worldIn.getState(position.add(i1, -k, j1)).getBlock(); - if (block.getMaterial() == Material.air || block == Blocks.dirt || block == Blocks.snow || block == Blocks.ice) + if (block == Blocks.air || block == Blocks.dirt || block == Blocks.snow || block == Blocks.ice) { this.setBlockAndNotifyAdequately(worldIn, position.add(i1, -k, j1), Blocks.packed_ice.getState()); } @@ -96,7 +95,7 @@ public class WorldGenIceSpike extends FeatureGenerator { Block block1 = worldIn.getState(blockpos).getBlock(); - if (block1.getMaterial() != Material.air && block1 != Blocks.dirt && block1 != Blocks.snow && block1 != Blocks.ice && block1 != Blocks.packed_ice) + if (block1 != Blocks.air && block1 != Blocks.dirt && block1 != Blocks.snow && block1 != Blocks.ice && block1 != Blocks.packed_ice) { break; } diff --git a/java/src/game/worldgen/feature/WorldGenSand.java b/server/src/main/java/server/worldgen/feature/WorldGenSand.java similarity index 88% rename from java/src/game/worldgen/feature/WorldGenSand.java rename to server/src/main/java/server/worldgen/feature/WorldGenSand.java index d1bed59..edc5cad 100755 --- a/java/src/game/worldgen/feature/WorldGenSand.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenSand.java @@ -1,11 +1,11 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.block.Block; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Block; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenSand extends FeatureGenerator { diff --git a/java/src/game/worldgen/feature/WorldGenSpikes.java b/server/src/main/java/server/worldgen/feature/WorldGenSpikes.java similarity index 90% rename from java/src/game/worldgen/feature/WorldGenSpikes.java rename to server/src/main/java/server/worldgen/feature/WorldGenSpikes.java index ea88f57..9885fe8 100755 --- a/java/src/game/worldgen/feature/WorldGenSpikes.java +++ b/server/src/main/java/server/worldgen/feature/WorldGenSpikes.java @@ -1,13 +1,13 @@ -package game.worldgen.feature; +package server.worldgen.feature; -import game.block.Block; -import game.entity.Entity; -import game.entity.item.EntityCrystal; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Block; +import common.entity.Entity; +import common.entity.item.EntityCrystal; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenSpikes extends FeatureGenerator { diff --git a/java/src/game/worldgen/foliage/FeatureDoublePlant.java b/server/src/main/java/server/worldgen/foliage/FeatureDoublePlant.java similarity index 81% rename from java/src/game/worldgen/foliage/FeatureDoublePlant.java rename to server/src/main/java/server/worldgen/foliage/FeatureDoublePlant.java index a276dc2..548e584 100755 --- a/java/src/game/worldgen/foliage/FeatureDoublePlant.java +++ b/server/src/main/java/server/worldgen/foliage/FeatureDoublePlant.java @@ -1,10 +1,10 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.block.BlockDoublePlant; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; +import common.block.foliage.BlockDoublePlant; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; public class FeatureDoublePlant { diff --git a/java/src/game/worldgen/foliage/WorldGenBigMushroom.java b/server/src/main/java/server/worldgen/foliage/WorldGenBigMushroom.java similarity index 95% rename from java/src/game/worldgen/foliage/WorldGenBigMushroom.java rename to server/src/main/java/server/worldgen/foliage/WorldGenBigMushroom.java index 11523ae..15c3723 100755 --- a/java/src/game/worldgen/foliage/WorldGenBigMushroom.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenBigMushroom.java @@ -1,13 +1,13 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.block.Block; -import game.block.BlockHugeMushroom; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockHugeMushroom; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenBigMushroom extends FeatureGenerator { @@ -56,7 +56,7 @@ public class WorldGenBigMushroom extends FeatureGenerator { Block block = worldIn.getState(blockpos$mutableblockpos.set(l, j, i1)).getBlock(); - if (block.getMaterial() != Material.air && block.getMaterial() != Material.leaves) + if (block != Blocks.air && block.getMaterial() != Material.LEAVES) { flag = false; } diff --git a/java/src/game/worldgen/foliage/WorldGenCactus.java b/server/src/main/java/server/worldgen/foliage/WorldGenCactus.java similarity index 80% rename from java/src/game/worldgen/foliage/WorldGenCactus.java rename to server/src/main/java/server/worldgen/foliage/WorldGenCactus.java index 195223b..74354e8 100755 --- a/java/src/game/worldgen/foliage/WorldGenCactus.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenCactus.java @@ -1,10 +1,10 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenCactus extends FeatureGenerator { diff --git a/java/src/game/worldgen/foliage/WorldGenDeadBush.java b/server/src/main/java/server/worldgen/foliage/WorldGenDeadBush.java similarity index 63% rename from java/src/game/worldgen/foliage/WorldGenDeadBush.java rename to server/src/main/java/server/worldgen/foliage/WorldGenDeadBush.java index 32d52b3..ae5c9f7 100755 --- a/java/src/game/worldgen/foliage/WorldGenDeadBush.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenDeadBush.java @@ -1,12 +1,12 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.block.Block; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Block; +import common.block.Material; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenDeadBush extends FeatureGenerator { @@ -14,7 +14,7 @@ public class WorldGenDeadBush extends FeatureGenerator { Block block; - while (((block = worldIn.getState(position).getBlock()).getMaterial() == Material.air || block.getMaterial() == Material.leaves) && position.getY() > 0) + while (((block = worldIn.getState(position).getBlock()) == Blocks.air || block.getMaterial() == Material.LEAVES) && position.getY() > 0) { position = position.down(); } diff --git a/java/src/game/worldgen/foliage/WorldGenFlowers.java b/server/src/main/java/server/worldgen/foliage/WorldGenFlowers.java similarity index 83% rename from java/src/game/worldgen/foliage/WorldGenFlowers.java rename to server/src/main/java/server/worldgen/foliage/WorldGenFlowers.java index 452e279..4bc978c 100755 --- a/java/src/game/worldgen/foliage/WorldGenFlowers.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenFlowers.java @@ -1,11 +1,11 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.block.BlockFlower; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.foliage.BlockFlower; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenFlowers extends FeatureGenerator { diff --git a/java/src/game/worldgen/foliage/WorldGenMelon.java b/server/src/main/java/server/worldgen/foliage/WorldGenMelon.java similarity index 76% rename from java/src/game/worldgen/foliage/WorldGenMelon.java rename to server/src/main/java/server/worldgen/foliage/WorldGenMelon.java index 50f3029..c8e7319 100755 --- a/java/src/game/worldgen/foliage/WorldGenMelon.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenMelon.java @@ -1,10 +1,10 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenMelon extends FeatureGenerator { diff --git a/java/src/game/worldgen/foliage/WorldGenMushroom.java b/server/src/main/java/server/worldgen/foliage/WorldGenMushroom.java similarity index 80% rename from java/src/game/worldgen/foliage/WorldGenMushroom.java rename to server/src/main/java/server/worldgen/foliage/WorldGenMushroom.java index 113a43d..07b999b 100755 --- a/java/src/game/worldgen/foliage/WorldGenMushroom.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenMushroom.java @@ -1,10 +1,10 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.block.BlockBush; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.foliage.BlockBush; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenMushroom extends FeatureGenerator { diff --git a/java/src/game/worldgen/foliage/WorldGenPumpkin.java b/server/src/main/java/server/worldgen/foliage/WorldGenPumpkin.java similarity index 73% rename from java/src/game/worldgen/foliage/WorldGenPumpkin.java rename to server/src/main/java/server/worldgen/foliage/WorldGenPumpkin.java index e93d8c0..1aa47b3 100755 --- a/java/src/game/worldgen/foliage/WorldGenPumpkin.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenPumpkin.java @@ -1,12 +1,12 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.block.BlockPumpkin; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.foliage.BlockPumpkin; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenPumpkin extends FeatureGenerator { diff --git a/java/src/game/worldgen/foliage/WorldGenReed.java b/server/src/main/java/server/worldgen/foliage/WorldGenReed.java similarity index 65% rename from java/src/game/worldgen/foliage/WorldGenReed.java rename to server/src/main/java/server/worldgen/foliage/WorldGenReed.java index d540343..45be4d9 100755 --- a/java/src/game/worldgen/foliage/WorldGenReed.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenReed.java @@ -1,11 +1,11 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Material; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenReed extends FeatureGenerator { @@ -19,7 +19,7 @@ public class WorldGenReed extends FeatureGenerator { BlockPos blockpos1 = blockpos.down(); - if (worldIn.getState(blockpos1.west()).getBlock().getMaterial() == Material.water || worldIn.getState(blockpos1.east()).getBlock().getMaterial() == Material.water || worldIn.getState(blockpos1.north()).getBlock().getMaterial() == Material.water || worldIn.getState(blockpos1.south()).getBlock().getMaterial() == Material.water) + if (worldIn.getState(blockpos1.west()).getBlock().getMaterial() == Material.WATER || worldIn.getState(blockpos1.east()).getBlock().getMaterial() == Material.WATER || worldIn.getState(blockpos1.north()).getBlock().getMaterial() == Material.WATER || worldIn.getState(blockpos1.south()).getBlock().getMaterial() == Material.WATER) { int j = 2 + rand.zrange(rand.zrange(3) + 1); diff --git a/java/src/game/worldgen/foliage/WorldGenShrub.java b/server/src/main/java/server/worldgen/foliage/WorldGenShrub.java similarity index 80% rename from java/src/game/worldgen/foliage/WorldGenShrub.java rename to server/src/main/java/server/worldgen/foliage/WorldGenShrub.java index 01f342e..65d9376 100755 --- a/java/src/game/worldgen/foliage/WorldGenShrub.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenShrub.java @@ -1,14 +1,14 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.block.Block; -import game.block.BlockLeaves; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.tree.WorldGenBaseTree; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockLeaves; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; +import server.worldgen.tree.WorldGenBaseTree; public class WorldGenShrub extends WorldGenBaseTree { @@ -26,7 +26,7 @@ public class WorldGenShrub extends WorldGenBaseTree { Block block; - while (((block = worldIn.getState(position).getBlock()).getMaterial() == Material.air || block.getMaterial() == Material.leaves) && position.getY() > 0) + while (((block = worldIn.getState(position).getBlock()) == Blocks.air || block.getMaterial() == Material.LEAVES) && position.getY() > 0) { position = position.down(); } diff --git a/java/src/game/worldgen/foliage/WorldGenTallGrass.java b/server/src/main/java/server/worldgen/foliage/WorldGenTallGrass.java similarity index 66% rename from java/src/game/worldgen/foliage/WorldGenTallGrass.java rename to server/src/main/java/server/worldgen/foliage/WorldGenTallGrass.java index d841f23..81a1d75 100755 --- a/java/src/game/worldgen/foliage/WorldGenTallGrass.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenTallGrass.java @@ -1,14 +1,14 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.block.Block; -import game.block.BlockTallGrass; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockTallGrass; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenTallGrass extends FeatureGenerator { @@ -23,7 +23,7 @@ public class WorldGenTallGrass extends FeatureGenerator { Block block; - while (((block = worldIn.getState(position).getBlock()).getMaterial() == Material.air || block.getMaterial() == Material.leaves) && position.getY() > 0) + while (((block = worldIn.getState(position).getBlock()) == Blocks.air || block.getMaterial() == Material.LEAVES) && position.getY() > 0) { position = position.down(); } diff --git a/java/src/game/worldgen/foliage/WorldGenVines.java b/server/src/main/java/server/worldgen/foliage/WorldGenVines.java similarity index 80% rename from java/src/game/worldgen/foliage/WorldGenVines.java rename to server/src/main/java/server/worldgen/foliage/WorldGenVines.java index fb2333b..86fd327 100755 --- a/java/src/game/worldgen/foliage/WorldGenVines.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenVines.java @@ -1,13 +1,13 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.block.BlockVine; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.foliage.BlockVine; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenVines extends FeatureGenerator { diff --git a/java/src/game/worldgen/foliage/WorldGenWaterlily.java b/server/src/main/java/server/worldgen/foliage/WorldGenWaterlily.java similarity index 74% rename from java/src/game/worldgen/foliage/WorldGenWaterlily.java rename to server/src/main/java/server/worldgen/foliage/WorldGenWaterlily.java index 02d2df0..c5a7858 100755 --- a/java/src/game/worldgen/foliage/WorldGenWaterlily.java +++ b/server/src/main/java/server/worldgen/foliage/WorldGenWaterlily.java @@ -1,12 +1,12 @@ -package game.worldgen.foliage; +package server.worldgen.foliage; -import game.block.BlockDirectional; -import game.init.Blocks; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.BlockDirectional; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public class WorldGenWaterlily extends FeatureGenerator { diff --git a/java/src/game/worldgen/layer/GenLayer.java b/server/src/main/java/server/worldgen/layer/GenLayer.java similarity index 91% rename from java/src/game/worldgen/layer/GenLayer.java rename to server/src/main/java/server/worldgen/layer/GenLayer.java index 321cb6f..675f884 100755 --- a/java/src/game/worldgen/layer/GenLayer.java +++ b/server/src/main/java/server/worldgen/layer/GenLayer.java @@ -1,6 +1,7 @@ -package game.worldgen.layer; +package server.worldgen.layer; -import game.biome.Biome; +import common.biome.Biome; +import server.biome.GenBiome; public abstract class GenLayer { private long worldGenSeed; @@ -13,8 +14,8 @@ public abstract class GenLayer { return true; } else { // if(id1 != Biome.mesaPlateau_F.id && id1 != Biome.mesaPlateau.id) { - final Biome biome1 = Biome.getBiome(id1); - final Biome biome2 = Biome.getBiome(id2); + final GenBiome biome1 = GenBiome.getBiome(id1); + final GenBiome biome2 = GenBiome.getBiome(id2); return biome1 != null && biome2 != null ? biome1.isEqualTo(biome2) : false; } // else { @@ -23,7 +24,7 @@ public abstract class GenLayer { } protected static boolean isSea(int id) { - return id == Biome.sea.id || id == Biome.frozenSea.id; + return id == Biome.SEA.id || id == Biome.FROZENSEA.id; } public GenLayer(long base) { diff --git a/java/src/game/worldgen/layer/GenLayerAddAreas.java b/server/src/main/java/server/worldgen/layer/GenLayerAddAreas.java similarity index 99% rename from java/src/game/worldgen/layer/GenLayerAddAreas.java rename to server/src/main/java/server/worldgen/layer/GenLayerAddAreas.java index fa9a323..757a2b7 100755 --- a/java/src/game/worldgen/layer/GenLayerAddAreas.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerAddAreas.java @@ -1,4 +1,4 @@ -package game.worldgen.layer; +package server.worldgen.layer; public class GenLayerAddAreas extends GenLayer { diff --git a/java/src/game/worldgen/layer/GenLayerAddExtra.java b/server/src/main/java/server/worldgen/layer/GenLayerAddExtra.java similarity index 96% rename from java/src/game/worldgen/layer/GenLayerAddExtra.java rename to server/src/main/java/server/worldgen/layer/GenLayerAddExtra.java index f18e670..54a1d4a 100755 --- a/java/src/game/worldgen/layer/GenLayerAddExtra.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerAddExtra.java @@ -1,6 +1,6 @@ -package game.worldgen.layer; +package server.worldgen.layer; -import game.biome.Biome; +import common.biome.Biome; public class GenLayerAddExtra extends GenLayer { diff --git a/java/src/game/worldgen/layer/GenLayerAddSea.java b/server/src/main/java/server/worldgen/layer/GenLayerAddSea.java similarity index 95% rename from java/src/game/worldgen/layer/GenLayerAddSea.java rename to server/src/main/java/server/worldgen/layer/GenLayerAddSea.java index e573bec..f958542 100755 --- a/java/src/game/worldgen/layer/GenLayerAddSea.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerAddSea.java @@ -1,6 +1,6 @@ -package game.worldgen.layer; +package server.worldgen.layer; -import game.biome.Biome; +import common.biome.Biome; public class GenLayerAddSea extends GenLayer { @@ -60,7 +60,7 @@ public class GenLayerAddSea extends GenLayer this.initChunkSeed((long)(areaX + j1), (long)(areaY + i1)); if (k2 == 0 && this.nextInt(this.rarity) == 0) { - aint1[j1 + i1 * areaWidth] = l2 > 1 ? Biome.frozenSea.id : Biome.sea.id; + aint1[j1 + i1 * areaWidth] = l2 > 1 ? Biome.FROZENSEA.id : Biome.SEA.id; } else { diff --git a/java/src/game/worldgen/layer/GenLayerAddSnow.java b/server/src/main/java/server/worldgen/layer/GenLayerAddSnow.java similarity index 98% rename from java/src/game/worldgen/layer/GenLayerAddSnow.java rename to server/src/main/java/server/worldgen/layer/GenLayerAddSnow.java index 4e8cfe2..5b7b07a 100755 --- a/java/src/game/worldgen/layer/GenLayerAddSnow.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerAddSnow.java @@ -1,4 +1,4 @@ -package game.worldgen.layer; +package server.worldgen.layer; public class GenLayerAddSnow extends GenLayer { diff --git a/java/src/game/worldgen/layer/GenLayerBase.java b/server/src/main/java/server/worldgen/layer/GenLayerBase.java similarity index 95% rename from java/src/game/worldgen/layer/GenLayerBase.java rename to server/src/main/java/server/worldgen/layer/GenLayerBase.java index d82ae3e..f0c596e 100755 --- a/java/src/game/worldgen/layer/GenLayerBase.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerBase.java @@ -1,4 +1,4 @@ -package game.worldgen.layer; +package server.worldgen.layer; public class GenLayerBase extends GenLayer { diff --git a/java/src/game/worldgen/layer/GenLayerBiome.java b/server/src/main/java/server/worldgen/layer/GenLayerBiome.java similarity index 97% rename from java/src/game/worldgen/layer/GenLayerBiome.java rename to server/src/main/java/server/worldgen/layer/GenLayerBiome.java index d20fd9f..a61c14f 100755 --- a/java/src/game/worldgen/layer/GenLayerBiome.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerBiome.java @@ -1,6 +1,6 @@ -package game.worldgen.layer; +package server.worldgen.layer; -import game.biome.Biome; +import common.biome.Biome; public class GenLayerBiome extends GenLayer { diff --git a/java/src/game/worldgen/layer/GenLayerBiomeEdge.java b/server/src/main/java/server/worldgen/layer/GenLayerBiomeEdge.java similarity index 82% rename from java/src/game/worldgen/layer/GenLayerBiomeEdge.java rename to server/src/main/java/server/worldgen/layer/GenLayerBiomeEdge.java index 9fd5068..b2ae7be 100755 --- a/java/src/game/worldgen/layer/GenLayerBiomeEdge.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerBiomeEdge.java @@ -1,7 +1,8 @@ -package game.worldgen.layer; +package server.worldgen.layer; -import game.biome.Biome; -import game.biome.Temperature; +import common.biome.Biome; +import server.biome.GenBiome; +import server.biome.Temperature; public class GenLayerBiomeEdge extends GenLayer { @@ -27,45 +28,45 @@ public class GenLayerBiomeEdge extends GenLayer this.initChunkSeed((long)(j + areaX), (long)(i + areaY)); int k = aint[j + 1 + (i + 1) * (areaWidth + 2)]; - if (!this.replaceBiomeEdgeIfNecessary(aint, aint1, j, i, areaWidth, k, Biome.extremeHills.id, Biome.extremeHillsEdge.id) && /* !this.replaceBiomeEdge(aint, aint1, j, i, areaWidth, k, Biome.mesaPlateau_F.id, Biome.mesa.id) && !this.replaceBiomeEdge(aint, aint1, j, i, areaWidth, k, Biome.mesaPlateau.id, Biome.mesa.id) && */ !this.replaceBiomeEdge(aint, aint1, j, i, areaWidth, k, Biome.megaTaiga.id, Biome.taiga.id)) + if (!this.replaceBiomeEdgeIfNecessary(aint, aint1, j, i, areaWidth, k, Biome.EXTREMEHILLS.id, Biome.EXTREMEHILLSEDGE.id) && /* !this.replaceBiomeEdge(aint, aint1, j, i, areaWidth, k, Biome.mesaPlateau_F.id, Biome.mesa.id) && !this.replaceBiomeEdge(aint, aint1, j, i, areaWidth, k, Biome.mesaPlateau.id, Biome.mesa.id) && */ !this.replaceBiomeEdge(aint, aint1, j, i, areaWidth, k, Biome.MEGATAIGA.id, Biome.TAIGA.id)) { - if (k == Biome.desert.id) + if (k == Biome.DESERT.id) { int l1 = aint[j + 1 + (i + 1 - 1) * (areaWidth + 2)]; int i2 = aint[j + 1 + 1 + (i + 1) * (areaWidth + 2)]; int j2 = aint[j + 1 - 1 + (i + 1) * (areaWidth + 2)]; int k2 = aint[j + 1 + (i + 1 + 1) * (areaWidth + 2)]; - if (l1 != Biome.icePlains.id && i2 != Biome.icePlains.id && j2 != Biome.icePlains.id && k2 != Biome.icePlains.id) + if (l1 != Biome.ICEPLAINS.id && i2 != Biome.ICEPLAINS.id && j2 != Biome.ICEPLAINS.id && k2 != Biome.ICEPLAINS.id) { aint1[j + i * areaWidth] = k; } else { - aint1[j + i * areaWidth] = Biome.extremeHillsPlus.id; + aint1[j + i * areaWidth] = Biome.EXTREMEHILLSPLUS.id; } } - else if (k == Biome.swampland.id) + else if (k == Biome.SWAMPLAND.id) { int l = aint[j + 1 + (i + 1 - 1) * (areaWidth + 2)]; int i1 = aint[j + 1 + 1 + (i + 1) * (areaWidth + 2)]; int j1 = aint[j + 1 - 1 + (i + 1) * (areaWidth + 2)]; int k1 = aint[j + 1 + (i + 1 + 1) * (areaWidth + 2)]; - if (l != Biome.desert.id && i1 != Biome.desert.id && j1 != Biome.desert.id && k1 != Biome.desert.id && l != Biome.coldTaiga.id && i1 != Biome.coldTaiga.id && j1 != Biome.coldTaiga.id && k1 != Biome.coldTaiga.id && l != Biome.icePlains.id && i1 != Biome.icePlains.id && j1 != Biome.icePlains.id && k1 != Biome.icePlains.id) + if (l != Biome.DESERT.id && i1 != Biome.DESERT.id && j1 != Biome.DESERT.id && k1 != Biome.DESERT.id && l != Biome.COLDTAIGA.id && i1 != Biome.COLDTAIGA.id && j1 != Biome.COLDTAIGA.id && k1 != Biome.COLDTAIGA.id && l != Biome.ICEPLAINS.id && i1 != Biome.ICEPLAINS.id && j1 != Biome.ICEPLAINS.id && k1 != Biome.ICEPLAINS.id) { - if (l != Biome.jungle.id && k1 != Biome.jungle.id && i1 != Biome.jungle.id && j1 != Biome.jungle.id) + if (l != Biome.JUNGLE.id && k1 != Biome.JUNGLE.id && i1 != Biome.JUNGLE.id && j1 != Biome.JUNGLE.id) { aint1[j + i * areaWidth] = k; } else { - aint1[j + i * areaWidth] = Biome.jungleEdge.id; + aint1[j + i * areaWidth] = Biome.JUNGLEEDGE.id; } } else { - aint1[j + i * areaWidth] = Biome.plains.id; + aint1[j + i * areaWidth] = Biome.PLAINS.id; } } else @@ -149,8 +150,8 @@ public class GenLayerBiomeEdge extends GenLayer } else { - Biome biomegenbase = Biome.getBiome(p_151634_1_); - Biome biomegenbase1 = Biome.getBiome(p_151634_2_); + GenBiome biomegenbase = GenBiome.getBiome(p_151634_1_); + GenBiome biomegenbase1 = GenBiome.getBiome(p_151634_2_); if (biomegenbase != null && biomegenbase1 != null) { diff --git a/java/src/game/worldgen/layer/GenLayerEdge.java b/server/src/main/java/server/worldgen/layer/GenLayerEdge.java similarity index 99% rename from java/src/game/worldgen/layer/GenLayerEdge.java rename to server/src/main/java/server/worldgen/layer/GenLayerEdge.java index 243506e..26600a3 100755 --- a/java/src/game/worldgen/layer/GenLayerEdge.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerEdge.java @@ -1,4 +1,4 @@ -package game.worldgen.layer; +package server.worldgen.layer; public class GenLayerEdge extends GenLayer { diff --git a/java/src/game/worldgen/layer/GenLayerFuzzyZoom.java b/server/src/main/java/server/worldgen/layer/GenLayerFuzzyZoom.java similarity index 94% rename from java/src/game/worldgen/layer/GenLayerFuzzyZoom.java rename to server/src/main/java/server/worldgen/layer/GenLayerFuzzyZoom.java index b4c4fc7..6db73ee 100755 --- a/java/src/game/worldgen/layer/GenLayerFuzzyZoom.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerFuzzyZoom.java @@ -1,4 +1,4 @@ -package game.worldgen.layer; +package server.worldgen.layer; public class GenLayerFuzzyZoom extends GenLayerZoom { diff --git a/java/src/game/worldgen/layer/GenLayerHills.java b/server/src/main/java/server/worldgen/layer/GenLayerHills.java similarity index 75% rename from java/src/game/worldgen/layer/GenLayerHills.java rename to server/src/main/java/server/worldgen/layer/GenLayerHills.java index 284261a..c2865ae 100755 --- a/java/src/game/worldgen/layer/GenLayerHills.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerHills.java @@ -1,7 +1,7 @@ -package game.worldgen.layer; +package server.worldgen.layer; -import game.biome.Biome; -import game.log.Log; +import common.biome.Biome; +import common.log.Log; public class GenLayerHills extends GenLayer { @@ -37,7 +37,7 @@ public class GenLayerHills extends GenLayer if (k > 255) { - Log.JNI.warn("Altes Biom (" + k + ")!"); + Log.TICK.warn("Altes Biom (" + k + ")!"); } if (k != 0 && l >= 2 && (l - 2) % 29 == 1 && k < 128) @@ -59,80 +59,80 @@ public class GenLayerHills extends GenLayer { int i1 = k; - if (k == Biome.desert.id) + if (k == Biome.DESERT.id) { - i1 = Biome.desertHills.id; + i1 = Biome.DESERTHILLS.id; } - else if (k == Biome.forest.id) + else if (k == Biome.FOREST.id) { - i1 = Biome.forestHills.id; + i1 = Biome.FORESTHILLS.id; } - else if (k == Biome.birchForest.id) + else if (k == Biome.BIRCHFOREST.id) { - i1 = Biome.birchForestHills.id; + i1 = Biome.BIRCHFORESTHILLS.id; } - else if (k == Biome.roofedForest.id) + else if (k == Biome.ROOFEDFOREST.id) { - i1 = Biome.plains.id; + i1 = Biome.PLAINS.id; } - else if (k == Biome.taiga.id) + else if (k == Biome.TAIGA.id) { - i1 = Biome.taigaHills.id; + i1 = Biome.TAIGAHILLS.id; } - else if (k == Biome.megaTaiga.id) + else if (k == Biome.MEGATAIGA.id) { - i1 = Biome.megaTaigaHills.id; + i1 = Biome.MEGATAIGAHILLS.id; } - else if (k == Biome.coldTaiga.id) + else if (k == Biome.COLDTAIGA.id) { - i1 = Biome.coldTaigaHills.id; + i1 = Biome.COLDTAIGAHILLS.id; } - else if (k == Biome.plains.id) + else if (k == Biome.PLAINS.id) { if (this.nextInt(3) == 0) { - i1 = Biome.forestHills.id; + i1 = Biome.FORESTHILLS.id; } else { - i1 = Biome.forest.id; + i1 = Biome.FOREST.id; } } - else if (k == Biome.icePlains.id) + else if (k == Biome.ICEPLAINS.id) { - i1 = Biome.iceMountains.id; + i1 = Biome.ICEMOUNTAINS.id; } - else if (k == Biome.jungle.id) + else if (k == Biome.JUNGLE.id) { - i1 = Biome.jungleHills.id; + i1 = Biome.JUNGLEHILLS.id; } - else if (k == Biome.none.id) + else if (k == Biome.NONE.id) { i1 = this.def; } - else if (k == Biome.extremeHills.id) + else if (k == Biome.EXTREMEHILLS.id) { - i1 = Biome.extremeHillsPlus.id; + i1 = Biome.EXTREMEHILLSPLUS.id; } - else if (k == Biome.savanna.id) + else if (k == Biome.SAVANNA.id) { - i1 = Biome.savannaPlateau.id; + i1 = Biome.SAVANNAPLATEAU.id; } // else if (canBeNearby(k, Biome.mesaPlateau_F.id)) // { // i1 = Biome.mesa.id; // } - else if (k == Biome.sea.id && this.nextInt(3) == 0) + else if (k == Biome.SEA.id && this.nextInt(3) == 0) { int j1 = this.nextInt(2); if (j1 == 0) { - i1 = Biome.plains.id; + i1 = Biome.PLAINS.id; } else { - i1 = Biome.forest.id; + i1 = Biome.FOREST.id; } } diff --git a/java/src/game/worldgen/layer/GenLayerRemoveEmpty.java b/server/src/main/java/server/worldgen/layer/GenLayerRemoveEmpty.java similarity index 98% rename from java/src/game/worldgen/layer/GenLayerRemoveEmpty.java rename to server/src/main/java/server/worldgen/layer/GenLayerRemoveEmpty.java index e35145c..ec07585 100755 --- a/java/src/game/worldgen/layer/GenLayerRemoveEmpty.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerRemoveEmpty.java @@ -1,4 +1,4 @@ -package game.worldgen.layer; +package server.worldgen.layer; public class GenLayerRemoveEmpty extends GenLayer { diff --git a/java/src/game/worldgen/layer/GenLayerRiver.java b/server/src/main/java/server/worldgen/layer/GenLayerRiver.java similarity index 92% rename from java/src/game/worldgen/layer/GenLayerRiver.java rename to server/src/main/java/server/worldgen/layer/GenLayerRiver.java index cced208..00a0348 100755 --- a/java/src/game/worldgen/layer/GenLayerRiver.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerRiver.java @@ -1,6 +1,6 @@ -package game.worldgen.layer; +package server.worldgen.layer; -import game.biome.Biome; +import common.biome.Biome; public class GenLayerRiver extends GenLayer { @@ -39,7 +39,7 @@ public class GenLayerRiver extends GenLayer } else { - aint1[j1 + i1 * areaWidth] = Biome.river.id; + aint1[j1 + i1 * areaWidth] = Biome.RIVER.id; } } } diff --git a/java/src/game/worldgen/layer/GenLayerRiverInit.java b/server/src/main/java/server/worldgen/layer/GenLayerRiverInit.java similarity index 96% rename from java/src/game/worldgen/layer/GenLayerRiverInit.java rename to server/src/main/java/server/worldgen/layer/GenLayerRiverInit.java index 80a65a2..4bb9ed2 100755 --- a/java/src/game/worldgen/layer/GenLayerRiverInit.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerRiverInit.java @@ -1,4 +1,4 @@ -package game.worldgen.layer; +package server.worldgen.layer; public class GenLayerRiverInit extends GenLayer { diff --git a/java/src/game/worldgen/layer/GenLayerRiverMix.java b/server/src/main/java/server/worldgen/layer/GenLayerRiverMix.java similarity index 84% rename from java/src/game/worldgen/layer/GenLayerRiverMix.java rename to server/src/main/java/server/worldgen/layer/GenLayerRiverMix.java index a98d6d8..05d47f8 100755 --- a/java/src/game/worldgen/layer/GenLayerRiverMix.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerRiverMix.java @@ -1,6 +1,6 @@ -package game.worldgen.layer; +package server.worldgen.layer; -import game.biome.Biome; +import common.biome.Biome; public class GenLayerRiverMix extends GenLayer { @@ -39,23 +39,23 @@ public class GenLayerRiverMix extends GenLayer for (int i = 0; i < areaWidth * areaHeight; ++i) { - if(biome[i] == Biome.none.id) + if(biome[i] == Biome.NONE.id) { out[i] = this.def; } - else if(biome[i] == Biome.sea.id || biome[i] == Biome.frozenSea.id) + else if(biome[i] == Biome.SEA.id || biome[i] == Biome.FROZENSEA.id) { out[i] = biome[i]; } - else if (river[i] == Biome.river.id) + else if (river[i] == Biome.RIVER.id) { - if (biome[i] == Biome.icePlains.id) + if (biome[i] == Biome.ICEPLAINS.id) { - out[i] = Biome.frozenRiver.id; + out[i] = Biome.FROZENRIVER.id; } else // if (biome[i] != Biome.mushroomPlains.id && biome[i] != Biome.mushroomPlainsEdge.id) { - out[i] = Biome.river.id; + out[i] = Biome.RIVER.id; } // else // { diff --git a/java/src/game/worldgen/layer/GenLayerShore.java b/server/src/main/java/server/worldgen/layer/GenLayerShore.java similarity index 87% rename from java/src/game/worldgen/layer/GenLayerShore.java rename to server/src/main/java/server/worldgen/layer/GenLayerShore.java index 4e94d33..715e37a 100755 --- a/java/src/game/worldgen/layer/GenLayerShore.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerShore.java @@ -1,7 +1,8 @@ -package game.worldgen.layer; +package server.worldgen.layer; -import game.biome.Biome; -import game.biome.BiomeJungle; +import common.biome.Biome; +import server.biome.GenBiome; +import server.biome.BiomeJungle; public class GenLayerShore extends GenLayer { @@ -22,7 +23,7 @@ public class GenLayerShore extends GenLayer { this.initChunkSeed((long)(j + x), (long)(i + z)); int id = pre[j + 1 + (i + 1) * (width + 2)]; - Biome biome = Biome.getBiome(id); + GenBiome biome = GenBiome.getBiome(id); // if (id == Biome.mushroomPlains.id) // { @@ -56,19 +57,19 @@ public class GenLayerShore extends GenLayer } else { - data[j + i * width] = Biome.beach.id; + data[j + i * width] = Biome.BEACH.id; } } else { - data[j + i * width] = Biome.jungleEdge.id; + data[j + i * width] = Biome.JUNGLEEDGE.id; } } - else if (id != Biome.extremeHills.id && id != Biome.extremeHillsPlus.id && id != Biome.extremeHillsEdge.id) + else if (id != Biome.EXTREMEHILLS.id && id != Biome.EXTREMEHILLSPLUS.id && id != Biome.EXTREMEHILLSEDGE.id) { if (biome != null && biome.allowColdBeach) { - this.putBeach(pre, data, j, i, width, id, Biome.coldBeach.id); + this.putBeach(pre, data, j, i, width, id, Biome.COLDBEACH.id); } else // if (id != Biome.mesa.id && id != Biome.mesaPlateau_F.id) // { @@ -85,7 +86,7 @@ public class GenLayerShore extends GenLayer } else { - data[j + i * width] = Biome.beach.id; + data[j + i * width] = Biome.BEACH.id; } } else @@ -119,7 +120,7 @@ public class GenLayerShore extends GenLayer } else { - this.putBeach(pre, data, j, i, width, id, Biome.stoneBeach.id); + this.putBeach(pre, data, j, i, width, id, Biome.STONEBEACH.id); } } } @@ -153,7 +154,8 @@ public class GenLayerShore extends GenLayer private boolean canNBJungle(int id) { - return Biome.getBiome(id) != null && Biome.getBiome(id).getBiomeClass() == BiomeJungle.class ? true : id == Biome.jungleEdge.id || id == Biome.jungle.id || id == Biome.jungleHills.id || id == Biome.forest.id || id == Biome.taiga.id || isSea(id); + GenBiome biome = GenBiome.getBiome(id); + return biome != null && biome.getBiomeClass() == BiomeJungle.class ? true : id == Biome.JUNGLEEDGE.id || id == Biome.JUNGLE.id || id == Biome.JUNGLEHILLS.id || id == Biome.FOREST.id || id == Biome.TAIGA.id || isSea(id); } // private boolean canNBMesa(int id) diff --git a/java/src/game/worldgen/layer/GenLayerSmooth.java b/server/src/main/java/server/worldgen/layer/GenLayerSmooth.java similarity index 98% rename from java/src/game/worldgen/layer/GenLayerSmooth.java rename to server/src/main/java/server/worldgen/layer/GenLayerSmooth.java index 1893663..e071367 100755 --- a/java/src/game/worldgen/layer/GenLayerSmooth.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerSmooth.java @@ -1,4 +1,4 @@ -package game.worldgen.layer; +package server.worldgen.layer; public class GenLayerSmooth extends GenLayer { diff --git a/java/src/game/worldgen/layer/GenLayerVoronoiZoom.java b/server/src/main/java/server/worldgen/layer/GenLayerVoronoiZoom.java similarity index 99% rename from java/src/game/worldgen/layer/GenLayerVoronoiZoom.java rename to server/src/main/java/server/worldgen/layer/GenLayerVoronoiZoom.java index e8c76ac..f58e306 100755 --- a/java/src/game/worldgen/layer/GenLayerVoronoiZoom.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerVoronoiZoom.java @@ -1,4 +1,4 @@ -package game.worldgen.layer; +package server.worldgen.layer; public class GenLayerVoronoiZoom extends GenLayer { diff --git a/java/src/game/worldgen/layer/GenLayerZoom.java b/server/src/main/java/server/worldgen/layer/GenLayerZoom.java similarity index 98% rename from java/src/game/worldgen/layer/GenLayerZoom.java rename to server/src/main/java/server/worldgen/layer/GenLayerZoom.java index 8dd4565..0b9d45c 100755 --- a/java/src/game/worldgen/layer/GenLayerZoom.java +++ b/server/src/main/java/server/worldgen/layer/GenLayerZoom.java @@ -1,4 +1,4 @@ -package game.worldgen.layer; +package server.worldgen.layer; public class GenLayerZoom extends GenLayer { diff --git a/java/src/game/worldgen/layer/IntCache.java b/server/src/main/java/server/worldgen/layer/IntCache.java similarity index 97% rename from java/src/game/worldgen/layer/IntCache.java rename to server/src/main/java/server/worldgen/layer/IntCache.java index 38a4766..e9ac30a 100755 --- a/java/src/game/worldgen/layer/IntCache.java +++ b/server/src/main/java/server/worldgen/layer/IntCache.java @@ -1,8 +1,8 @@ -package game.worldgen.layer; +package server.worldgen.layer; import java.util.List; -import game.collect.Lists; +import common.collect.Lists; public class IntCache { diff --git a/java/src/game/worldgen/structure/MapGenBridge.java b/server/src/main/java/server/worldgen/structure/MapGenBridge.java similarity index 94% rename from java/src/game/worldgen/structure/MapGenBridge.java rename to server/src/main/java/server/worldgen/structure/MapGenBridge.java index 2fa6862..0a998ba 100755 --- a/java/src/game/worldgen/structure/MapGenBridge.java +++ b/server/src/main/java/server/worldgen/structure/MapGenBridge.java @@ -1,9 +1,9 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.List; -import game.rng.Random; -import game.world.WorldServer; +import common.rng.Random; +import server.world.WorldServer; public class MapGenBridge extends MapGenStructure { diff --git a/java/src/game/worldgen/structure/MapGenMineshaft.java b/server/src/main/java/server/worldgen/structure/MapGenMineshaft.java similarity index 96% rename from java/src/game/worldgen/structure/MapGenMineshaft.java rename to server/src/main/java/server/worldgen/structure/MapGenMineshaft.java index 6a5ca50..2fee1e7 100755 --- a/java/src/game/worldgen/structure/MapGenMineshaft.java +++ b/server/src/main/java/server/worldgen/structure/MapGenMineshaft.java @@ -1,4 +1,4 @@ -package game.worldgen.structure; +package server.worldgen.structure; public class MapGenMineshaft extends MapGenStructure { diff --git a/java/src/game/worldgen/structure/MapGenScatteredFeature.java b/server/src/main/java/server/worldgen/structure/MapGenScatteredFeature.java similarity index 85% rename from java/src/game/worldgen/structure/MapGenScatteredFeature.java rename to server/src/main/java/server/worldgen/structure/MapGenScatteredFeature.java index 0228027..c0393ae 100755 --- a/java/src/game/worldgen/structure/MapGenScatteredFeature.java +++ b/server/src/main/java/server/worldgen/structure/MapGenScatteredFeature.java @@ -1,16 +1,16 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.Arrays; import java.util.List; -import game.biome.Biome; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; +import common.biome.Biome; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; public class MapGenScatteredFeature extends MapGenStructure { - private static final List biomelist = Arrays.asList(new Biome[] {Biome.desert, Biome.desertHills, Biome.jungle, Biome.jungleHills, Biome.swampland}); + private static final List biomelist = Arrays.asList(Biome.DESERT, Biome.DESERTHILLS, Biome.JUNGLE, Biome.JUNGLEHILLS, Biome.SWAMPLAND); private static final int MAX_DISTANCE = 32; private static final int MIN_DISTANCE = 8; @@ -44,7 +44,7 @@ public class MapGenScatteredFeature extends MapGenStructure if (i == k && j == l) { - Biome biomegenbase = this.worldObj.getBiomeGenerator().getBiomeGenerator(new BlockPos(i * 16 + 8, 0, j * 16 + 8), null); + Biome biomegenbase = this.worldObj.getBiomeGenerator().getBiomeGenerator(new BlockPos(i * 16 + 8, 0, j * 16 + 8), null); if (biomegenbase == null) { @@ -94,14 +94,14 @@ public class MapGenScatteredFeature extends MapGenStructure super(p_i2060_3_, p_i2060_4_); Biome biomegenbase = worldIn.getBiomeGenForCoords(new BlockPos(p_i2060_3_ * 16 + 8, 0, p_i2060_4_ * 16 + 8)); - if (biomegenbase != Biome.jungle && biomegenbase != Biome.jungleHills) + if (biomegenbase != Biome.JUNGLE && biomegenbase != Biome.JUNGLEHILLS) { - if (biomegenbase == Biome.swampland) + if (biomegenbase == Biome.SWAMPLAND) { StructureScattered.SwampHut componentscatteredfeaturepieces$swamphut = new StructureScattered.SwampHut(p_i2060_2_, p_i2060_3_ * 16, p_i2060_4_ * 16); this.components.add(componentscatteredfeaturepieces$swamphut); } - else if (biomegenbase == Biome.desert || biomegenbase == Biome.desertHills) + else if (biomegenbase == Biome.DESERT || biomegenbase == Biome.DESERTHILLS) { StructureScattered.DesertPyramid componentscatteredfeaturepieces$desertpyramid = new StructureScattered.DesertPyramid(p_i2060_2_, p_i2060_3_ * 16, p_i2060_4_ * 16); this.components.add(componentscatteredfeaturepieces$desertpyramid); diff --git a/java/src/game/worldgen/structure/MapGenStronghold.java b/server/src/main/java/server/worldgen/structure/MapGenStronghold.java similarity index 98% rename from java/src/game/worldgen/structure/MapGenStronghold.java rename to server/src/main/java/server/worldgen/structure/MapGenStronghold.java index 760a240..cefc2f3 100755 --- a/java/src/game/worldgen/structure/MapGenStronghold.java +++ b/server/src/main/java/server/worldgen/structure/MapGenStronghold.java @@ -1,9 +1,9 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.List; -import game.rng.Random; -import game.world.WorldServer; +import common.rng.Random; +import server.world.WorldServer; public class MapGenStronghold extends MapGenStructure { diff --git a/java/src/game/worldgen/structure/MapGenStructure.java b/server/src/main/java/server/worldgen/structure/MapGenStructure.java similarity index 81% rename from java/src/game/worldgen/structure/MapGenStructure.java rename to server/src/main/java/server/worldgen/structure/MapGenStructure.java index 7712648..5f6c0d5 100755 --- a/java/src/game/worldgen/structure/MapGenStructure.java +++ b/server/src/main/java/server/worldgen/structure/MapGenStructure.java @@ -1,27 +1,25 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.Iterator; import java.util.Map; -import game.collect.Maps; - -import game.nbt.NBTBase; -import game.nbt.NBTTagCompound; -import game.rng.Random; -import game.world.BlockPos; -import game.world.ChunkPos; -import game.world.LongHashMap; -import game.world.World; -import game.world.WorldServer; -import game.world.WorldServer.WorldSavedData; -import game.worldgen.ChunkPrimer; -import game.worldgen.caves.MapGenBase; +import common.collect.Maps; +import common.rng.Random; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.ChunkPos; +import common.util.LongHashMap; +import common.world.World; +import server.world.WorldServer; +import server.world.WorldServer.WorldSavedData; +import server.worldgen.ChunkPrimer; +import server.worldgen.caves.MapGenBase; public abstract class MapGenStructure extends MapGenBase { private WorldSavedData structureData; protected Map structureMap = Maps.newHashMap(); - + public abstract String getStructureName(); /** @@ -191,38 +189,36 @@ public abstract class MapGenStructure extends MapGenBase // return null; // } - private void initializeStructureData(WorldServer worldIn) + private void initializeStructureData(WorldServer world) { if (this.structureData == null) { - this.structureData = worldIn.loadItemData(this.getStructureName()); + this.structureData = world.loadItemData(this.getStructureName()); if (this.structureData == null) { - this.structureData = new WorldSavedData(this.getStructureName(), new NBTTagCompound()); - worldIn.setItemData(this.getStructureName(), this.structureData); + this.structureData = new WorldSavedData(this.getStructureName(), new TagObject()); + world.setItemData(this.getStructureName(), this.structureData); } else { - NBTTagCompound tag = this.structureData.tag; + TagObject tag = this.structureData.tag; - for (String s : tag.getKeySet()) + for (String s : tag.keySet()) { - NBTBase nbtbase = tag.getTag(s); - - if (nbtbase.getId() == 10) + if (tag.hasObject(s)) { - NBTTagCompound nbttagcompound1 = (NBTTagCompound)nbtbase; + TagObject start = tag.getObject(s); - if (nbttagcompound1.hasKey("ChunkX") && nbttagcompound1.hasKey("ChunkZ")) + if (start.hasInt("ChunkX") && start.hasInt("ChunkZ")) { - int i = nbttagcompound1.getInteger("ChunkX"); - int j = nbttagcompound1.getInteger("ChunkZ"); - StructureStart structurestart = MapGenStructureIO.getStructureStart(nbttagcompound1, worldIn); + int i = start.getInt("ChunkX"); + int j = start.getInt("ChunkZ"); + StructureStart structure = MapGenStructureIO.getStructureStart(start, world); - if (structurestart != null) + if (structure != null) { - this.structureMap.put(Long.valueOf(LongHashMap.packInt(i, j)), structurestart); + this.structureMap.put(Long.valueOf(LongHashMap.packInt(i, j)), structure); } } } @@ -233,7 +229,7 @@ public abstract class MapGenStructure extends MapGenBase private void setStructureStart(int chunkX, int chunkZ, StructureStart start) { - this.structureData.tag.setTag("[" + chunkX + "," + chunkZ + "]", start.writeStructureComponentsToNBT(chunkX, chunkZ)); + this.structureData.tag.setObject("[" + chunkX + "," + chunkZ + "]", start.writeComponents(chunkX, chunkZ)); this.structureData.dirty = true; } diff --git a/java/src/game/worldgen/structure/MapGenStructureIO.java b/server/src/main/java/server/worldgen/structure/MapGenStructureIO.java similarity index 77% rename from java/src/game/worldgen/structure/MapGenStructureIO.java rename to server/src/main/java/server/worldgen/structure/MapGenStructureIO.java index 06a3f4e..0a74793 100755 --- a/java/src/game/worldgen/structure/MapGenStructureIO.java +++ b/server/src/main/java/server/worldgen/structure/MapGenStructureIO.java @@ -1,12 +1,11 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.Map; -import game.collect.Maps; - -import game.log.Log; -import game.nbt.NBTTagCompound; -import game.world.WorldServer; +import common.collect.Maps; +import common.log.Log; +import common.tags.TagObject; +import server.world.WorldServer; public class MapGenStructureIO { @@ -37,7 +36,7 @@ public class MapGenStructureIO return (String)componentClassToNameMap.get(component.getClass()); } - public static StructureStart getStructureStart(NBTTagCompound tagCompound, WorldServer worldIn) + public static StructureStart getStructureStart(TagObject tagCompound, WorldServer worldIn) { StructureStart structurestart = null; @@ -47,28 +46,28 @@ public class MapGenStructureIO if (oclass != null) { - structurestart = (StructureStart)oclass.newInstance(); + structurestart = (StructureStart)oclass.getConstructor().newInstance(); } } catch (Exception exception) { - Log.JNI.warn("Fehler bei Strukturanfang mit ID " + tagCompound.getString("id")); + Log.TICK.warn("Fehler bei Strukturanfang mit ID " + tagCompound.getString("id")); exception.printStackTrace(); } if (structurestart != null) { - structurestart.readStructureComponentsFromNBT(worldIn, tagCompound); + structurestart.readComponents(worldIn, tagCompound); } else { - Log.JNI.warn("Überspringe Struktur mit ID " + tagCompound.getString("id")); + Log.TICK.warn("Überspringe Struktur mit ID " + tagCompound.getString("id")); } return structurestart; } - public static StructureComponent getStructureComponent(NBTTagCompound tagCompound, WorldServer worldIn) + public static StructureComponent getStructureComponent(TagObject tagCompound, WorldServer worldIn) { StructureComponent structurecomponent = null; @@ -78,22 +77,22 @@ public class MapGenStructureIO if (oclass != null) { - structurecomponent = (StructureComponent)oclass.newInstance(); + structurecomponent = (StructureComponent)oclass.getConstructor().newInstance(); } } catch (Exception exception) { - Log.JNI.warn("Fehler bei Strukturteil mit ID " + tagCompound.getString("id")); + Log.TICK.warn("Fehler bei Strukturteil mit ID " + tagCompound.getString("id")); exception.printStackTrace(); } if (structurecomponent != null) { - structurecomponent.readStructureBaseNBT(worldIn, tagCompound); + structurecomponent.readBase(worldIn, tagCompound); } else { - Log.JNI.warn("Überspringe Strukturteil mit ID " + tagCompound.getString("id")); + Log.TICK.warn("Überspringe Strukturteil mit ID " + tagCompound.getString("id")); } return structurecomponent; diff --git a/java/src/game/worldgen/structure/MapGenVillage.java b/server/src/main/java/server/worldgen/structure/MapGenVillage.java similarity index 88% rename from java/src/game/worldgen/structure/MapGenVillage.java rename to server/src/main/java/server/worldgen/structure/MapGenVillage.java index fef7738..fb4a1a6 100755 --- a/java/src/game/worldgen/structure/MapGenVillage.java +++ b/server/src/main/java/server/worldgen/structure/MapGenVillage.java @@ -1,18 +1,17 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.List; import java.util.Set; -import game.collect.Sets; - -import game.biome.Biome; -import game.nbt.NBTTagCompound; -import game.rng.Random; -import game.world.WorldServer; +import common.biome.Biome; +import common.collect.Sets; +import common.rng.Random; +import common.tags.TagObject; +import server.world.WorldServer; public class MapGenVillage extends MapGenStructure { - public static final Set villageSpawnBiomes = Sets.newHashSet(Biome.plains, Biome.desert, Biome.savanna); + public static final Set villageSpawnBiomes = Sets.newHashSet(Biome.PLAINS, Biome.DESERT, Biome.SAVANNA); /** World terrain type, 0 for normal, 1 for flat map */ private int terrainType; @@ -141,16 +140,16 @@ public class MapGenVillage extends MapGenStructure return this.hasMoreThanTwoComponents; } - public void writeToNBT(NBTTagCompound tagCompound) + public void writeTags(TagObject tagCompound) { - super.writeToNBT(tagCompound); - tagCompound.setBoolean("Valid", this.hasMoreThanTwoComponents); + super.writeTags(tagCompound); + tagCompound.setBool("Valid", this.hasMoreThanTwoComponents); } - public void readFromNBT(NBTTagCompound tagCompound) + public void readTags(TagObject tagCompound) { - super.readFromNBT(tagCompound); - this.hasMoreThanTwoComponents = tagCompound.getBoolean("Valid"); + super.readTags(tagCompound); + this.hasMoreThanTwoComponents = tagCompound.getBool("Valid"); } } } diff --git a/java/src/game/worldgen/structure/StructureBoundingBox.java b/server/src/main/java/server/worldgen/structure/StructureBoundingBox.java similarity index 90% rename from java/src/game/worldgen/structure/StructureBoundingBox.java rename to server/src/main/java/server/worldgen/structure/StructureBoundingBox.java index 43bf49f..a4b8110 100755 --- a/java/src/game/worldgen/structure/StructureBoundingBox.java +++ b/server/src/main/java/server/worldgen/structure/StructureBoundingBox.java @@ -1,9 +1,8 @@ -package game.worldgen.structure; +package server.worldgen.structure; -import game.nbt.NBTTagIntArray; -import game.world.BlockPos; -import game.world.Facing; -import game.world.Vec3i; +import common.util.BlockPos; +import common.util.Facing; +import common.util.Vec3i; public class StructureBoundingBox { @@ -42,6 +41,16 @@ public class StructureBoundingBox } } + public StructureBoundingBox(int[] coords, int offset) + { + this.minX = coords[offset + 0]; + this.minY = coords[offset + 1]; + this.minZ = coords[offset + 2]; + this.maxX = coords[offset + 3]; + this.maxY = coords[offset + 4]; + this.maxZ = coords[offset + 5]; + } + /** * returns a new StructureBoundingBox with MAX values */ @@ -209,8 +218,18 @@ public class StructureBoundingBox // return Objects.toStringHelper(this).add("x0", this.minX).add("y0", this.minY).add("z0", this.minZ).add("x1", this.maxX).add("y1", this.maxY).add("z1", this.maxZ).toString(); // } - public NBTTagIntArray toNBTTagIntArray() + public int[] toIntArray() { - return new NBTTagIntArray(new int[] {this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ}); + return new int[] {this.minX, this.minY, this.minZ, this.maxX, this.maxY, this.maxZ}; + } + + public void toIntArray(int[] data, int offset) + { + data[offset + 0] = this.minX; + data[offset + 1] = this.minY; + data[offset + 2] = this.minZ; + data[offset + 3] = this.maxX; + data[offset + 4] = this.maxY; + data[offset + 5] = this.maxZ; } } diff --git a/java/src/game/worldgen/structure/StructureBridge.java b/server/src/main/java/server/worldgen/structure/StructureBridge.java similarity index 97% rename from java/src/game/worldgen/structure/StructureBridge.java rename to server/src/main/java/server/worldgen/structure/StructureBridge.java index 1dcba01..42ccbd3 100755 --- a/java/src/game/worldgen/structure/StructureBridge.java +++ b/server/src/main/java/server/worldgen/structure/StructureBridge.java @@ -1,18 +1,17 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.List; -import game.collect.Lists; - -import game.init.Blocks; -import game.nbt.NBTTagCompound; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityMobSpawner; -import game.world.BlockPos; -import game.world.Facing; -import game.world.WorldServer; -import game.worldgen.LootConstants; +import common.collect.Lists; +import common.entity.npc.EntityDarkMage; +import common.init.Blocks; +import common.rng.Random; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.Facing; +import server.vars.SVars; +import server.world.WorldServer; +import server.worldgen.LootConstants; public class StructureBridge @@ -116,16 +115,16 @@ public class StructureBridge this.field_111021_b = p_i45615_2_.zrange(3) == 0; } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.field_111021_b = tagCompound.getBoolean("Chest"); + super.readTags(tagCompound); + this.field_111021_b = tagCompound.getBool("Chest"); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("Chest", this.field_111021_b); + super.writeTags(tagCompound); + tagCompound.setBool("Chest", this.field_111021_b); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -187,16 +186,16 @@ public class StructureBridge this.field_111020_b = p_i45613_2_.zrange(3) == 0; } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.field_111020_b = tagCompound.getBoolean("Chest"); + super.readTags(tagCompound); + this.field_111020_b = tagCompound.getBool("Chest"); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("Chest", this.field_111020_b); + super.writeTags(tagCompound); + tagCompound.setBool("Chest", this.field_111020_b); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -637,16 +636,16 @@ public class StructureBridge return isAboveGround(structureboundingbox) && StructureComponent.findIntersecting(p_175884_0_, structureboundingbox) == null ? new StructureBridge.End(p_175884_6_, p_175884_1_, structureboundingbox, p_175884_5_) : null; } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.fillSeed = tagCompound.getInteger("Seed"); + super.readTags(tagCompound); + this.fillSeed = tagCompound.getInt("Seed"); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setInteger("Seed", this.fillSeed); + super.writeTags(tagCompound); + tagCompound.setInt("Seed", this.fillSeed); } public boolean addComponentParts(WorldServer worldIn, Random randomIn, StructureBoundingBox structureBoundingBoxIn) @@ -952,11 +951,11 @@ public class StructureBridge super(p_i2054_1_); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { } @@ -1244,14 +1243,14 @@ public class StructureBridge } } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); + super.readTags(tagCompound); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); + super.writeTags(tagCompound); } } @@ -1326,16 +1325,16 @@ public class StructureBridge this.boundingBox = p_i45611_3_; } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.hasSpawner = tagCompound.getBoolean("Mob"); + super.readTags(tagCompound); + this.hasSpawner = tagCompound.getBool("Mob"); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("Mob", this.hasSpawner); + super.writeTags(tagCompound); + tagCompound.setBool("Mob", this.hasSpawner); } public static StructureBridge.Throne func_175874_a(List p_175874_0_, Random p_175874_1_, int p_175874_2_, int p_175874_3_, int p_175874_4_, int p_175874_5_, Facing p_175874_6_) @@ -1365,20 +1364,17 @@ public class StructureBridge this.fillWithBlocks(worldIn, structureBoundingBoxIn, 1, 6, 8, 5, 7, 8, Blocks.blood_brick_fence.getState(), Blocks.blood_brick_fence.getState(), false); this.fillWithBlocks(worldIn, structureBoundingBoxIn, 2, 8, 8, 4, 8, 8, Blocks.blood_brick_fence.getState(), Blocks.blood_brick_fence.getState(), false); - if (!this.hasSpawner) + if (!this.hasSpawner && SVars.mobs && SVars.spawnBridgeMobs) { BlockPos blockpos = new BlockPos(this.getXWithOffset(3, 5), this.getYWithOffset(5), this.getZWithOffset(3, 5)); if (structureBoundingBoxIn.isVecInside(blockpos)) { this.hasSpawner = true; - worldIn.setState(blockpos, Blocks.mob_spawner.getState(), 2); - TileEntity tileentity = worldIn.getTileEntity(blockpos); - - if (tileentity instanceof TileEntityMobSpawner) - { - ((TileEntityMobSpawner)tileentity).setEntityName("DarkMage"); - } + EntityDarkMage entity = new EntityDarkMage(worldIn); + entity.setLocationAndAngles((double)blockpos.getX() + 0.5D, (double)blockpos.getY(), (double)blockpos.getZ() + 0.5D, worldIn.rand.floatv() * 360.0F, 0.0F); + entity.onInitialSpawn(null); + worldIn.spawnEntityInWorld(entity); } } diff --git a/java/src/game/worldgen/structure/StructureComponent.java b/server/src/main/java/server/worldgen/structure/StructureComponent.java similarity index 92% rename from java/src/game/worldgen/structure/StructureComponent.java rename to server/src/main/java/server/worldgen/structure/StructureComponent.java index 4a3fb47..bbc96a9 100755 --- a/java/src/game/worldgen/structure/StructureComponent.java +++ b/server/src/main/java/server/worldgen/structure/StructureComponent.java @@ -1,24 +1,23 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.List; -import game.block.Block; -import game.block.BlockDirectional; -import game.block.BlockDoor; -import game.init.Blocks; -import game.item.ItemDoor; -import game.item.RngLoot; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.rng.Random; -import game.rng.WeightedList; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityChest; -import game.tileentity.TileEntityDispenser; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.BlockDirectional; +import common.block.artificial.BlockDoor; +import common.init.Blocks; +import common.item.ItemDoor; +import common.item.RngLoot; +import common.rng.Random; +import common.rng.WeightedList; +import common.tags.TagObject; +import common.tileentity.TileEntity; +import common.tileentity.TileEntityChest; +import common.tileentity.TileEntityDispenser; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import server.world.WorldServer; public abstract class StructureComponent { @@ -42,47 +41,47 @@ public abstract class StructureComponent /** * Writes structure base data (id, boundingbox, {@link * game.worldgen.structure.StructureComponent#coordBaseMode coordBase} and {@link - * game.worldgen.structure.StructureComponent#componentType componentType}) to new NBTTagCompound and + * game.worldgen.structure.StructureComponent#componentType componentType}) to new tag and * returns it. */ - public NBTTagCompound createStructureBaseNBT() + public TagObject writeBase() { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setString("id", MapGenStructureIO.getStructureComponentName(this)); - nbttagcompound.setTag("BB", this.boundingBox.toNBTTagIntArray()); - nbttagcompound.setInteger("O", this.coordBaseMode == null ? -1 : this.coordBaseMode.getHorizontalIndex()); - nbttagcompound.setInteger("GD", this.componentType); - this.writeStructureToNBT(nbttagcompound); - return nbttagcompound; + TagObject tag = new TagObject(); + tag.setString("id", MapGenStructureIO.getStructureComponentName(this)); + tag.setIntArray("BB", this.boundingBox.toIntArray()); + tag.setInt("O", this.coordBaseMode == null ? -1 : this.coordBaseMode.getHorizontalIndex()); + tag.setInt("GD", this.componentType); + this.writeTags(tag); + return tag; } /** - * (abstract) Helper method to write subclass data to NBT + * (abstract) Helper method to write subclass data to tag */ - protected abstract void writeStructureToNBT(NBTTagCompound tagCompound); + protected abstract void writeTags(TagObject tag); /** * Reads and sets structure base data (boundingbox, {@link * game.worldgen.structure.StructureComponent#coordBaseMode coordBase} and {@link * game.worldgen.structure.StructureComponent#componentType componentType}) */ - public void readStructureBaseNBT(WorldServer worldIn, NBTTagCompound tagCompound) + public void readBase(WorldServer world, TagObject tag) { - if (tagCompound.hasKey("BB")) + if (tag.hasIntArray("BB")) { - this.boundingBox = new StructureBoundingBox(tagCompound.getIntArray("BB")); + this.boundingBox = new StructureBoundingBox(tag.getIntArray("BB")); } - int i = tagCompound.getInteger("O"); + int i = tag.getInt("O"); this.coordBaseMode = i == -1 ? null : Facing.getHorizontal(i); - this.componentType = tagCompound.getInteger("GD"); - this.readStructureFromNBT(tagCompound); + this.componentType = tag.getInt("GD"); + this.readTags(tag); } /** - * (abstract) Helper method to read subclass data from NBT + * (abstract) Helper method to read subclass data from tag */ - protected abstract void readStructureFromNBT(NBTTagCompound tagCompound); + protected abstract void readTags(TagObject tag); /** * Initiates construction of the Structure Component picked, at the current Location of StructGen @@ -638,7 +637,7 @@ public abstract class StructureComponent { for (int k = zMin; k <= zMax; ++k) { - if (!existingOnly || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock().getMaterial() != Material.air) + if (!existingOnly || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() != Blocks.air) { if (i != yMin && i != yMax && j != xMin && j != xMax && k != zMin && k != zMax) { @@ -666,7 +665,7 @@ public abstract class StructureComponent { for (int k = minZ; k <= maxZ; ++k) { - if (!alwaysReplace || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock().getMaterial() != Material.air) + if (!alwaysReplace || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() != Blocks.air) { blockselector.selectBlocks(rand, j, i, k, i == minY || i == maxY || j == minX || j == maxX || k == minZ || k == maxZ); this.setBlockState(worldIn, blockselector.getBlockState(), j, i, k, boundingboxIn); @@ -684,7 +683,7 @@ public abstract class StructureComponent { for (int k = minZ; k <= maxZ; ++k) { - if (rand.floatv() <= chance && (!p_175805_13_ || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock().getMaterial() != Material.air)) + if (rand.floatv() <= chance && (!p_175805_13_ || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() != Blocks.air)) { if (i != minY && i != maxY && j != minX && j != maxX && k != minZ && k != maxZ) { @@ -728,7 +727,7 @@ public abstract class StructureComponent { float f7 = ((float)k - f4) / (f2 * 0.5F); - if (!p_180777_10_ || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock().getMaterial() != Material.air) + if (!p_180777_10_ || this.getBlockStateFromPos(worldIn, j, i, k, boundingboxIn).getBlock() != Blocks.air) { float f8 = f6 * f6 + f5 * f5 + f7 * f7; diff --git a/java/src/game/worldgen/structure/StructureMineshaft.java b/server/src/main/java/server/worldgen/structure/StructureMineshaft.java similarity index 92% rename from java/src/game/worldgen/structure/StructureMineshaft.java rename to server/src/main/java/server/worldgen/structure/StructureMineshaft.java index c73f00f..7ede565 100755 --- a/java/src/game/worldgen/structure/StructureMineshaft.java +++ b/server/src/main/java/server/worldgen/structure/StructureMineshaft.java @@ -1,24 +1,22 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.LinkedList; import java.util.List; -import game.entity.item.EntityChestCart; -import game.init.Blocks; -import game.init.Items; -import game.item.RngLoot; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.rng.Random; -import game.rng.WeightedList; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityMobSpawner; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.LootConstants; +import common.entity.item.EntityChestCart; +import common.entity.npc.EntityArachnoid; +import common.init.Blocks; +import common.init.Items; +import common.item.RngLoot; +import common.rng.Random; +import common.rng.WeightedList; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import server.vars.SVars; +import server.world.WorldServer; +import server.worldgen.LootConstants; public class StructureMineshaft @@ -101,20 +99,20 @@ public class StructureMineshaft { } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - tagCompound.setBoolean("hr", this.hasRails); - tagCompound.setBoolean("sc", this.hasSpiders); - tagCompound.setBoolean("hps", this.spawnerPlaced); - tagCompound.setInteger("Num", this.sectionCount); + tagCompound.setBool("hr", this.hasRails); + tagCompound.setBool("sc", this.hasSpiders); + tagCompound.setBool("hps", this.spawnerPlaced); + tagCompound.setInt("Num", this.sectionCount); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - this.hasRails = tagCompound.getBoolean("hr"); - this.hasSpiders = tagCompound.getBoolean("sc"); - this.spawnerPlaced = tagCompound.getBoolean("hps"); - this.sectionCount = tagCompound.getInteger("Num"); + this.hasRails = tagCompound.getBool("hr"); + this.hasSpiders = tagCompound.getBool("sc"); + this.spawnerPlaced = tagCompound.getBool("hps"); + this.sectionCount = tagCompound.getInt("Num"); } public Corridor(int type, Random rand, StructureBoundingBox structurebb, Facing facing) @@ -289,7 +287,7 @@ public class StructureMineshaft { BlockPos blockpos = new BlockPos(this.getXWithOffset(x, z), this.getYWithOffset(y), this.getZWithOffset(x, z)); - if (boundingBoxIn.isVecInside(blockpos) && worldIn.getState(blockpos).getBlock().getMaterial() == Material.air) + if (boundingBoxIn.isVecInside(blockpos) && worldIn.getState(blockpos).getBlock() == Blocks.air) { int i = rand.chance() ? 1 : 0; worldIn.setState(blockpos, Blocks.rail.getStateFromMeta(this.getMetadataWithOffset(Blocks.rail, i)), 2); @@ -362,7 +360,7 @@ public class StructureMineshaft this.generateChestContents(worldIn, structureBoundingBoxIn, randomIn, 0, 0, k1 + 1, RngLoot.addToList(LootConstants.MINESHAFT_CHEST, Items.enchanted_book.getRandom(randomIn)), 3 + randomIn.zrange(4)); } - if (this.hasSpiders && !this.spawnerPlaced) + if (this.hasSpiders && !this.spawnerPlaced && SVars.mobs && SVars.spawnMineshaftMobs) { int l1 = this.getYWithOffset(0); int i2 = k1 - 1 + randomIn.zrange(3); @@ -373,13 +371,10 @@ public class StructureMineshaft if (structureBoundingBoxIn.isVecInside(blockpos)) { this.spawnerPlaced = true; - worldIn.setState(blockpos, Blocks.mob_spawner.getState(), 2); - TileEntity tileentity = worldIn.getTileEntity(blockpos); - - if (tileentity instanceof TileEntityMobSpawner) - { - ((TileEntityMobSpawner)tileentity).setEntityName("Arachnoid"); - } + EntityArachnoid entity = new EntityArachnoid(worldIn); + entity.setLocationAndAngles((double)blockpos.getX() + 0.5D, (double)blockpos.getY(), (double)blockpos.getZ() + 0.5D, worldIn.rand.floatv() * 360.0F, 0.0F); + entity.onInitialSpawn(null); + worldIn.spawnEntityInWorld(entity); } } } @@ -391,7 +386,7 @@ public class StructureMineshaft int j3 = -1; State iblockstate1 = this.getBlockStateFromPos(worldIn, k2, j3, i3, structureBoundingBoxIn); - if (iblockstate1.getBlock().getMaterial() == Material.air) + if (iblockstate1.getBlock() == Blocks.air) { int k3 = -1; this.setBlockState(worldIn, Blocks.oak_planks.getState(), k2, k3, i3, structureBoundingBoxIn); @@ -405,7 +400,7 @@ public class StructureMineshaft { State iblockstate = this.getBlockStateFromPos(worldIn, 1, -1, l2, structureBoundingBoxIn); - if (iblockstate.getBlock().getMaterial() != Material.air && iblockstate.getBlock().isFullBlock()) + if (iblockstate.getBlock() != Blocks.air && iblockstate.getBlock().isFullBlock()) { this.randomlyPlaceBlock(worldIn, structureBoundingBoxIn, randomIn, 0.7F, 1, 0, l2, Blocks.rail.getStateFromMeta(this.getMetadataWithOffset(Blocks.rail, 0))); } @@ -426,16 +421,16 @@ public class StructureMineshaft { } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - tagCompound.setBoolean("tf", this.isMultipleFloors); - tagCompound.setInteger("D", this.corridorDirection.getHorizontalIndex()); + tagCompound.setBool("tf", this.isMultipleFloors); + tagCompound.setInt("D", this.corridorDirection.getHorizontalIndex()); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - this.isMultipleFloors = tagCompound.getBoolean("tf"); - this.corridorDirection = Facing.getHorizontal(tagCompound.getInteger("D")); + this.isMultipleFloors = tagCompound.getBool("tf"); + this.corridorDirection = Facing.getHorizontal(tagCompound.getInt("D")); } public Cross(int type, Random rand, StructureBoundingBox structurebb, Facing facing) @@ -569,7 +564,7 @@ public class StructureMineshaft { for (int j = this.boundingBox.minZ; j <= this.boundingBox.maxZ; ++j) { - if (this.getBlockStateFromPos(worldIn, i, this.boundingBox.minY - 1, j, structureBoundingBoxIn).getBlock().getMaterial() == Material.air) + if (this.getBlockStateFromPos(worldIn, i, this.boundingBox.minY - 1, j, structureBoundingBoxIn).getBlock() == Blocks.air) { this.setBlockState(worldIn, Blocks.oak_planks.getState(), i, this.boundingBox.minY - 1, j, structureBoundingBoxIn); } @@ -711,25 +706,25 @@ public class StructureMineshaft } } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tag) { - NBTTagList nbttaglist = new NBTTagList(); + int[] rooms = new int[this.roomsLinkedToTheRoom.size() * 6]; - for (StructureBoundingBox structureboundingbox : this.roomsLinkedToTheRoom) + for (int z = 0; z < rooms.length / 6; z++) { - nbttaglist.appendTag(structureboundingbox.toNBTTagIntArray()); + this.roomsLinkedToTheRoom.get(z).toIntArray(rooms, z * 6); } - tagCompound.setTag("Entrances", nbttaglist); + tag.setIntArray("Entrances", rooms); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tag) { - NBTTagList nbttaglist = tagCompound.getTagList("Entrances", 11); + int[] rooms = tag.getIntArray("Entrances"); - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int z = 0; z < rooms.length / 6; z++) { - this.roomsLinkedToTheRoom.add(new StructureBoundingBox(nbttaglist.getIntArrayAt(i))); + this.roomsLinkedToTheRoom.add(new StructureBoundingBox(rooms, z * 6)); } } } @@ -747,11 +742,11 @@ public class StructureMineshaft this.boundingBox = structurebb; } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { } diff --git a/java/src/game/worldgen/structure/StructureMineshaftStart.java b/server/src/main/java/server/worldgen/structure/StructureMineshaftStart.java similarity index 87% rename from java/src/game/worldgen/structure/StructureMineshaftStart.java rename to server/src/main/java/server/worldgen/structure/StructureMineshaftStart.java index bd1763b..789b500 100755 --- a/java/src/game/worldgen/structure/StructureMineshaftStart.java +++ b/server/src/main/java/server/worldgen/structure/StructureMineshaftStart.java @@ -1,7 +1,7 @@ -package game.worldgen.structure; +package server.worldgen.structure; -import game.rng.Random; -import game.world.WorldServer; +import common.rng.Random; +import server.world.WorldServer; public class StructureMineshaftStart extends StructureStart { diff --git a/java/src/game/worldgen/structure/StructureScattered.java b/server/src/main/java/server/worldgen/structure/StructureScattered.java similarity index 93% rename from java/src/game/worldgen/structure/StructureScattered.java rename to server/src/main/java/server/worldgen/structure/StructureScattered.java index fe095d1..5d2705a 100755 --- a/java/src/game/worldgen/structure/StructureScattered.java +++ b/server/src/main/java/server/worldgen/structure/StructureScattered.java @@ -1,24 +1,24 @@ -package game.worldgen.structure; +package server.worldgen.structure; -import game.block.BlockFlower; -import game.block.BlockFlowerPot; -import game.block.BlockLever; -import game.block.BlockSandStone; -import game.block.BlockStoneBrick; -import game.block.BlockTripWire; -import game.block.BlockTripWireHook; -import game.color.DyeColor; -import game.entity.npc.EntityMage; -import game.init.Blocks; -import game.init.Config; -import game.init.Items; -import game.item.RngLoot; -import game.nbt.NBTTagCompound; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.WorldServer; -import game.worldgen.LootConstants; +import common.block.artificial.BlockFlowerPot; +import common.block.artificial.BlockStoneBrick; +import common.block.foliage.BlockFlower; +import common.block.natural.BlockSandStone; +import common.block.tech.BlockLever; +import common.block.tech.BlockTripWire; +import common.block.tech.BlockTripWireHook; +import common.color.DyeColor; +import common.entity.npc.EntityMage; +import common.init.Blocks; +import common.init.Items; +import common.item.RngLoot; +import common.rng.Random; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.Facing; +import server.vars.SVars; +import server.world.WorldServer; +import server.worldgen.LootConstants; public class StructureScattered { @@ -41,22 +41,22 @@ public class StructureScattered super(p_i2062_1_, p_i2062_2_, 64, p_i2062_3_, 21, 15, 21); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("hasPlacedChest0", this.hasPlacedChest[0]); - tagCompound.setBoolean("hasPlacedChest1", this.hasPlacedChest[1]); - tagCompound.setBoolean("hasPlacedChest2", this.hasPlacedChest[2]); - tagCompound.setBoolean("hasPlacedChest3", this.hasPlacedChest[3]); + super.writeTags(tagCompound); + tagCompound.setBool("hasPlacedChest0", this.hasPlacedChest[0]); + tagCompound.setBool("hasPlacedChest1", this.hasPlacedChest[1]); + tagCompound.setBool("hasPlacedChest2", this.hasPlacedChest[2]); + tagCompound.setBool("hasPlacedChest3", this.hasPlacedChest[3]); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.hasPlacedChest[0] = tagCompound.getBoolean("hasPlacedChest0"); - this.hasPlacedChest[1] = tagCompound.getBoolean("hasPlacedChest1"); - this.hasPlacedChest[2] = tagCompound.getBoolean("hasPlacedChest2"); - this.hasPlacedChest[3] = tagCompound.getBoolean("hasPlacedChest3"); + super.readTags(tagCompound); + this.hasPlacedChest[0] = tagCompound.getBool("hasPlacedChest0"); + this.hasPlacedChest[1] = tagCompound.getBool("hasPlacedChest1"); + this.hasPlacedChest[2] = tagCompound.getBool("hasPlacedChest2"); + this.hasPlacedChest[3] = tagCompound.getBool("hasPlacedChest3"); } public boolean addComponentParts(WorldServer worldIn, Random randomIn, StructureBoundingBox structureBoundingBoxIn) @@ -293,20 +293,20 @@ public class StructureScattered } } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - tagCompound.setInteger("Width", this.scatteredFeatureSizeX); - tagCompound.setInteger("Height", this.scatteredFeatureSizeY); - tagCompound.setInteger("Depth", this.scatteredFeatureSizeZ); - tagCompound.setInteger("HPos", this.field_74936_d); + tagCompound.setInt("Width", this.scatteredFeatureSizeX); + tagCompound.setInt("Height", this.scatteredFeatureSizeY); + tagCompound.setInt("Depth", this.scatteredFeatureSizeZ); + tagCompound.setInt("HPos", this.field_74936_d); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - this.scatteredFeatureSizeX = tagCompound.getInteger("Width"); - this.scatteredFeatureSizeY = tagCompound.getInteger("Height"); - this.scatteredFeatureSizeZ = tagCompound.getInteger("Depth"); - this.field_74936_d = tagCompound.getInteger("HPos"); + this.scatteredFeatureSizeX = tagCompound.getInt("Width"); + this.scatteredFeatureSizeY = tagCompound.getInt("Height"); + this.scatteredFeatureSizeZ = tagCompound.getInt("Depth"); + this.field_74936_d = tagCompound.getInt("HPos"); } protected boolean func_74935_a(WorldServer worldIn, StructureBoundingBox p_74935_2_, int p_74935_3_) @@ -366,22 +366,22 @@ public class StructureScattered super(p_i2064_1_, p_i2064_2_, 64, p_i2064_3_, 12, 10, 15); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("placedMainChest", this.placedMainChest); - tagCompound.setBoolean("placedHiddenChest", this.placedHiddenChest); - tagCompound.setBoolean("placedTrap1", this.placedTrap1); - tagCompound.setBoolean("placedTrap2", this.placedTrap2); + super.writeTags(tagCompound); + tagCompound.setBool("placedMainChest", this.placedMainChest); + tagCompound.setBool("placedHiddenChest", this.placedHiddenChest); + tagCompound.setBool("placedTrap1", this.placedTrap1); + tagCompound.setBool("placedTrap2", this.placedTrap2); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.placedMainChest = tagCompound.getBoolean("placedMainChest"); - this.placedHiddenChest = tagCompound.getBoolean("placedHiddenChest"); - this.placedTrap1 = tagCompound.getBoolean("placedTrap1"); - this.placedTrap2 = tagCompound.getBoolean("placedTrap2"); + super.readTags(tagCompound); + this.placedMainChest = tagCompound.getBool("placedMainChest"); + this.placedHiddenChest = tagCompound.getBool("placedHiddenChest"); + this.placedTrap1 = tagCompound.getBool("placedTrap1"); + this.placedTrap2 = tagCompound.getBool("placedTrap2"); } public boolean addComponentParts(WorldServer worldIn, Random randomIn, StructureBoundingBox structureBoundingBoxIn) @@ -613,16 +613,16 @@ public class StructureScattered super(p_i2066_1_, p_i2066_2_, 64, p_i2066_3_, 7, 7, 9); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("Mage", this.hasMage); + super.writeTags(tagCompound); + tagCompound.setBool("Mage", this.hasMage); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.hasMage = tagCompound.getBoolean("Mage"); + super.readTags(tagCompound); + this.hasMage = tagCompound.getBool("Mage"); } public boolean addComponentParts(WorldServer worldIn, Random randomIn, StructureBoundingBox structureBoundingBoxIn) @@ -650,7 +650,7 @@ public class StructureScattered this.setBlockState(worldIn, Blocks.air.getState(), 5, 3, 4, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.air.getState(), 5, 3, 5, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.flower_pot.getState().withProperty(BlockFlowerPot.CONTENTS, 2 + BlockFlower.EnumFlowerType.BLACK_LOTUS.getMeta()), 1, 3, 5, structureBoundingBoxIn); - this.setBlockState(worldIn, Blocks.crafting_table.getState(), 3, 2, 6, structureBoundingBoxIn); + this.setBlockState(worldIn, Blocks.workbench.getState(), 3, 2, 6, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.cauldron.getState(), 4, 2, 6, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.oak_fence.getState(), 1, 2, 1, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.oak_fence.getState(), 5, 2, 1, structureBoundingBoxIn); @@ -671,7 +671,7 @@ public class StructureScattered } } - if (!this.hasMage && Config.mobs && Config.spawnHutMage) + if (!this.hasMage && SVars.mobs && SVars.spawnHutMage) { int l1 = this.getXWithOffset(2, 5); int i2 = this.getYWithOffset(2); diff --git a/java/src/game/worldgen/structure/StructureStart.java b/server/src/main/java/server/worldgen/structure/StructureStart.java similarity index 69% rename from java/src/game/worldgen/structure/StructureStart.java rename to server/src/main/java/server/worldgen/structure/StructureStart.java index 0f200c3..ecb455d 100755 --- a/java/src/game/worldgen/structure/StructureStart.java +++ b/server/src/main/java/server/worldgen/structure/StructureStart.java @@ -1,13 +1,14 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.Iterator; import java.util.LinkedList; -import game.nbt.NBTTagCompound; -import game.nbt.NBTTagList; -import game.rng.Random; -import game.world.ChunkPos; -import game.world.WorldServer; +import common.collect.Lists; +import common.rng.Random; +import common.tags.TagObject; +import java.util.List; +import common.util.ChunkPos; +import server.world.WorldServer; public abstract class StructureStart { @@ -67,50 +68,50 @@ public abstract class StructureStart } } - public NBTTagCompound writeStructureComponentsToNBT(int chunkX, int chunkZ) + public TagObject writeComponents(int chunkX, int chunkZ) { - NBTTagCompound nbttagcompound = new NBTTagCompound(); - nbttagcompound.setString("id", MapGenStructureIO.getStructureStartName(this)); - nbttagcompound.setInteger("ChunkX", chunkX); - nbttagcompound.setInteger("ChunkZ", chunkZ); - nbttagcompound.setTag("BB", this.boundingBox.toNBTTagIntArray()); - NBTTagList nbttaglist = new NBTTagList(); + TagObject tag = new TagObject(); + tag.setString("id", MapGenStructureIO.getStructureStartName(this)); + tag.setInt("ChunkX", chunkX); + tag.setInt("ChunkZ", chunkZ); + tag.setIntArray("BB", this.boundingBox.toIntArray()); + List list = Lists.newArrayList(); - for (StructureComponent structurecomponent : this.components) + for (StructureComponent comp : this.components) { - nbttaglist.appendTag(structurecomponent.createStructureBaseNBT()); + list.add(comp.writeBase()); } - nbttagcompound.setTag("Children", nbttaglist); - this.writeToNBT(nbttagcompound); - return nbttagcompound; + tag.setList("Children", list); + this.writeTags(tag); + return tag; } - public void writeToNBT(NBTTagCompound tagCompound) + public void writeTags(TagObject tag) { } - public void readStructureComponentsFromNBT(WorldServer worldIn, NBTTagCompound tagCompound) + public void readComponents(WorldServer world, TagObject tag) { - this.chunkPosX = tagCompound.getInteger("ChunkX"); - this.chunkPosZ = tagCompound.getInteger("ChunkZ"); + this.chunkPosX = tag.getInt("ChunkX"); + this.chunkPosZ = tag.getInt("ChunkZ"); - if (tagCompound.hasKey("BB")) + if (tag.hasIntArray("BB")) { - this.boundingBox = new StructureBoundingBox(tagCompound.getIntArray("BB")); + this.boundingBox = new StructureBoundingBox(tag.getIntArray("BB")); } - NBTTagList nbttaglist = tagCompound.getTagList("Children", 10); + List list = tag.getList("Children"); - for (int i = 0; i < nbttaglist.tagCount(); ++i) + for (int i = 0; i < list.size(); ++i) { - this.components.add(MapGenStructureIO.getStructureComponent(nbttaglist.getCompoundTagAt(i), worldIn)); + this.components.add(MapGenStructureIO.getStructureComponent(list.get(i), world)); } - this.readFromNBT(tagCompound); + this.readTags(tag); } - public void readFromNBT(NBTTagCompound tagCompound) + public void readTags(TagObject tag) { } diff --git a/java/src/game/worldgen/structure/StructureStronghold.java b/server/src/main/java/server/worldgen/structure/StructureStronghold.java similarity index 95% rename from java/src/game/worldgen/structure/StructureStronghold.java rename to server/src/main/java/server/worldgen/structure/StructureStronghold.java index e76b7ac..b96c6c4 100755 --- a/java/src/game/worldgen/structure/StructureStronghold.java +++ b/server/src/main/java/server/worldgen/structure/StructureStronghold.java @@ -1,24 +1,23 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.List; import java.util.Map; -import game.collect.Lists; -import game.collect.Maps; - -import game.block.BlockSlab; -import game.block.BlockStoneBrick; -import game.init.Blocks; -import game.init.Items; -import game.item.RngLoot; -import game.nbt.NBTTagCompound; -import game.rng.Random; -import game.tileentity.TileEntity; -import game.tileentity.TileEntityMobSpawner; -import game.world.BlockPos; -import game.world.Facing; -import game.world.WorldServer; -import game.worldgen.LootConstants; +import common.block.artificial.BlockSlab; +import common.block.artificial.BlockStoneBrick; +import common.collect.Lists; +import common.collect.Maps; +import common.entity.npc.EntityHaunter; +import common.init.Blocks; +import common.init.Items; +import common.item.RngLoot; +import common.rng.Random; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.Facing; +import server.vars.SVars; +import server.world.WorldServer; +import server.worldgen.LootConstants; public class StructureStronghold @@ -253,16 +252,16 @@ public class StructureStronghold this.boundingBox = p_i45582_3_; } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("Chest", this.hasMadeChest); + super.writeTags(tagCompound); + tagCompound.setBool("Chest", this.hasMadeChest); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.hasMadeChest = tagCompound.getBoolean("Chest"); + super.readTags(tagCompound); + this.hasMadeChest = tagCompound.getBool("Chest"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -325,16 +324,16 @@ public class StructureStronghold this.field_74993_a = p_i45581_4_ != Facing.NORTH && p_i45581_4_ != Facing.SOUTH ? p_i45581_3_.getXSize() : p_i45581_3_.getZSize(); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setInteger("Steps", this.field_74993_a); + super.writeTags(tagCompound); + tagCompound.setInt("Steps", this.field_74993_a); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.field_74993_a = tagCompound.getInteger("Steps"); + super.readTags(tagCompound); + this.field_74993_a = tagCompound.getInt("Steps"); } public static StructureBoundingBox func_175869_a(List p_175869_0_, Random p_175869_1_, int p_175869_2_, int p_175869_3_, int p_175869_4_, Facing p_175869_5_) @@ -426,22 +425,22 @@ public class StructureStronghold this.field_74999_h = p_i45580_2_.zrange(3) > 0; } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("leftLow", this.field_74996_b); - tagCompound.setBoolean("leftHigh", this.field_74997_c); - tagCompound.setBoolean("rightLow", this.field_74995_d); - tagCompound.setBoolean("rightHigh", this.field_74999_h); + super.writeTags(tagCompound); + tagCompound.setBool("leftLow", this.field_74996_b); + tagCompound.setBool("leftHigh", this.field_74997_c); + tagCompound.setBool("rightLow", this.field_74995_d); + tagCompound.setBool("rightHigh", this.field_74999_h); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.field_74996_b = tagCompound.getBoolean("leftLow"); - this.field_74997_c = tagCompound.getBoolean("leftHigh"); - this.field_74995_d = tagCompound.getBoolean("rightLow"); - this.field_74999_h = tagCompound.getBoolean("rightHigh"); + super.readTags(tagCompound); + this.field_74996_b = tagCompound.getBool("leftLow"); + this.field_74997_c = tagCompound.getBool("leftHigh"); + this.field_74995_d = tagCompound.getBool("rightLow"); + this.field_74999_h = tagCompound.getBool("rightHigh"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -609,16 +608,16 @@ public class StructureStronghold this.isLargeRoom = p_i45578_3_.getYSize() > 6; } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("Tall", this.isLargeRoom); + super.writeTags(tagCompound); + tagCompound.setBool("Tall", this.isLargeRoom); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.isLargeRoom = tagCompound.getBoolean("Tall"); + super.readTags(tagCompound); + this.isLargeRoom = tagCompound.getBool("Tall"); } public static StructureStronghold.Library func_175864_a(List p_175864_0_, Random p_175864_1_, int p_175864_2_, int p_175864_3_, int p_175864_4_, Facing p_175864_5_, int p_175864_6_) @@ -793,16 +792,16 @@ public class StructureStronghold this.boundingBox = p_i45577_3_; } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("Mob", this.hasSpawner); + super.writeTags(tagCompound); + tagCompound.setBool("Mob", this.hasSpawner); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.hasSpawner = tagCompound.getBoolean("Mob"); + super.readTags(tagCompound); + this.hasSpawner = tagCompound.getBool("Mob"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -900,7 +899,7 @@ public class StructureStronghold // this.setBlockState(worldIn, Blocks.end_portal_frame.getStateFromMeta(j1).withProperty(BlockPortalFrame.ORB, Boolean.valueOf(randomIn.floatv() > 0.9F)), 7, 3, 10, structureBoundingBoxIn); // this.setBlockState(worldIn, Blocks.end_portal_frame.getStateFromMeta(j1).withProperty(BlockPortalFrame.ORB, Boolean.valueOf(randomIn.floatv() > 0.9F)), 7, 3, 11, structureBoundingBoxIn); - if (!this.hasSpawner) + if (!this.hasSpawner && SVars.mobs && SVars.spawnStrongholdMobs) { i = this.getYWithOffset(3); BlockPos blockpos = new BlockPos(this.getXWithOffset(5, 6), i, this.getZWithOffset(5, 6)); @@ -908,13 +907,10 @@ public class StructureStronghold if (structureBoundingBoxIn.isVecInside(blockpos)) { this.hasSpawner = true; - worldIn.setState(blockpos, Blocks.mob_spawner.getState(), 2); - TileEntity tileentity = worldIn.getTileEntity(blockpos); - - if (tileentity instanceof TileEntityMobSpawner) - { - ((TileEntityMobSpawner)tileentity).setEntityName("Haunter"); - } + EntityHaunter entity = new EntityHaunter(worldIn); + entity.setLocationAndAngles((double)blockpos.getX() + 0.5D, (double)blockpos.getY() + 1.0D, (double)blockpos.getZ() + 0.5D, worldIn.rand.floatv() * 360.0F, 0.0F); + entity.onInitialSpawn(null); + worldIn.spawnEntityInWorld(entity); } } @@ -1031,16 +1027,16 @@ public class StructureStronghold this.roomType = p_i45575_2_.zrange(5); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setInteger("Type", this.roomType); + super.writeTags(tagCompound); + tagCompound.setInt("Type", this.roomType); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.roomType = tagCompound.getInteger("Type"); + super.readTags(tagCompound); + this.roomType = tagCompound.getInt("Type"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -1200,16 +1196,16 @@ public class StructureStronghold this.boundingBox = p_i45574_3_; } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("Source", this.field_75024_a); + super.writeTags(tagCompound); + tagCompound.setBool("Source", this.field_75024_a); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.field_75024_a = tagCompound.getBoolean("Source"); + super.readTags(tagCompound); + this.field_75024_a = tagCompound.getBool("Source"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -1394,18 +1390,18 @@ public class StructureStronghold this.expandsZ = p_i45573_2_.zrange(2) == 0; } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("Left", this.expandsX); - tagCompound.setBoolean("Right", this.expandsZ); + super.writeTags(tagCompound); + tagCompound.setBool("Left", this.expandsX); + tagCompound.setBool("Right", this.expandsZ); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.expandsX = tagCompound.getBoolean("Left"); - this.expandsZ = tagCompound.getBoolean("Right"); + super.readTags(tagCompound); + this.expandsX = tagCompound.getBool("Left"); + this.expandsZ = tagCompound.getBool("Right"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -1473,12 +1469,12 @@ public class StructureStronghold super(p_i2087_1_); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { tagCompound.setString("EntryDoor", this.field_143013_d.getName()); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { this.field_143013_d = StructureStronghold.Stronghold.Door.getByName(tagCompound.getString("EntryDoor")); } diff --git a/java/src/game/worldgen/structure/StructureVillage.java b/server/src/main/java/server/worldgen/structure/StructureVillage.java similarity index 94% rename from java/src/game/worldgen/structure/StructureVillage.java rename to server/src/main/java/server/worldgen/structure/StructureVillage.java index 1188590..d88fb76 100755 --- a/java/src/game/worldgen/structure/StructureVillage.java +++ b/server/src/main/java/server/worldgen/structure/StructureVillage.java @@ -1,31 +1,29 @@ -package game.worldgen.structure; +package server.worldgen.structure; import java.util.Iterator; import java.util.List; -import game.collect.Lists; - -import game.biome.Biome; -import game.block.Block; -import game.block.BlockLog; -import game.block.BlockSandStone; -import game.block.BlockSlab; -import game.block.BlockStairs; -import game.block.BlockTorch; -import game.color.DyeColor; -import game.entity.npc.EntityHuman; -import game.init.BlockRegistry; -import game.init.Blocks; -import game.init.Config; -import game.material.Material; -import game.nbt.NBTTagCompound; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.WorldServer; -import game.worldgen.BiomeGenerator; -import game.worldgen.LootConstants; +import common.biome.Biome; +import common.block.Block; +import common.block.artificial.BlockSlab; +import common.block.artificial.BlockStairs; +import common.block.foliage.BlockLog; +import common.block.natural.BlockSandStone; +import common.block.tech.BlockTorch; +import common.collect.Lists; +import common.color.DyeColor; +import common.entity.npc.EntityHuman; +import common.init.BlockRegistry; +import common.init.Blocks; +import common.rng.Random; +import common.tags.TagObject; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import server.vars.SVars; +import server.world.WorldServer; +import server.worldgen.BiomeGenerator; +import server.worldgen.LootConstants; public class StructureVillage @@ -359,7 +357,7 @@ public class StructureVillage this.setBlockState(worldIn, Blocks.air.getState(), 2, 2, 0, structureBoundingBoxIn); this.placeDoorCurrentPosition(worldIn, structureBoundingBoxIn, randomIn, 2, 1, 0, Facing.getHorizontal(this.getMetadataWithOffset(Blocks.oak_door, 1))); - if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) + if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 2, 0, -1, structureBoundingBoxIn); } @@ -405,22 +403,22 @@ public class StructureVillage this.cropTypeD = this.func_151559_a(rand); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setInteger("CA", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeA)); - tagCompound.setInteger("CB", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeB)); - tagCompound.setInteger("CC", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeC)); - tagCompound.setInteger("CD", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeD)); + super.writeTags(tagCompound); + tagCompound.setString("CA", BlockRegistry.getNameFromBlock(this.cropTypeA)); + tagCompound.setString("CB", BlockRegistry.getNameFromBlock(this.cropTypeB)); + tagCompound.setString("CC", BlockRegistry.getNameFromBlock(this.cropTypeC)); + tagCompound.setString("CD", BlockRegistry.getNameFromBlock(this.cropTypeD)); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.cropTypeA = BlockRegistry.getBlockById(tagCompound.getInteger("CA")); - this.cropTypeB = BlockRegistry.getBlockById(tagCompound.getInteger("CB")); - this.cropTypeC = BlockRegistry.getBlockById(tagCompound.getInteger("CC")); - this.cropTypeD = BlockRegistry.getBlockById(tagCompound.getInteger("CD")); + super.readTags(tagCompound); + this.cropTypeA = BlockRegistry.getRegisteredBlock(tagCompound.getString("CA")); + this.cropTypeB = BlockRegistry.getRegisteredBlock(tagCompound.getString("CB")); + this.cropTypeC = BlockRegistry.getRegisteredBlock(tagCompound.getString("CC")); + this.cropTypeD = BlockRegistry.getRegisteredBlock(tagCompound.getString("CD")); } private Block func_151559_a(Random rand) @@ -514,18 +512,18 @@ public class StructureVillage this.cropTypeB = this.func_151560_a(rand); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setInteger("CA", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeA)); - tagCompound.setInteger("CB", BlockRegistry.REGISTRY.getIDForObject(this.cropTypeB)); + super.writeTags(tagCompound); + tagCompound.setString("CA", BlockRegistry.getNameFromBlock(this.cropTypeA)); + tagCompound.setString("CB", BlockRegistry.getNameFromBlock(this.cropTypeB)); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.cropTypeA = BlockRegistry.getBlockById(tagCompound.getInteger("CA")); - this.cropTypeB = BlockRegistry.getBlockById(tagCompound.getInteger("CB")); + super.readTags(tagCompound); + this.cropTypeA = BlockRegistry.getRegisteredBlock(tagCompound.getString("CA")); + this.cropTypeB = BlockRegistry.getRegisteredBlock(tagCompound.getString("CB")); } private Block func_151560_a(Random rand) @@ -684,7 +682,7 @@ public class StructureVillage this.setBlockState(worldIn, Blocks.torch.getState().withProperty(BlockTorch.FACING, this.coordBaseMode), 2, 3, 1, structureBoundingBoxIn); this.placeDoorCurrentPosition(worldIn, structureBoundingBoxIn, randomIn, 2, 1, 0, Facing.getHorizontal(this.getMetadataWithOffset(Blocks.oak_door, 1))); - if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) + if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 2, 0, -1, structureBoundingBoxIn); } @@ -807,12 +805,12 @@ public class StructureVillage this.setBlockState(worldIn, Blocks.wooden_pressure_plate.getState(), 6, 2, 3, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.oak_fence.getState(), 4, 1, 3, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.wooden_pressure_plate.getState(), 4, 2, 3, structureBoundingBoxIn); - this.setBlockState(worldIn, Blocks.crafting_table.getState(), 7, 1, 1, structureBoundingBoxIn); + this.setBlockState(worldIn, Blocks.workbench.getState(), 7, 1, 1, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.air.getState(), 1, 1, 0, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.air.getState(), 1, 2, 0, structureBoundingBoxIn); this.placeDoorCurrentPosition(worldIn, structureBoundingBoxIn, randomIn, 1, 1, 0, Facing.getHorizontal(this.getMetadataWithOffset(Blocks.oak_door, 1))); - if (this.getBlockStateFromPos(worldIn, 1, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 1, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) + if (this.getBlockStateFromPos(worldIn, 1, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 1, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 1, 0, -1, structureBoundingBoxIn); } @@ -857,16 +855,16 @@ public class StructureVillage return canVillageGoDeeper(structureboundingbox) && StructureComponent.findIntersecting(p_175855_1_, structureboundingbox) == null ? new StructureVillage.House2(start, p_175855_7_, rand, structureboundingbox, facing) : null; } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("Chest", this.hasMadeChest); + super.writeTags(tagCompound); + tagCompound.setBool("Chest", this.hasMadeChest); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.hasMadeChest = tagCompound.getBoolean("Chest"); + super.readTags(tagCompound); + this.hasMadeChest = tagCompound.getBool("Chest"); } public boolean addComponentParts(WorldServer worldIn, Random randomIn, StructureBoundingBox structureBoundingBoxIn) @@ -927,7 +925,7 @@ public class StructureVillage for (int i = 6; i <= 8; ++i) { - if (this.getBlockStateFromPos(worldIn, i, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, i, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) + if (this.getBlockStateFromPos(worldIn, i, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, i, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), i, 0, -1, structureBoundingBoxIn); } @@ -1081,7 +1079,7 @@ public class StructureVillage this.placeDoorCurrentPosition(worldIn, structureBoundingBoxIn, randomIn, 2, 1, 0, Facing.getHorizontal(this.getMetadataWithOffset(Blocks.oak_door, 1))); this.fillWithBlocks(worldIn, structureBoundingBoxIn, 1, 0, -1, 3, 2, -1, Blocks.air.getState(), Blocks.air.getState(), false); - if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) + if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 2, 0, -1, structureBoundingBoxIn); } @@ -1125,16 +1123,16 @@ public class StructureVillage this.isRoofAccessible = rand.chance(); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("Terrace", this.isRoofAccessible); + super.writeTags(tagCompound); + tagCompound.setBool("Terrace", this.isRoofAccessible); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.isRoofAccessible = tagCompound.getBoolean("Terrace"); + super.readTags(tagCompound); + this.isRoofAccessible = tagCompound.getBool("Terrace"); } public static StructureVillage.House4Garden func_175858_a(StructureVillage.Start start, List p_175858_1_, Random rand, int p_175858_3_, int p_175858_4_, int p_175858_5_, Facing facing, int p_175858_7_) @@ -1186,7 +1184,7 @@ public class StructureVillage this.setBlockState(worldIn, Blocks.oak_planks.getState(), 3, 2, 0, structureBoundingBoxIn); this.setBlockState(worldIn, Blocks.oak_planks.getState(), 3, 1, 0, structureBoundingBoxIn); - if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) + if (this.getBlockStateFromPos(worldIn, 2, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 2, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 2, 0, -1, structureBoundingBoxIn); } @@ -1254,16 +1252,16 @@ public class StructureVillage this.length = Math.max(p_i45562_4_.getXSize(), p_i45562_4_.getZSize()); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setInteger("Length", this.length); + super.writeTags(tagCompound); + tagCompound.setInt("Length", this.length); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.length = tagCompound.getInteger("Length"); + super.readTags(tagCompound); + this.length = tagCompound.getInt("Length"); } public void buildComponent(StructureComponent componentIn, List listIn, Random rand) @@ -1432,7 +1430,7 @@ public class StructureVillage this.structureVillageWeightedPieceList = p_i2104_6_; this.terrainType = p_i2104_7_; Biome biomegenbase = genIn.getBiomeGenerator(new BlockPos(p_i2104_4_, 0, p_i2104_5_), Biome.DEF_BIOME); - this.inDesert = biomegenbase == Biome.desert || biomegenbase == Biome.desertHills; + this.inDesert = biomegenbase == Biome.DESERT || biomegenbase == Biome.DESERTHILLS; this.func_175846_a(this.inDesert); } @@ -1509,18 +1507,18 @@ public class StructureVillage } } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - tagCompound.setInteger("HPos", this.field_143015_k); - tagCompound.setInteger("VCount", this.villagersSpawned); - tagCompound.setBoolean("Desert", this.isDesertVillage); + tagCompound.setInt("HPos", this.field_143015_k); + tagCompound.setInt("VCount", this.villagersSpawned); + tagCompound.setBool("Desert", this.isDesertVillage); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - this.field_143015_k = tagCompound.getInteger("HPos"); - this.villagersSpawned = tagCompound.getInteger("VCount"); - this.isDesertVillage = tagCompound.getBoolean("Desert"); + this.field_143015_k = tagCompound.getInt("HPos"); + this.villagersSpawned = tagCompound.getInt("VCount"); + this.isDesertVillage = tagCompound.getBool("Desert"); } protected StructureComponent getNextComponentNN(StructureVillage.Start start, List p_74891_2_, Random rand, int p_74891_4_, int p_74891_5_) @@ -1606,7 +1604,7 @@ public class StructureVillage protected void spawnVillagers(WorldServer worldIn, StructureBoundingBox p_74893_2_, int p_74893_3_, int p_74893_4_, int p_74893_5_, int p_74893_6_) { - if (this.villagersSpawned < p_74893_6_ && Config.mobs && Config.spawnVillager) + if (this.villagersSpawned < p_74893_6_ && SVars.mobs && SVars.spawnVillager) { for (int i = this.villagersSpawned; i < p_74893_6_; ++i) { @@ -1791,18 +1789,18 @@ public class StructureVillage this.tablePosition = rand.zrange(3); } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setInteger("T", this.tablePosition); - tagCompound.setBoolean("C", this.isTallHouse); + super.writeTags(tagCompound); + tagCompound.setInt("T", this.tablePosition); + tagCompound.setBool("C", this.isTallHouse); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.tablePosition = tagCompound.getInteger("T"); - this.isTallHouse = tagCompound.getBoolean("C"); + super.readTags(tagCompound); + this.tablePosition = tagCompound.getInt("T"); + this.isTallHouse = tagCompound.getBool("C"); } public static StructureVillage.WoodHut func_175853_a(StructureVillage.Start start, List p_175853_1_, Random rand, int p_175853_3_, int p_175853_4_, int p_175853_5_, Facing facing, int p_175853_7_) @@ -1869,7 +1867,7 @@ public class StructureVillage this.setBlockState(worldIn, Blocks.air.getState(), 1, 2, 0, structureBoundingBoxIn); this.placeDoorCurrentPosition(worldIn, structureBoundingBoxIn, randomIn, 1, 1, 0, Facing.getHorizontal(this.getMetadataWithOffset(Blocks.oak_door, 1))); - if (this.getBlockStateFromPos(worldIn, 1, 0, -1, structureBoundingBoxIn).getBlock().getMaterial() == Material.air && this.getBlockStateFromPos(worldIn, 1, -1, -1, structureBoundingBoxIn).getBlock().getMaterial() != Material.air) + if (this.getBlockStateFromPos(worldIn, 1, 0, -1, structureBoundingBoxIn).getBlock() == Blocks.air && this.getBlockStateFromPos(worldIn, 1, -1, -1, structureBoundingBoxIn).getBlock() != Blocks.air) { this.setBlockState(worldIn, Blocks.cobblestone_stairs.getStateFromMeta(this.getMetadataWithOffset(Blocks.cobblestone_stairs, 3)), 1, 0, -1, structureBoundingBoxIn); } @@ -1903,16 +1901,16 @@ public class StructureVillage this.boundingBox = p_i45565_4_; } - protected void writeStructureToNBT(NBTTagCompound tagCompound) + protected void writeTags(TagObject tagCompound) { - super.writeStructureToNBT(tagCompound); - tagCompound.setBoolean("VSpawn", this.villagerSpawned); + super.writeTags(tagCompound); + tagCompound.setBool("VSpawn", this.villagerSpawned); } - protected void readStructureFromNBT(NBTTagCompound tagCompound) + protected void readTags(TagObject tagCompound) { - super.readStructureFromNBT(tagCompound); - this.villagerSpawned = tagCompound.getBoolean("VSpawn"); + super.readTags(tagCompound); + this.villagerSpawned = tagCompound.getBool("VSpawn"); } public static StructureVillage.Cage func_175853_a(StructureVillage.Start start, List p_175853_1_, Random rand, int p_175853_3_, int p_175853_4_, int p_175853_5_, Facing facing, int p_175853_7_) @@ -1923,7 +1921,7 @@ public class StructureVillage protected void spawnVillager(WorldServer worldIn, StructureBoundingBox p_74893_2_, int x, int y, int z) { - if (!this.villagerSpawned && Config.mobs && Config.spawnCagedVillager) + if (!this.villagerSpawned && SVars.mobs && SVars.spawnCageMobs) { int j = this.getXWithOffset(x, z); int k = this.getYWithOffset(y); diff --git a/java/src/game/worldgen/tree/WorldGenBaseTree.java b/server/src/main/java/server/worldgen/tree/WorldGenBaseTree.java similarity index 90% rename from java/src/game/worldgen/tree/WorldGenBaseTree.java rename to server/src/main/java/server/worldgen/tree/WorldGenBaseTree.java index 464f038..5858316 100755 --- a/java/src/game/worldgen/tree/WorldGenBaseTree.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenBaseTree.java @@ -1,17 +1,17 @@ -package game.worldgen.tree; +package server.worldgen.tree; -import game.block.Block; -import game.block.BlockCocoa; -import game.block.BlockLeaves; -import game.block.BlockVine; -import game.init.Blocks; -import game.material.Material; -import game.properties.PropertyBool; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockCocoa; +import common.block.foliage.BlockLeaves; +import common.block.foliage.BlockVine; +import common.init.Blocks; +import common.properties.PropertyBool; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import server.world.WorldServer; public class WorldGenBaseTree extends WorldGenTree { @@ -116,7 +116,7 @@ public class WorldGenBaseTree extends WorldGenTree BlockPos blockpos = new BlockPos(k1, i3, i2); Block block = worldIn.getState(blockpos).getBlock(); - if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves || block.getMaterial() == Material.vine) + if (block == Blocks.air || block.getMaterial() == Material.LEAVES || block.getMaterial() == Material.BUSH) { this.setBlockAndNotifyAdequately(worldIn, blockpos, this.metaLeaves.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(blockpos))); } @@ -129,7 +129,7 @@ public class WorldGenBaseTree extends WorldGenTree { Block block2 = worldIn.getState(position.up(j3)).getBlock(); - if (block2.getMaterial() == Material.air || block2.getMaterial() == Material.leaves || block2.getMaterial() == Material.vine) + if (block2 == Blocks.air || block2.getMaterial() == Material.LEAVES || block2.getMaterial() == Material.BUSH) { this.setBlockAndNotifyAdequately(worldIn, position.up(j3), this.metaWood); @@ -172,29 +172,29 @@ public class WorldGenBaseTree extends WorldGenTree { blockpos$mutableblockpos1.set(l4, k3, i5); - if (worldIn.getState(blockpos$mutableblockpos1).getBlock().getMaterial() == Material.leaves) + if (worldIn.getState(blockpos$mutableblockpos1).getBlock().getMaterial() == Material.LEAVES) { BlockPos blockpos2 = blockpos$mutableblockpos1.west(); BlockPos blockpos3 = blockpos$mutableblockpos1.east(); BlockPos blockpos4 = blockpos$mutableblockpos1.north(); BlockPos blockpos1 = blockpos$mutableblockpos1.south(); - if (rand.zrange(4) == 0 && worldIn.getState(blockpos2).getBlock().getMaterial() == Material.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos2).getBlock() == Blocks.air) { this.func_181650_b(worldIn, blockpos2, BlockVine.EAST); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos3).getBlock().getMaterial() == Material.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos3).getBlock() == Blocks.air) { this.func_181650_b(worldIn, blockpos3, BlockVine.WEST); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos4).getBlock().getMaterial() == Material.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos4).getBlock() == Blocks.air) { this.func_181650_b(worldIn, blockpos4, BlockVine.SOUTH); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos1).getBlock().getMaterial() == Material.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos1).getBlock() == Blocks.air) { this.func_181650_b(worldIn, blockpos1, BlockVine.NORTH); } @@ -248,7 +248,7 @@ public class WorldGenBaseTree extends WorldGenTree this.func_181651_a(p_181650_1_, p_181650_2_, p_181650_3_); int i = 4; - for (p_181650_2_ = p_181650_2_.down(); p_181650_1_.getState(p_181650_2_).getBlock().getMaterial() == Material.air && i > 0; --i) + for (p_181650_2_ = p_181650_2_.down(); p_181650_1_.getState(p_181650_2_).getBlock() == Blocks.air && i > 0; --i) { this.func_181651_a(p_181650_1_, p_181650_2_, p_181650_3_); p_181650_2_ = p_181650_2_.down(); diff --git a/java/src/game/worldgen/tree/WorldGenBigTree.java b/server/src/main/java/server/worldgen/tree/WorldGenBigTree.java similarity index 95% rename from java/src/game/worldgen/tree/WorldGenBigTree.java rename to server/src/main/java/server/worldgen/tree/WorldGenBigTree.java index fba563a..4daf686 100755 --- a/java/src/game/worldgen/tree/WorldGenBigTree.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenBigTree.java @@ -1,19 +1,18 @@ -package game.worldgen.tree; +package server.worldgen.tree; import java.util.List; -import game.collect.Lists; - -import game.block.Block; -import game.block.BlockLeaves; -import game.block.BlockLog; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockLeaves; +import common.block.foliage.BlockLog; +import common.collect.Lists; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.State; +import server.world.WorldServer; public class WorldGenBigTree extends WorldGenTree { @@ -126,9 +125,9 @@ public class WorldGenBigTree extends WorldGenTree if (Math.pow((double)Math.abs(j) + 0.5D, 2.0D) + Math.pow((double)Math.abs(k) + 0.5D, 2.0D) <= (double)(p_181631_2_ * p_181631_2_)) { BlockPos blockpos = p_181631_1_.add(j, 0, k); - Material material = this.world.getState(blockpos).getBlock().getMaterial(); + Block block = this.world.getState(blockpos).getBlock(); - if (material == Material.air || material == Material.leaves) + if (block == Blocks.air || block.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(this.world, blockpos, p_181631_3_); } diff --git a/java/src/game/worldgen/tree/WorldGenBirch.java b/server/src/main/java/server/worldgen/tree/WorldGenBirch.java similarity index 90% rename from java/src/game/worldgen/tree/WorldGenBirch.java rename to server/src/main/java/server/worldgen/tree/WorldGenBirch.java index bde4f4e..58bdda1 100755 --- a/java/src/game/worldgen/tree/WorldGenBirch.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenBirch.java @@ -1,13 +1,13 @@ -package game.worldgen.tree; +package server.worldgen.tree; -import game.block.Block; -import game.block.BlockLeaves; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockLeaves; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; public class WorldGenBirch extends WorldGenTree { @@ -101,7 +101,7 @@ public class WorldGenBirch extends WorldGenTree BlockPos blockpos = new BlockPos(i3, i2, k1); Block block = worldIn.getState(blockpos).getBlock(); - if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves) + if (block == Blocks.air || block.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(worldIn, blockpos, leavesBlock.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(blockpos))); } @@ -114,7 +114,7 @@ public class WorldGenBirch extends WorldGenTree { Block block2 = worldIn.getState(position.up(j2)).getBlock(); - if (block2.getMaterial() == Material.air || block2.getMaterial() == Material.leaves) + if (block2 == Blocks.air || block2.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(worldIn, position.up(j2), logBlock); } diff --git a/java/src/game/worldgen/tree/WorldGenDarkOak.java b/server/src/main/java/server/worldgen/tree/WorldGenDarkOak.java similarity index 93% rename from java/src/game/worldgen/tree/WorldGenDarkOak.java rename to server/src/main/java/server/worldgen/tree/WorldGenDarkOak.java index 6c7379a..65286b2 100755 --- a/java/src/game/worldgen/tree/WorldGenDarkOak.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenDarkOak.java @@ -1,14 +1,14 @@ -package game.worldgen.tree; +package server.worldgen.tree; -import game.block.Block; -import game.block.BlockLeaves; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockLeaves; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import server.world.WorldServer; public class WorldGenDarkOak extends WorldGenTree { @@ -66,9 +66,9 @@ public class WorldGenDarkOak extends WorldGenTree int k2 = k + j2; BlockPos blockpos1 = new BlockPos(k1, k2, l1); - Material material = worldIn.getState(blockpos1).getBlock().getMaterial(); + Block block1 = worldIn.getState(blockpos1).getBlock(); - if (material == Material.air || material == Material.leaves) + if (block1 == Blocks.air || block1.getMaterial() == Material.LEAVES) { this.func_181639_b(worldIn, blockpos1); this.func_181639_b(worldIn, blockpos1.east()); @@ -210,7 +210,7 @@ public class WorldGenDarkOak extends WorldGenTree BlockPos blockpos = new BlockPos(p_150526_2_, p_150526_3_, p_150526_4_); Block block = worldIn.getState(blockpos).getBlock(); - if (block.getMaterial() == Material.air) + if (block == Blocks.air) { this.setBlockAndNotifyAdequately(worldIn, blockpos, leavesBlock.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(blockpos))); } diff --git a/java/src/game/worldgen/tree/WorldGenHugeTree.java b/server/src/main/java/server/worldgen/tree/WorldGenHugeTree.java similarity index 88% rename from java/src/game/worldgen/tree/WorldGenHugeTree.java rename to server/src/main/java/server/worldgen/tree/WorldGenHugeTree.java index 145f879..05ddd76 100755 --- a/java/src/game/worldgen/tree/WorldGenHugeTree.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenHugeTree.java @@ -1,13 +1,13 @@ -package game.worldgen.tree; +package server.worldgen.tree; -import game.block.Block; -import game.block.BlockLeaves; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockLeaves; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; public abstract class WorldGenHugeTree extends WorldGenTree { @@ -119,9 +119,9 @@ public abstract class WorldGenHugeTree extends WorldGenTree if (j * j + k * k <= i || l * l + i1 * i1 <= i || j * j + i1 * i1 <= i || l * l + k * k <= i) { BlockPos blockpos = p_175925_2_.add(j, 0, k); - Material material = worldIn.getState(blockpos).getBlock().getMaterial(); + Block block = worldIn.getState(blockpos).getBlock(); - if (material == Material.air || material == Material.leaves) + if (block == Blocks.air || block.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(worldIn, blockpos, this.leavesMetadata.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(blockpos))); } @@ -141,9 +141,9 @@ public abstract class WorldGenHugeTree extends WorldGenTree if (j * j + k * k <= i) { BlockPos blockpos = p_175928_2_.add(j, 0, k); - Material material = worldIn.getState(blockpos).getBlock().getMaterial(); + Block block = worldIn.getState(blockpos).getBlock(); - if (material == Material.air || material == Material.leaves) + if (block == Blocks.air || block.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(worldIn, blockpos, this.leavesMetadata.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(blockpos))); } diff --git a/java/src/game/worldgen/tree/WorldGenJungle.java b/server/src/main/java/server/worldgen/tree/WorldGenJungle.java similarity index 94% rename from java/src/game/worldgen/tree/WorldGenJungle.java rename to server/src/main/java/server/worldgen/tree/WorldGenJungle.java index 92e7057..ba30cdb 100755 --- a/java/src/game/worldgen/tree/WorldGenJungle.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenJungle.java @@ -1,13 +1,13 @@ -package game.worldgen.tree; +package server.worldgen.tree; -import game.block.BlockVine; -import game.init.Blocks; -import game.properties.PropertyBool; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.block.foliage.BlockVine; +import common.init.Blocks; +import common.properties.PropertyBool; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.State; +import server.world.WorldServer; public class WorldGenJungle extends WorldGenHugeTree { diff --git a/java/src/game/worldgen/tree/WorldGenPine.java b/server/src/main/java/server/worldgen/tree/WorldGenPine.java similarity index 85% rename from java/src/game/worldgen/tree/WorldGenPine.java rename to server/src/main/java/server/worldgen/tree/WorldGenPine.java index 8351b5b..26b9820 100755 --- a/java/src/game/worldgen/tree/WorldGenPine.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenPine.java @@ -1,14 +1,14 @@ -package game.worldgen.tree; +package server.worldgen.tree; -import game.block.Block; -import game.block.BlockDirt; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.util.ExtMath; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.natural.BlockDirt; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.ExtMath; +import common.world.State; +import server.world.WorldServer; public class WorldGenPine extends WorldGenHugeTree { @@ -39,7 +39,7 @@ public class WorldGenPine extends WorldGenHugeTree { Block block = worldIn.getState(position.up(j)).getBlock(); - if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves) + if (block == Blocks.air || block.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(worldIn, position.up(j), this.woodMetadata); } @@ -48,21 +48,21 @@ public class WorldGenPine extends WorldGenHugeTree { block = worldIn.getState(position.add(1, j, 0)).getBlock(); - if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves) + if (block == Blocks.air || block.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(worldIn, position.add(1, j, 0), this.woodMetadata); } block = worldIn.getState(position.add(1, j, 1)).getBlock(); - if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves) + if (block == Blocks.air || block.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(worldIn, position.add(1, j, 1), this.woodMetadata); } block = worldIn.getState(position.add(0, j, 1)).getBlock(); - if (block.getMaterial() == Material.air || block.getMaterial() == Material.leaves) + if (block == Blocks.air || block.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(worldIn, position.add(0, j, 1), this.woodMetadata); } @@ -134,7 +134,7 @@ public class WorldGenPine extends WorldGenHugeTree break; } - if (block.getMaterial() != Material.air && i < 0) + if (block != Blocks.air && i < 0) { break; } diff --git a/java/src/game/worldgen/tree/WorldGenSavanna.java b/server/src/main/java/server/worldgen/tree/WorldGenSavanna.java similarity index 89% rename from java/src/game/worldgen/tree/WorldGenSavanna.java rename to server/src/main/java/server/worldgen/tree/WorldGenSavanna.java index 7ad81aa..dfd389b 100755 --- a/java/src/game/worldgen/tree/WorldGenSavanna.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenSavanna.java @@ -1,14 +1,14 @@ -package game.worldgen.tree; +package server.worldgen.tree; -import game.block.Block; -import game.block.BlockLeaves; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.Facing; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockLeaves; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.util.Facing; +import common.world.State; +import server.world.WorldServer; public class WorldGenSavanna extends WorldGenTree { @@ -95,9 +95,9 @@ public class WorldGenSavanna extends WorldGenTree } BlockPos blockpos = new BlockPos(i3, i2, j1); - Material material = worldIn.getState(blockpos).getBlock().getMaterial(); + Block block1 = worldIn.getState(blockpos).getBlock(); - if (material == Material.air || material == Material.leaves) + if (block1 == Blocks.air || block1.getMaterial() == Material.LEAVES) { this.func_181642_b(worldIn, blockpos); k1 = i2; @@ -149,9 +149,9 @@ public class WorldGenSavanna extends WorldGenTree i3 += enumfacing1.getFrontOffsetX(); j1 += enumfacing1.getFrontOffsetZ(); BlockPos blockpos1 = new BlockPos(i3, j2, j1); - Material material1 = worldIn.getState(blockpos1).getBlock().getMaterial(); + Block block1 = worldIn.getState(blockpos1).getBlock(); - if (material1 == Material.air || material1 == Material.leaves) + if (block1 == Blocks.air || block1.getMaterial() == Material.LEAVES) { this.func_181642_b(worldIn, blockpos1); k1 = j2; @@ -209,9 +209,9 @@ public class WorldGenSavanna extends WorldGenTree private void func_175924_b(WorldServer worldIn, BlockPos p_175924_2_) { - Material material = worldIn.getState(p_175924_2_).getBlock().getMaterial(); + Block block = worldIn.getState(p_175924_2_).getBlock(); - if (material == Material.air || material == Material.leaves) + if (block == Blocks.air || block.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(worldIn, p_175924_2_, field_181644_b.withProperty(BlockLeaves.TYPE, worldIn.getLeavesGen(p_175924_2_))); } diff --git a/java/src/game/worldgen/tree/WorldGenSwamp.java b/server/src/main/java/server/worldgen/tree/WorldGenSwamp.java similarity index 87% rename from java/src/game/worldgen/tree/WorldGenSwamp.java rename to server/src/main/java/server/worldgen/tree/WorldGenSwamp.java index 9f440a2..276ed3c 100755 --- a/java/src/game/worldgen/tree/WorldGenSwamp.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenSwamp.java @@ -1,15 +1,15 @@ -package game.worldgen.tree; +package server.worldgen.tree; -import game.block.Block; -import game.block.BlockLeaves; -import game.block.BlockVine; -import game.init.Blocks; -import game.material.Material; -import game.properties.PropertyBool; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockLeaves; +import common.block.foliage.BlockVine; +import common.init.Blocks; +import common.properties.PropertyBool; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; public class WorldGenSwamp extends WorldGenTree { @@ -28,7 +28,7 @@ public class WorldGenSwamp extends WorldGenTree { int i; - for (i = rand.zrange(4) + 5; worldIn.getState(position.down()).getBlock().getMaterial() == Material.water; position = position.down()) + for (i = rand.zrange(4) + 5; worldIn.getState(position.down()).getBlock().getMaterial() == Material.WATER; position = position.down()) { ; } @@ -61,7 +61,7 @@ public class WorldGenSwamp extends WorldGenTree { Block block = worldIn.getState(blockpos$mutableblockpos.set(l, j, i1)).getBlock(); - if (block.getMaterial() != Material.air && block.getMaterial() != Material.leaves) + if (block != Blocks.air && block.getMaterial() != Material.LEAVES) { if (block != Blocks.water && block != Blocks.flowing_water) { @@ -123,7 +123,7 @@ public class WorldGenSwamp extends WorldGenTree { Block block2 = worldIn.getState(position.up(i2)).getBlock(); - if (block2.getMaterial() == Material.air || block2.getMaterial() == Material.leaves || block2 == Blocks.flowing_water || block2 == Blocks.water) + if (block2 == Blocks.air || block2.getMaterial() == Material.LEAVES || block2 == Blocks.flowing_water || block2 == Blocks.water) { this.setBlockAndNotifyAdequately(worldIn, position.up(i2), field_181648_a); } @@ -141,29 +141,29 @@ public class WorldGenSwamp extends WorldGenTree { blockpos$mutableblockpos1.set(i4, j2, j4); - if (worldIn.getState(blockpos$mutableblockpos1).getBlock().getMaterial() == Material.leaves) + if (worldIn.getState(blockpos$mutableblockpos1).getBlock().getMaterial() == Material.LEAVES) { BlockPos blockpos3 = blockpos$mutableblockpos1.west(); BlockPos blockpos4 = blockpos$mutableblockpos1.east(); BlockPos blockpos1 = blockpos$mutableblockpos1.north(); BlockPos blockpos2 = blockpos$mutableblockpos1.south(); - if (rand.zrange(4) == 0 && worldIn.getState(blockpos3).getBlock().getMaterial() == Material.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos3).getBlock() == Blocks.air) { this.func_181647_a(worldIn, blockpos3, BlockVine.EAST); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos4).getBlock().getMaterial() == Material.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos4).getBlock() == Blocks.air) { this.func_181647_a(worldIn, blockpos4, BlockVine.WEST); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos1).getBlock().getMaterial() == Material.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos1).getBlock() == Blocks.air) { this.func_181647_a(worldIn, blockpos1, BlockVine.SOUTH); } - if (rand.zrange(4) == 0 && worldIn.getState(blockpos2).getBlock().getMaterial() == Material.air) + if (rand.zrange(4) == 0 && worldIn.getState(blockpos2).getBlock() == Blocks.air) { this.func_181647_a(worldIn, blockpos2, BlockVine.NORTH); } @@ -192,7 +192,7 @@ public class WorldGenSwamp extends WorldGenTree this.setBlockAndNotifyAdequately(p_181647_1_, p_181647_2_, iblockstate); int i = 4; - for (p_181647_2_ = p_181647_2_.down(); p_181647_1_.getState(p_181647_2_).getBlock().getMaterial() == Material.air && i > 0; --i) + for (p_181647_2_ = p_181647_2_.down(); p_181647_1_.getState(p_181647_2_).getBlock() == Blocks.air && i > 0; --i) { this.setBlockAndNotifyAdequately(p_181647_1_, p_181647_2_, iblockstate); p_181647_2_ = p_181647_2_.down(); diff --git a/java/src/game/worldgen/tree/WorldGenTaiga1.java b/server/src/main/java/server/worldgen/tree/WorldGenTaiga1.java similarity index 92% rename from java/src/game/worldgen/tree/WorldGenTaiga1.java rename to server/src/main/java/server/worldgen/tree/WorldGenTaiga1.java index 8427191..2ae3859 100755 --- a/java/src/game/worldgen/tree/WorldGenTaiga1.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenTaiga1.java @@ -1,13 +1,13 @@ -package game.worldgen.tree; +package server.worldgen.tree; -import game.block.Block; -import game.block.BlockLeaves; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockLeaves; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; public class WorldGenTaiga1 extends WorldGenTree { @@ -115,7 +115,7 @@ public class WorldGenTaiga1 extends WorldGenTree { Block block1 = worldIn.getState(position.up(i3)).getBlock(); - if (block1.getMaterial() == Material.air || block1.getMaterial() == Material.leaves) + if (block1 == Blocks.air || block1.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(worldIn, position.up(i3), field_181636_a); } diff --git a/java/src/game/worldgen/tree/WorldGenTaiga2.java b/server/src/main/java/server/worldgen/tree/WorldGenTaiga2.java similarity index 91% rename from java/src/game/worldgen/tree/WorldGenTaiga2.java rename to server/src/main/java/server/worldgen/tree/WorldGenTaiga2.java index 0adba2a..ba017a3 100755 --- a/java/src/game/worldgen/tree/WorldGenTaiga2.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenTaiga2.java @@ -1,13 +1,13 @@ -package game.worldgen.tree; +package server.worldgen.tree; -import game.block.Block; -import game.block.BlockLeaves; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.State; -import game.world.WorldServer; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockLeaves; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import common.world.State; +import server.world.WorldServer; public class WorldGenTaiga2 extends WorldGenTree { @@ -55,7 +55,7 @@ public class WorldGenTaiga2 extends WorldGenTree { Block block = worldIn.getState(blockpos$mutableblockpos.set(k1, i1, l1)).getBlock(); - if (block.getMaterial() != Material.air && block.getMaterial() != Material.leaves) + if (block != Blocks.air && block.getMaterial() != Material.LEAVES) { flag = false; } @@ -130,7 +130,7 @@ public class WorldGenTaiga2 extends WorldGenTree { Block block2 = worldIn.getState(position.up(k4)).getBlock(); - if (block2.getMaterial() == Material.air || block2.getMaterial() == Material.leaves) + if (block2 == Blocks.air || block2.getMaterial() == Material.LEAVES) { this.setBlockAndNotifyAdequately(worldIn, position.up(k4), field_181645_a); } diff --git a/java/src/game/worldgen/tree/WorldGenTree.java b/server/src/main/java/server/worldgen/tree/WorldGenTree.java similarity index 53% rename from java/src/game/worldgen/tree/WorldGenTree.java rename to server/src/main/java/server/worldgen/tree/WorldGenTree.java index 260c603..412f0e6 100755 --- a/java/src/game/worldgen/tree/WorldGenTree.java +++ b/server/src/main/java/server/worldgen/tree/WorldGenTree.java @@ -1,14 +1,14 @@ -package game.worldgen.tree; +package server.worldgen.tree; -import game.block.Block; -import game.block.BlockLog; -import game.block.BlockSapling; -import game.init.Blocks; -import game.material.Material; -import game.rng.Random; -import game.world.BlockPos; -import game.world.WorldServer; -import game.worldgen.FeatureGenerator; +import common.block.Block; +import common.block.Material; +import common.block.foliage.BlockLog; +import common.block.foliage.BlockSapling; +import common.init.Blocks; +import common.rng.Random; +import common.util.BlockPos; +import server.world.WorldServer; +import server.worldgen.FeatureGenerator; public abstract class WorldGenTree extends FeatureGenerator { @@ -19,8 +19,7 @@ public abstract class WorldGenTree extends FeatureGenerator protected boolean canBeReplaced(Block block) { - Material material = block.getMaterial(); - return material == Material.air || material == Material.leaves || block == Blocks.grass || block == Blocks.dirt || block instanceof BlockLog || block instanceof BlockSapling || block == Blocks.vine; + return block == Blocks.air || block.getMaterial() == Material.LEAVES || block == Blocks.grass || block == Blocks.dirt || block instanceof BlockLog || block instanceof BlockSapling || block == Blocks.vine; } public void prepare() diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..60f7529 --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,5 @@ + +rootProject.name = "TCR" +include("common") +include("client") +include("server")