repo_id
stringclasses
383 values
file_path
stringlengths
7
168
content
stringlengths
0
1.75M
amidst
src\main\java\amidst\gui\main\menu\MenuShortcut.java
package amidst.gui.main.menu; import javax.swing.KeyStroke; public interface MenuShortcut { KeyStroke getKeyStroke(); }
amidst
src\main\java\amidst\gui\main\menu\MenuShortcuts.java
package amidst.gui.main.menu; import java.awt.Toolkit; import javax.swing.KeyStroke; import amidst.documentation.Immutable; /** * This enum declares all menu shortcuts. This makes it easier to ensure that * each menu shortcut is only used for a single action. */ @Immutable public enum MenuShortcuts implements MenuShortcut { NEW_FROM_SEED("menu N"), NEW_FROM_RANDOM_SEED("menu R"), SEARCH_FOR_RANDOM_SEED("menu F"), OPEN_SAVE_GAME("menu O"), EXPORT_BIOMES("menu X"), SWITCH_PROFILE("menu W"), EXIT("menu Q"), GO_TO_COORDINATE("menu shift C"), GO_TO_WORLD_SPAWN("menu shift S"), GO_TO_STRONGHOLD("menu shift H"), GO_TO_PLAYER("menu shift P"), ZOOM_IN("menu K"), ZOOM_OUT("menu J"), SAVE_PLAYER_LOCATIONS("menu S"), RELOAD_PLAYER_LOCATIONS("F5"), COPY_SEED_TO_CLIPBOARD("menu C"), TAKE_SCREENSHOT("menu T"), DISPLAY_DIMENSION_OVERWORLD("menu shift 1"), DISPLAY_DIMENSION_END("menu shift 2"), SHOW_SLIME_CHUNKS("menu 1"), SHOW_WORLD_SPAWN("menu 2"), SHOW_STRONGHOLDS("menu 3"), SHOW_VILLAGES("menu 4"), SHOW_TEMPLES("menu 5"), SHOW_MINESHAFTS("menu 6"), SHOW_OCEAN_MONUMENTS("menu 7"), SHOW_WOODLAND_MANSIONS("menu 8"), SHOW_OCEAN_FEATURES("menu 9"), SHOW_NETHER_FEATURES("menu 0"), // It's okay to duplicate the Overworld layers shortcuts here, because // the End layers will never be active at the same time. SHOW_END_CITIES("menu 1"), SHOW_GRID("menu G"), SHOW_PLAYERS("menu P"), ENABLE_ALL_LAYERS("menu E"), RELOAD_BIOME_PROFILES("menu B"),; public static KeyStroke getKeyStroke(String accelerator) { return getPlatformSpecificKeyStroke(accelerator.replace("menu", ""), accelerator.contains("menu")); } private static KeyStroke getPlatformSpecificKeyStroke(String accelerator, boolean addMenuMask) { KeyStroke keyStroke = KeyStroke.getKeyStroke(accelerator); int keycode = keyStroke.getKeyCode(); int keymask = keyStroke.getModifiers(); if (addMenuMask) { keymask |= Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); } return KeyStroke.getKeyStroke(keycode, keymask); } private final KeyStroke keystroke; private MenuShortcuts(String shortcut) { this.keystroke = getKeyStroke(shortcut); } @Override public KeyStroke getKeyStroke() { return keystroke; } }
amidst
src\main\java\amidst\gui\main\menu\MovePlayerPopupMenu.java
package amidst.gui.main.menu; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenuItem; import javax.swing.JPopupMenu; import amidst.documentation.NotThreadSafe; import amidst.gui.main.Actions; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.player.MovablePlayerList; import amidst.mojangapi.world.player.Player; @NotThreadSafe public class MovePlayerPopupMenu { private final Actions actions; private final MovablePlayerList movablePlayerList; private final CoordinatesInWorld targetCoordinates; public MovePlayerPopupMenu( Actions actions, MovablePlayerList movablePlayerList, CoordinatesInWorld targetCoordinates) { this.actions = actions; this.movablePlayerList = movablePlayerList; this.targetCoordinates = targetCoordinates; } public void show(Component component, int x, int y) { createPlayerMenu().show(component, x, y); } private JPopupMenu createPlayerMenu() { JPopupMenu result = new JPopupMenu(); for (Player player : movablePlayerList) { result.add(createPlayerMenuItem(player, targetCoordinates)); } return result; } private JMenuItem createPlayerMenuItem(final Player player, final CoordinatesInWorld targetCoordinates) { JMenuItem result = new JMenuItem(player.getPlayerName()); result.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { actions.movePlayer(player, targetCoordinates); } }); return result; } }
amidst
src\main\java\amidst\gui\main\viewer\BiomeSelection.java
package amidst.gui.main.viewer; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import amidst.documentation.ThreadSafe; @ThreadSafe public class BiomeSelection { private final ConcurrentHashMap<Integer, AtomicBoolean> selectedBiomes = new ConcurrentHashMap<>(); // Should newly encountered biomes be selected by default or not? private final AtomicBoolean unknownBiomesSelected = new AtomicBoolean(false); private final AtomicBoolean isHighlightMode = new AtomicBoolean(false); private final AtomicBoolean shouldWidgetBeVisible = new AtomicBoolean(false); public BiomeSelection() { } public boolean toggleWidgetVisibility() { return toggle(shouldWidgetBeVisible); } public boolean isWidgetVisible() { return shouldWidgetBeVisible.get(); } public boolean isSelected(int id) { return getSelected(id).get(); } private AtomicBoolean getSelected(int id) { return selectedBiomes.computeIfAbsent(id, i -> { return new AtomicBoolean(unknownBiomesSelected.get()); }); } public boolean isVisible(int id) { return !isHighlightMode.get() || isSelected(id); } public void selectAll() { setAll(true); } public void deselectAll() { setAll(false); } public boolean toggle(int id) { return toggle(getSelected(id)); } private void setAll(boolean value) { selectedBiomes.clear(); unknownBiomesSelected.set(value); } public boolean toggleHighlightMode() { return toggle(isHighlightMode); } public boolean isHighlightMode() { return isHighlightMode.get(); } private boolean toggle(AtomicBoolean atomicBoolean) { boolean value; do { value = atomicBoolean.get(); } while (!atomicBoolean.compareAndSet(value, !value)); return !value; } }
amidst
src\main\java\amidst\gui\main\viewer\Drawer.java
package amidst.gui.main.viewer; import java.awt.AlphaComposite; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.TexturePaint; import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.util.List; import amidst.ResourceLoader; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.fragment.Fragment; import amidst.fragment.FragmentGraph; import amidst.fragment.FragmentGraphItem; import amidst.fragment.drawer.FragmentDrawer; import amidst.gui.main.viewer.widget.Widget; import amidst.mojangapi.world.Dimension; import amidst.settings.Setting; @NotThreadSafe public class Drawer { private static final BufferedImage DROP_SHADOW_BOTTOM_LEFT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/inner_bottom_left.png"); private static final BufferedImage DROP_SHADOW_BOTTOM_RIGHT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/inner_bottom_right.png"); private static final BufferedImage DROP_SHADOW_TOP_LEFT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/inner_top_left.png"); private static final BufferedImage DROP_SHADOW_TOP_RIGHT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/inner_top_right.png"); private static final BufferedImage DROP_SHADOW_BOTTOM = ResourceLoader .getImage("/amidst/gui/main/dropshadow/inner_bottom.png"); private static final BufferedImage DROP_SHADOW_TOP = ResourceLoader .getImage("/amidst/gui/main/dropshadow/inner_top.png"); private static final BufferedImage DROP_SHADOW_LEFT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/inner_left.png"); private static final BufferedImage DROP_SHADOW_RIGHT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/inner_right.png"); private static final BufferedImage VOID_TEXTURE = ResourceLoader.getImage("/amidst/gui/main/void.png"); private final AffineTransform originalLayerMatrix = new AffineTransform(); private final AffineTransform layerMatrix = new AffineTransform(); private final FragmentGraph graph; private final FragmentGraphToScreenTranslator translator; private final Zoom zoom; private final Movement movement; private final List<Widget> widgets; private final Iterable<FragmentDrawer> drawers; private final Setting<Dimension> dimensionSetting; private final Graphics2DAccelerationCounter accelerationCounter; private final TexturePaint voidTexturePaint; private Graphics2D g2d; private int viewerWidth; private int viewerHeight; private Point mousePosition; private FontMetrics widgetFontMetrics; private long lastTime = System.currentTimeMillis(); private float time; @CalledOnlyBy(AmidstThread.EDT) public Drawer( FragmentGraph graph, FragmentGraphToScreenTranslator translator, Zoom zoom, Movement movement, List<Widget> widgets, Iterable<FragmentDrawer> drawers, Setting<Dimension> dimensionSetting, Graphics2DAccelerationCounter accelerationCounter) { this.graph = graph; this.translator = translator; this.zoom = zoom; this.movement = movement; this.widgets = widgets; this.drawers = drawers; this.dimensionSetting = dimensionSetting; this.accelerationCounter = accelerationCounter; this.voidTexturePaint = new TexturePaint( VOID_TEXTURE, new Rectangle(0, 0, VOID_TEXTURE.getWidth(), VOID_TEXTURE.getHeight())); } @CalledOnlyBy(AmidstThread.EDT) public void drawScreenshot( Graphics2D g2d, int viewerWidth, int viewerHeight, Point mousePosition, FontMetrics widgetFontMetrics) { this.g2d = g2d; this.viewerWidth = viewerWidth; this.viewerHeight = viewerHeight; this.mousePosition = mousePosition; this.widgetFontMetrics = widgetFontMetrics; this.time = 0; updateTranslator(); clear(); drawFragments(); drawWidgets(); } @CalledOnlyBy(AmidstThread.EDT) public void draw( Graphics2D g2d, int viewerWidth, int viewerHeight, Point mousePosition, FontMetrics widgetFontMetrics) { this.g2d = g2d; this.viewerWidth = viewerWidth; this.viewerHeight = viewerHeight; this.mousePosition = mousePosition; this.widgetFontMetrics = widgetFontMetrics; this.time = calculateTimeSpanSinceLastDrawInSeconds(); updateZoom(); updateMovement(); updateTranslator(); clear(); drawFragments(); drawBorder(); drawWidgets(); } @CalledOnlyBy(AmidstThread.EDT) private float calculateTimeSpanSinceLastDrawInSeconds() { long currentTime = System.currentTimeMillis(); float result = Math.min(Math.max(0, currentTime - lastTime), 100) / 1000.0f; lastTime = currentTime; return result; } @CalledOnlyBy(AmidstThread.EDT) private void updateZoom() { zoom.update(translator); } @CalledOnlyBy(AmidstThread.EDT) private void updateMovement() { movement.update(translator, mousePosition); } @CalledOnlyBy(AmidstThread.EDT) private void updateTranslator() { translator.update(viewerWidth, viewerHeight); } @CalledOnlyBy(AmidstThread.EDT) private void clear() { if (dimensionSetting.get().equals(Dimension.END)) { g2d.setPaint(voidTexturePaint); } else { g2d.setColor(Color.black); } g2d.fillRect(0, 0, viewerWidth, viewerHeight); } @CalledOnlyBy(AmidstThread.EDT) private void drawFragments() { // TODO: is this needed? Graphics2D old = g2d; g2d = (Graphics2D) g2d.create(); doDrawFragments(); g2d = old; } @CalledOnlyBy(AmidstThread.EDT) private void doDrawFragments() { g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); AffineTransform originalGraphicsTransform = g2d.getTransform(); initOriginalLayerMatrix(originalGraphicsTransform); drawLayers(); g2d.setTransform(originalGraphicsTransform); } @CalledOnlyBy(AmidstThread.EDT) private void initOriginalLayerMatrix(AffineTransform originalGraphicsTransform) { double scale = zoom.getCurrentValue(); originalLayerMatrix.setTransform(originalGraphicsTransform); originalLayerMatrix.translate(translator.getLeftOnScreen(), translator.getTopOnScreen()); originalLayerMatrix.scale(scale, scale); } @CalledOnlyBy(AmidstThread.EDT) private void drawLayers() { for (FragmentDrawer drawer : drawers) { if (drawer.isEnabled()) { initLayerMatrix(); for (FragmentGraphItem fragmentGraphItem : graph) { Fragment fragment = fragmentGraphItem.getFragment(); if (drawer.isDrawUnloaded()) { setAlphaComposite(1.0f); g2d.setTransform(layerMatrix); drawer.draw(fragment, g2d, time); } else if (fragment.getState().equals(Fragment.State.LOADED)) { setAlphaComposite(fragment.getAlpha()); g2d.setTransform(layerMatrix); drawer.draw(fragment, g2d, time); } updateLayerMatrix(fragmentGraphItem, graph.getFragmentsPerRow()); } } } setAlphaComposite(1.0f); } @CalledOnlyBy(AmidstThread.EDT) private void initLayerMatrix() { layerMatrix.setTransform(originalLayerMatrix); } @CalledOnlyBy(AmidstThread.EDT) private void updateLayerMatrix(FragmentGraphItem fragmentGraphItem, int fragmentsPerRow) { layerMatrix.translate(Fragment.SIZE, 0); if (fragmentGraphItem.isEndOfLine()) { layerMatrix.translate(-Fragment.SIZE * fragmentsPerRow, Fragment.SIZE); } } @CalledOnlyBy(AmidstThread.EDT) private void drawBorder() { int width10 = viewerWidth - 10; int height10 = viewerHeight - 10; int width20 = viewerWidth - 20; int height20 = viewerHeight - 20; drawAndLog(DROP_SHADOW_TOP_LEFT, 0, 0); drawAndLog(DROP_SHADOW_TOP_RIGHT, width10, 0); drawAndLog(DROP_SHADOW_BOTTOM_LEFT, 0, height10); drawAndLog(DROP_SHADOW_BOTTOM_RIGHT, width10, height10); drawAndLog(DROP_SHADOW_TOP, 10, 0, width20, 10); drawAndLog(DROP_SHADOW_BOTTOM, 10, height10, width20, 10); drawAndLog(DROP_SHADOW_LEFT, 0, 10, 10, height20); drawAndLog(DROP_SHADOW_RIGHT, width10, 10, 10, height20); } @CalledOnlyBy(AmidstThread.EDT) private void drawAndLog(BufferedImage image, int x, int y) { g2d.drawImage(image, x, y, null); accelerationCounter.log(image); } @CalledOnlyBy(AmidstThread.EDT) private void drawAndLog(BufferedImage image, int x, int y, int width, int height) { g2d.drawImage(image, x, y, width, height, null); accelerationCounter.log(image); } @CalledOnlyBy(AmidstThread.EDT) private void drawWidgets() { g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); for (Widget widget : widgets) { widget.update(viewerWidth, viewerHeight, mousePosition, widgetFontMetrics, time); if (widget.isVisible()) { setAlphaComposite(widget.getAlpha()); widget.draw(g2d); } } } @CalledOnlyBy(AmidstThread.EDT) private void setAlphaComposite(float alpha) { g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha)); } }
amidst
src\main\java\amidst\gui\main\viewer\FragmentGraphToScreenTranslator.java
package amidst.gui.main.viewer; import java.awt.Point; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.fragment.Fragment; import amidst.fragment.FragmentGraph; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; @NotThreadSafe public class FragmentGraphToScreenTranslator { private final FragmentGraph graph; private final Zoom zoom; private double leftOnScreen; private double topOnScreen; private int viewerWidth; private int viewerHeight; private boolean isFirstUpdate = true; @CalledOnlyBy(AmidstThread.EDT) public FragmentGraphToScreenTranslator(FragmentGraph graph, Zoom zoom) { this.graph = graph; this.zoom = zoom; } @CalledOnlyBy(AmidstThread.EDT) public void update(int viewerWidth, int viewerHeight) { this.viewerWidth = viewerWidth; this.viewerHeight = viewerHeight; centerOnOriginIfNecessary(); adjustNumberOfRowsAndColumns(); } private void centerOnOriginIfNecessary() { if (isFirstUpdate) { isFirstUpdate = false; centerOn(CoordinatesInWorld.origin()); } } @CalledOnlyBy(AmidstThread.EDT) private void adjustNumberOfRowsAndColumns() { double fragmentSizeOnScreen = zoom.worldToScreen(Fragment.SIZE); int desiredFragmentsPerRow = (int) (viewerWidth / fragmentSizeOnScreen + 2); int desiredFragmentsPerColumn = (int) (viewerHeight / fragmentSizeOnScreen + 2); int newColumns = desiredFragmentsPerRow - graph.getFragmentsPerRow(); int newRows = desiredFragmentsPerColumn - graph.getFragmentsPerColumn(); int newLeft = getNewLeft(fragmentSizeOnScreen); int newAbove = getNewAbove(fragmentSizeOnScreen); int newRight = newColumns - newLeft; int newBelow = newRows - newAbove; graph.adjust(newLeft, newAbove, newRight, newBelow); adjustTopLeftOnScreen(fragmentSizeOnScreen * -newLeft, fragmentSizeOnScreen * -newAbove); } @CalledOnlyBy(AmidstThread.EDT) private int getNewLeft(double fragmentSizeOnScreen) { if (leftOnScreen > 0) { return (int) (leftOnScreen / fragmentSizeOnScreen) + 1; } else { return (int) (leftOnScreen / fragmentSizeOnScreen); } } @CalledOnlyBy(AmidstThread.EDT) private int getNewAbove(double fragmentSizeOnScreen) { if (topOnScreen > 0) { return (int) (topOnScreen / fragmentSizeOnScreen) + 1; } else { return (int) (topOnScreen / fragmentSizeOnScreen); } } @CalledOnlyBy(AmidstThread.EDT) public void centerOn(final CoordinatesInWorld coordinates) { graph.init(coordinates); int xCenterOnScreen = viewerWidth >> 1; int yCenterOnScreen = viewerHeight >> 1; long xFragmentRelative = coordinates.getXRelativeToFragment(); long yFragmentRelative = coordinates.getYRelativeToFragment(); setTopLeftOnScreen( xCenterOnScreen - zoom.worldToScreen(xFragmentRelative), yCenterOnScreen - zoom.worldToScreen(yFragmentRelative)); } @CalledOnlyBy(AmidstThread.EDT) public void adjustToMovement(int deltaX, int deltaY) { adjustTopLeftOnScreen(deltaX, deltaY); } @CalledOnlyBy(AmidstThread.EDT) public void adjustToZoom(double previous, double current, Point mousePosition) { double baseX = mousePosition.x - leftOnScreen; double baseY = mousePosition.y - topOnScreen; double deltaX = baseX - (baseX / previous) * current; double deltaY = baseY - (baseY / previous) * current; adjustTopLeftOnScreen(deltaX, deltaY); } @CalledOnlyBy(AmidstThread.EDT) private void setTopLeftOnScreen(double leftOnScreen, double topOnScreen) { this.leftOnScreen = leftOnScreen; this.topOnScreen = topOnScreen; } @CalledOnlyBy(AmidstThread.EDT) private void adjustTopLeftOnScreen(double deltaX, double deltaY) { this.leftOnScreen += deltaX; this.topOnScreen += deltaY; } @CalledOnlyBy(AmidstThread.EDT) public double getLeftOnScreen() { return leftOnScreen; } @CalledOnlyBy(AmidstThread.EDT) public double getTopOnScreen() { return topOnScreen; } public double getWidth() { return viewerWidth; } public double getHeight() { return viewerHeight; } @CalledOnlyBy(AmidstThread.EDT) public CoordinatesInWorld screenToWorld(Point pointOnScreen) { CoordinatesInWorld corner = graph.getCorner(); return corner.add( (long) zoom.screenToWorld(pointOnScreen.x - leftOnScreen), (long) zoom.screenToWorld(pointOnScreen.y - topOnScreen)); } }
amidst
src\main\java\amidst\gui\main\viewer\Graphics2DAccelerationCounter.java
package amidst.gui.main.viewer; import java.awt.GraphicsConfiguration; import java.awt.GraphicsEnvironment; import java.awt.Image; import java.util.concurrent.atomic.AtomicInteger; import amidst.documentation.AmidstThread; import amidst.documentation.CalledByAny; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; /** * Maintains performance-counting totals so that 2D hardware acceleration * metrics can be calculated. */ @NotThreadSafe public class Graphics2DAccelerationCounter { private static final int UPDATE_PERCENTAGE_AFTER = 1000; private AtomicInteger accelerated = new AtomicInteger(0); private AtomicInteger total = new AtomicInteger(0); private volatile float acceleratedPercentage = 0; private static final GraphicsConfiguration GC = GraphicsEnvironment .getLocalGraphicsEnvironment() .getDefaultScreenDevice() .getDefaultConfiguration(); /** * Records that a graphics operation was performed, in this case with an * image, so that 2D hardware acceleration metrics can be calculated */ @CalledOnlyBy(AmidstThread.EDT) public void log(Image image) { if (image.getCapabilities(GC).isAccelerated()) { accelerated.incrementAndGet(); } if (total.incrementAndGet() == UPDATE_PERCENTAGE_AFTER) { acceleratedPercentage = 100f * accelerated.getAndSet(0) / total.getAndSet(0); } } /** * Returns a value between 0 and 1, 0 being not accelerated, and 1 meaning * all operations were accelerated. */ @CalledByAny public float getAcceleratedPercentage() { return acceleratedPercentage; } }
amidst
src\main\java\amidst\gui\main\viewer\Movement.java
package amidst.gui.main.viewer; import java.awt.Point; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.settings.Setting; @NotThreadSafe public class Movement { private double speedX = 0; private double speedY = 0; private Point lastMouse; private final Setting<Boolean> smoothScrollingSetting; @CalledOnlyBy(AmidstThread.EDT) public Movement(Setting<Boolean> smoothScrollingSetting) { this.smoothScrollingSetting = smoothScrollingSetting; } @CalledOnlyBy(AmidstThread.EDT) public void update(FragmentGraphToScreenTranslator translator, Point currentMouse) { updateMovementSpeed(currentMouse); adjustTranslator(translator); throttleMovementSpeed(); } @CalledOnlyBy(AmidstThread.EDT) private void updateMovementSpeed(Point currentMouse) { if (lastMouse != null) { if (currentMouse != null) { double dX = currentMouse.x - lastMouse.x; double dY = currentMouse.y - lastMouse.y; // TODO: Scale with time speedX = dX * 0.2; speedY = dY * 0.2; } lastMouse.translate((int) speedX, (int) speedY); } } @CalledOnlyBy(AmidstThread.EDT) private void adjustTranslator(FragmentGraphToScreenTranslator translator) { translator.adjustToMovement((int) speedX, (int) speedY); } @CalledOnlyBy(AmidstThread.EDT) private void throttleMovementSpeed() { if (smoothScrollingSetting.get()) { speedX *= 0.95f; speedY *= 0.95f; } else { speedX = 0; speedY = 0; } } @CalledOnlyBy(AmidstThread.EDT) public void setLastMouse(Point lastMouse) { this.lastMouse = lastMouse; } }
amidst
src\main\java\amidst\gui\main\viewer\Viewer.java
package amidst.gui.main.viewer; import java.awt.Component; import java.awt.FontMetrics; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.image.BufferedImage; import javax.swing.JComponent; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.gui.main.viewer.widget.Widget; @NotThreadSafe public class Viewer { @SuppressWarnings("serial") private static class ViewerComponent extends JComponent { private final FontMetrics widgetFontMetrics = getFontMetrics(Widget.TEXT_FONT); private final Drawer drawer; @CalledOnlyBy(AmidstThread.EDT) public ViewerComponent(Drawer drawer) { this.drawer = drawer; } @CalledOnlyBy(AmidstThread.EDT) @Override public void paintComponent(Graphics g) { Graphics2D g2d = (Graphics2D) g.create(); drawer.draw(g2d, getWidth(), getHeight(), getMousePositionOrNull(), widgetFontMetrics); } @CalledOnlyBy(AmidstThread.EDT) public BufferedImage createScreenshot() { int width = getWidth(); int height = getHeight(); Point mousePosition = getMousePositionOrNull(); BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = result.createGraphics(); drawer.drawScreenshot(g2d, width, height, mousePosition, widgetFontMetrics); g2d.dispose(); return result; } /** * The method getMousePosition() might throw a null pointer exception in * a multi-monitor setup, as soon as the window is dragged to the other * monitor. */ @CalledOnlyBy(AmidstThread.EDT) private Point getMousePositionOrNull() { try { return getMousePosition(); } catch (NullPointerException e) { return null; } } } private final ViewerMouseListener mouseListener; private final ViewerComponent component; @CalledOnlyBy(AmidstThread.EDT) public Viewer(ViewerMouseListener mouseListener, Drawer drawer) { this.mouseListener = mouseListener; this.component = createComponent(drawer); } @CalledOnlyBy(AmidstThread.EDT) private ViewerComponent createComponent(Drawer drawer) { ViewerComponent result = new ViewerComponent(drawer); result.addMouseListener(mouseListener); result.addMouseWheelListener(mouseListener); result.setFocusable(true); return result; } @CalledOnlyBy(AmidstThread.EDT) public BufferedImage createScreenshot() { return component.createScreenshot(); } @CalledOnlyBy(AmidstThread.EDT) public Point getMousePositionOrCenter() { Point result = component.getMousePositionOrNull(); if (result == null) { result = new Point(component.getWidth() >> 1, component.getHeight() >> 1); } return result; } @CalledOnlyBy(AmidstThread.REPAINTER) public void repaintComponent() { component.repaint(); } @CalledOnlyBy(AmidstThread.EDT) public Component getComponent() { return component; } }
amidst
src\main\java\amidst\gui\main\viewer\ViewerFacade.java
package amidst.gui.main.viewer; import amidst.AmidstSettings; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.fragment.FragmentGraph; import amidst.fragment.FragmentManager; import amidst.fragment.FragmentQueueProcessor; import amidst.fragment.layer.LayerBuilder; import amidst.fragment.layer.LayerManager; import amidst.fragment.layer.LayerReloader; import amidst.gui.export.BiomeExporterDialog; import amidst.gui.main.Actions; import amidst.gui.main.viewer.widget.*; import amidst.gui.main.viewer.widget.ProgressWidget.ProgressEntryType; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.World; import amidst.mojangapi.world.WorldOptions; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.icon.WorldIcon; import amidst.mojangapi.world.player.MovablePlayerList; import amidst.threading.WorkerExecutor; import java.awt.Component; import java.awt.Point; import java.awt.image.BufferedImage; import java.util.Arrays; import java.util.List; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; /** * This class works as wrapper around a world instance. It holds everything that * is needed to display the world on the screen. This allows us to easily * exchange the currently displayed world. */ @NotThreadSafe public class ViewerFacade { private final World world; private final FragmentManager fragmentManager; private final FragmentGraph graph; private final FragmentGraphToScreenTranslator translator; private final Zoom zoom; private final Viewer viewer; private final LayerReloader layerReloader; private final WorldIconSelection worldIconSelection; private final LayerManager layerManager; private final WorkerExecutor workerExecutor; private final BiomeExporterDialog biomeExporterDialog; private final FragmentQueueProcessor fragmentQueueProcessor; private final AtomicReference<Entry<ProgressEntryType, Integer>> progressEntryHolder; @CalledOnlyBy(AmidstThread.EDT) public ViewerFacade( AmidstSettings settings, World world, FragmentManager fragmentManager, Zoom zoom, WorkerExecutor workerExecutor, BiomeExporterDialog biomeExporterDialog, LayerBuilder layerBuilder, BiomeSelection biomeSelection, Actions actions) { this.world = world; this.fragmentManager = fragmentManager; this.zoom = zoom; this.workerExecutor = workerExecutor; this.biomeExporterDialog = biomeExporterDialog; Graphics2DAccelerationCounter accelerationCounter = new Graphics2DAccelerationCounter(); Movement movement = new Movement(settings.smoothScrolling); this.worldIconSelection = new WorldIconSelection(); this.layerManager = layerBuilder.create(settings, world, biomeSelection, worldIconSelection, zoom, accelerationCounter); this.graph = new FragmentGraph(layerManager.getDeclarations(), fragmentManager); this.translator = new FragmentGraphToScreenTranslator(graph, zoom); this.fragmentQueueProcessor = fragmentManager.createQueueProcessor(layerManager, settings.dimension); this.layerReloader = layerManager.createLayerReloader(world); this.progressEntryHolder = new AtomicReference<Entry<ProgressEntryType, Integer>>(); DebugWidget debugWidget = new DebugWidget(Widget.CornerAnchorPoint.BOTTOM_RIGHT, graph, fragmentManager, settings.showDebug, accelerationCounter, zoom); BiomeWidget biomeWidget = new BiomeWidget(Widget.CornerAnchorPoint.NONE, biomeSelection, layerReloader, settings.biomeProfileSelection, world.getBiomeList()); BiomeToggleWidget biomeToggleWidget = new BiomeToggleWidget(Widget.CornerAnchorPoint.BOTTOM_RIGHT, biomeWidget, biomeSelection); WorldOptions worldOptions = world.getWorldOptions(); List<Widget> widgets = Arrays.asList( new FpsWidget(Widget.CornerAnchorPoint.BOTTOM_LEFT, new FramerateTimer(2), settings.showFPS), new ScaleWidget(Widget.CornerAnchorPoint.BOTTOM_CENTER, zoom, settings.showScale), new SeedAndWorldTypeWidget(Widget.CornerAnchorPoint.TOP_LEFT, worldOptions.getWorldSeed(), worldOptions.getWorldType()), new SelectedIconWidget(Widget.CornerAnchorPoint.TOP_LEFT, worldIconSelection), debugWidget, new CursorInformationWidget(Widget.CornerAnchorPoint.TOP_RIGHT, graph, translator, settings.dimension, world.getBiomeList()), biomeToggleWidget, new BiomeExporterProgressWidget(Widget.CornerAnchorPoint.BOTTOM_RIGHT, progressEntryHolder::get, -20, settings.showDebug, debugWidget, biomeToggleWidget.getWidth()), biomeWidget ); Drawer drawer = new Drawer( graph, translator, zoom, movement, widgets, layerManager.getDrawers(), settings.dimension, accelerationCounter); ViewerMouseListener viewerMouseListener = new ViewerMouseListener(new WidgetManager(widgets), graph, translator, zoom, movement, actions); this.viewer = new Viewer(viewerMouseListener, drawer); } @CalledOnlyBy(AmidstThread.EDT) public Component getComponent() { return viewer.getComponent(); } @CalledOnlyBy(AmidstThread.EDT) public void reloadBackgroundLayer() { layerReloader.reloadBackgroundLayer(); } @CalledOnlyBy(AmidstThread.EDT) public void reloadPlayerLayer() { layerReloader.reloadPlayerLayer(); } @CalledOnlyBy(AmidstThread.EDT) public void dispose() { graph.dispose(); zoom.skipFading(); zoom.reset(); fragmentManager.clear(); fragmentManager.restartThreadPool(); } @CalledOnlyBy(AmidstThread.EDT) public Runnable getOnRepainterTick() { return viewer::repaintComponent; } @CalledOnlyBy(AmidstThread.EDT) public Runnable getOnFragmentLoaderTick() { return fragmentQueueProcessor::processQueues; } @CalledOnlyBy(AmidstThread.EDT) public void centerOn(CoordinatesInWorld coordinates) { translator.centerOn(coordinates); } @CalledOnlyBy(AmidstThread.EDT) public void centerOn(WorldIcon worldIcon) { translator.centerOn(worldIcon.getCoordinates()); worldIconSelection.select(worldIcon); } @CalledOnlyBy(AmidstThread.EDT) public BufferedImage createScreenshot() { return viewer.createScreenshot(); } @CalledOnlyBy(AmidstThread.EDT) public void adjustZoom(int notches) { zoom.adjustZoom(viewer.getMousePositionOrCenter(), notches); } @CalledOnlyBy(AmidstThread.EDT) public void adjustZoom(Point mousePosition, int notches) { zoom.adjustZoom(mousePosition, notches); } @CalledOnlyBy(AmidstThread.EDT) public void selectWorldIcon(WorldIcon worldIcon) { worldIconSelection.select(worldIcon); } @CalledOnlyBy(AmidstThread.EDT) public WorldOptions getWorldOptions() { return world.getWorldOptions(); } @CalledOnlyBy(AmidstThread.EDT) public WorldIcon getSpawnWorldIcon() { return world.getSpawnWorldIcon(); } @CalledOnlyBy(AmidstThread.EDT) public List<WorldIcon> getStrongholdWorldIcons() { return world.getStrongholdWorldIcons(); } @CalledOnlyBy(AmidstThread.EDT) public List<WorldIcon> getPlayerWorldIcons() { return world.getPlayerWorldIcons(); } @CalledOnlyBy(AmidstThread.EDT) public MovablePlayerList getMovablePlayerList() { return world.getMovablePlayerList(); } @CalledOnlyBy(AmidstThread.EDT) public boolean canLoadPlayerLocations() { return world.getMovablePlayerList().canLoad(); } @CalledOnlyBy(AmidstThread.EDT) public void loadPlayers() { worldIconSelection.clear(); world.getMovablePlayerList().load(workerExecutor, layerReloader::reloadPlayerLayer); } @CalledOnlyBy(AmidstThread.EDT) public boolean canSavePlayerLocations() { return world.getMovablePlayerList().canSave(); } @CalledOnlyBy(AmidstThread.EDT) public void savePlayerLocations() { world.getMovablePlayerList().save(); } @CalledOnlyBy(AmidstThread.EDT) public boolean calculateIsLayerEnabled(int layerId, Dimension dimension) { return layerManager.calculateIsEnabled(layerId, dimension); } @CalledOnlyBy(AmidstThread.EDT) public boolean hasLayer(int layerId) { return world.getEnabledLayers().contains(layerId); } @CalledOnlyBy(AmidstThread.EDT) public void openExportDialog() { biomeExporterDialog.createAndShow(world, translator, progressEntryHolder::set); } public boolean isFullyLoaded() { return fragmentManager.getLoadingQueueSize() == 0; } }
amidst
src\main\java\amidst\gui\main\viewer\ViewerMouseListener.java
package amidst.gui.main.viewer; import java.awt.Component; import java.awt.Point; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseWheelEvent; import java.awt.event.MouseWheelListener; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.fragment.FragmentGraph; import amidst.gui.main.Actions; import amidst.gui.main.viewer.widget.WidgetManager; @NotThreadSafe public class ViewerMouseListener implements MouseListener, MouseWheelListener { private final WidgetManager widgetManager; private final FragmentGraph graph; private final FragmentGraphToScreenTranslator translator; private final Zoom zoom; private final Movement movement; private final Actions actions; @CalledOnlyBy(AmidstThread.EDT) public ViewerMouseListener( WidgetManager widgetManager, FragmentGraph graph, FragmentGraphToScreenTranslator translator, Zoom zoom, Movement movement, Actions actions) { this.widgetManager = widgetManager; this.graph = graph; this.translator = translator; this.zoom = zoom; this.movement = movement; this.actions = actions; } @CalledOnlyBy(AmidstThread.EDT) @Override public void mouseWheelMoved(MouseWheelEvent e) { Point mousePosition = e.getPoint(); int notches = e.getWheelRotation(); if (!widgetManager.mouseWheelMoved(mousePosition, notches)) { doMouseWheelMoved(mousePosition, notches); } } @CalledOnlyBy(AmidstThread.EDT) @Override public void mouseClicked(MouseEvent e) { Point mousePosition = e.getPoint(); if (isRightClick(e)) { // noop } else if (!widgetManager.mouseClicked(mousePosition)) { doMouseClicked(mousePosition); } } @CalledOnlyBy(AmidstThread.EDT) @Override public void mousePressed(MouseEvent e) { Point mousePosition = e.getPoint(); if (isPopup(e)) { showPopupMenu(mousePosition, e.getComponent(), e.getX(), e.getY()); } else if (isRightClick(e)) { // noop } else if (!widgetManager.mousePressed(mousePosition)) { doMousePressed(mousePosition); } } @CalledOnlyBy(AmidstThread.EDT) @Override public void mouseReleased(MouseEvent e) { Point mousePosition = e.getPoint(); if (isPopup(e)) { showPopupMenu(mousePosition, e.getComponent(), e.getX(), e.getY()); } else if (!widgetManager.mouseReleased()) { doMouseReleased(); } } @CalledOnlyBy(AmidstThread.EDT) @Override public void mouseEntered(MouseEvent e) { // noop } @CalledOnlyBy(AmidstThread.EDT) @Override public void mouseExited(MouseEvent e) { // noop } @CalledOnlyBy(AmidstThread.EDT) private boolean isPopup(MouseEvent e) { return e.isPopupTrigger(); } @CalledOnlyBy(AmidstThread.EDT) private boolean isRightClick(MouseEvent e) { return e.isMetaDown(); } @CalledOnlyBy(AmidstThread.EDT) private void doMouseWheelMoved(Point mousePosition, int notches) { actions.adjustZoom(mousePosition, notches); } @CalledOnlyBy(AmidstThread.EDT) private void doMouseClicked(Point mousePosition) { actions.selectWorldIcon( graph.getClosestWorldIcon(translator.screenToWorld(mousePosition), zoom.screenToWorld(50))); } @CalledOnlyBy(AmidstThread.EDT) private void doMousePressed(Point mousePosition) { movement.setLastMouse(mousePosition); } @CalledOnlyBy(AmidstThread.EDT) private void doMouseReleased() { movement.setLastMouse(null); } @CalledOnlyBy(AmidstThread.EDT) private void showPopupMenu(Point mousePosition, Component component, int x, int y) { actions.showPlayerPopupMenu(translator.screenToWorld(mousePosition), component, x, y); } }
amidst
src\main\java\amidst\gui\main\viewer\WorldIconSelection.java
package amidst.gui.main.viewer; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.icon.WorldIcon; @ThreadSafe public class WorldIconSelection { private volatile WorldIcon selection; public WorldIcon get() { return selection; } public void select(WorldIcon selection) { this.selection = selection; } public void clear() { this.selection = null; } public boolean isSelected(WorldIcon worldIcon) { return selection == worldIcon; } public boolean hasSelection() { return selection != null; } }
amidst
src\main\java\amidst\gui\main\viewer\Zoom.java
package amidst.gui.main.viewer; import java.awt.Point; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.settings.Setting; @NotThreadSafe public class Zoom { private int remainingTicks = 0; private int level = 0; private double target = zoomFromLevel(0); private double current = zoomFromLevel(0); private Point mousePosition = new Point(); private final Setting<Boolean> maxZoomSetting; @CalledOnlyBy(AmidstThread.EDT) public Zoom(Setting<Boolean> maxZoomSetting) { this.maxZoomSetting = maxZoomSetting; } private static float zoomFromLevel(int level) { return (float) (0.25 * Math.pow(2, -level / 8.0)); } @CalledOnlyBy(AmidstThread.EDT) public void update(FragmentGraphToScreenTranslator translator) { remainingTicks--; if (remainingTicks >= 0) { double previous = updateCurrent(); translator.adjustToZoom(previous, current, mousePosition); } } @CalledOnlyBy(AmidstThread.EDT) private double updateCurrent() { double previous = current; current = (target + current) * 0.5; return previous; } @CalledOnlyBy(AmidstThread.EDT) public void adjustZoom(Point mousePosition, int notches) { int oldLevel = level; int maxLevel = getMaxZoomLevel(); int minLevel = getMinZoomLevel(); if (notches > 0) { if (level < maxLevel) { level = Math.min(level + notches, maxLevel); } } else if (notches < 0) { if (level > minLevel) { level = Math.max(level + notches, minLevel); } } if (oldLevel != level) { this.mousePosition = mousePosition; target = zoomFromLevel(level); remainingTicks = 100 * Math.abs(oldLevel - level); } } @CalledOnlyBy(AmidstThread.EDT) private int getMaxZoomLevel() { return maxZoomSetting.get() ? 12 : 10000; } @CalledOnlyBy(AmidstThread.EDT) private int getMinZoomLevel() { return -20; } @CalledOnlyBy(AmidstThread.EDT) public double getCurrentValue() { return current; } @CalledOnlyBy(AmidstThread.EDT) public void skipFading() { remainingTicks = 0; current = target; } @CalledOnlyBy(AmidstThread.EDT) public void reset() { mousePosition = new Point(); } @CalledOnlyBy(AmidstThread.EDT) public double screenToWorld(double coordinate) { return coordinate / current; } @CalledOnlyBy(AmidstThread.EDT) public double worldToScreen(double coordinate) { return coordinate * current; } }
amidst
src\main\java\amidst\gui\main\viewer\widget\BiomeExporterProgressWidget.java
package amidst.gui.main.viewer.widget; import java.awt.FontMetrics; import java.util.Map.Entry; import java.util.function.Supplier; import amidst.settings.Setting; public class BiomeExporterProgressWidget extends ProgressWidget { private volatile int xOffset; private final Setting<Boolean> showDebug; private final DebugWidget debugWidget; private final int iconWidth; public BiomeExporterProgressWidget(CornerAnchorPoint anchor, Supplier<Entry<ProgressEntryType, Integer>> progressEntrySupplier, int xOffset, Setting<Boolean> showDebug, DebugWidget debugWidget, int iconWidth) { super(anchor, progressEntrySupplier, xOffset, 0, 0, 100, -1, 150, 25); this.xOffset = xOffset; this.showDebug = showDebug; this.debugWidget = debugWidget; this.iconWidth = iconWidth; } @Override protected void doUpdate(FontMetrics fontMetrics, float time) { super.doUpdate(fontMetrics, time); setXOffset(showDebug.get() ? xOffset - debugWidget.getWidth() : xOffset - iconWidth); } }
amidst
src\main\java\amidst\gui\main\viewer\widget\BiomeToggleWidget.java
package amidst.gui.main.viewer.widget; import java.awt.Color; import java.awt.Graphics2D; import amidst.ResourceLoader; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.gui.main.viewer.BiomeSelection; @NotThreadSafe public class BiomeToggleWidget extends ImmutableIconWidget { private final BiomeWidget biomeWidget; private final BiomeSelection biomeSelection; @CalledOnlyBy(AmidstThread.EDT) public BiomeToggleWidget(CornerAnchorPoint anchor, BiomeWidget biomeWidget, BiomeSelection biomeSelection) { super(anchor, ResourceLoader.getImage("/amidst/gui/main/highlighter.png")); this.biomeWidget = biomeWidget; this.biomeSelection = biomeSelection; } @CalledOnlyBy(AmidstThread.EDT) @Override public boolean onMousePressed(int x, int y) { biomeWidget.toggleVisibility(); return true; } @CalledOnlyBy(AmidstThread.EDT) @Override protected void doDraw(Graphics2D g2d) { super.doDraw(g2d); if(biomeSelection.isHighlightMode()) { g2d.setColor(new Color(255, 255, 255, 64)); g2d.fillRect(getX(), getY(), getWidth(), getHeight()); } } @CalledOnlyBy(AmidstThread.EDT) @Override protected boolean onVisibilityCheck() { return true; } }
amidst
src\main\java\amidst\gui\main\viewer\widget\BiomeWidget.java
package amidst.gui.main.viewer.widget; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Rectangle; import java.util.ArrayList; import java.util.List; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.fragment.layer.LayerReloader; import amidst.gui.main.viewer.BiomeSelection; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.biome.BiomeColor; import amidst.mojangapi.world.biome.BiomeList; import amidst.settings.biomeprofile.BiomeProfileSelection; @NotThreadSafe public class BiomeWidget extends Widget { // @formatter:off private static final Color INNER_BOX_BG_COLOR = new Color(0.3f, 0.3f, 0.3f, 0.3f); private static final Color BIOME_BG_COLOR_1 = new Color(0.8f, 0.8f, 0.8f, 0.2f); private static final Color BIOME_BG_COLOR_2 = new Color(0.6f, 0.6f, 0.6f, 0.2f); private static final Color BIOME_LIT_BG_COLOR_1 = new Color(0.8f, 0.8f, 1.0f, 0.7f); private static final Color BIOME_LIT_BG_COLOR_2 = new Color(0.6f, 0.6f, 0.8f, 0.7f); private static final Color INNER_BOX_BORDER_COLOR = new Color(1.0f, 1.0f, 1.0f, 1.0f); private static final Color SCROLLBAR_COLOR = new Color(0.6f, 0.6f, 0.6f, 0.8f); private static final Color SCROLLBAR_LIT_COLOR = new Color(0.6f, 0.6f, 0.8f, 0.8f); private static final Color SELECT_BUTTON_COLOR = new Color(0.6f, 0.6f, 0.8f, 1.0f); // @formatter:on private final BiomeSelection biomeSelection; private final LayerReloader layerReloader; private final BiomeProfileSelection biomeProfileSelection; private List<Biome> biomes = new ArrayList<>(); private BiomeList biomeList; private int maxNameWidth = 0; private int biomeListHeight; private boolean isInitialized = false; private boolean isVisible = false; private Rectangle innerBox = new Rectangle(0, 0, 1, 1); private int biomeListYOffset = 0; private boolean scrollbarVisible = false; private boolean scrollbarGrabbed = false; private int scrollbarHeight = 0; private int scrollbarWidth = 10; private int scrollbarY = 0; private int mouseYOnGrab = 0; private int scrollbarYOnGrab; @CalledOnlyBy(AmidstThread.EDT) public BiomeWidget( CornerAnchorPoint anchor, BiomeSelection biomeSelection, LayerReloader layerReloader, BiomeProfileSelection biomeProfileSelection, BiomeList biomeList) { super(anchor); this.biomeSelection = biomeSelection; this.layerReloader = layerReloader; this.biomeProfileSelection = biomeProfileSelection; this.biomeList = biomeList; this.isVisible = biomeSelection.isWidgetVisible(); setWidth(250); setHeight(400); setY(100); } @CalledOnlyBy(AmidstThread.EDT) public void toggleVisibility() { isVisible = biomeSelection.toggleWidgetVisibility(); } @CalledOnlyBy(AmidstThread.EDT) @Override protected void doUpdate(FontMetrics fontMetrics, float time) { initializeIfNecessary(fontMetrics); updateX(); updateHeight(); updateInnerBoxPositionAndSize(); updateBiomeListYOffset(); updateScrollbarVisibility(); if (scrollbarVisible) { updateInnerBoxWidth(); updateScrollbarParameter(getMousePosition()); } } @CalledOnlyBy(AmidstThread.EDT) private void initializeIfNecessary(FontMetrics fontMetrics) { if (!isInitialized) { isInitialized = true; for (Biome biome : biomeList.iterable()) { biomes.add(biome); int width = fontMetrics.stringWidth(biome.getName()); maxNameWidth = Math.max(width, maxNameWidth); } biomeListHeight = biomes.size() * 16; } } @CalledOnlyBy(AmidstThread.EDT) private void updateX() { setX(getViewerWidth() - getWidth()); } @CalledOnlyBy(AmidstThread.EDT) private void updateHeight() { setHeight(Math.max(200, getViewerHeight() - 200)); } @CalledOnlyBy(AmidstThread.EDT) private void updateInnerBoxPositionAndSize() { innerBox.x = getX() + 8; innerBox.y = getY() + 30; innerBox.width = getWidth() - 16; innerBox.height = getHeight() - 58; } @CalledOnlyBy(AmidstThread.EDT) private void updateBiomeListYOffset() { biomeListYOffset = Math.min(0, Math.max(-biomeListHeight + innerBox.height, biomeListYOffset)); } @CalledOnlyBy(AmidstThread.EDT) private void updateScrollbarVisibility() { if (biomeListHeight > innerBox.height) { scrollbarVisible = true; } else { scrollbarVisible = false; } } @CalledOnlyBy(AmidstThread.EDT) private void updateInnerBoxWidth() { innerBox.width -= scrollbarWidth; } @CalledOnlyBy(AmidstThread.EDT) private void updateScrollbarParameter(Point mousePosition) { float boxHeight = innerBox.height; float listHeight = biomeListHeight; if (scrollbarGrabbed) { if (mousePosition != null) { biomeListYOffset = (int) ((listHeight / boxHeight) * (-scrollbarYOnGrab - (mousePosition.y - mouseYOnGrab))); updateBiomeListYOffset(); } else { scrollbarGrabbed = false; } } scrollbarY = (int) ((-biomeListYOffset / listHeight) * boxHeight); scrollbarHeight = (int) (Math.ceil(boxHeight * (boxHeight / listHeight))); } @CalledOnlyBy(AmidstThread.EDT) @Override protected void doDraw(Graphics2D g2d) { drawTextHighlightBiomes(g2d); drawInnerBoxBackground(g2d); drawInnerBoxBorder(g2d); setClipToInnerBox(g2d); for (int i = 0; i < biomes.size(); i++) { Biome biome = biomes.get(i); drawBiomeBackgroundColor(g2d, i, getBiomeBackgroudColor(i, biome)); drawBiomeColor(g2d, i, getBiomeColorOrUnknown(biome)); drawBiomeName(g2d, i, biome); } clearClip(g2d); if (scrollbarVisible) { drawScrollbar(g2d); } drawTextSelect(g2d); drawSpecialButtons(g2d); } @CalledOnlyBy(AmidstThread.EDT) private void drawTextHighlightBiomes(Graphics2D g2d) { g2d.drawString("Highlight Biomes", getX() + 10, getY() + 20); } @CalledOnlyBy(AmidstThread.EDT) private void drawInnerBoxBackground(Graphics2D g2d) { g2d.setColor(INNER_BOX_BG_COLOR); g2d.fillRect(innerBox.x, innerBox.y, innerBox.width, innerBox.height); } @CalledOnlyBy(AmidstThread.EDT) private void drawInnerBoxBorder(Graphics2D g2d) { g2d.setColor(INNER_BOX_BORDER_COLOR); g2d.drawRect( innerBox.x - 1, innerBox.y - 1, innerBox.width + 1 + (scrollbarVisible ? scrollbarWidth : 0), innerBox.height + 1); } @CalledOnlyBy(AmidstThread.EDT) private void setClipToInnerBox(Graphics2D g2d) { g2d.setClip(innerBox); } @CalledOnlyBy(AmidstThread.EDT) private Color getBiomeBackgroudColor(int i, Biome biome) { if (biomeSelection.isSelected(biome.getId())) { if (i % 2 != 0) { return BIOME_LIT_BG_COLOR_1; } else { return BIOME_LIT_BG_COLOR_2; } } else { if (i % 2 != 0) { return BIOME_BG_COLOR_1; } else { return BIOME_BG_COLOR_2; } } } @CalledOnlyBy(AmidstThread.EDT) private void drawBiomeBackgroundColor(Graphics2D g2d, int i, Color color) { g2d.setColor(color); g2d.fillRect(innerBox.x, innerBox.y + i * 16 + biomeListYOffset, innerBox.width, 16); } @CalledOnlyBy(AmidstThread.EDT) private BiomeColor getBiomeColorOrUnknown(Biome biome) { return biomeProfileSelection.getBiomeColorOrUnknown(biome.getId()); } @CalledOnlyBy(AmidstThread.EDT) private void drawBiomeColor(Graphics2D g2d, int i, BiomeColor biomeColor) { g2d.setColor(biomeColor.getColor()); g2d.fillRect(innerBox.x, innerBox.y + i * 16 + biomeListYOffset, 20, 16); } @CalledOnlyBy(AmidstThread.EDT) private void drawBiomeName(Graphics2D g2d, int i, Biome biome) { g2d.setColor(Color.white); g2d.drawString(biomeList.getByIdOrNull(biome.getId()).getName(), innerBox.x + 25, innerBox.y + 13 + i * 16 + biomeListYOffset); } @CalledOnlyBy(AmidstThread.EDT) private void clearClip(Graphics2D g2d) { g2d.setClip(null); } @CalledOnlyBy(AmidstThread.EDT) private void drawScrollbar(Graphics2D g2d) { g2d.setColor(scrollbarGrabbed ? SCROLLBAR_LIT_COLOR : SCROLLBAR_COLOR); g2d.fillRect(innerBox.x + innerBox.width, innerBox.y + scrollbarY, scrollbarWidth, scrollbarHeight); } @CalledOnlyBy(AmidstThread.EDT) private void drawTextSelect(Graphics2D g2d) { g2d.setColor(Color.white); g2d.drawString("Select:", getX() + 8, getY() + getHeight() - 10); } @CalledOnlyBy(AmidstThread.EDT) private void drawSpecialButtons(Graphics2D g2d) { g2d.setColor(SELECT_BUTTON_COLOR); String activeText = biomeSelection.isHighlightMode() ? "Active" : "Inactive"; g2d.drawString(activeText, getX() + getWidth() - 65, getY() + 20); g2d.drawString("All Special None", getX() + 120, getY() + getHeight() - 10); } @CalledOnlyBy(AmidstThread.EDT) @Override public boolean onMouseWheelMoved(int mouseX, int mouseY, int notches) { if (!isInitialized) { return false; } if (isInBoundsOfInnerBox(mouseX, mouseY)) { biomeListYOffset = Math .min(0, Math.max(-biomeListHeight + innerBox.height, biomeListYOffset - notches * 35)); } return true; } @CalledOnlyBy(AmidstThread.EDT) @Override public void onMouseReleased() { scrollbarGrabbed = false; } @CalledOnlyBy(AmidstThread.EDT) @Override public boolean onMousePressed(int mouseX, int mouseY) { if (!isInitialized) { return false; } updateScrollbarParameters(mouseX, mouseY); if (processClick(mouseX, mouseY)) { layerReloader.reloadBackgroundLayer(); } return true; } @CalledOnlyBy(AmidstThread.EDT) private void updateScrollbarParameters(int mouseX, int mouseY) { if (scrollbarVisible) { if (isInBoundsOfScrollbar(mouseX, mouseY)) { mouseYOnGrab = mouseY + getY(); scrollbarYOnGrab = scrollbarY; scrollbarGrabbed = true; } } } @CalledOnlyBy(AmidstThread.EDT) private boolean processClick(int mouseX, int mouseY) { if (isInBoundsOfInnerBox(mouseX, mouseY)) { int id = (mouseY - (innerBox.y - getY()) - biomeListYOffset) / 16; if (id < biomes.size()) { int index = biomes.get(id).getId(); biomeSelection.toggle(index); return biomeSelection.isHighlightMode(); } } else if (isActiveButton(mouseX, mouseY)) { biomeSelection.toggleHighlightMode(); return true; } else if (isBottomButton(mouseY)) { if (isSelectAllButton(mouseX)) { biomeSelection.selectAll(); return biomeSelection.isHighlightMode(); } else if (isSelectSpecialBiomesButton(mouseX)) { selectOnlySpecialBiomes(); return biomeSelection.isHighlightMode(); } else if (isDeselectAllButton(mouseX)) { biomeSelection.deselectAll(); return biomeSelection.isHighlightMode(); } } return false; } @CalledOnlyBy(AmidstThread.EDT) private void selectOnlySpecialBiomes() { biomeSelection.deselectAll(); for (Biome biome: biomeList.iterable()) { if (biome.isSpecialBiome()) { biomeSelection.toggle(biome.getId()); } } } @CalledOnlyBy(AmidstThread.EDT) private boolean isInBoundsOfInnerBox(int mouseX, int mouseY) { int offsetX = translateXToWidgetCoordinates(innerBox.x); int offsetY = translateYToWidgetCoordinates(innerBox.y); int width = innerBox.width; int height = innerBox.height; return Widget.isInBounds(mouseX, mouseY, offsetX, offsetY, width, height); } @CalledOnlyBy(AmidstThread.EDT) private boolean isInBoundsOfScrollbar(int mouseX, int mouseY) { int offsetX = translateXToWidgetCoordinates(innerBox.x + innerBox.width); int offsetY = translateYToWidgetCoordinates(innerBox.y + scrollbarY); int width = scrollbarWidth; int height = scrollbarHeight; return Widget.isInBounds(mouseX, mouseY, offsetX, offsetY, width, height); } // TODO: These values are temporarily hard coded for the sake of a fast // release @CalledOnlyBy(AmidstThread.EDT) private boolean isBottomButton(int mouseY) { return mouseY > getHeight() - 25 && mouseY < getHeight() - 9; } @CalledOnlyBy(AmidstThread.EDT) private boolean isSelectAllButton(int mouseX) { return mouseX > 117 && mouseX < 139; } @CalledOnlyBy(AmidstThread.EDT) private boolean isSelectSpecialBiomesButton(int mouseX) { return mouseX > 143 && mouseX < 197; } @CalledOnlyBy(AmidstThread.EDT) private boolean isDeselectAllButton(int mouseX) { return mouseX > 203 && mouseX < 242; } @CalledOnlyBy(AmidstThread.EDT) private boolean isActiveButton(int mouseX, int mouseY) { return mouseX >= getWidth() - 65 && mouseX < getWidth() - 5 && mouseY >= 5 && mouseY < 21; } @CalledOnlyBy(AmidstThread.EDT) @Override public boolean onVisibilityCheck() { return isVisible && getHeight() > 200; } }
amidst
src\main\java\amidst\gui\main\viewer\widget\ChangeableTextWidget.java
package amidst.gui.main.viewer.widget; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.Supplier; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; @NotThreadSafe public class ChangeableTextWidget extends TextWidget { private final Supplier<String> text; @CalledOnlyBy(AmidstThread.EDT) public ChangeableTextWidget(CornerAnchorPoint anchor, Supplier<String> text) { super(anchor); this.text = text; } @CalledOnlyBy(AmidstThread.EDT) @Override protected List<String> updateTextLines() { String currentText = text.get(); if (currentText == null) { return Collections.emptyList(); } else { return Arrays.asList(text.get()); } } }
amidst
src\main\java\amidst\gui\main\viewer\widget\CursorInformationWidget.java
package amidst.gui.main.viewer.widget; import java.awt.Point; import java.util.Arrays; import java.util.List; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.fragment.Fragment; import amidst.fragment.FragmentGraph; import amidst.gui.main.viewer.FragmentGraphToScreenTranslator; import amidst.logging.AmidstLogger; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.biome.Biome; import amidst.mojangapi.world.biome.BiomeList; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.mojangapi.world.coordinates.Resolution; import amidst.mojangapi.world.versionfeatures.DefaultBiomes; import amidst.settings.Setting; @NotThreadSafe public class CursorInformationWidget extends TextWidget { private static final String UNKNOWN_BIOME_NAME = "Unknown"; private final FragmentGraph graph; private final FragmentGraphToScreenTranslator translator; private final Setting<Dimension> dimensionSetting; private final BiomeList biomeList; @CalledOnlyBy(AmidstThread.EDT) public CursorInformationWidget( CornerAnchorPoint anchor, FragmentGraph graph, FragmentGraphToScreenTranslator translator, Setting<Dimension> dimensionSetting, BiomeList biomeList) { super(anchor); this.graph = graph; this.translator = translator; this.dimensionSetting = dimensionSetting; this.biomeList = biomeList; } @CalledOnlyBy(AmidstThread.EDT) @Override protected List<String> updateTextLines() { Point mousePosition = getMousePosition(); if (mousePosition != null) { CoordinatesInWorld coordinates = translator.screenToWorld(mousePosition); String biomeName = getBiomeNameAt(coordinates); return Arrays.asList(biomeName + " " + coordinates.toString()); } else { return null; } } @CalledOnlyBy(AmidstThread.EDT) private String getBiomeNameAt(CoordinatesInWorld coordinates) { Dimension dimension = dimensionSetting.get(); if (dimension.equals(Dimension.OVERWORLD)) { return getOverworldBiomeNameAt(coordinates); } else if (dimension.equals(Dimension.END)) { return biomeList.getByIdOrNull(DefaultBiomes.theEnd).getName(); } else { AmidstLogger.warn("unsupported dimension"); return UNKNOWN_BIOME_NAME; } } @CalledOnlyBy(AmidstThread.EDT) private String getOverworldBiomeNameAt(CoordinatesInWorld coordinates) { Fragment fragment = graph.getFragmentAt(coordinates); if (fragment != null && fragment.getState().equals(Fragment.State.LOADED)) { long x = coordinates.getXRelativeToFragmentAs(Resolution.QUARTER); long y = coordinates.getYRelativeToFragmentAs(Resolution.QUARTER); short biome = fragment.getBiomeDataAt((int) x, (int) y); Biome b = biomeList.getByIdOrNull(biome); if (b != null) { return b.getName(); } else if (biome != -1) { return UNKNOWN_BIOME_NAME + " (ID: " + biome + ")"; } } return UNKNOWN_BIOME_NAME; } }
amidst
src\main\java\amidst\gui\main\viewer\widget\DebugWidget.java
package amidst.gui.main.viewer.widget; import java.util.Arrays; import java.util.List; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.fragment.FragmentGraph; import amidst.fragment.FragmentManager; import amidst.gui.main.viewer.Graphics2DAccelerationCounter; import amidst.gui.main.viewer.Zoom; import amidst.settings.Setting; @NotThreadSafe public class DebugWidget extends TextWidget { private final FragmentGraph graph; private final FragmentManager fragmentManager; private final Setting<Boolean> isVisibleSetting; private final Graphics2DAccelerationCounter accelerationCounter; private final Zoom zoom; @CalledOnlyBy(AmidstThread.EDT) public DebugWidget( CornerAnchorPoint anchor, FragmentGraph graph, FragmentManager fragmentManager, Setting<Boolean> isVisibleSetting, Graphics2DAccelerationCounter accelerationCounter, Zoom zoom) { super(anchor); this.graph = graph; this.fragmentManager = fragmentManager; this.isVisibleSetting = isVisibleSetting; this.accelerationCounter = accelerationCounter; this.zoom = zoom; } @CalledOnlyBy(AmidstThread.EDT) @Override protected List<String> updateTextLines() { if (isVisibleSetting.get()) { int columns = graph.getFragmentsPerRow(); int rows = graph.getFragmentsPerColumn(); return Arrays.asList( "Fragment Manager:", "Cache Size: " + fragmentManager.getCacheSize(), "Available Queue Size: " + fragmentManager.getAvailableQueueSize(), "Loading Queue Size: " + fragmentManager.getLoadingQueueSize(), "Recycle Queue Size: " + fragmentManager.getRecycleQueueSize(), "", "Viewer:", "Size: " + columns + "x" + rows + " [" + (columns * rows) + "]", String.format("Pixel Scale: %1$.3fx", zoom.getCurrentValue() * 4), String.format("Acceleration: %1$.1f%%", accelerationCounter.getAcceleratedPercentage())); } else { return null; } } }
amidst
src\main\java\amidst\gui\main\viewer\widget\FpsWidget.java
package amidst.gui.main.viewer.widget; import java.lang.management.ManagementFactory; import java.util.Arrays; import java.util.List; import java.util.Timer; import java.util.TimerTask; import com.sun.management.OperatingSystemMXBean; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.settings.Setting; @SuppressWarnings("restriction") @NotThreadSafe public class FpsWidget extends TextWidget { private final FramerateTimer fpsTimer; private final Setting<Boolean> isVisibleSetting; private final OperatingSystemMXBean operatingSystemMXBean; private final Timer usageTimer = new Timer("UsageTimer", true); private volatile double cpuLoad; @CalledOnlyBy(AmidstThread.EDT) public FpsWidget(CornerAnchorPoint anchor, FramerateTimer fpsTimer, Setting<Boolean> isVisibleSetting) { super(anchor); this.fpsTimer = fpsTimer; this.isVisibleSetting = isVisibleSetting; this.operatingSystemMXBean = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean(); usageTimer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { cpuLoad = operatingSystemMXBean.getProcessCpuLoad() * 100; } }, 0, 500); } @CalledOnlyBy(AmidstThread.EDT) @Override protected List<String> updateTextLines() { fpsTimer.tick(); if (isVisibleSetting.get()) { return Arrays.asList( "CPU: " + String.format("%.1f", cpuLoad) + "%", "FPS: " + String.format("%.1f", fpsTimer.getCurrentFPS())); } else { return null; } } }
amidst
src\main\java\amidst\gui\main\viewer\widget\FramerateTimer.java
package amidst.gui.main.viewer.widget; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; @NotThreadSafe public class FramerateTimer { private int tickCounter; private long lastTime; private long msPerUpdate; private float currentFPS = 0.0f; @CalledOnlyBy(AmidstThread.EDT) public FramerateTimer(int updatesPerSecond) { msPerUpdate = (long) (1000f * (1f / updatesPerSecond)); reset(); } @CalledOnlyBy(AmidstThread.EDT) public void reset() { tickCounter = 0; lastTime = System.currentTimeMillis(); } @CalledOnlyBy(AmidstThread.EDT) public void tick() { tickCounter++; long currentTime = System.currentTimeMillis(); if (currentTime - lastTime > msPerUpdate) { currentFPS = calculateCurrentFPS(currentTime); tickCounter = 0; lastTime = currentTime; } } @CalledOnlyBy(AmidstThread.EDT) private float calculateCurrentFPS(long currentTime) { float timeDifference = currentTime - lastTime; timeDifference /= 1000f; timeDifference = tickCounter / timeDifference; return timeDifference; } @CalledOnlyBy(AmidstThread.EDT) public float getCurrentFPS() { return currentFPS; } }
amidst
src\main\java\amidst\gui\main\viewer\widget\IconTextWidget.java
package amidst.gui.main.viewer.widget; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.RenderingHints; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.mojangapi.world.icon.WorldIconImage; @NotThreadSafe public abstract class IconTextWidget extends TextWidget { private static final int ICON_HEIGHT = 24; private WorldIconImage icon = null; private int iconWidth; private int iconHeight; private int iconOffsetY; @CalledOnlyBy(AmidstThread.EDT) protected IconTextWidget(CornerAnchorPoint anchor) { super(anchor); setWidth(20); setHeight(35); } @CalledOnlyBy(AmidstThread.EDT) @Override protected void doUpdate(FontMetrics fontMetrics, float time) { WorldIconImage newIcon = updateIcon(); if (newIcon != null && newIcon != icon) { icon = newIcon; double scale = ((double) ICON_HEIGHT) / icon.getFrameHeight(); iconWidth = (int) Math.round(scale * icon.getImage().getWidth()); iconHeight = (int) Math.round(scale * icon.getImage().getHeight()); iconOffsetY = (int) Math.round(scale * icon.getFrameOffsetY()); } super.doUpdate(fontMetrics, time); } @CalledOnlyBy(AmidstThread.EDT) @Override protected void doDraw(Graphics2D g2d) { super.doDraw(g2d); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); g2d.drawImage(icon.getImage(), getX() + 5, getY() + 5 - iconOffsetY, iconWidth, iconHeight, null); g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); } @CalledOnlyBy(AmidstThread.EDT) @Override protected int getMarginLeft() { return 5 + iconWidth + 5; } @CalledOnlyBy(AmidstThread.EDT) @Override protected int getMarginTop() { // Lower the text slightly to align it with the icon return super.getMarginTop() + 2; } @CalledOnlyBy(AmidstThread.EDT) @Override protected int getMinimumHeight() { return 5 + ICON_HEIGHT + 5; } @CalledOnlyBy(AmidstThread.EDT) protected abstract WorldIconImage updateIcon(); }
amidst
src\main\java\amidst\gui\main\viewer\widget\ImmutableIconWidget.java
package amidst.gui.main.viewer.widget; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; public abstract class ImmutableIconWidget extends Widget { private BufferedImage icon; @CalledOnlyBy(AmidstThread.EDT) protected ImmutableIconWidget(CornerAnchorPoint anchor, BufferedImage icon) { super(anchor); this.icon = icon; setWidth(icon.getWidth()); setHeight(icon.getHeight()); } @CalledOnlyBy(AmidstThread.EDT) @Override protected void doUpdate(FontMetrics fontMetrics, float time) { // noop } @CalledOnlyBy(AmidstThread.EDT) @Override protected void doDraw(Graphics2D g2d) { g2d.drawImage(icon, getX(), getY(), icon.getWidth(), icon.getHeight(), null); } }
amidst
src\main\java\amidst\gui\main\viewer\widget\ImmutableTextWidget.java
package amidst.gui.main.viewer.widget; import java.util.Arrays; import java.util.List; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; @NotThreadSafe public class ImmutableTextWidget extends TextWidget { private final List<String> textLines; @CalledOnlyBy(AmidstThread.EDT) public ImmutableTextWidget(CornerAnchorPoint anchor, String... textLines) { super(anchor); this.textLines = Arrays.asList(textLines); } @CalledOnlyBy(AmidstThread.EDT) @Override protected List<String> updateTextLines() { return textLines; } }
amidst
src\main\java\amidst\gui\main\viewer\widget\OffsetWidget.java
package amidst.gui.main.viewer.widget; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; public abstract class OffsetWidget extends Widget { private volatile int xOffset, yOffset; protected OffsetWidget(CornerAnchorPoint anchor, int xOffset, int yOffset) { super(anchor); this.xOffset = xOffset; this.yOffset = yOffset; } public void setXOffset(int xOffset) { this.xOffset = xOffset; } public void setYOffset(int yOffset) { this.yOffset = yOffset; } @CalledOnlyBy(AmidstThread.EDT) @Override protected void setX(int x) { super.setX(x + xOffset); } @CalledOnlyBy(AmidstThread.EDT) @Override protected void setY(int y) { super.setY(y + yOffset); } }
amidst
src\main\java\amidst\gui\main\viewer\widget\ProgressWidget.java
package amidst.gui.main.viewer.widget; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.util.Map.Entry; import java.util.function.Supplier; import amidst.documentation.ThreadSafe; @ThreadSafe public abstract class ProgressWidget extends OffsetWidget { private static final int VERTICAL_MARGIN = 4; private static final int HORIZONTAL_MARGIN = 4; private final Supplier<Entry<ProgressEntryType, Integer>> progressEntrySupplier; private int min; private int max; private int progress; public ProgressWidget(CornerAnchorPoint anchor, Supplier<Entry<ProgressEntryType, Integer>> progressEntrySupplier, int xOffset, int yOffset, int initialMin, int initialMax, int initialProgress, int width, int height) { super(anchor, xOffset, yOffset); this.progressEntrySupplier = progressEntrySupplier; setWidth(width); setHeight(height); } @Override protected void doUpdate(FontMetrics fontMetrics, float time) { updateProgress(progressEntrySupplier.get()); } private void updateProgress(Entry<ProgressEntryType, Integer> value) { if(value != null) { switch (value.getKey()) { case MIN: setMin(value.getValue()); break; case MAX: setMax(value.getValue()); break; case PROGRESS: setProgress(value.getValue()); break; } } } @Override protected void doDraw(Graphics2D g2d) { int widthMax = getWidth() - (HORIZONTAL_MARGIN * 2) - 2; int calculatedWidth = (int) ((double) progress / max * widthMax); g2d.setColor(Color.GRAY); g2d.drawRect( getX() + HORIZONTAL_MARGIN, getY() + VERTICAL_MARGIN, getWidth() - (HORIZONTAL_MARGIN * 2) - 1, getHeight() - (VERTICAL_MARGIN * 2) -1 ); g2d.setColor(Color.GREEN.darker()); g2d.fillRect( getX() + HORIZONTAL_MARGIN + 1, getY() + VERTICAL_MARGIN + 1, calculatedWidth, getHeight() - (VERTICAL_MARGIN * 2) - 2 ); } public void setMin(int min) { this.min = min; } public void setMax(int max) { this.max = max; } public void setProgress(int progress) { this.progress = progress; } @Override protected boolean onVisibilityCheck() { return progress < max && progress >= min; } public enum ProgressEntryType { MAX, MIN, PROGRESS } }
amidst
src\main\java\amidst\gui\main\viewer\widget\ScaleWidget.java
package amidst.gui.main.viewer.widget; import java.awt.Color; import java.awt.FontMetrics; import java.awt.Graphics2D; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.gui.main.viewer.Zoom; import amidst.settings.Setting; @NotThreadSafe public class ScaleWidget extends Widget { public static final int MAX_SCALE_LENGTH_ON_SCREEN = 200; public static final int MARGIN = 8; private final Zoom zoom; private final Setting<Boolean> isVisibleSetting; private int scaleLengthOnScreen; private String text; private int textWidth; @CalledOnlyBy(AmidstThread.EDT) public ScaleWidget(CornerAnchorPoint anchor, Zoom zoom, Setting<Boolean> isVisibleSetting) { super(anchor); this.zoom = zoom; this.isVisibleSetting = isVisibleSetting; setWidth(100); setHeight(34); } @CalledOnlyBy(AmidstThread.EDT) @Override protected void doUpdate(FontMetrics fontMetrics, float time) { int scaleLengthInWorld = getScaleLengthInWorld(); scaleLengthOnScreen = (int) zoom.worldToScreen(scaleLengthInWorld); text = scaleLengthInWorld + " blocks"; textWidth = fontMetrics.stringWidth(text); setWidth(Math.max(scaleLengthOnScreen, textWidth) + (MARGIN * 2)); } @CalledOnlyBy(AmidstThread.EDT) private int getScaleLengthInWorld() { int first = 1; int base = 100; int result = first * base; int previousResult = result; while (zoom.worldToScreen(result) < MAX_SCALE_LENGTH_ON_SCREEN) { first = getNextFirst(first); base = getNextBase(first, base); previousResult = result; result = first * base; } return previousResult; } @CalledOnlyBy(AmidstThread.EDT) private int getNextFirst(int first) { if (first == 1) { return 2; } else if (first == 2) { return 5; } else { return 1; } } @CalledOnlyBy(AmidstThread.EDT) private int getNextBase(int first, int base) { if (first == 1) { return base * 10; } else { return base; } } @CalledOnlyBy(AmidstThread.EDT) @Override protected void doDraw(Graphics2D g2d) { drawText(g2d); drawLines(g2d); } @CalledOnlyBy(AmidstThread.EDT) private void drawText(Graphics2D g2d) { int x = getX() + 1 + ((getWidth() - textWidth) >> 1); int y = getY() + 18; g2d.drawString(text, x, y); } @CalledOnlyBy(AmidstThread.EDT) private void drawLines(Graphics2D g2d) { int x1 = getX() + 1 + ((getWidth() - scaleLengthOnScreen) >> 1); int x2 = x1 + scaleLengthOnScreen; int y1 = getY() + 23; int y2 = getY() + 26; int y3 = getY() + 28; g2d.setColor(Color.white); g2d.setStroke(LINE_STROKE_2); g2d.drawLine(x1, y2, x2, y2); g2d.setStroke(LINE_STROKE_1); g2d.drawLine(x1, y1, x1, y3); g2d.drawLine(x2, y1, x2, y3); } @CalledOnlyBy(AmidstThread.EDT) @Override protected boolean onVisibilityCheck() { return isVisibleSetting.get(); } }
amidst
src\main\java\amidst\gui\main\viewer\widget\SeedAndWorldTypeWidget.java
package amidst.gui.main.viewer.widget; import java.awt.FontMetrics; import amidst.documentation.NotThreadSafe; import amidst.mojangapi.world.WorldSeed; import amidst.mojangapi.world.WorldType; @NotThreadSafe public class SeedAndWorldTypeWidget extends ImmutableTextWidget { public SeedAndWorldTypeWidget(CornerAnchorPoint anchor, WorldSeed worldSeed, WorldType worldType) { super(anchor, worldSeed.getLabel(), "World Type: " + worldType.getName()); } /** * Add some extra line spacing because the seed and world type are separate * items, rather than multi-line paragraph text. */ @Override protected int getLineSeparationHeight(FontMetrics fontMetrics) { return (int) Math.round(super.getLineSeparationHeight(fontMetrics) * 1.2); } }
amidst
src\main\java\amidst\gui\main\viewer\widget\SelectedIconWidget.java
package amidst.gui.main.viewer.widget; import java.util.Arrays; import java.util.List; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.gui.main.viewer.WorldIconSelection; import amidst.mojangapi.world.icon.WorldIcon; import amidst.mojangapi.world.icon.WorldIconImage; @NotThreadSafe public class SelectedIconWidget extends IconTextWidget { private final WorldIconSelection worldIconSelection; @CalledOnlyBy(AmidstThread.EDT) public SelectedIconWidget(CornerAnchorPoint anchor, WorldIconSelection worldIconSelection) { super(anchor); this.worldIconSelection = worldIconSelection; increaseYMargin(65); } @CalledOnlyBy(AmidstThread.EDT) @Override protected WorldIconImage updateIcon() { WorldIcon selection = worldIconSelection.get(); if (selection != null) { return selection.getImage(); } else { return null; } } @CalledOnlyBy(AmidstThread.EDT) @Override protected List<String> updateTextLines() { WorldIcon selection = worldIconSelection.get(); if (selection != null) { return Arrays.asList(selection.toString(true).split("\n")); } else { return null; } } }
amidst
src\main\java\amidst\gui\main\viewer\widget\TextWidget.java
package amidst.gui.main.viewer.widget; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.util.List; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; @NotThreadSafe public abstract class TextWidget extends Widget { private List<String> textLines = null; private boolean isVisible = false; @CalledOnlyBy(AmidstThread.EDT) public TextWidget(CornerAnchorPoint anchor) { super(anchor); setWidth(20); setHeight(30); } @CalledOnlyBy(AmidstThread.EDT) @Override protected void doUpdate(FontMetrics fontMetrics, float time) { List<String> newTextLines = updateTextLines(); if (newTextLines != null && !newTextLines.isEmpty() && !newTextLines.equals(textLines)) { textLines = newTextLines; setWidth(getMarginLeft() + getMaxStringWidth(fontMetrics) + getMarginRight()); setHeight(Math.max(getMinimumHeight(), getMarginTop() + getStringHeight(fontMetrics) + getMarginBottom())); } isVisible = newTextLines != null && newTextLines.size() > 0; } @CalledOnlyBy(AmidstThread.EDT) private int getMaxStringWidth(FontMetrics fontMetrics) { int result = 0; for (String line : textLines) { result = Math.max(result, fontMetrics.stringWidth(line)); } return result; } @CalledOnlyBy(AmidstThread.EDT) private int getStringHeight(FontMetrics fontMetrics) { int lineHeight = fontMetrics.getHeight(); int lineSeparationHeight = getLineSeparationHeight(fontMetrics); return textLines.size() * lineSeparationHeight + lineHeight - lineSeparationHeight; } @CalledOnlyBy(AmidstThread.EDT) @Override protected void doDraw(Graphics2D g2d) { int x = getX() + getMarginLeft(); int y = getY() + getMarginTop() + g2d.getFontMetrics().getAscent(); int lineSeparationHeight = getLineSeparationHeight(g2d.getFontMetrics()); for (String line : textLines) { g2d.drawString(line, x, y); y += lineSeparationHeight; } } @CalledOnlyBy(AmidstThread.EDT) @Override protected boolean onVisibilityCheck() { return isVisible; } /** * Override this to adjust the spacing between lines of text */ @CalledOnlyBy(AmidstThread.EDT) protected int getLineSeparationHeight(FontMetrics fontMetrics) { return fontMetrics.getHeight(); } @CalledOnlyBy(AmidstThread.EDT) protected int getMarginLeft() { return 10; } @CalledOnlyBy(AmidstThread.EDT) protected int getMarginRight() { return 10; } @CalledOnlyBy(AmidstThread.EDT) protected int getMarginTop() { return 6; } @CalledOnlyBy(AmidstThread.EDT) protected int getMarginBottom() { return 6; } @CalledOnlyBy(AmidstThread.EDT) protected int getMinimumHeight() { return 0; } @CalledOnlyBy(AmidstThread.EDT) protected abstract List<String> updateTextLines(); }
amidst
src\main\java\amidst\gui\main\viewer\widget\Widget.java
package amidst.gui.main.viewer.widget; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.Stroke; import java.awt.image.BufferedImage; import amidst.ResourceLoader; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; @NotThreadSafe public abstract class Widget { public static enum CornerAnchorPoint { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT, BOTTOM_CENTER, CENTER, NONE } protected static boolean isInBounds(int x, int y, int offsetX, int offsetY, int width, int height) { return x >= offsetX && x < offsetX + width && y >= offsetY && y < offsetY + height; } private static final BufferedImage DROP_SHADOW_BOTTOM_LEFT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/outer_bottom_left.png"); private static final BufferedImage DROP_SHADOW_BOTTOM_RIGHT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/outer_bottom_right.png"); private static final BufferedImage DROP_SHADOW_TOP_LEFT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/outer_top_left.png"); private static final BufferedImage DROP_SHADOW_TOP_RIGHT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/outer_top_right.png"); private static final BufferedImage DROP_SHADOW_BOTTOM = ResourceLoader .getImage("/amidst/gui/main/dropshadow/outer_bottom.png"); private static final BufferedImage DROP_SHADOW_TOP = ResourceLoader .getImage("/amidst/gui/main/dropshadow/outer_top.png"); private static final BufferedImage DROP_SHADOW_LEFT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/outer_left.png"); private static final BufferedImage DROP_SHADOW_RIGHT = ResourceLoader .getImage("/amidst/gui/main/dropshadow/outer_right.png"); public static final Font TEXT_FONT = new Font("arial", Font.BOLD, 15); private static final Color TEXT_COLOR = new Color(1f, 1f, 1f); private static final Color PANEL_COLOR = new Color(0.15f, 0.15f, 0.15f, 0.8f); protected static final Stroke LINE_STROKE_1 = new BasicStroke(1); protected static final Stroke LINE_STROKE_2 = new BasicStroke(2, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER); private final CornerAnchorPoint anchor; private int x; private int y; private int width; private int height; private int xMargin = 10; private int yMargin = 10; private boolean isFirstVisibilityCheck = true; private float alpha = 1.0f; private float targetAlpha = 1.0f; private int viewerWidth; private int viewerHeight; private Point mousePosition; @CalledOnlyBy(AmidstThread.EDT) protected Widget(CornerAnchorPoint anchor) { this.anchor = anchor; } @CalledOnlyBy(AmidstThread.EDT) public void update(int viewerWidth, int viewerHeight, Point mousePosition, FontMetrics fontMetrics, float time) { this.viewerWidth = viewerWidth; this.viewerHeight = viewerHeight; this.mousePosition = mousePosition; updateAlpha(time); doUpdate(fontMetrics, time); updatePosition(); } @CalledOnlyBy(AmidstThread.EDT) private void updateAlpha(float time) { if (alpha < targetAlpha) { alpha = Math.min(targetAlpha, alpha + time * 4.0f); } else if (alpha > targetAlpha) { alpha = Math.max(targetAlpha, alpha - time * 4.0f); } } @CalledOnlyBy(AmidstThread.EDT) private void updatePosition() { if (anchor == CornerAnchorPoint.TOP_LEFT) { setX(getLeftX()); setY(getTopY()); } else if (anchor == CornerAnchorPoint.BOTTOM_LEFT) { setX(getLeftX()); setY(getBottomY(viewerHeight)); } else if (anchor == CornerAnchorPoint.BOTTOM_RIGHT) { setX(getRightX(viewerWidth)); setY(getBottomY(viewerHeight)); } else if (anchor == CornerAnchorPoint.BOTTOM_CENTER) { setX(getCenterX(viewerWidth)); setY(getBottomY(viewerHeight)); } else if (anchor == CornerAnchorPoint.TOP_RIGHT) { setX(getRightX(viewerWidth)); setY(getTopY()); } else if (anchor == CornerAnchorPoint.CENTER) { setX(getCenterX(viewerWidth)); setY(getCenterY(viewerHeight)); } else if (anchor == CornerAnchorPoint.NONE) { // TODO: set x and y? } } @CalledOnlyBy(AmidstThread.EDT) private int getLeftX() { return xMargin; } @CalledOnlyBy(AmidstThread.EDT) private int getTopY() { return yMargin; } @CalledOnlyBy(AmidstThread.EDT) private int getRightX(int viewerWidth) { return viewerWidth - (width + xMargin); } @CalledOnlyBy(AmidstThread.EDT) private int getBottomY(int viewerHeight) { return viewerHeight - (height + yMargin); } @CalledOnlyBy(AmidstThread.EDT) private int getCenterX(int viewerWidth) { return (viewerWidth >> 1) - (width >> 1); } @CalledOnlyBy(AmidstThread.EDT) private int getCenterY(int viewerHeight) { return (viewerHeight >> 1) - (height >> 1); } @CalledOnlyBy(AmidstThread.EDT) public void draw(Graphics2D g2d) { initGraphics(g2d); drawBorder(g2d); drawBackground(g2d); initGraphicsForContent(g2d); doDraw(g2d); } @CalledOnlyBy(AmidstThread.EDT) private void initGraphics(Graphics2D g2d) { g2d.setColor(PANEL_COLOR); } @CalledOnlyBy(AmidstThread.EDT) private void drawBorder(Graphics2D g2d) { int x10 = x - 10; int y10 = y - 10; int xWidth = x + width; int yHeight = y + height; g2d.drawImage(DROP_SHADOW_TOP_LEFT, x10, y10, null); g2d.drawImage(DROP_SHADOW_TOP_RIGHT, xWidth, y10, null); g2d.drawImage(DROP_SHADOW_BOTTOM_LEFT, x10, yHeight, null); g2d.drawImage(DROP_SHADOW_BOTTOM_RIGHT, xWidth, yHeight, null); g2d.drawImage(DROP_SHADOW_TOP, x, y10, width, 10, null); g2d.drawImage(DROP_SHADOW_BOTTOM, x, yHeight, width, 10, null); g2d.drawImage(DROP_SHADOW_LEFT, x10, y, 10, height, null); g2d.drawImage(DROP_SHADOW_RIGHT, xWidth, y, 10, height, null); } @CalledOnlyBy(AmidstThread.EDT) private void drawBackground(Graphics2D g2d) { g2d.fillRect(x, y, width, height); } @CalledOnlyBy(AmidstThread.EDT) private void initGraphicsForContent(Graphics2D g2d) { g2d.setFont(TEXT_FONT); g2d.setColor(TEXT_COLOR); } @CalledOnlyBy(AmidstThread.EDT) protected void increaseYMargin(int delta) { yMargin += delta; } @CalledOnlyBy(AmidstThread.EDT) public boolean isInBounds(Point mouse) { return isInBounds(mouse.x, mouse.y); } @CalledOnlyBy(AmidstThread.EDT) public boolean isInBounds(int x, int y) { return isInBounds(x, y, this.x, this.y, this.width, this.height); } @CalledOnlyBy(AmidstThread.EDT) public int translateXToWidgetCoordinates(Point mouse) { return translateXToWidgetCoordinates(mouse.x); } @CalledOnlyBy(AmidstThread.EDT) public int translateYToWidgetCoordinates(Point mouse) { return translateYToWidgetCoordinates(mouse.y); } @CalledOnlyBy(AmidstThread.EDT) public int translateXToWidgetCoordinates(int x) { return x - this.x; } @CalledOnlyBy(AmidstThread.EDT) public int translateYToWidgetCoordinates(int y) { return y - this.y; } @CalledOnlyBy(AmidstThread.EDT) public boolean isVisible() { boolean isVisible = onVisibilityCheck(); targetAlpha = getTargetAlpha(isVisible); if (isFirstVisibilityCheck) { isFirstVisibilityCheck = false; skipFading(); } return isVisible || isFading(); } @CalledOnlyBy(AmidstThread.EDT) private float getTargetAlpha(boolean isVisible) { if (isVisible) { return 1.0f; } else { return 0.0f; } } @CalledOnlyBy(AmidstThread.EDT) private void skipFading() { alpha = targetAlpha; } @CalledOnlyBy(AmidstThread.EDT) private boolean isFading() { return targetAlpha != alpha; } @CalledOnlyBy(AmidstThread.EDT) public float getAlpha() { return alpha; } @CalledOnlyBy(AmidstThread.EDT) public int getX() { return x; } @CalledOnlyBy(AmidstThread.EDT) public int getY() { return y; } @CalledOnlyBy(AmidstThread.EDT) public int getWidth() { return width; } @CalledOnlyBy(AmidstThread.EDT) public int getHeight() { return height; } @CalledOnlyBy(AmidstThread.EDT) protected void setX(int x) { this.x = x; } @CalledOnlyBy(AmidstThread.EDT) protected void setY(int y) { this.y = y; } @CalledOnlyBy(AmidstThread.EDT) protected void setWidth(int width) { this.width = width; } @CalledOnlyBy(AmidstThread.EDT) protected void setHeight(int height) { this.height = height; } @CalledOnlyBy(AmidstThread.EDT) public boolean onClick(int x, int y) { return false; } @CalledOnlyBy(AmidstThread.EDT) public boolean onMouseWheelMoved(int x, int y, int rotation) { return false; } @CalledOnlyBy(AmidstThread.EDT) public boolean onMousePressed(int x, int y) { return false; } @CalledOnlyBy(AmidstThread.EDT) public void onMouseReleased() { // noop } @CalledOnlyBy(AmidstThread.EDT) protected int getViewerWidth() { return viewerWidth; } @CalledOnlyBy(AmidstThread.EDT) protected int getViewerHeight() { return viewerHeight; } @CalledOnlyBy(AmidstThread.EDT) protected Point getMousePosition() { return mousePosition; } @CalledOnlyBy(AmidstThread.EDT) protected abstract void doUpdate(FontMetrics fontMetrics, float time); @CalledOnlyBy(AmidstThread.EDT) protected abstract void doDraw(Graphics2D g2d); @CalledOnlyBy(AmidstThread.EDT) protected abstract boolean onVisibilityCheck(); }
amidst
src\main\java\amidst\gui\main\viewer\widget\WidgetManager.java
package amidst.gui.main.viewer.widget; import java.awt.Point; import java.util.List; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; @NotThreadSafe public class WidgetManager { private final List<Widget> widgets; private Widget mouseOwner; @CalledOnlyBy(AmidstThread.EDT) public WidgetManager(List<Widget> widgets) { this.widgets = widgets; } @CalledOnlyBy(AmidstThread.EDT) public boolean mouseWheelMoved(Point mousePosition, int notches) { for (Widget widget : widgets) { if (widget.isVisible() && widget.isInBounds(mousePosition) && widget.onMouseWheelMoved( widget.translateXToWidgetCoordinates(mousePosition), widget.translateYToWidgetCoordinates(mousePosition), notches)) { return true; } } return false; } @CalledOnlyBy(AmidstThread.EDT) public boolean mouseClicked(Point mousePosition) { for (Widget widget : widgets) { if (widget.isVisible() && widget.isInBounds(mousePosition) && widget.onClick( widget.translateXToWidgetCoordinates(mousePosition), widget.translateYToWidgetCoordinates(mousePosition))) { return true; } } return false; } @CalledOnlyBy(AmidstThread.EDT) public boolean mousePressed(Point mousePosition) { for (Widget widget : widgets) { if (widget.isVisible() && widget.isInBounds(mousePosition) && widget.onMousePressed( widget.translateXToWidgetCoordinates(mousePosition), widget.translateYToWidgetCoordinates(mousePosition))) { mouseOwner = widget; return true; } } return false; } @CalledOnlyBy(AmidstThread.EDT) public boolean mouseReleased() { if (mouseOwner != null) { mouseOwner.onMouseReleased(); mouseOwner = null; return true; } else { return false; } } }
amidst
src\main\java\amidst\mojangapi\file\DotMinecraftDirectoryNotFoundException.java
package amidst.mojangapi.file; import java.io.FileNotFoundException; @SuppressWarnings("serial") public class DotMinecraftDirectoryNotFoundException extends FileNotFoundException { public DotMinecraftDirectoryNotFoundException(String message) { super(message); } }
amidst
src\main\java\amidst\mojangapi\file\ImmutablePlayerInformationProvider.java
package amidst.mojangapi.file; import amidst.documentation.Immutable; import amidst.documentation.NotNull; import amidst.mojangapi.world.player.PlayerInformation; @Immutable public class ImmutablePlayerInformationProvider implements PlayerInformationProvider { private final PlayerInformation playerInformation; public ImmutablePlayerInformationProvider(PlayerInformation playerInformation) { this.playerInformation = playerInformation; } @NotNull @Override public PlayerInformation getByPlayerUUID(String playerUUID) { return playerInformation; } @NotNull @Override public PlayerInformation getByPlayerName(String playerName) { return playerInformation; } }
amidst
src\main\java\amidst\mojangapi\file\LauncherProfile.java
package amidst.mojangapi.file; import java.net.MalformedURLException; import java.net.URLClassLoader; import java.nio.file.Path; import amidst.documentation.Immutable; import amidst.mojangapi.file.directory.DotMinecraftDirectory; import amidst.mojangapi.file.directory.ProfileDirectory; import amidst.mojangapi.file.directory.VersionDirectory; import amidst.mojangapi.file.json.version.VersionJson; import amidst.mojangapi.file.service.ClassLoaderService; @Immutable public class LauncherProfile { private final ClassLoaderService classLoaderService = new ClassLoaderService(); private final DotMinecraftDirectory dotMinecraftDirectory; private final ProfileDirectory profileDirectory; private final VersionDirectory versionDirectory; private final VersionJson versionJson; private final boolean isVersionListedInProfile; private final String profileName; public LauncherProfile( DotMinecraftDirectory dotMinecraftDirectory, ProfileDirectory profileDirectory, VersionDirectory versionDirectory, VersionJson versionJson, boolean isVersionListedInProfile, String profileName) { this.dotMinecraftDirectory = dotMinecraftDirectory; this.profileDirectory = profileDirectory; this.versionDirectory = versionDirectory; this.versionJson = versionJson; this.isVersionListedInProfile = isVersionListedInProfile; this.profileName = profileName; } public String getVersionId() { return versionJson.getId(); } /** * True, iff the contained version was listed in the profile. Especially, * this is false if a modded profiles was resolved via * {@link UnresolvedLauncherProfile#resolveToVanilla(VersionList)}. */ public boolean isVersionListedInProfile() { return isVersionListedInProfile; } public String getVersionName() { return getVersionNamePrefix() + versionJson.getId(); } private String getVersionNamePrefix() { if (isVersionListedInProfile) { return ""; } else { return "*"; } } public String getProfileName() { return profileName; } public Path getJar() { return versionDirectory.getJar(); } public Path getSaves() { return profileDirectory.getSaves(); } public URLClassLoader newClassLoader() throws MalformedURLException { return classLoaderService.createClassLoader( dotMinecraftDirectory.getLibraries(), versionJson.getLibraries(), versionDirectory.getJar()); } }
amidst
src\main\java\amidst\mojangapi\file\MinecraftInstallation.java
package amidst.mojangapi.file; import amidst.documentation.Immutable; import amidst.logging.AmidstLogger; import amidst.mojangapi.file.directory.DotMinecraftDirectory; import amidst.mojangapi.file.directory.SaveDirectory; import amidst.mojangapi.file.directory.VersionDirectory; import amidst.mojangapi.file.json.launcherprofiles.LauncherProfilesJson; import amidst.mojangapi.file.json.version.VersionJson; import amidst.mojangapi.file.service.SaveDirectoryService; import amidst.parsing.FormatException; import amidst.parsing.json.JsonReader; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; @Immutable public class MinecraftInstallation { public static MinecraftInstallation newCustomMinecraftInstallation( Path libraries, Path versions, Path launcherProfilesJson) throws DotMinecraftDirectoryNotFoundException { DotMinecraftDirectory dotMinecraftDirectory = new DotMinecraftDirectory(DotMinecraftDirectory.getMinecraftDirectory(), libraries, versions, launcherProfilesJson); AmidstLogger.info("using '.minecraft' directory at: '" + dotMinecraftDirectory.getRoot() + "'"); return new MinecraftInstallation(dotMinecraftDirectory); } public static MinecraftInstallation newLocalMinecraftInstallation(Path dotMinecraftDirectory2) { DotMinecraftDirectory dotMinecraftDirectory = DotMinecraftDirectory .createDotMinecraftDirectory(dotMinecraftDirectory2); AmidstLogger.info("using '.minecraft' directory at: '" + dotMinecraftDirectory.getRoot() + "'"); return new MinecraftInstallation(dotMinecraftDirectory); } private final SaveDirectoryService saveDirectoryService = new SaveDirectoryService(); private final DotMinecraftDirectory dotMinecraftDirectory; public MinecraftInstallation(DotMinecraftDirectory dotMinecraftDirectory) { this.dotMinecraftDirectory = dotMinecraftDirectory; } public List<LauncherProfile> readInstalledVersionsAsLauncherProfiles() throws FormatException { Path versions = dotMinecraftDirectory.getVersions(); if (!Files.isDirectory(versions)) { return new ArrayList<>(); } try { List<VersionDirectory> installedValidVersionDirectories = Files .list(versions) .filter(Files::isDirectory) .map(Path::getFileName) .map(id -> DotMinecraftDirectory.createVersionDirectory(dotMinecraftDirectory, id.toString())) .filter(VersionDirectory::isValid) .toList(); List<LauncherProfile> result = new LinkedList<>(); for (VersionDirectory versionDirectory : installedValidVersionDirectories) { result.add(newLauncherProfile(versionDirectory)); } return result; } catch (IOException e) { AmidstLogger.error(e, "Error while reading directory " + versions); return new ArrayList<>(); } } public List<UnresolvedLauncherProfile> readLauncherProfiles() throws FormatException, IOException { return JsonReader.readLocation(dotMinecraftDirectory.getLauncherProfilesJson(), LauncherProfilesJson.class) .getProfiles() .values() .stream() .map(p -> new UnresolvedLauncherProfile(dotMinecraftDirectory, p)) .collect(Collectors.toList()); } public LauncherProfile newLauncherProfile(String versionId) throws FormatException, IOException { return newLauncherProfile( DotMinecraftDirectory.createValidVersionDirectory(dotMinecraftDirectory, versionId)); } private LauncherProfile newLauncherProfile(VersionDirectory versionDirectory) throws FormatException, IOException { VersionJson versionJson = JsonReader.readLocation(versionDirectory.getJson(), VersionJson.class); return new LauncherProfile( dotMinecraftDirectory, dotMinecraftDirectory.asProfileDirectory(), versionDirectory, versionJson, false, versionJson.getId()); } public SaveGame newSaveGame(Path location) throws IOException, FormatException { SaveDirectory saveDirectory = saveDirectoryService.newSaveDirectory(location); return new SaveGame(saveDirectory, saveDirectoryService.readLevelDat(saveDirectory)); } public Optional<LauncherProfile> tryReadLauncherProfile( Path minecraftJarFile, Path minecraftJsonFile) { if (minecraftJarFile == null || minecraftJsonFile == null) { return Optional.empty(); } VersionDirectory versionDirectory = new VersionDirectory(minecraftJarFile, minecraftJsonFile); if (!versionDirectory.isValid()) { AmidstLogger.error("Cannot read launcher profile. minecraftJarFile: '" + minecraftJarFile + "', minecraftJsonFile: '" + minecraftJsonFile + "'"); return Optional.empty(); } try { return Optional.of(newLauncherProfile(versionDirectory)); } catch (FormatException | IOException e) { AmidstLogger.error( e, "cannot read launcher profile. minecraftJarFile: '" + minecraftJarFile + "', minecraftJsonFile: '" + minecraftJsonFile + "'"); return Optional.empty(); } } /** * Try to locate a local profile with a name that matches the given string. No remote profiles are * supported. Any errors are ignored and will result in a non-match. */ public Optional<LauncherProfile> tryGetLauncherProfileFromName(String profileName) { try { List<Version> versionList = Version.newLocalVersionList(); for (UnresolvedLauncherProfile unresolvedProfile : readLauncherProfiles()) { LauncherProfile profile = unresolvedProfile.resolveToVanilla(versionList); if (profile.getProfileName().equalsIgnoreCase(profileName)) { return Optional.of(profile); } } } catch (FormatException | IOException e) { AmidstLogger.error(e, "error while reading launcher profiles"); } return Optional.empty(); } }
amidst
src\main\java\amidst\mojangapi\file\PlayerInformationCache.java
package amidst.mojangapi.file; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import amidst.documentation.NotNull; import amidst.documentation.ThreadSafe; import amidst.logging.AmidstLogger; import amidst.mojangapi.file.service.PlayerInformationService; import amidst.mojangapi.world.player.PlayerInformation; /** * Even though this class is thread-safe, it is possible that the same player * information is loaded more than once. This will be the case, if the first * request did not finish before the second request arrives. However, this use * case is very unlikely to happen for amidst. If it happens, it should not be a * problem. */ @ThreadSafe public class PlayerInformationCache implements PlayerInformationProvider { private final Map<String, PlayerInformation> byUUID = new ConcurrentHashMap<>(); private final Map<String, PlayerInformation> byName = new ConcurrentHashMap<>(); private final PlayerInformationService playerInformationService = new PlayerInformationService(); @NotNull @Override public PlayerInformation getByPlayerUUID(String playerUUID) { String cleanUUID = getCleanUUID(playerUUID); PlayerInformation result = byUUID.get(cleanUUID); if (result != null) { return result; } else { AmidstLogger.info("requesting player information for uuid: " + cleanUUID); result = playerInformationService.fromUUID(cleanUUID); put(result); return result; } } @NotNull @Override public PlayerInformation getByPlayerName(String playerName) { PlayerInformation result = byName.get(playerName); if (result != null) { return result; } else { AmidstLogger.info("requesting player information for name: " + playerName); result = playerInformationService.fromName(playerName); put(result); return result; } } private void put(PlayerInformation result) { if (result.getUUID() != null) { byUUID.put(result.getUUID(), result); } if (result.getName() != null) { byName.put(result.getName(), result); } } /** * The uuid in the filename contains dashes that are not allowed in the url. */ private String getCleanUUID(String uuid) { return uuid.replace("-", ""); } }
amidst
src\main\java\amidst\mojangapi\file\PlayerInformationProvider.java
package amidst.mojangapi.file; import amidst.documentation.NotNull; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.player.PlayerInformation; @ThreadSafe public interface PlayerInformationProvider { @NotNull PlayerInformation getByPlayerUUID(String playerUUID); @NotNull PlayerInformation getByPlayerName(String playerName); }
amidst
src\main\java\amidst\mojangapi\file\RemoteVersion.java
package amidst.mojangapi.file; import amidst.mojangapi.file.json.ReleaseType; import amidst.mojangapi.file.json.versionlist.RemoteVersionJson; import amidst.parsing.FormatException; import amidst.parsing.URIUtils; import amidst.parsing.json.JsonReader; import java.io.*; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Objects; public class RemoteVersion { private final RemoteVersionJson remoteVersionJson; private final byte[] rawJson; private RemoteVersion(RemoteVersionJson remoteVersionJson, byte[] rawJson) { this.remoteVersionJson = remoteVersionJson; this.rawJson = rawJson; } public static RemoteVersion from(URL metaUrl) throws FormatException, IOException { byte[] rawJson = URIUtils.readBytes(metaUrl); Reader jsonReader = new InputStreamReader(new ByteArrayInputStream(rawJson)); RemoteVersionJson remoteVersionJson = JsonReader.read(jsonReader, RemoteVersionJson.class); return new RemoteVersion(remoteVersionJson, rawJson); } public String getId() { return Objects.requireNonNull(remoteVersionJson.getId()); } public ReleaseType getType() { return Objects.requireNonNull(remoteVersionJson.getType()); } public boolean hasClient() { return remoteVersionJson.getClientUrl() != null; } public boolean hasServer() { return remoteVersionJson.getServerUrl() != null; } public void downloadClient(String prefix) throws IOException { String versionId1 = getId(); copyToFile(URIUtils.newInputStream(remoteVersionJson.getClientUrl()), Paths.get(prefix + versionId1 + "/" + versionId1 + ".jar")); String versionId = getId(); copyToFile(new ByteArrayInputStream(rawJson), Paths.get(prefix + versionId + "/" + versionId + ".json")); } public void downloadServer(String prefix) throws IOException { String versionId = getId(); copyToFile(URIUtils.newInputStream(remoteVersionJson.getServerUrl()), Paths.get(prefix + versionId + "/minecraft_server." + versionId + ".jar")); } private void copyToFile(InputStream from, Path to) throws IOException { Path parent = to.getParent(); if (parent != null) Files.createDirectories(parent); if (Files.exists(to)) { return; } Path part = to.resolveSibling(to.getFileName() + ".part"); Files.copy(from, part, StandardCopyOption.REPLACE_EXISTING); Files.move(part, to, StandardCopyOption.REPLACE_EXISTING); } }
amidst
src\main\java\amidst\mojangapi\file\SaveGame.java
package amidst.mojangapi.file; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import amidst.documentation.Immutable; import amidst.mojangapi.file.directory.SaveDirectory; import amidst.mojangapi.file.nbt.LevelDatNbt; import amidst.mojangapi.file.service.SaveDirectoryService; import amidst.mojangapi.world.WorldType; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; @Immutable public class SaveGame { private final SaveDirectoryService saveDirectoryService = new SaveDirectoryService(); private final SaveDirectory saveDirectory; private final LevelDatNbt levelDatNbt; public SaveGame(SaveDirectory saveDirectory, LevelDatNbt levelDatNbt) { this.saveDirectory = saveDirectory; this.levelDatNbt = levelDatNbt; } public long getSeed() { return levelDatNbt.getSeed(); } public CoordinatesInWorld getWorldSpawn() { return levelDatNbt.getWorldSpawn(); } public WorldType getWorldType() { return levelDatNbt.getWorldType(); } public String getGeneratorOptions() { return levelDatNbt.getGeneratorOptions(); } public boolean hasSingleplayerPlayer() { return levelDatNbt.hasPlayer(); } public boolean hasMultiplayerPlayers() { return saveDirectory.hasMultiplayerPlayers(); } public Optional<SaveGamePlayer> tryReadSingleplayerPlayer() { return saveDirectoryService .tryReadSingleplayerPlayerNbt(saveDirectory) .map(p -> new SaveGamePlayer(saveDirectory, p)); } public List<SaveGamePlayer> tryReadMultiplayerPlayers() { return saveDirectoryService .tryReadMultiplayerPlayerNbts(saveDirectory) .stream() .map(p -> new SaveGamePlayer(saveDirectory, p)) .collect(Collectors.toList()); } public List<SaveGamePlayer> tryReadAllPlayers() { List<SaveGamePlayer> result = new LinkedList<>(); result.addAll(tryReadSingleplayerPlayer().map(Collections::singletonList).orElseGet(Collections::emptyList)); result.addAll(tryReadMultiplayerPlayers()); return result; } }
amidst
src\main\java\amidst\mojangapi\file\SaveGamePlayer.java
package amidst.mojangapi.file; import amidst.documentation.Immutable; import amidst.mojangapi.file.directory.SaveDirectory; import amidst.mojangapi.file.nbt.player.PlayerNbt; import amidst.mojangapi.file.service.SaveDirectoryService; import amidst.mojangapi.world.player.PlayerCoordinates; import amidst.mojangapi.world.player.PlayerInformation; @Immutable public class SaveGamePlayer { private final SaveDirectoryService saveDirectoryService = new SaveDirectoryService(); private final SaveDirectory saveDirectory; private final PlayerNbt playerNbt; public SaveGamePlayer(SaveDirectory saveDirectory, PlayerNbt playerNbt) { this.saveDirectory = saveDirectory; this.playerNbt = playerNbt; } public PlayerCoordinates getPlayerCoordinates() { return playerNbt.getPlayerCoordinates(); } public boolean tryBackupAndWritePlayerCoordinates(PlayerCoordinates coordinates) { return saveDirectoryService.tryBackup(saveDirectory, playerNbt) && saveDirectoryService.tryWriteCoordinates(saveDirectory, playerNbt, coordinates); } public PlayerInformation getPlayerInformation(PlayerInformationProvider playerInformationProvider) { return playerNbt.map( () -> PlayerInformation.theSingleplayerPlayer(), playerUUID -> playerInformationProvider.getByPlayerUUID(playerUUID), playerName -> playerInformationProvider.getByPlayerName(playerName)); } }
amidst
src\main\java\amidst\mojangapi\file\UnresolvedLauncherProfile.java
package amidst.mojangapi.file; import amidst.documentation.Immutable; import amidst.mojangapi.file.directory.DotMinecraftDirectory; import amidst.mojangapi.file.directory.ProfileDirectory; import amidst.mojangapi.file.directory.VersionDirectory; import amidst.mojangapi.file.json.launcherprofiles.LauncherProfileJson; import amidst.mojangapi.file.json.version.VersionJson; import amidst.parsing.FormatException; import amidst.parsing.json.JsonReader; import java.io.IOException; import java.util.List; @Immutable public class UnresolvedLauncherProfile { private final DotMinecraftDirectory dotMinecraftDirectory; private final LauncherProfileJson launcherProfileJson; public UnresolvedLauncherProfile( DotMinecraftDirectory dotMinecraftDirectory, LauncherProfileJson launcherProfileJson) { this.dotMinecraftDirectory = dotMinecraftDirectory; this.launcherProfileJson = launcherProfileJson; } public String getName() { return launcherProfileJson.getName(); } public String getIcon() { return launcherProfileJson.getIcon(); } public String getVersionId() { return launcherProfileJson.getLastVersionId(); } public LauncherProfile resolve(List<Version> versionList) throws FormatException, IOException { ProfileDirectory profileDirectory = DotMinecraftDirectory .createValidProfileDirectory(launcherProfileJson, dotMinecraftDirectory); VersionDirectory versionDirectory = DotMinecraftDirectory .createValidVersionDirectory(launcherProfileJson, versionList, dotMinecraftDirectory); VersionJson versionJson = JsonReader.readLocation(versionDirectory.getJson(), VersionJson.class); return new LauncherProfile( dotMinecraftDirectory, profileDirectory, versionDirectory, versionJson, true, launcherProfileJson.getName()); } public LauncherProfile resolveToVanilla(List<Version> versionList) throws FormatException, IOException { ProfileDirectory profileDirectory = DotMinecraftDirectory .createValidProfileDirectory(launcherProfileJson, dotMinecraftDirectory); VersionDirectory versionDirectory = DotMinecraftDirectory .createValidVersionDirectory(launcherProfileJson, versionList, dotMinecraftDirectory); VersionJson versionJson = JsonReader.readLocation(versionDirectory.getJson(), VersionJson.class); boolean isVersionListedInProfile = true; while (versionJson.getInheritsFrom() != null) { versionDirectory = DotMinecraftDirectory .createValidVersionDirectory(dotMinecraftDirectory, versionJson.getInheritsFrom()); versionJson = JsonReader.readLocation(versionDirectory.getJson(), VersionJson.class); isVersionListedInProfile = false; } return new LauncherProfile( dotMinecraftDirectory, profileDirectory, versionDirectory, versionJson, isVersionListedInProfile, launcherProfileJson.getName()); } }
amidst
src\main\java\amidst\mojangapi\file\Version.java
package amidst.mojangapi.file; import amidst.ResourceLoader; import amidst.documentation.Immutable; import amidst.mojangapi.file.json.ReleaseType; import amidst.mojangapi.file.json.versionlist.VersionListEntryJson; import amidst.mojangapi.file.json.versionlist.VersionListJson; import amidst.parsing.FormatException; import amidst.parsing.json.JsonReader; import java.io.IOException; import java.nio.file.Path; import java.util.List; import java.util.stream.Collectors; /** * Data representing a version of Minecraft. */ @Immutable public class Version { private final VersionListEntryJson versionListEntryJson; public Version(VersionListEntryJson versionListEntryJson) { this.versionListEntryJson = versionListEntryJson; } /** * Gets the version list provided by the Mojang API. * * @return a list of versions * @throws FormatException if the JSON parser fails * @throws IOException if the JSON parser fails */ public static List<Version> newRemoteVersionList() throws FormatException, IOException { return JsonReader .readLocation("https://launchermeta.mojang.com/mc/game/version_manifest.json", VersionListJson.class) .getVersions() .stream() .map(Version::new) .collect(Collectors.toList()); } /** * Gets the version list available on disk. * * @return a list of versions * @throws FormatException if the JSON parser fails * @throws IOException if the JSON parser fails */ public static List<Version> newLocalVersionList() throws FormatException, IOException { return JsonReader .readLocation(ResourceLoader.getResourceURL("/amidst/mojangapi/version_manifest.json"), VersionListJson.class) .getVersions() .stream() .map(Version::new) .collect(Collectors.toList()); } public String getId() { return versionListEntryJson.getId(); } public ReleaseType getType() { return versionListEntryJson.getType(); } public RemoteVersion fetchRemoteVersion() throws FormatException, IOException { return RemoteVersion.from(versionListEntryJson.getMetaUrl()); } /*public boolean hasServer() { return downloadService.hasServer(versionListEntryJson.getId()); } public boolean hasClient() { return downloadService.hasClient(versionListEntryJson.getId()); } public void downloadServer(String prefix) throws IOException { downloadService.downloadServer(prefix, versionListEntryJson.getId()); } public void downloadClient(String prefix) throws IOException { downloadService.downloadClient(prefix, versionListEntryJson.getId()); }*/ public Path getClientJarFile(Path prefix) { String versionId = versionListEntryJson.getId(); return prefix.resolve(versionId + "/" + versionId + ".jar"); } public Path getClientJsonFile(Path prefix) { String versionId = versionListEntryJson.getId(); return prefix.resolve(versionId + "/" + versionId + ".json"); } }
amidst
src\main\java\amidst\mojangapi\file\VersionListProvider.java
package amidst.mojangapi.file; import amidst.documentation.AmidstThread; import amidst.documentation.CalledOnlyBy; import amidst.documentation.NotThreadSafe; import amidst.logging.AmidstLogger; import amidst.threading.WorkerExecutor; import java.util.List; import java.util.concurrent.ConcurrentLinkedQueue; /** * This class is responsible to provide the version list provided by * Mojang's web API. */ @NotThreadSafe public class VersionListProvider { /** * The version list that will be populated once the async request * gets back to us. */ private volatile List<Version> remote; /** * Listeners to inform when we've downloaded the version list. */ private final ConcurrentLinkedQueue<Runnable> listeners = new ConcurrentLinkedQueue<>(); @CalledOnlyBy(AmidstThread.EDT) public VersionListProvider(WorkerExecutor workerExecutor) { workerExecutor.run(() -> { AmidstLogger.info("Starting to download remote version list."); return Version.newRemoteVersionList(); }, remote -> { AmidstLogger.info("Successfully loaded remote version list."); this.remote = remote; listeners.forEach(Runnable::run); listeners.clear(); }, e -> AmidstLogger.warn(e, "Error while downloading remote version list.")); } @CalledOnlyBy(AmidstThread.EDT) public void onDownloadRemoteFinished(Runnable listener) { if (remote == null) { listeners.offer(listener); } } /** * Gets the version list provided by Mojang's API, if it's responded. * * @return a list of versions, or {@code null} */ public List<Version> getRemote() { return remote; } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\LoggingMinecraftInterface.java
package amidst.mojangapi.minecraftinterface; import java.util.concurrent.atomic.AtomicBoolean; import amidst.documentation.ThreadSafe; import amidst.logging.AmidstLogger; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.WorldOptions; @ThreadSafe public class LoggingMinecraftInterface implements MinecraftInterface { private final MinecraftInterface inner; // This is used so we don't log the message every time a thread creates a new WorldAccessor. private final AtomicBoolean shouldLogAccessor = new AtomicBoolean(true); public LoggingMinecraftInterface(MinecraftInterface minecraftInterface) { this.inner = minecraftInterface; } public void logNextAccessor() { shouldLogAccessor.set(true); } @Override public WorldAccessor createWorldAccessor(WorldOptions worldOptions) throws MinecraftInterfaceException { WorldAccessor innerAccessor; if(shouldLogAccessor.getAndSet(false)) { AmidstLogger.info("Creating world with seed '{}' and type '{}'", worldOptions.getWorldSeed().getLong(), worldOptions.getWorldType().getName()); AmidstLogger.info("Using the following generator options: {}", worldOptions.getGeneratorOptions()); innerAccessor = inner.createWorldAccessor(worldOptions); StringBuilder sb = new StringBuilder("Supported dimensions for world: "); boolean firstDim = true; for(Dimension dimension : innerAccessor.supportedDimensions()) { if(firstDim) { firstDim = false; } else { sb.append(", "); } sb.append(dimension.getDisplayName()); } AmidstLogger.info(sb.toString()); } else { innerAccessor = inner.createWorldAccessor(worldOptions); } return innerAccessor; } @Override public RecognisedVersion getRecognisedVersion() { return inner.getRecognisedVersion(); } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\MinecraftInterface.java
package amidst.mojangapi.minecraftinterface; import java.util.Set; import java.util.function.Function; import amidst.documentation.ThreadSafe; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.WorldOptions; /** * Acts as an additional layer of abstraction for interfacing with Minecraft. * This allows for other sources of data other than direct reflection against a * loaded jar of Minecraft. * * Implementing classes need to be thread-safe! */ @ThreadSafe public interface MinecraftInterface { public WorldAccessor createWorldAccessor(WorldOptions worldOptions) throws MinecraftInterfaceException; public RecognisedVersion getRecognisedVersion(); /** * Represents a Minecraft world, allowing for querying of biome data. * * Implementing classes need to be thread-safe! */ @ThreadSafe public static interface WorldAccessor { /** * Calling this method from different threads must be valid, but implementations * may allow only one thread to progress at any given moment. To ensure true * concurrency, it is best to obtain a separate WorldAccessor object for each thread. * * @param useQuarterResolution Minecraft calculates biomes at * quarter-resolution, then noisily interpolates the biome-map up * to 1:1 resolution when needed, set useQuarterResolutionMap to * true to read from the quarter-resolution map, or false to read * values that have been interpolated up to full resolution. * * When useQuarterResolution is true, the x, y, width, and height * paramaters must all correspond to a quarter of the Minecraft * block coordinates/sizes you wish to obtain the biome data for. * * Amidst displays the quarter-resolution biome map, however full * resolution is required to determine the position and nature of * structures, as the noisy interpolation can change which biome * a structure is located in (if the structure is located on a * biome boundary). * * @param biomeDataMapper This callback is called with the biome data as an * argument; this array is only valid for the scope of the closure * and should not escape it. Any attempt to read the array once * the callback returned may return invalid data. */ public<T> T getBiomeData(Dimension dimension, int x, int y, int width, int height, boolean useQuarterResolution, Function<int[], T> biomeDataMapper) throws MinecraftInterfaceException; public Set<Dimension> supportedDimensions(); } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\MinecraftInterfaceCreationException.java
package amidst.mojangapi.minecraftinterface; import amidst.documentation.Immutable; @SuppressWarnings("serial") @Immutable public class MinecraftInterfaceCreationException extends Exception { public MinecraftInterfaceCreationException(String message, Throwable cause) { super(message, cause); } public MinecraftInterfaceCreationException(String message) { super(message); } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\MinecraftInterfaceException.java
package amidst.mojangapi.minecraftinterface; @SuppressWarnings("serial") public class MinecraftInterfaceException extends Exception { public MinecraftInterfaceException(String message, Throwable cause) { super(message, cause); } public MinecraftInterfaceException(String message) { super(message); } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\MinecraftInterfaces.java
package amidst.mojangapi.minecraftinterface; import java.io.IOException; import java.net.URLClassLoader; import java.util.Map; import java.util.function.BiFunction; import amidst.clazz.Classes; import amidst.clazz.real.JarFileParsingException; import amidst.clazz.symbolic.SymbolicClass; import amidst.clazz.symbolic.SymbolicClassGraphCreationException; import amidst.clazz.translator.ClassTranslator; import amidst.documentation.NotNull; import amidst.logging.AmidstLogger; import amidst.mojangapi.file.LauncherProfile; import amidst.mojangapi.minecraftinterface.legacy.BetaClassTranslator; import amidst.mojangapi.minecraftinterface.legacy.BetaMinecraftInterface; import amidst.mojangapi.minecraftinterface.legacy.LegacyClassTranslator; import amidst.mojangapi.minecraftinterface.legacy.LegacyMinecraftInterface; import amidst.mojangapi.minecraftinterface.legacy._1_13ClassTranslator; import amidst.mojangapi.minecraftinterface.legacy._1_13MinecraftInterface; import amidst.mojangapi.minecraftinterface.legacy._1_15ClassTranslator; import amidst.mojangapi.minecraftinterface.legacy._1_15MinecraftInterface; import amidst.mojangapi.minecraftinterface.local.DefaultClassTranslator; import amidst.mojangapi.minecraftinterface.local.LocalMinecraftInterface; public enum MinecraftInterfaces { ; @NotNull public static MinecraftInterface fromLocalProfile(LauncherProfile launcherProfile) throws MinecraftInterfaceCreationException { try { URLClassLoader classLoader = launcherProfile.newClassLoader(); RecognisedVersion recognisedVersion = RecognisedVersion.from(classLoader); Factory factory = fromVersion(recognisedVersion); Map<String, SymbolicClass> symbolicClassMap = Classes .createSymbolicClassMap(launcherProfile.getJar(), classLoader, factory.classTranslator); MinecraftInterface minecraftInterface = factory.factory.apply(symbolicClassMap, recognisedVersion); AmidstLogger.info("Minecraft load complete."); return minecraftInterface; } catch ( ClassNotFoundException | JarFileParsingException | SymbolicClassGraphCreationException | IOException e) { throw new MinecraftInterfaceCreationException("Unable to create local minecraft interface", e); } catch (UnsupportedClassVersionError e) { throw new MinecraftInterfaceCreationException("This version of Minecraft isn't compatible with your Java installation", e); } } @NotNull public static ClassTranslator getClassTranslatorFromVersion(RecognisedVersion recognisedVersion) { return fromVersion(recognisedVersion).classTranslator; } @NotNull private static Factory fromVersion(RecognisedVersion version) { if(RecognisedVersion.isOlderOrEqualTo(version, BetaMinecraftInterface.LAST_COMPATIBLE_VERSION)) { return new Factory(BetaClassTranslator.get(version), BetaMinecraftInterface::new); } else if(RecognisedVersion.isOlderOrEqualTo(version, LegacyMinecraftInterface.LAST_COMPATIBLE_VERSION)) { return new Factory(LegacyClassTranslator.get(), LegacyMinecraftInterface::new); } else if(RecognisedVersion.isOlderOrEqualTo(version, _1_13MinecraftInterface.LAST_COMPATIBLE_VERSION)) { return new Factory(_1_13ClassTranslator.get(), _1_13MinecraftInterface::new); } else if(RecognisedVersion.isOlderOrEqualTo(version, _1_15MinecraftInterface.LAST_COMPATIBLE_VERSION)) { return new Factory(_1_15ClassTranslator.get(), _1_15MinecraftInterface::new); } else { return new Factory(DefaultClassTranslator.get(), LocalMinecraftInterface::new); } } private static class Factory { public ClassTranslator classTranslator; public BiFunction<Map<String, SymbolicClass>, RecognisedVersion, MinecraftInterface> factory; public Factory(ClassTranslator classTranslator, BiFunction<Map<String, SymbolicClass>, RecognisedVersion, MinecraftInterface> factory) { this.classTranslator = classTranslator; this.factory = factory; } } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\RecognisedVersion.java
package amidst.mojangapi.minecraftinterface; import java.lang.reflect.Field; import java.net.URLClassLoader; import java.util.LinkedHashMap; import java.util.Map; import java.util.Objects; import amidst.documentation.Immutable; import amidst.documentation.NotNull; import amidst.logging.AmidstLogger; /** * Information about what each supported version is */ @Immutable public enum RecognisedVersion { // @formatter:off // Make sure UNKNOWN is the first entry, so it is always considered newer than all other versions, since an unknown version is most likely a new snapshot. // The 128 stronghold algorithm changes in version 16w06a. However, we cannot uniquely identify this version. // 1.8.4, 1.8.5, 1.8.6, 1.8.7, and 1.8.8 all have the same typeDump version ID. They are all security issue fixes. // 1.8.3 and 1.8.2 have the same typeDump version ID - probably because 1.8.2 -> 1.8.3 was a fix for a server-side bug (https://minecraft.gamepedia.com/Java_Edition_1.8.3/) // TODO: Remove these versions before V1_0? // TODO: stronghold reset on V1_9pre4? UNKNOWN, _1_17 ("1.17", "bwtdib$adifashaciwagx$baeh[Jaedadixldhvxoxiaguxkdcp"), // matches the launcher version id: 1.17-pre1 1.17-pre2 1.17-pre3 1.17-pre4 1.17-pre5 1.17-rc1 1.17-rc2 1.17 _21w19a ("21w19a", "bwcdhi$adhmarraphaccvvgs$baeb[Jadxadcxgdhcxjxdagnxfdbw"), // matches the launcher version id: 21w19a _21w17a ("21w17a", "bwbdhh$adhlarqapgacavtgs$badz[Jadvadaxedhbxhxbaglxddbv"), // matches the launcher version id: 21w17a 21w18a _21w16a ("21w16a", "bwbdhf$adhjarqapgacavtgs$badz[Jadvadaxedgzxhxbaglxddbt"), // matches the launcher version id: 21w16a _21w15a ("21w15a", "bwbdhc$adhgarqapgacavtgs$badz[Jadvadaxedgwxhxbaglxddbq"), // matches the launcher version id: 21w15a _21w14a ("21w14a", "bvvdhb$adhfarnapfacavtgs$badz[Jadvadaxedgvxhxbaglxddbp"), // matches the launcher version id: 21w14a _21w13a ("21w13a", "bvvdgz$adhdarnapfacavtgs$badz[Jadvadaxedgtxhxbaglxddbn"), // matches the launcher version id: 21w13a _21w11a ("21w11a", "bvedfy$adgcaqzapiabwvpgo$badv[Jadracwxadfsxdwxaglwzdam"), // matches the launcher version id: 21w11a _21w10a ("21w10a", "buudfn$adfraqqapfabwvpgo$badv[Jadracwxadfhxdwxaglwzdab"), // matches the launcher version id: 21w10a _21w08b ("21w08b", "busdex$adfbaqqapfabyvrgo$badw[Jadsacyxcderxfwzagmxbczl"), // matches the launcher version id: 20w08b _21w07a ("21w07a", "bubdec$adegapzaooabmvfgo$badk[Jadgacmwqddwwtwnafwwpcyq"), // matches the launcher version id: 20w07a _21w06a ("21w06a", "buaddy$adecapyaonabmvfgo$badk[Jadgacmwqddswtwnafvwpcym"), // matches the launcher version id: 20w06a _21w05b ("21w05b", "btzddu$addyapxaomabmvfgo$badk[Jadgacmwqddowtwnafuwpcyj"), // matches the launcher version id: 21w05a 21w05b _21w03a ("21w03a", "btydda$addeapwaolabmvfgo$badk[Jadgacmwqdcuwtwnafuwpcxq"), // matches the launcher version id: 21w03a _20w51a ("20w51a", "btudcs$adcwaptaohabjvcgo$badh[Jaddacjwndcmwqwkafrwmcxi"), // matches the launcher version id: 20w51a _20w49a ("20w49a", "btfdcd$adchapsaogabjvcgo$badh[Jaddacjwndbxwqwkafrwmcwt"), // matches the launcher version id: 20w49a _20w48a ("20w48a", "bszdaz$adbdapmaoaabfuwgn$badd[Jaczacfwidatwlwfaflwhcvp"), // matches the launcher version id: 20w48a _20w46a ("20w46a", "bszdaw$adbaapmaoaabfuwgn$badd[Jaczacfwidaqwlwfaflwhcvm"), // matches the launcher version id: 20w46a _20w45a ("20w45a", "bstdap$adatapmaoaabguwgn$badd[Jaczacfwjdajwmwgaflwicvf"), // matches the launcher version id: 20w45a _1_16_4 ("1.16.4", "bsacyg$acykapcanqaaxungn$bacu[Jacqabwwacyawdvxafcvzcsw"), // matches the launcher version id: 1.16.4-pre2 1.16.4-rc1 1.16.4 1.16.5-rc1 1.16.5 _1_16_4_pre1("1.16.4-pre1", "brzcyf$acyjapbanpaaxungn$bacu[Jacqabwwacxzwdvxafbvzcsv"), // matches the launcher version id: 1.16.4-pre1 _1_16_2 ("1.16.2", "brxcyd$acyhaozannaaxungn$bacs[Jacoabuwacxxwdvxaezvzcst"), // matches the launcher version id: 1.16.2-pre2 1.16.2-pre3 1.16.2-rc1 1.16.2-rc2 1.16.2 1.16-3-rc1 1.16.3 _1_16_2_pre1("1.16.2-pre1", "brvcya$acyeaoxanlaavumgn$bacq[Jacmabsvycxuwbvvaexvxcsr"), // matches the launcher version id: 1.16.2-pre1 _20w30a ("20w30a", "brucxw$acyaaoxanlaavumgn$bacq[Jacmabsvycxqwbvvaexvxcso"), // matches the launcher version id: 20w30a _20w29a ("20w29a", "brvcxx$acybaoxanlaayupgn$bact[Jacpabvwbcxrwevyaeywacsp"), // matches the launcher version id: 20w29a _20w28a ("20w28a", "buodar$adavarqaqeadrxigm$bafm[Jafiaeoyudalyxyrahrytcvj"), // matches the launcher version id: 20w28a _20w27a ("20w27a", "bqndap$adatanqamezstjgk$aabn[Jabjaapuvdajuyusadtuucvl"), // matches the launcher version id: 20w27a _1_16 ("1.16", "bqedae$adaianoamczutlgm$aabp[Jablaaruxczyvauuadsuwcva"), // matches the launcher version id: 1.16-pre8 1.16-rc1 1.16 1.16.1 _1_16_pre6 ("1.16-pre6", "bqedaf$adajanoamczutlgm$aabp[Jablaaruxczzvauuadsuwcvb"), // matches the launcher version id: 1.16-pre6 1.16-pre7 _1_16_pre5 ("1.16-pre5", "bqddae$adaiannambzttkgl$aabo[Jabkaaquwczyuzutadruvcva"), // matches the launcher version id: 1.16-pre5 _1_16_pre3 ("1.16-pre3", "bqddae$adaiannambzutlgl$aabp[Jablaaruxczyvauuadsuwcva"), // matches the launcher version id: 1.16-pre3 1.16-pre4 _1_16_pre1 ("1.16-pre1", "bqadaa$adaeanlalzzutlgl$aabp[Jablaaruxczuvauuadruwcuw"), // matches the launcher version id: 1.16-pre1 1.16-pre2 _20w22a ("20w22a", "bpnczm$aczqanfaltzqtmgl$aabk[Jabgaamutczguwuqadmuscui"), // matches the launcher version id: 20w22a _20w21a ("20w21a", "bpdczc$aczganaalozntlgl$aabh[Jabdaajaahczbmaacxuqcywutczvczuunuoadhcty"), // matches the launcher version id: 20w21a _20w20b ("20w20b", "bpdczl$aczoanaalozntmabh[Jabdaajaahczbmaacxuqczfutdaddacunuoadicug"), // matches the launcher version id: 20w20a 20w20b _20w19a ("20w19a", "bozczq$acztamwalkzktjabe[Jabaaagaaecxblwacuunczkuqdaidahukuladfcul"), // matches the launcher version id: 20w19a _20w18a ("20w18a", "bowczn$aczqamvaljzktjabe[Jabaaagaaecxbltacuunczhuqdafdaeukuladfcui"), // matches the launcher version id: 20w18a _20w17a ("20w17a", "botczj$aczmamqalezithabc[Jaayaaeaaccvblqacsulczduoczyczxuiujadccue"), // matches the launcher version id: 20w17a _20w16a ("20w16a", "bolcyw$aamiakwzdtdaax[Jaatzzzxcvbliacluhcyqukczjcziueufacv"), // matches the launcher version id: 20w16a _20w15a ("20w15a", "boicye$aamfaktzctcaaw[Jaaszyzwcvblfackugcxyujcyrcyqudueacu"), // matches the launcher version id: 20w15a _20w14a ("20w14a", "bobcxp$aameakszbtbaav[Jaarzxzvcvbkyacjufcxjuicyccybucudact"), // matches the launcher version id: 20w14a _20w13a ("20w13a", "bnwcxfalyakmzbtbaav[Jaarzxzvcvbksaciufcwzuicxscxrucudacq"), // matches the launcher version id: 20w13a 20w13b _20w12a ("20w12a", "bnkcwoalrakfyysyaas[Jaaozuzsctbkgacfuccwiufcxbcxatzuaacn"), // matches the launcher version id: 20w12a _20w11a ("20w11a", "bnccwdaljajxyxsxaar[Jaanztzrcsbjyaceubcvxuecwqcwptytzacm"), // matches the launcher version id: 20w11a _20w10a ("20w10a", "bnccvyalkajyyxsxaar[Jaanztzrcsbjzaceubcvsuecwlcwktytzacn"), // matches the launcher version id: 20w10a _20w09a ("20w09a", "bmbcuuakkaiyxyrzzs[Jzoyuyscsbiyabftdcuotgcvhcvgtatbabo"), // matches the launcher version id: 20w09a _20w08a ("20w08a", "blycuoakhaivxxryzr[Jznytyrcrbivabetccuitfcvbcvasztaabn"), // matches the launcher version id: 20w07a 20w08a _20w06a ("20w06a", "bkjcsyakaaioxvrwzp[Jzlyrypcrbhgabctacsstdctlctksxsyabk"), // matches the launcher version id: 20w06a _1_15_2 ("1.15.2", "bkacrpajsaikxurwzo[Jzkyqyocrbgxabbtacrjtdcsccsbsxsyabj"), // matches the launcher version id: 1.15.2-pre1 1.15.2-pre2 1.15.2 _1_15_1 ("1.15.1", "bjxcrmajpaiixurwzo[Jzkyqyocrbguabbtacrgtdcrzcrysxsyabj"), // matches the launcher version id: 1.15-pre3 1.15-pre4 1.15-pre5 1.15-pre6 1.15-pre7 1.15 1.15.1-pre1 1.15.1 _1_15_pre2 ("1.15-pre2", "bjxcrlajpaiixurwzo[Jzkyqyocrbguabbtacrftdcrycrxsxsyabj"), // matches the launcher version id: 1.15-pre2 _1_15_pre1 ("1.15-pre1", "bjxcrkajpaiixurwzo[Jzkyqyocrbguabbtacretdcrxcrwsxsyabj"), // matches the launcher version id: 1.15-pre1 _19w46b ("19w46b", "bjxcrjajpaiixurwzo[Jzkyqyocrbguabbtacrdtdcrwcrvsxsyabj"), // matches the launcher version id: 19w46b _19w45b ("19w45b", "bjtcreajlaiexrrtzl[Jzhynylcobgqaaysxcqytacrrcrqsusvabg"), // matches the launcher version id: 19w45b 19w44a _19w42a ("19w42a", "bjtcrdajlaiexrrtzl[Jzhynylcobgqaaysxcqxtacrqcrpsusvabg"), // matches the launcher version id: 19w42a _19w41a ("19w41a", "bjscrcajkaidxrrtzl[Jzhynylcobgpaaysxcqwtacrpcrosusvabg"), // matches the launcher version id: 19w41a _19w39a ("19w39a", "bjocqtajfahyxorrzi[Jzeykyicobglaavsvcqnsycrgcrfssstabd"), // matches the launcher version id: 19w39a 19w40a _19w38b ("19w38b", "bjgcqlaiyahrxhrkzb[Jyxydybckbgdaaosocqfsrcqycqxslsmaaw"), // matches the launcher version id: 19w38b _19w36a ("19w36a", "bjbcqfaisahlxareyu[Jyqxwxucebfxaahsislcqssfsgaaq"), // matches the launcher version id: 19w36a 19w37a _19w35a ("19w35a", "bizcpyaiqahjxareyu[Jyqxwxucebfvaahsislcqlsfsgaaq"), // matches the launcher version id: 19w35a _19w34a ("19w34a", "bixcpwaiqahjxareyu[Jyqxwxucebfuaahsislcqjsfsgaaq"), // matches the launcher version id: 19w34a _1_14_4 ("1.14.4", "bhvcoqahqagjwbqfxv[Jxrwxwvcebeszirjrmcpdrgrhzr"), // matches the launcher version id: 1.14.4-pre4 1.14.4-pre5 1.14.4-pre6 1.14.4-pre7 1.14.4 _1_14_4_pre3("1.14.4-pre3", "bhucopahpagiwaqexu[Jxqwwwuceberzhrirlcpcrfrgzq"), // matches the launcher version id: 1.14.4-pre3 _1_14_4_pre2("1.14.4-pre2", "bhtcooahoaghvzqdxt[Jxpwvwtcebeqzgrhrkcpbrerfzp"), // matches the launcher version id: 1.14.4-pre2 _1_14_4_pre1("1.14.4-pre1", "bhscolahoaghvzqdxt[Jxpwvwtcebepzgrhrkcozrerfzp"), // matches the launcher version id: 1.14.4-pre1 _1_14_3 ("1.14.3", "bhqcojahnaggvzqdxt[Jxpwvwtcebenzgrhrkcoxrerfzo"), // matches the launcher version id: 1.14.3-pre3 1.14.3-pre4 1.14.3 _1_14_3_pre2("1.14.3-pre2", "bhpcoiahnaggvzqdxt[Jxpwvwtcebenzgrhrkcowrerfzo"), // matches the launcher version id: 1.14.3-pre2 _1_14_3_pre1("1.14.3-pre1", "bhncogahlagevxqcxr[Jxnwtwrcebelzergrjcourdrezm"), // matches the launcher version id: 1.14.3-pre1 _1_14_2 ("1.14.2", "bhmcofahkagdvxqcxq[Jxmwtwrcebekzdrgrjcotrdrezl"), // matches the launcher version id: 1.14.1-pre1 1.14.1-pre2 1.14.1 1.14.2-pre1 1.14.2-pre2 1.14.2-pre3 1.14.2-pre4 1.14.2 _1_14 ("1.14", "bhlcodahhagavxqcxq[Jxmwtwrcebejzdrgrjcorrdrezl"), // matches the launcher version id: 1.14-pre5 1.14 _1_14_pre4 ("1.14-pre4", "bhjcobahgafzvwqcxp[Jxlwswqcebeizcrgrjcoprdrezk"), // matches the launcher version id: 1.14-pre4 _1_14_pre3 ("1.14-pre3", "bhhcnzahfafyvwqcxp[Jxlwswqcebegzcrgrjcomrdrezk"), // matches the launcher version id: 1.14-pre3 _1_14_pre1 ("1.14-pre1", "bhecnwahfafyvwqcxp[Jxlwswqcebedzcrgrjcojrdrezk"), // matches the launcher version id: 1.14-pre1 1.14-pre2 _19w14b ("19w14b", "bhbcntahcafvvwqcxp[Jxlwswqcebeazcrgrjcogrdrezk"), // matches the launcher version id: 19w14b _19w13b ("19w13b", "bgzcnoahbafuvvqbxo[Jxkwrwpcebdyzbrfricobrcrdzj"), // matches the launcher version id: 19w13b _19w12b ("19w12b", "bgjcmwahaaftvuqaxn[Jxjwqwocebdizarerhcnjrbrczi"), // matches the launcher version id: 19w12b _19w11b ("19w11b", "bgbcmoagyafrvtpzxm[Jxiwpwncdbdayzrdrgcnbrarbzh"), // matches the launcher version id: 19w11b _19w09a ("19w09a", "bdjcjuagoafivmpsxf[Jxbwiwgcbbaiysqwqzckhqtquza"), // matches the launcher version id: 19w08b 19w09a _19w07a ("19w07a", "bdfcjpagoafivmprxe[Jxawiwgcbbaeyrqvqzckcqsqtyz"), // matches the launcher version id: 19w07a _19w06a ("19w06a", "bcycjiaglaffvjpnxc[Jwywfwdcbazxypqsqwcjvqpqqyx"), // matches the launcher version id: 19w06a _19w05a ("19w05a", "bcvcjfaghafbvkpnwy[Jwuwgwecbaztylqsqwcjsqpqqyt"), // matches the launcher version id: 19w05a _19w04b ("19w04b", "bcqcjaageaeyvkpnwy[Jwuwgwecbazoylqsqwcjnqpqqyt"), // matches the launcher version id: 19w04b _19w03c ("19w03c", "ageaexvkpmwy[Jwuwgwecbaznylqrqvcjtqoqpyt"), // matches the launcher version id: 19w03c _19w02a ("19w02a", "aggaezvmpoxa[Jwwwiwgcbaznynqtqxcjpqqqryv"), // matches the launcher version id: 19w02a _18w50a ("18w50a", "afyaeqvfpmwt[Jwpwbvzcbayxygqrqvcjaqoqpyo"), // matches the launcher version id: 18w50a _18w49a ("18w49a", "afnaehuzpjwn[Jwjvvvtcbaybyaqoqschwqlqmyi"), // matches the launcher version id: 18w49a _18w48b ("18w48b", "aflaeguypiwm[Jwivuvscbaxzxzqnqrchnqkqlyh"), // matches the launcher version id: 18w48b _18w47b ("18w47b", "afiaeduwpiwk[Jwgvsvqcbaxvxxqnqscgwqkqlye"), // matches the launcher version id: 18w47b _18w46a ("18w46a", "affaeauuphwi[Jwevqvocaaxmxvqmqrcgqqjqkyc"), // matches the launcher version id: 18w46a _18w45a ("18w45a", "afbadwuspgwg[Jwcvovmcaaxhxtqlqqcfqqiqjya"), // matches the launcher version id: 18w45a _18w44a ("18w44a", "aeyadtuppewd[Jvzvlvjbyaxcxqqjqncfkqgqhxx"), // matches the launcher version id: 18w44a _18w43c ("18w43c", "aekyfuopdwc[Jvyvkvibyawjxpqiqmcecqfqgxw"), // matches the launcher version id: 18w43c _18w43a ("18w43a", "aekyfuopdwc[Jvyvkvibyawjxpqiqmcebqfqg"), // matches the launcher version id: 18w43a _1_13_2 ("1.13.2", "aduxrubomvp[Jvluxuvbvavlxbprpvcctpopp"), // matches the launcher version id: 1.13.2-pre1 1.13.2-pre2 1.13.2 _1_13_1 ("1.13.1", "aduxrubomvp[Jvluxuvbvavkxbprpvccspopp"), // matches the launcher version id: 1.13.1-pre1 1.13.1-pre2 1.13.1 _18w33a ("18w33a", "adtxquaolvo[Jvkuwuubvavjxapqpuccrpnpo"), // matches the launcher version id: 18w33a _18w32a ("18w32a", "adsxquaolvo[Jvkuwuubvavixapqpuccqpnpo"), // matches the launcher version id: 18w32a _18w31a ("18w31a", "aduxsuconvq[Jvmuyuwbvavkxcpspwccqpppq"), // matches the launcher version id: 18w31a _18w30b ("18w30b", "adtxruaom[Ltc;vo[J[[Jvkuwuubvavjxaprpvcclpopp"), // matches the launcher version id: 18w30b _1_13 ("1.13", "adrxquaom[Ltc;vo[J[[Jvkuwuubvavhxaprpvccipopp"), // matches the launcher version id: 1.13 _1_13_pre10("1.13-pre10", "adpxquaom[Ltc;vo[J[[Jvkuwuubvavfxaprpvccgpopp"), // matches the launcher version id: 1.13-pre10 _1_13_pre8 ("1.13-pre8", "adoxquaom[Ltc;vo[J[[Jvkuwuubvavexaprpvccgpopp"), // matches the launcher version id: 1.13-pre8 1.13-pre9 _1_13_pre7 ("1.13-pre7", "adixquaom[Ltc;vo[J[[Jvkuwuubvauyxaprpvcbxpopp"), // matches the launcher version id: 1.13-pre7 _1_13_pre6 ("1.13-pre6", "adexntxoj[Lsz;vl[J[[Jvhuturbvautwxpopscbtplpm"), // matches the launcher version id: 1.13-pre6 _1_13_pre5 ("1.13-pre5", "adbxltvoh[Lsx;vj[J[[Jvfurupbvauqwvpmpqcbqpjpk"), // matches the launcher version id: 1.13-pre5 _1_13_pre4 ("1.13-pre4", "ahyxntvohya[Lsx;vj[J[[Jvfurupbvazowvpmpqcgnpjpk"), // matches the launcher version id: 1.13-pre4 _1_13_pre3 ("1.13-pre3", "ahqxftnnzxs[Lsp;vb[J[[Juxujuhbvazgwnpepicgepbpc"), // matches the launcher version id: 1.13-pre3 _1_13_pre2 ("1.13-pre2", "ahixdtlnxxp[Lsn;uz[J[[Juvuhufbvayywlpcpgcfvozpa"), // matches the launcher version id: 1.13-pre2 _1_13_pre1 ("1.13-pre1", "ahhxctknwxo[Lsm;uy[J[[Juuuguebuayxwkpbpfcfsoyoz"), // matches the launcher version id: 1.13-pre1 _18w22c ("18w22c", "ahfxctknwxo[Lsm;uy[J[[Juuuguebuayvwkpbpfcfqoyoz"), // matches the launcher version id: 18w22c _18w21b ("18w21b", "ahdxbtjnvxn[Lsl;ux[J[[Jutufudbtaytwjpapecfooxoy"), // matches the launcher version id: 18w21b _18w20c ("18w20c", "ahcxatinuxm[Lsk;uw[J[[Jusueucbtayswiozpdcexowox"), // matches the launcher version id: 18w20c _18w19b ("18w19b", "agwwzthntxm[Lsj;uv[J[[Jurudubbsaymwhoypccerovow"), // matches the launcher version id: 18w19b _18w19a ("18w19a", "afcwytgntxl[Lsi;uu[J[[Juqucuabsawswgoxpbccxouov"), // matches the launcher version id: 18w19a _18w16a ("18w16a", "aavwutfnsxf[Lsh;ut[J[[Jupubtzbsaskweowpabyhotou"), // matches the launcher version id: 18w16a _18w15a ("18w15a", "aauwttensxe[Lsh;us[J[[Juouatybsasjwdowpabxrotou"), // matches the launcher version id: 18w15a _18w14b ("18w14b", "aauwttensxe[Lsh;us[J[[Juouatybsasawdowpabwyotou"), // matches the launcher version id: 18w14b _18w11a ("18w11a", "aaqwqtbnpxb[Lse;up[J[[Jultxtvbparwwaotoxbwroqor"), // matches the launcher version id: 18w11a _18w10d ("18w10d", "aaqwqtbnpxb[Lse;up[J[[Jultxtvbparvwaotoxbwmoqor"), // matches the launcher version id: 18w10d _18w09a ("18w09a", "aakwlswnkww[Lrz;uk[J[[Jugtstqbparovvooosbvkolom"), // matches the launcher version id: 18w09a _18w08b ("18w08b", "aaiwjsuniwu[Lrx;ui[J[[Juetqtobparmvtomoqbvdojok"), // matches the launcher version id: 18w08b _18w08a ("18w08a", "aaiwjsuniwu[Lrx;ui[J[[Juetqtobpargvtomoqbuxojok"), // matches the launcher version id: 18w08a _18w07c ("18w07c", "aahwistniwt[Lrx;uh[J[[Judtptnbparfvsomoqbuhojok"), // matches the launcher version id: 18w07c _18w06a ("18w06a", "aalwlswniwx[Lsa;uk[J[[Jugtstqbpargvvonorbuaokol"), // matches the launcher version id: 18w06a _18w05a ("18w05a", "znvssdnfwe[Lrs;tr[J[[Jtnszsxbnaqgvcoiombliofog"), // matches the launcher version id: 18w05a _18w03b ("18w03b", "zjvorznfwa[Lro;tn[J[[Jtjsvstbnaqcuyoibleofog"), // matches the launcher version id: 18w03b 18w02a _18w01a ("18w01a", "zhvnrynevz[Lrn;tm[J[[Jtisussbnapsuxohbkyoeof"), // matches the launcher version id: 18w01a _17w50a ("17w50a", "ykutremkvf[Lqt;ss[J[[Jsosarybnaovud"), // matches the launcher version id: 17w50a _17w49b ("17w49b", "yiusrdmjve[Lqs;sr[J[[Jsnrzrxbnaoquc"), // matches the launcher version id: 17w49b _17w48a ("17w48a", "xvugqxmdus[Lqm;sl[J[[Jshrtrrblaoe"), // matches the launcher version id: 17w48a _17w47b ("17w47b", "xuufqwmcur[Lql;sk[J[[Jsgrsrqbl"), // matches the launcher version id: 17w47b _17w46a ("17w46a", "xiugqslyut[Lqh;sg[J[[Jscrormbl"), // matches the launcher version id: 17w46a _17w45b ("17w45b", "wvttqflmug[Lpu;rt[J[[Jrprbqzbl"), // matches the launcher version id: 17w45b _17w43b ("17w43b", "vosnozmtta[Loo;qn[J[[Jqjpvpt"), // matches the launcher version id: 17w43b _1_12_2 ("1.12.2", "ulrlozmtry[Loo;pl[J[[Jph"), // matches the launcher version id: 1.12.2 1.12.1 _1_12 ("1.12", "ujrjoxmsrw[Lom;pj[J[[Jpf"), // matches the launcher version id: 1.12 _1_12_pre2 ("1.12-pre2", "uhrhovmqru[Lok;ph[J[[Jpd"), // matches the launcher version id: 1.12-pre2 _1_12_pre1 ("1.12-pre1", "ugrgoumprt[Loj;pg[J[[Jpc"), // matches the launcher version id: 1.12-pre1 _17w18b ("17w18b", "tyqyommirl[Lob;oy[J[[Jou"), // matches the launcher version id: 17w18b _17w17b ("17w17b", "tpqroemare[Lnt;oq[J[[Jom"), // matches the launcher version id: 17w17b _17w16b ("17w16b", "tnqpoclyrc[Lnr;oo[J[[Jok"), // matches the launcher version id: 17w16b _17w15a ("17w15a", "tlqnoalwra[Lnp;om[J[[Joi"), // matches the launcher version id: 17w15a _17w14a ("17w14a", "tkqmoalwqz[Lnp;om[J[[Joi"), // matches the launcher version id: 17w14a _17w13b ("17w13b", "tgqinwlsqv[Lnl;oi[J[[Joe"), // matches the launcher version id: 17w13b _1_11_2 ("1.11.2", "rsoumhkfph[Llw;mt[J[[Jmp"), // matches the launcher version id: 1.11.2 1.11.1 _1_11 ("1.11", "rroumhkfph[Llw;mt[J[[Jmp"), // matches the launcher version id: 1.11 1.11-pre1 _16w44a ("16w44a", "rqotmgkfpg[Llv;ms[J[[Jmo"), // matches the launcher version id: 16w44a _16w43a ("16w43a", "rpotmgkfpg[Llv;ms[J[[Jmo"), // matches the launcher version id: 16w43a 16w42a 16w41a 16w40a 16w39c _16w38a ("16w38a", "rlosmfkepf[Llu;mr[J[[Jmn"), // matches the launcher version id: 16w38a _16w36a ("16w36a", "rkosmfkepf[Llu;mr[J[[Jmn"), // matches the launcher version id: 16w36a _16w35a ("16w35a", "rjosmfkepf[Llu;mr[J[[Jmn"), // matches the launcher version id: 16w35a 16w33a 16w32b _1_10_2 ("1.10.2", "rboqmdkcpd[Lls;mp[J[[Jml"), // matches the launcher version id: 1.10.2 1.10.1 1.10 _16w21b ("16w21b", "qzopmckbpc[Llr;mo[J[[Jmk"), // matches the launcher version id: 16w21b _16w20a ("16w20a", "qxopmckbpc[Llr;mo[J[[Jmk"), // matches the launcher version id: 16w20a _1_9_4 ("1.9.4", "qwoombkapb[Llq;mn[J[[Jmj"), // matches the launcher version id: 1.9.4 1.9.3 _1_9_2 ("1.9.2", "qwoomajzpb[Llp;mm[J[[Jmi"), // matches the launcher version id: 1.9.2 1.9.1 1.9 _1_9_pre2 ("1.9-pre2", "qvoomajzpb[Llp;mm[J[[Jmi"), // matches the launcher version id: 1.9-pre2 1.9-pre1 16w07b 16w06a 16w05b 16w04a 16w03a 16w02a _15w51b ("15w51b", "quonmajzpa[Llp;mm[J[[Jmi"), // matches the launcher version id: 15w51b _15w50a ("15w50a", "qtonmajzpa[Llp;mm[J[[Jmi"), // matches the launcher version id: 15w50a 15w49b 15w47c _15w46a ("15w46a", "qsonmajzpa[Llp;mm[J[[Jmi"), // matches the launcher version id: 15w46a _15w45a ("15w45a", "qtoombkapb[Llq;mn[J[[Jmj"), // matches the launcher version id: 15w45a 15w44b _15w43c ("15w43c", "qsoombkapb[Llq;mn[J[[Jmj"), // matches the launcher version id: 15w43c _15w42a ("15w42a", "qnojlzjzow[Llp;ml[J[[Jmh"), // matches the launcher version id: 15w42a _15w41b ("15w41b", "qmoilyjyov[Llo;mk[J[[Jmg"), // matches the launcher version id: 15w41b _15w40b ("15w40b", "qhoelujuor[Llk;mg[J[[Jmc"), // matches the launcher version id: 15w40b 15w39c 15w38b 15w37a _15w36d ("15w36d", "qgodltjuoq[Lll;mf[J[[Jmb"), // matches the launcher version id: 15w36d _15w35e ("15w35e", "qeoclsjuop[Llk;me[J[[Jma"), // matches the launcher version id: 15w35e _15w34d ("15w34d", "qdoblsjuoo[Lll;me[J[[Jma"), // matches the launcher version id: 15w34d _15w33c ("15w33c", "qanzlrjtom[Llk;md[J[[Jlz"), // matches the launcher version id: _15w32c ("15w32c", "pmnvlnjt[Llg;lz[J[[Jlv"), // matches the launcher version id: _15w31c ("15w31c", "oxnvlnjt[Llg;lz[J[[Jlv"), // matches the launcher version id: _1_8_9 ("1.8.9", "orntlljs[Lle;lx[J[[Jlt"), // matches the launcher version id: 1.8.9 1.8.8 1.8.7 1.8.6 1.8.5 1.8.4 _1_8_3 ("1.8.3", "osnulmjt[Llf;ly[J[[Jlu"), // matches the launcher version id: 1.8.3 1.8.2 _1_8_1 ("1.8.1", "wduyrdnq[Lqu;sp[J[[Jsa"), // matches the launcher version id: 1.8.1 _1_8 ("1.8", "wbuwrcnp[Lqt;sn[J[[Jry"), // matches the launcher version id: 1.8 _14w21b ("14w21b", "tjseoylw[Loq;qd[J[[Jpo"), // matches the launcher version id: _14w17a ("14w17a", "sxrtonlk[Loe;ps[J[[Jpd"), // matches the launcher version id: 14w17a _1_7_10 ("1.7.10", "riqinckb[Lmt;oi[J[[Jns"), // matches the launcher version id: 1.7.10 _1_7_9 ("1.7.9", "rhqhnbkb[Lms;oh[J[[Jnr"), // matches the launcher version id: 1.7.9 1.7.8 1.7.7 1.7.6 _14w02a ("14w02a", "qrponkki[Lnb;lv[J[[J"), // matches the launcher version id: _1_7_5 ("1.7.5", "qfpfnbjy[Lms;lm[J[[J"), // matches the launcher version id: 1.7.5 _1_7_4 ("1.7.4", "pzozmvjs[Lmm;lg[J[[J"), // matches the launcher version id: 1.7.4 1.7.3 _1_7_2 ("1.7.2", "pvovmsjp[Lmj;ld[J[[J"), // matches the launcher version id: 1.7.2 _13w39a ("13w39a", "npmp[Lkn;jh[J[J[J[J[J[[J"), // matches the launcher version id: _13w37b ("13w37b", "ntmt[Lkm;jg[J[J[J[J[J[[J"), // matches the launcher version id: _13w37a ("13w37a", "nsms[Lkl;jf[J[J[J[J[J[[J"), // matches the launcher version id: _13w36b ("13w36b", "nkmk[Lkd;hw[J[J[J[J[J[[J"), // matches the launcher version id: _13w36a ("13w36a", "nkmk[Lkd;hx[J[J[J[J[J[[J"), // matches the launcher version id: _1_6_4 ("1.6.4", "mvlv[Ljs;hn[J[J[J[J[J[[J"), // matches the launcher version id: 1.6.4 _1_6_2 ("1.6.2", "mulu[Ljr;hm[J[J[J[J[J[[J"), // matches the launcher version id: 1.6.2 _1_6_1 ("1.6.1", "msls[Ljp;hk[J[J[J[J[J[[J"), // matches the launcher version id: 1.6.1 _1_5_2 ("1.5.2", "[Bbdzbdrbawemabdsbfybdvngngbeuawfbgeawvawvaxrawbbfqausbjgaycawwaraavybkcavwbjubkila"), // matches the launcher version id: 1.5.2 _1_5_1 ("1.5.1", "[Bbeabdsbawemabdtbfzbdwngngbevawfbgfawvawvaxrawbbfrausbjhaycawwaraavybkdavwbjvbkila"), // matches the launcher version id: 1.5.1 _1_4_7 ("1.4.7", "[Baywayoaaszleaypbavaysmdazratabbaatqatqaulaswbanarnbdzauwatraohastbevasrbenbezbdmbdjkh"), // matches the launcher version id: 1.4.7 1.4.6 _1_4_5 ("1.4.5", "[Bayoaygaasrleayhbakaykmdazfassbapatjatjaueasobacarfbdoaupatkanzaslbekasjbecbenbdbbcykh"), // matches the launcher version id: 1.4.5 1.4.4 _1_4_2 ("1.4.2", "[Baxgawyaarjkpawzayyaxclnaxxarkazcasbasbaswargaytaqabcbathascamuardbcxarbbcpbdabbobbljy"), // matches the launcher version id: 1.4.2 _1_3_2 ("1.3.2", "[Batkatcaaofjbatdavbatgjwaubaogavfaovaovapnaocauwamxaxvapyaowajqanzayqanxayjaytaxkaxhik"), // matches the launcher version id: 1.3.2 _1_3_1 ("1.3.1", "[Batjatbaaoejaatcavaatfjvauaaofaveaouaouapmaobauvamwaxuapxaovajpanyaypanwayiaysaxjaxgij"), // matches the launcher version id: 1.3.1 _1_3pre ("1.3pre", "acl"), // matches the launcher version id: _12w27a ("12w27a", "acs"), // matches the launcher version id: _12w25a ("12w25a", "acg"), // matches the launcher version id: _12w24a ("12w24a", "aca"), // matches the launcher version id: _12w22a ("12w22a", "ace"), // matches the launcher version id: _12w21b ("12w21b", "aby"), // matches the launcher version id: _12w21a ("12w21a", "abm"), // matches the launcher version id: _12w19a ("12w19a", "aau"), // matches the launcher version id: _1_2_5 ("1.2.5", "[Bkivmaftxdlvqacqcwfcaawnlnlvpjclrckqdaiyxgplhusdakagi[J[Jalfqabv"), // matches the launcher version id: 1.2.5 1.2.4 _1_2_3 ("1.2.3", "[Bkfviafowzlvmaclcueyaarninivlizlocipzaisxcphhrrzajugf[J[Jakzpwbt"), // matches the launcher version id: 1.2.3 1.2.2 1.2.1 _12w08a ("12w08a", "wj"), // matches the launcher version id: _12w07b ("12w07b", "wd"), // matches the launcher version id: _12w06a ("12w06a", "wb"), // matches the launcher version id: _12w05a ("12w05a", "vy"), // matches the launcher version id: _12w04a ("12w04a", "vu"), // matches the launcher version id: _12w03a ("12w03a", "vj"), // matches the launcher version id: _1_1 ("1.1", "[Bjsudadrvqluhaarcqevyzmqmqugiokzcepgagqvsonhhrgahqfy[J[Jaitpdbo"), // matches the launcher version id: 1.1 _12w01a ("12w01a", "[Bjqtyadmvllucaancpetyumomoubimkxcdpcaglvnokhfrbahkfw[J[Jainozbn"), // matches the launcher version id: 12w01a _1_0 ("1.0", "[Baesmmaijryafvdinqfdrzhabeabexexwadtnglkqdfagvkiahmhsadk[J[Jtkgkyu"), // matches the launcher version id: 1.0 _b1_9_pre6 ("b1.9-pre6", "uk"), // matches the launcher version id: _b1_9_pre5 ("b1.9-pre5", "ug"), // matches the launcher version id: _b1_9_pre4 ("b1.9-pre4", "uh"), // matches the launcher version id: _b1_9_pre3 ("b1.9-pre3", "to"), // matches the launcher version id: _b1_9_pre2 ("b1.9-pre2", "sv"), // matches the launcher version id: _b1_9_pre1 ("b1.9-pre1", "[Biorvaaitdiryxqcfebwdlcrxhljqbtnkaddtfmvgjpgaeafd[J[Jafanhbe"), // matches the launcher version id: b1.9-pre1 _b1_8_1 ("b1.8.1", "[Bhwqpyrrviqswdbzdqurkhqrgviwbomnabjrxmafvoeacfer[J[Jaddmkbb"), // matches the launcher version id: b1.8.1 b1.8 _b1_7_3 ("b1.7.3", "[Bobcxpyfdndclsdngrjisjdamkpxczvuuqfhvfkvyovyik[J[Jxivscg"), // matches the launcher version id: b1.7.3 b1.7.2 b1.7 _b1_6_6 ("b1.6.6", "[Bnxcvpufbmdalodlgpjfsecymgptcxvmukffuxkryfvqih[J[Jwzvkce"), // matches the launcher version id: b1.6.6 b1.6.5 b1.6.4 b1.6.3 b1.6.2 b1.6.1 b1.6 _b1_5_01 ("b1.5_01", "nfcpozetmcukwdfggiprfcslooycruntlextyjzxeurhv[J[Jvyulbz"), // matches the launcher version id: b1.5_01 b1.5 _b1_4_01 ("b1.4_01", "lncdmxebichjmcsfkhooxcfkcmwcerqqvefrkisujsbgw[J[Jtervbo"), // matches the launcher version id: b1.4_01 _b1_4 ("b1.4", "lncdmxebichjmcsfkhooxcfkcmwcerpqvefrkisujsagw[J[Jterubo"), // matches the launcher version id: b1.4 _b1_3_01 ("b1.3_01", "kybymidthccizcnfbhfoicbjpmhbzqfdxquigtmrhgn[J[Jrbbk"), // matches the launcher version id: b1.3_01 _b1_3b ("b1.3b", "kybymidthccizcnfbhfoicbjpmhbzqgdxqvigtnrign[J[Jrcbk"), // matches the launcher version id: b1.3b _b1_2_02 ("b1.2_02", "kbbvlmdnhbzcjesgsnhbyiwllbwpedrprhqsgqega[J[Jpybj"), // matches the launcher version id: b1.2_02 b1.2_01 b1.2 _b1_1_02 ("b1.1_02", "jjboksddfbsccehgemjbrifkrbpobdhonhbqvoyfo[J[Joubc"), // matches the launcher version id: b1.1_02 b1.1_01 _b1_0_2 ("b1.0.2", "jibokrddfbscceggdmibriekqbpoadhomhaquoxfn[J[Jotbc"), // matches the launcher version id: b1.0.2 b1.0_01 b1.0 _a1_2_6 ("a1.2.6", "ivbmkccyfbqbzeafulsbphukbbnnldcnxgqqgoiff[J[Joeba"), // matches the launcher version id: a1.2.6 _a1_2_5 ("a1.2.5", "iubmkbcxfbqbydzftlrbphtkabnnkdbnwgpqfohfe[J[Jodba"), // matches the launcher version id: a1.2.5 a1.2.4_01 _a1_2_3_04 ("a1.2.3_04", "iubmkbcxfbqbydzftlqbphtkabnnjdbnvgpqeogfe[J[Jocba"), // matches the launcher version id: a1.2.3_04 a1.2.3_02 a1.2.3_01 a1.2.3 _a1_2_2b ("a1.2.2b", "isbmjycwfbqbydyfrlnbphrjxbnngdansgnqbodfd[J[Jnzba"), // matches the launcher version id: a1.2.2b a1.2.2a _a1_2_1_01 ("a1.2.1_01", "imbkjrcudbobwdufmlgbnhmjqblmzcynlgiptnv[J[Jnray"), // matches the launcher version id: a1.2.1_01 a1.2.1 a1.2.0_02 a1.2.0_01 a1.2.0 _a1_1_2_01 ("a1.1.2_01", "hqbeircnebibqdleykdbhgriqbflucrmffrofmp[Jmlat"), // matches the launcher version id: a1.1.2_01 a1.1.2 _a1_1_0 ("a1.1.0", "hqbeircnebibqdleykdbhgriqbflucrmffroemo[Jmlat"), // matches the launcher version id: a1.1.0 _a1_0_17_04("a1.0.17_04", "hpbdiqcmebhbpdkexkbbggqipbeltcqmdfqobmm[Jmjar"), // matches the launcher version id: a1.0.17_04 a1.0.17_02 _a1_0_16 ("a1.0.16", "hgazihcjebebmdferjtbdgiigbblkcnlvfinrmd[Jmbap"), // matches the launcher version id: a1.0.16 _a1_0_15 ("a1.0.15", "hfazigcjebebmdferjsbdgiifbbljcnlufinqmc[Jmaap"), // matches the launcher version id: a1.0.15 _a1_0_14 ("a1.0.14", "hcazidcjebebmdfeqjpbdghicbblfcnlpfhnmly[Jlwap"), // matches the launcher version id: a1.0.14 _a1_0_11 ("a1.0.11", "haaziacjebebmddenjlbdgfhzbbkzcnljfenels[Jlqap"); // matches the launcher version id: a1.0.11 // @formatter:on @NotNull public static RecognisedVersion from(URLClassLoader classLoader) throws ClassNotFoundException { return from(generateMagicString(classLoader)); } @NotNull public static String generateMagicString(URLClassLoader classLoader) throws ClassNotFoundException { return generateMagicString(getMainClassFields(classLoader)); } @NotNull private static Field[] getMainClassFields(URLClassLoader classLoader) throws ClassNotFoundException { try { if (classLoader.findResource(CLIENT_CLASS_RESOURCE) != null) { return classLoader.loadClass(CLIENT_CLASS).getDeclaredFields(); } else if (classLoader.findResource(SERVER_CLASS_RESOURCE) != null) { return classLoader.loadClass(SERVER_CLASS).getDeclaredFields(); } else { throw new ClassNotFoundException("unable to find the main class in the given jar file"); } } catch (NoClassDefFoundError e) { throw new ClassNotFoundException("error while loading main class; are some libraries missing?", e); } } @NotNull public static RecognisedVersion from(Field[] fields) { return from(generateMagicString(fields)); } @NotNull public static String generateMagicString(Field[] fields) { String result = ""; for (Field field : fields) { String typeString = field.getType().toString(); if (typeString.startsWith("class ") && !typeString.contains(".")) { result += typeString.substring(6); } } return result; } @NotNull public static RecognisedVersion from(String magicString) { for (RecognisedVersion recognisedVersion : RecognisedVersion.values()) { if (magicString.equals(recognisedVersion.magicString)) { logFound(recognisedVersion); return recognisedVersion; } } AmidstLogger.info("Unable to recognise Minecraft Version with the magic string \"" + magicString + "\"."); return RecognisedVersion.UNKNOWN; } @NotNull public static RecognisedVersion fromName(String name) { for (RecognisedVersion recognisedVersion : RecognisedVersion.values()) { if (name.equals(recognisedVersion.name)) { logFound(recognisedVersion); return recognisedVersion; } } AmidstLogger.info("Unable to recognise Minecraft Version with the name \"" + name + "\"."); return RecognisedVersion.UNKNOWN; } private static void logFound(RecognisedVersion recognisedVersion) { AmidstLogger.info( "Recognised Minecraft Version " + recognisedVersion.name + " with the magic string \"" + recognisedVersion.magicString + "\"."); } public static boolean isNewerOrEqualTo(RecognisedVersion version1, RecognisedVersion version2) { return compareNewerIsLower(version1, version2) <= 0; } public static boolean isNewer(RecognisedVersion version1, RecognisedVersion version2) { return compareNewerIsLower(version1, version2) < 0; } public static boolean isOlderOrEqualTo(RecognisedVersion version1, RecognisedVersion version2) { return compareNewerIsLower(version1, version2) >= 0; } public static boolean isOlder(RecognisedVersion version1, RecognisedVersion version2) { return compareNewerIsLower(version1, version2) > 0; } public static int compareNewerIsGreater(RecognisedVersion version1, RecognisedVersion version2) { return compareNewerIsLower(version2, version1); } public static int compareNewerIsLower(RecognisedVersion version1, RecognisedVersion version2) { Objects.requireNonNull(version1); Objects.requireNonNull(version2); return version1.ordinal() - version2.ordinal(); } public static Map<String, RecognisedVersion> generateNameToRecognisedVersionMap() { Map<String, RecognisedVersion> result = new LinkedHashMap<>(); for (RecognisedVersion recognisedVersion : RecognisedVersion.values()) { if (result.containsKey(recognisedVersion.getName())) { RecognisedVersion colliding = result.get(recognisedVersion.getName()); throw new RuntimeException( "name collision for the recognised versions " + recognisedVersion.getName() + " and " + colliding.getName()); } else { result.put(recognisedVersion.getName(), recognisedVersion); } } return result; } public static Map<String, RecognisedVersion> generateMagicStringToRecognisedVersionMap() { Map<String, RecognisedVersion> result = new LinkedHashMap<>(); for (RecognisedVersion recognisedVersion : RecognisedVersion.values()) { if (result.containsKey(recognisedVersion.getMagicString())) { RecognisedVersion colliding = result.get(recognisedVersion.getMagicString()); throw new RuntimeException( "magic string collision for the recognised versions " + recognisedVersion.getName() + " and " + colliding.getName()); } else { result.put(recognisedVersion.getMagicString(), recognisedVersion); } } return result; } public static String createEnumIdentifier(String name) { return "_" + name.replaceAll("[^a-zA-Z0-9]", "_"); } private static final String CLIENT_CLASS_RESOURCE = "net/minecraft/client/Minecraft.class"; private static final String CLIENT_CLASS = "net.minecraft.client.Minecraft"; private static final String SERVER_CLASS_RESOURCE = "net/minecraft/server/MinecraftServer.class"; private static final String SERVER_CLASS = "net.minecraft.server.MinecraftServer"; private final boolean isKnown; private final String name; private final String magicString; private RecognisedVersion() { this.isKnown = false; this.name = "UNKNOWN"; this.magicString = null; } private RecognisedVersion(String name, String magicString) { this.isKnown = true; this.name = name; this.magicString = magicString; } public boolean isKnown() { return isKnown; } public String getName() { return name; } public String getMagicString() { return magicString; } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\ReflectionUtils.java
package amidst.mojangapi.minecraftinterface; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; import java.lang.reflect.Array; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import amidst.clazz.symbolic.SymbolicClass; public enum ReflectionUtils { ; public static MethodHandle getMethodHandle(SymbolicClass symbolicClass, String method) throws IllegalAccessException { Method rawMethod = symbolicClass.getMethod(method).getRawMethod(); MethodHandle mh = MethodHandles.lookup().unreflect(rawMethod); return mh.asType(eraseTypesKeepArrays(mh.type())); } public static MethodType eraseTypesKeepArrays(MethodType type) { Class<?>[] newParameters = type.parameterArray(); for (int i= 0; i < newParameters.length; i++){ newParameters[i] = eraseTypeKeepArrays(newParameters[i]); } return MethodType.methodType(eraseTypeKeepArrays(type.returnType()), newParameters); } public static Class<?> eraseTypeKeepArrays(Class<?> originalType) { Class<?> newType = originalType; boolean isArray = newType.isArray(); boolean isPrimitive = newType.isPrimitive() || (isArray ? newType.getComponentType().isPrimitive() : false); if (!isPrimitive) { newType = Object.class; if (isArray) { newType = Array.newInstance(newType, 0).getClass(); } } return newType; } public static Object callParameterlessMethodReturning(Object obj, Class<?> retClass) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, MinecraftInterfaceException { Method candidate = null; for (Method meth: obj.getClass().getMethods()) { if (((meth.getModifiers() & Modifier.STATIC) == 0) && meth.getParameterCount() == 0 && retClass.isAssignableFrom(meth.getReturnType())) { if (candidate == null) { candidate = meth; } else { throw new MinecraftInterfaceException("found multiple methods returning " + retClass.getCanonicalName() + " on class " + obj.getClass().getCanonicalName()); } } } if (candidate == null) { throw new MinecraftInterfaceException("couldn't find method returning " + retClass.getCanonicalName() + " on class " + obj.getClass().getCanonicalName()); } return candidate.invoke(obj); } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\ThreadedWorldAccessor.java
package amidst.mojangapi.minecraftinterface; import java.util.Set; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Function; import amidst.mojangapi.minecraftinterface.MinecraftInterface.WorldAccessor; import amidst.mojangapi.world.Dimension; import amidst.util.FaillibleFunction; public class ThreadedWorldAccessor implements WorldAccessor { private final ThreadLocal<WorldAccessor> rawThreadedAccessor; private final Set<Dimension> supportedDimensions; public ThreadedWorldAccessor(FaillibleFunction<Void, WorldAccessor, MinecraftInterfaceException> innerAccessorFactory) throws MinecraftInterfaceException { AtomicReference<MinecraftInterface.WorldAccessor> initialWorld = new AtomicReference<>(innerAccessorFactory.apply(null)); this.supportedDimensions = initialWorld.get().supportedDimensions(); this.rawThreadedAccessor = ThreadLocal.withInitial(() -> { WorldAccessor world = initialWorld.getAndSet(null); if (world == null) { try { return innerAccessorFactory.apply(null); } catch (MinecraftInterfaceException e) { throw new RuntimeException(e); } } else { return world; } }); } @Override public <T> T getBiomeData(Dimension dimension, int x, int y, int width, int height, boolean useQuarterResolution, Function<int[], T> biomeDataMapper) throws MinecraftInterfaceException { return rawThreadedAccessor.get().getBiomeData(dimension, x, y, width, height, useQuarterResolution, biomeDataMapper); } @Override public Set<Dimension> supportedDimensions() { return supportedDimensions; } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\UnsupportedDimensionException.java
package amidst.mojangapi.minecraftinterface; import amidst.mojangapi.world.Dimension; @SuppressWarnings("serial") public class UnsupportedDimensionException extends MinecraftInterfaceException { public UnsupportedDimensionException(Dimension dimension) { super("The dimension " + dimension.getName() + " isn't supported by this MinecraftInterface"); } }
amidst
src\main\java\amidst\mojangapi\world\Dimension.java
package amidst.mojangapi.world; import amidst.documentation.Immutable; import amidst.logging.AmidstLogger; import amidst.mojangapi.world.coordinates.Resolution; @Immutable public enum Dimension { // @formatter:off NETHER( -1, "minecraft:the_nether" , "Nether", Resolution.NETHER), OVERWORLD(0, "minecraft:overworld", "Overworld", Resolution.WORLD), END( 1, "minecraft:the_end", "End", Resolution.WORLD); // @formatter:on public static Dimension fromId(int id) { if (id == NETHER.getId()) { return NETHER; } else if (id == OVERWORLD.getId()) { return OVERWORLD; } else if (id == END.getId()) { return END; } else { AmidstLogger.warn("Unsupported dimension id: {}. Falling back to Overworld.", id); return OVERWORLD; } } public static Dimension fromName(String name) { if (NETHER.getName().equals(name)) { return NETHER; } else if (OVERWORLD.getName().equals(name)) { return OVERWORLD; } else if (END.getName().equals(name)) { return END; } else { AmidstLogger.warn("Unsupported dimension name: {}. Falling back to Overworld.", name); return OVERWORLD; } } public static String[] getSelectable() { return new String[] { OVERWORLD.getDisplayName(), END.getDisplayName() }; } private final int id; private final String name; private final String displayName; private final Resolution resolution; private Dimension(int id, String name, String displayName, Resolution resolution) { this.id = id; this.name = name; this.displayName = displayName; this.resolution = resolution; } public int getId() { return id; } public String getName() { return name; } public String getDisplayName() { return displayName; } public Resolution getResolution() { return resolution; } @Override public String toString() { return displayName; } }
amidst
src\main\java\amidst\mojangapi\world\SeedHistoryLogger.java
package amidst.mojangapi.world; import java.io.BufferedWriter; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.sql.Timestamp; import java.util.Date; import java.util.Objects; import amidst.documentation.NotNull; import amidst.documentation.ThreadSafe; import amidst.logging.AmidstLogger; import amidst.mojangapi.minecraftinterface.RecognisedVersion; @ThreadSafe public class SeedHistoryLogger { public static SeedHistoryLogger from(Path seedHistoryFile) { if (seedHistoryFile != null) { AmidstLogger.info("using seed history file: '" + seedHistoryFile + "'"); return new SeedHistoryLogger(seedHistoryFile, true, true); } else { return new SeedHistoryLogger(Paths.get(HISTORY_TXT), false, true); } } public static SeedHistoryLogger createDisabled() { return new SeedHistoryLogger(Paths.get(HISTORY_TXT), false, false); } private static final String HISTORY_TXT = "history.txt"; private final Path file; private final boolean createIfNecessary; private final boolean isEnabled; public SeedHistoryLogger(@NotNull Path file, boolean createIfNecessary, boolean isEnabled) { Objects.requireNonNull(file); this.file = file; this.createIfNecessary = createIfNecessary; this.isEnabled = isEnabled; } public void log(RecognisedVersion recognisedVersion, WorldSeed worldSeed) { if (isEnabled) { doLog(recognisedVersion, worldSeed); } } private synchronized void doLog(RecognisedVersion recognisedVersion, WorldSeed worldSeed) { if (createIfNecessary && !Files.exists(file)) { tryCreateFile(); } if (Files.isRegularFile(file)) { writeLine(createLine(recognisedVersion, worldSeed)); } else { AmidstLogger.info("Not writing to seed history file, because it does not exist: {}", file); } } private String createLine(RecognisedVersion recognisedVersion, WorldSeed worldSeed) { String recognisedVersionName = recognisedVersion.getName(); String timestamp = createTimestamp(); String seedString = getSeedString(worldSeed); return recognisedVersionName + ", " + timestamp + ", " + seedString; } private String createTimestamp() { return new Timestamp(new Date().getTime()).toString(); } private String getSeedString(WorldSeed worldSeed) { String text = worldSeed.getText(); if (text != null) { return worldSeed.getLong() + ", " + text; } else { return worldSeed.getLong() + ""; } } private void tryCreateFile() { try { Files.createFile(file); } catch (IOException e) { AmidstLogger.warn(e, "Unable to create seed history file: {}", file); } } private void writeLine(String line) { try (BufferedWriter writer = Files.newBufferedWriter(file, StandardOpenOption.WRITE, StandardOpenOption.APPEND)) { writer.write(line); writer.write('\n'); } catch (IOException e) { AmidstLogger.warn(e, "Unable to write to seed history file: {}", file); } } }
amidst
src\main\java\amidst\mojangapi\world\World.java
package amidst.mojangapi.world; import java.util.List; import java.util.Optional; import amidst.documentation.ThreadSafe; import amidst.mojangapi.minecraftinterface.RecognisedVersion; import amidst.mojangapi.world.biome.BiomeList; import amidst.mojangapi.world.icon.WorldIcon; import amidst.mojangapi.world.icon.producer.CachedWorldIconProducer; import amidst.mojangapi.world.icon.producer.WorldIconProducer; import amidst.mojangapi.world.oracle.BiomeDataOracle; import amidst.mojangapi.world.oracle.EndIsland; import amidst.mojangapi.world.oracle.EndIslandOracle; import amidst.mojangapi.world.oracle.SlimeChunkOracle; import amidst.mojangapi.world.player.MovablePlayerList; @ThreadSafe public class World { private final WorldOptions worldOptions; private final MovablePlayerList movablePlayerList; private final RecognisedVersion recognisedVersion; private final List<Integer> enabledLayers; private final BiomeList biomeList; private final BiomeDataOracle overworldBiomeDataOracle; private final Optional<BiomeDataOracle> netherBiomeDataOracle; private final EndIslandOracle endIslandOracle; private final SlimeChunkOracle slimeChunkOracle; private final CachedWorldIconProducer spawnProducer; private final CachedWorldIconProducer strongholdProducer; private final CachedWorldIconProducer playerProducer; private final WorldIconProducer<Void> villageProducer; private final WorldIconProducer<Void> templeProducer; private final WorldIconProducer<Void> mineshaftProducer; private final WorldIconProducer<Void> oceanMonumentProducer; private final WorldIconProducer<Void> woodlandMansionProducer; private final WorldIconProducer<Void> oceanFeaturesProducer; private final WorldIconProducer<Void> netherFortressProducer; private final WorldIconProducer<List<EndIsland>> endCityProducer; public World( WorldOptions worldOptions, MovablePlayerList movablePlayerList, RecognisedVersion recognisedVersion, BiomeList biomeList, List<Integer> enabledLayers, BiomeDataOracle overworldBiomeDataOracle, Optional<BiomeDataOracle> netherBiomeDataOracle, EndIslandOracle endIslandOracle, SlimeChunkOracle slimeChunkOracle, CachedWorldIconProducer spawnProducer, CachedWorldIconProducer strongholdProducer, CachedWorldIconProducer playerProducer, WorldIconProducer<Void> villageProducer, WorldIconProducer<Void> templeProducer, WorldIconProducer<Void> mineshaftProducer, WorldIconProducer<Void> oceanMonumentProducer, WorldIconProducer<Void> woodlandMansionProducer, WorldIconProducer<Void> oceanFeaturesProducer, WorldIconProducer<Void> netherFortressProducer, WorldIconProducer<List<EndIsland>> endCityProducer) { this.worldOptions = worldOptions; this.movablePlayerList = movablePlayerList; this.recognisedVersion = recognisedVersion; this.biomeList = biomeList; this.enabledLayers = enabledLayers; this.overworldBiomeDataOracle = overworldBiomeDataOracle; this.netherBiomeDataOracle = netherBiomeDataOracle; this.endIslandOracle = endIslandOracle; this.slimeChunkOracle = slimeChunkOracle; this.spawnProducer = spawnProducer; this.strongholdProducer = strongholdProducer; this.playerProducer = playerProducer; this.villageProducer = villageProducer; this.templeProducer = templeProducer; this.mineshaftProducer = mineshaftProducer; this.oceanMonumentProducer = oceanMonumentProducer; this.woodlandMansionProducer = woodlandMansionProducer; this.oceanFeaturesProducer = oceanFeaturesProducer; this.netherFortressProducer = netherFortressProducer; this.endCityProducer = endCityProducer; } public WorldOptions getWorldOptions() { return worldOptions; } public MovablePlayerList getMovablePlayerList() { return movablePlayerList; } public RecognisedVersion getRecognisedVersion() { return recognisedVersion; } public BiomeList getBiomeList() { return biomeList; } public List<Integer> getEnabledLayers() { return enabledLayers; } public BiomeDataOracle getOverworldBiomeDataOracle() { return overworldBiomeDataOracle; } public Optional<BiomeDataOracle> getNetherBiomeDataOracle() { return netherBiomeDataOracle; } public EndIslandOracle getEndIslandOracle() { return endIslandOracle; } public SlimeChunkOracle getSlimeChunkOracle() { return slimeChunkOracle; } public WorldIconProducer<Void> getSpawnProducer() { return spawnProducer; } public WorldIconProducer<Void> getStrongholdProducer() { return strongholdProducer; } public WorldIconProducer<Void> getPlayerProducer() { return playerProducer; } public WorldIconProducer<Void> getVillageProducer() { return villageProducer; } public WorldIconProducer<Void> getTempleProducer() { return templeProducer; } public WorldIconProducer<Void> getMineshaftProducer() { return mineshaftProducer; } public WorldIconProducer<Void> getOceanMonumentProducer() { return oceanMonumentProducer; } public WorldIconProducer<Void> getNetherFortressProducer() { return netherFortressProducer; } public WorldIconProducer<List<EndIsland>> getEndCityProducer() { return endCityProducer; } public WorldIconProducer<Void> getWoodlandMansionProducer() { return woodlandMansionProducer; } public WorldIconProducer<Void> getOceanFeaturesProducer() { return oceanFeaturesProducer; } public WorldIcon getSpawnWorldIcon() { return spawnProducer.getFirstWorldIcon(); } public List<WorldIcon> getStrongholdWorldIcons() { return strongholdProducer.getWorldIcons(); } public List<WorldIcon> getPlayerWorldIcons() { return playerProducer.getWorldIcons(); } public void reloadPlayerWorldIcons() { playerProducer.resetCache(); } }
amidst
src\main\java\amidst\mojangapi\world\WorldBuilder.java
package amidst.mojangapi.world; import java.io.IOException; import amidst.documentation.Immutable; import amidst.mojangapi.file.ImmutablePlayerInformationProvider; import amidst.mojangapi.file.PlayerInformationProvider; import amidst.mojangapi.file.SaveGame; import amidst.mojangapi.minecraftinterface.LoggingMinecraftInterface; import amidst.mojangapi.minecraftinterface.MinecraftInterface; import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException; import amidst.mojangapi.minecraftinterface.RecognisedVersion; import amidst.mojangapi.minecraftinterface.ThreadedWorldAccessor; import amidst.mojangapi.world.icon.producer.MultiProducer; import amidst.mojangapi.world.icon.producer.PlayerProducer; import amidst.mojangapi.world.icon.producer.SpawnProducer; import amidst.mojangapi.world.oracle.ImmutableWorldSpawnOracle; import amidst.mojangapi.world.oracle.WorldSpawnOracle; import amidst.mojangapi.world.player.MovablePlayerList; import amidst.mojangapi.world.player.PlayerInformation; import amidst.mojangapi.world.player.WorldPlayerType; import amidst.mojangapi.world.versionfeatures.DefaultVersionFeatures; import amidst.mojangapi.world.versionfeatures.FeatureKey; import amidst.mojangapi.world.versionfeatures.VersionFeatures; @Immutable public class WorldBuilder { /** * Create a new WorldBuilder that does not log any seeds and that provides * the singleplayer player information for each requested player. */ public static WorldBuilder createSilentPlayerless() { return new WorldBuilder( new ImmutablePlayerInformationProvider(PlayerInformation.theSingleplayerPlayer()), SeedHistoryLogger.createDisabled()); } private final PlayerInformationProvider playerInformationProvider; private final SeedHistoryLogger seedHistoryLogger; public WorldBuilder(PlayerInformationProvider playerInformationProvider, SeedHistoryLogger seedHistoryLogger) { this.playerInformationProvider = playerInformationProvider; this.seedHistoryLogger = seedHistoryLogger; } public World from( MinecraftInterface minecraftInterface, WorldOptions worldOptions) throws MinecraftInterfaceException { VersionFeatures versionFeatures = initInterfaceAndGetFeatures(worldOptions, minecraftInterface); return create( minecraftInterface.getRecognisedVersion(), MovablePlayerList.dummy(), versionFeatures, versionFeatures.get(FeatureKey.WORLD_SPAWN_ORACLE)); } public World fromSaveGame(MinecraftInterface minecraftInterface, SaveGame saveGame) throws IOException, MinecraftInterfaceException { VersionFeatures versionFeatures = initInterfaceAndGetFeatures(WorldOptions.fromSaveGame(saveGame), minecraftInterface); return create( minecraftInterface.getRecognisedVersion(), new MovablePlayerList( playerInformationProvider, saveGame, true, WorldPlayerType.from(saveGame)), versionFeatures, new ImmutableWorldSpawnOracle(saveGame.getWorldSpawn())); } private VersionFeatures initInterfaceAndGetFeatures(WorldOptions worldOptions, MinecraftInterface minecraftInterface) throws MinecraftInterfaceException { RecognisedVersion recognisedVersion = minecraftInterface.getRecognisedVersion(); if(minecraftInterface instanceof LoggingMinecraftInterface) { ((LoggingMinecraftInterface) minecraftInterface).logNextAccessor(); } MinecraftInterface.WorldAccessor worldAccessor = new ThreadedWorldAccessor(v -> minecraftInterface.createWorldAccessor(worldOptions)); seedHistoryLogger.log(recognisedVersion, worldOptions.getWorldSeed()); return DefaultVersionFeatures.builder(worldOptions, worldAccessor).create(recognisedVersion); } private World create( RecognisedVersion recognisedVersion, MovablePlayerList movablePlayerList, VersionFeatures versionFeatures, WorldSpawnOracle worldSpawnOracle) throws MinecraftInterfaceException { return new World( versionFeatures.get(FeatureKey.WORLD_OPTIONS), movablePlayerList, recognisedVersion, versionFeatures.get(FeatureKey.BIOME_LIST), versionFeatures.get(FeatureKey.ENABLED_LAYERS), versionFeatures.get(FeatureKey.OVERWORLD_BIOME_DATA_ORACLE), versionFeatures.get(FeatureKey.NETHER_BIOME_DATA_ORACLE), versionFeatures.get(FeatureKey.END_ISLAND_ORACLE), versionFeatures.get(FeatureKey.SLIME_CHUNK_ORACLE), new SpawnProducer(worldSpawnOracle), versionFeatures.get(FeatureKey.STRONGHOLD_PRODUCER), new PlayerProducer(movablePlayerList), new MultiProducer<>( versionFeatures.get(FeatureKey.VILLAGE_PRODUCER), versionFeatures.get(FeatureKey.PILLAGER_OUTPOST_PRODUCER) ), new MultiProducer<>( versionFeatures.get(FeatureKey.DESERT_TEMPLE_PRODUCER), versionFeatures.get(FeatureKey.IGLOO_PRODUCER), versionFeatures.get(FeatureKey.JUNGLE_TEMPLE_PRODUCER), versionFeatures.get(FeatureKey.WITCH_HUT_PRODUCER) ), versionFeatures.get(FeatureKey.MINESHAFT_PRODUCER), versionFeatures.get(FeatureKey.OCEAN_MONUMENT_PRODUCER), versionFeatures.get(FeatureKey.WOODLAND_MANSION_PRODUCER), new MultiProducer<>( versionFeatures.get(FeatureKey.OCEAN_RUINS_PRODUCER), versionFeatures.get(FeatureKey.SHIPWRECK_PRODUCER), versionFeatures.get(FeatureKey.BURIED_TREASURE_PRODUCER) ), new MultiProducer<>( versionFeatures.get(FeatureKey.NETHER_FORTRESS_PRODUCER), versionFeatures.get(FeatureKey.BASTION_REMNANT_PRODUCER) ), versionFeatures.get(FeatureKey.END_CITY_PRODUCER)); } }
amidst
src\main\java\amidst\mojangapi\world\WorldOptions.java
package amidst.mojangapi.world; import amidst.documentation.Immutable; import amidst.mojangapi.file.SaveGame; @Immutable public class WorldOptions { private final WorldSeed worldSeed; private final WorldType worldType; private final String genOptions; public WorldOptions(WorldSeed seed, WorldType type, String generatorOptions) { worldSeed = seed; worldType = type; genOptions = generatorOptions; } public WorldOptions(WorldSeed seed, WorldType type) { this(seed, type, ""); } public WorldOptions withGeneratorOptions(String generatorOptions) { return new WorldOptions(worldSeed, worldType, generatorOptions); } public static WorldOptions fromSaveGame(SaveGame saveGame) { return new WorldOptions(WorldSeed.fromSaveGame(saveGame.getSeed()), saveGame.getWorldType(), saveGame.getGeneratorOptions()); } public WorldSeed getWorldSeed() { return worldSeed; } public WorldType getWorldType() { return worldType; } public String getGeneratorOptions() { return genOptions; } }
amidst
src\main\java\amidst\mojangapi\world\WorldSeed.java
package amidst.mojangapi.world; import java.security.SecureRandom; import amidst.documentation.Immutable; @Immutable public class WorldSeed { public static enum WorldSeedType { // @formatter:off TEXT ("Text Seed"), NUMERIC ("Numeric Seed"), SAVE_GAME ("Save Game Seed"), RANDOM ("Random Seed"); // @formatter:on private final String labelPrefix; private WorldSeedType(String labelPrefix) { this.labelPrefix = labelPrefix; } private String getLabel(long seed, String text) { if (this == TEXT) { return labelPrefix + ": '" + text + "' (" + seed + ")"; } else { return labelPrefix + ": " + seed; } } } private static final SecureRandom random = new SecureRandom(); public static WorldSeed random() { /* * SecureRandom.nextLong() can generate 2^64 different results even * though it directly inherits it from Random. The key difference is * the nature of next() in the different classes. In Random it is * restricted to 2^48 bits, while SecureRandom uses (i think) 2^128 * bits. */ return new WorldSeed(random.nextLong(), null, WorldSeedType.RANDOM); } public static WorldSeed fromUserInput(String input) { if (input.isEmpty()) { return random(); } try { long seed = Long.parseLong(input); return new WorldSeed(seed, null, WorldSeedType.NUMERIC); } catch (NumberFormatException err) { int seed = input.hashCode(); return new WorldSeed(seed, input, WorldSeedType.TEXT); } } public static WorldSeed fromSaveGame(long seed) { return new WorldSeed(seed, null, WorldSeedType.SAVE_GAME); } private final long seed; private final String text; private final WorldSeedType type; private final String label; private WorldSeed(long seed, String text, WorldSeedType type) { this.seed = seed; this.text = text; this.type = type; this.label = type.getLabel(seed, text); } public long getLong() { return seed; } public String getText() { return text; } public WorldSeedType getType() { return type; } public String getLabel() { return label; } }
amidst
src\main\java\amidst\mojangapi\world\WorldType.java
package amidst.mojangapi.world; import java.util.Arrays; import java.util.List; import amidst.documentation.Immutable; import amidst.logging.AmidstLogger; import amidst.logging.AmidstMessageBox; import amidst.mojangapi.minecraftinterface.legacy.LegacySymbolicNames; @Immutable public enum WorldType { // @formatter:off DEFAULT ("Default", "default", LegacySymbolicNames.FIELD_WORLD_TYPE_DEFAULT), FLAT ("Flat", "flat", LegacySymbolicNames.FIELD_WORLD_TYPE_FLAT), LARGE_BIOMES ("Large Biomes", "large-biomes", LegacySymbolicNames.FIELD_WORLD_TYPE_LARGE_BIOMES), AMPLIFIED ("Amplified", "amplified", LegacySymbolicNames.FIELD_WORLD_TYPE_AMPLIFIED), CUSTOMIZED ("Customized", "customized", LegacySymbolicNames.FIELD_WORLD_TYPE_CUSTOMIZED); // @formatter:on public static final String PROMPT_EACH_TIME = "Prompt each time"; private static final WorldType[] SELECTABLE_WORLD_TYPES_ARRAY = new WorldType[] { WorldType.DEFAULT, WorldType.FLAT, WorldType.LARGE_BIOMES, WorldType.AMPLIFIED }; private static final List<WorldType> SELECTABLE_WORLD_TYPES = Arrays.asList(SELECTABLE_WORLD_TYPES_ARRAY); private static final String[] WORLD_TYPE_SETTING_AVAILABLE_VALUES = new String[] { PROMPT_EACH_TIME, WorldType.DEFAULT.getName(), WorldType.FLAT.getName(), WorldType.LARGE_BIOMES.getName(), WorldType.AMPLIFIED.getName() }; public static List<WorldType> getSelectable() { return SELECTABLE_WORLD_TYPES; } public static WorldType[] getSelectableArray() { return SELECTABLE_WORLD_TYPES_ARRAY; } public static String[] getWorldTypeSettingAvailableValues() { return WORLD_TYPE_SETTING_AVAILABLE_VALUES; } public static WorldType from(String nameOrSymbolicFieldName) { WorldType result = findInstance(nameOrSymbolicFieldName); if (result != null) { return result; } else { String message = "Unable to find World Type: " + nameOrSymbolicFieldName + ". Falling back to default world type."; AmidstLogger.error(message); AmidstMessageBox.displayError("Error", message); return DEFAULT; } } public static WorldType findInstance(String nameOrValue) { for (WorldType worldType : values()) { if (worldType.name.equalsIgnoreCase(nameOrValue) || worldType.symbolicFieldName.equalsIgnoreCase(nameOrValue)) { return worldType; } } return null; } private final String name; private final String filenameText; private final String symbolicFieldName; private WorldType(String name, String filenameText, String symbolicFieldName) { this.name = name; this.filenameText = filenameText; this.symbolicFieldName = symbolicFieldName; } public String getName() { return name; } public String getFilenameText() { return filenameText; } public String getSymbolicFieldName() { return symbolicFieldName; } @Override public String toString() { return name; } }
amidst
src\main\java\amidst\mojangapi\file\directory\DotMinecraftDirectory.java
package amidst.mojangapi.file.directory; import amidst.documentation.Immutable; import amidst.documentation.NotNull; import amidst.logging.AmidstLogger; import amidst.mojangapi.file.Version; import amidst.mojangapi.file.json.ReleaseType; import amidst.mojangapi.file.json.launcherprofiles.LauncherProfileJson; import amidst.mojangapi.file.json.launcherprofiles.ProfileType; import amidst.util.OperatingSystemDetector; import java.io.FileNotFoundException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; /** * API for interacting with the {@code .minecraft} user directory. */ @Immutable public class DotMinecraftDirectory { private final Path root; private final Path libraries; private final Path versions; private final Path launcherProfilesJson; public DotMinecraftDirectory(Path root) { this.root = root; this.libraries = root.resolve("libraries"); this.versions = root.resolve("versions"); this.launcherProfilesJson = root.resolve("launcher_profiles.json"); } public DotMinecraftDirectory(@NotNull Path root, Path libraries, Path versions, Path launcherProfilesJson) { this.root = root; this.libraries = libraries == null ? root.resolve("libraries") : libraries; this.versions = versions == null ? root.resolve("versions") : versions; this.launcherProfilesJson = launcherProfilesJson == null ? root.resolve("launcher_profiles.json") : launcherProfilesJson; } /** * Checks if the paths in this {@code .minecraft} directory are 'valid'. * <p> * Valid means that {@code root}, {@code libraries}, and {@code versions} * are {@link Files#isDirectory(Path, LinkOption...) directories} and * {@code launcherProfilesJson} is a {@link Files#isRegularFile(Path, LinkOption...) regular file}. * * @return {@code true} for valid directories, {@code false} otherwise */ public boolean isValid() { return Files.isDirectory(root) && Files.isDirectory(libraries) && Files.isDirectory(versions) && Files.isRegularFile(launcherProfilesJson); } public ProfileDirectory asProfileDirectory() { return new ProfileDirectory(root); } public Path getRoot() { return root; } public Path getLibraries() { return libraries; } public Path getVersions() { return versions; } public Path getLauncherProfilesJson() { return launcherProfilesJson; } @NotNull public static DotMinecraftDirectory createDotMinecraftDirectory(Path overrideDirectory) { if (overrideDirectory != null) { if (Files.isDirectory(overrideDirectory)) { return new DotMinecraftDirectory(overrideDirectory); } AmidstLogger.warn( "Unable to set Minecraft directory to: {} as that location does not exist or is not a folder.", overrideDirectory); } return new DotMinecraftDirectory(getMinecraftDirectory()); } @NotNull public static Path getMinecraftDirectory() { Path home = Paths.get(System.getProperty("user.home", ".")); if (OperatingSystemDetector.isWindows()) { Path appData = Paths.get(System.getenv("APPDATA")); if (Files.isDirectory(appData)) { return appData.resolve(".minecraft"); } } else if (OperatingSystemDetector.isMac()) { return home.resolve("Library/Application Support/minecraft"); } return home.resolve(".minecraft"); } @NotNull public static ProfileDirectory createValidProfileDirectory( LauncherProfileJson launcherProfileJson, DotMinecraftDirectory dotMinecraftDirectory) throws FileNotFoundException { String gameDir = launcherProfileJson.getGameDir(); ProfileDirectory result = gameDir != null ? new ProfileDirectory(Paths.get(gameDir)) : dotMinecraftDirectory.asProfileDirectory(); if (result.isValid()) { return result; } else { throw new FileNotFoundException( "cannot find valid profile directory for launcher profile '" + launcherProfileJson.getName() + "': " + gameDir); } } @NotNull public static VersionDirectory createValidVersionDirectory( LauncherProfileJson launcherProfileJson, List<Version> versionList, DotMinecraftDirectory dotMinecraftDirectory) throws FileNotFoundException { String lastVersionId = launcherProfileJson.getLastVersionId(); List<ReleaseType> releaseTypesToSearch = null; if (lastVersionId == null) { releaseTypesToSearch = launcherProfileJson.getAllowedReleaseTypes(); } else if (lastVersionId.equals("latest-release")) { releaseTypesToSearch = ProfileType.LATEST_RELEASE.getAllowedReleaseTypes().get(); } else if (lastVersionId.equals("latest-snapshot")) { releaseTypesToSearch = ProfileType.LATEST_SNAPSHOT.getAllowedReleaseTypes().get(); } if (releaseTypesToSearch == null) { VersionDirectory result = createVersionDirectory(dotMinecraftDirectory, lastVersionId); if (result.isValid()) { return result; } } else { VersionDirectory result = null; for (Version version : versionList) { if (releaseTypesToSearch.contains(version.getType())) { VersionDirectory versionDirectory = createVersionDirectory(dotMinecraftDirectory, version.getId()); if (versionDirectory.isValid()) { result = versionDirectory; break; } } } if (result != null) { return result; } } throw new FileNotFoundException( "cannot find valid version directory for launcher profile '" + launcherProfileJson.getName() + "'"); } @NotNull public static VersionDirectory createValidVersionDirectory(DotMinecraftDirectory dotMinecraftDirectory, String versionId) throws FileNotFoundException { VersionDirectory versionDirectory = createVersionDirectory(dotMinecraftDirectory, versionId); if (versionDirectory.isValid()) { return versionDirectory; } else { throw new FileNotFoundException("cannot find valid version directory for version id '" + versionId + "'"); } } @NotNull public static VersionDirectory createVersionDirectory(DotMinecraftDirectory dotMinecraftDirectory, String versionId) { Path versions = dotMinecraftDirectory.getVersions(); Path jar = versions.resolve(versionId + "/" + versionId + ".jar"); Path json = versions.resolve(versionId + "/" + versionId + ".json"); return new VersionDirectory(jar, json); } }
amidst
src\main\java\amidst\mojangapi\file\directory\ProfileDirectory.java
package amidst.mojangapi.file.directory; import java.nio.file.Files; import java.nio.file.Path; import amidst.documentation.Immutable; @Immutable public class ProfileDirectory { private final Path root; private final Path saves; public ProfileDirectory(Path root) { this.root = root; this.saves = root.resolve("saves"); } public boolean isValid() { return Files.isDirectory(root); } public Path getRoot() { return root; } public Path getSaves() { return saves; } }
amidst
src\main\java\amidst\mojangapi\file\directory\SaveAmidstBackupDirectory.java
package amidst.mojangapi.file.directory; import java.nio.file.Path; public class SaveAmidstBackupDirectory { private final Path root; private final Path players; private final Path playerdata; public SaveAmidstBackupDirectory(Path root) { this.root = root; this.players = root.resolve("players"); this.playerdata = root.resolve("playerdata"); } public Path getRoot() { return root; } public Path getPlayers() { return players; } public Path getPlayerdata() { return playerdata; } }
amidst
src\main\java\amidst\mojangapi\file\directory\SaveAmidstDirectory.java
package amidst.mojangapi.file.directory; import java.nio.file.Path; public class SaveAmidstDirectory { private final Path root; private final SaveAmidstBackupDirectory backup; public SaveAmidstDirectory(Path root) { this.root = root; this.backup = new SaveAmidstBackupDirectory(root.resolve("backup")); } public Path getRoot() { return root; } public SaveAmidstBackupDirectory getBackup() { return backup; } }
amidst
src\main\java\amidst\mojangapi\file\directory\SaveDirectory.java
package amidst.mojangapi.file.directory; import java.nio.file.Files; import java.nio.file.Path; import amidst.documentation.Immutable; @Immutable public class SaveDirectory { private final Path root; private final SaveAmidstDirectory amidst; private final Path players; private final Path playerdata; private final Path levelDat; public SaveDirectory(Path root) { this.root = root; this.amidst = new SaveAmidstDirectory(root.resolve("amidst")); this.players = root.resolve("players"); this.playerdata = root.resolve("playerdata"); this.levelDat = root.resolve("level.dat"); } public boolean isValid() { return Files.isDirectory(root) && Files.isRegularFile(levelDat); } public boolean hasMultiplayerPlayers() { return Files.isDirectory(playerdata) || Files.isDirectory(players); } public Path getRoot() { return root; } public SaveAmidstDirectory getAmidst() { return amidst; } public Path getPlayers() { return players; } public Path getPlayerdata() { return playerdata; } public Path getLevelDat() { return levelDat; } public Path getPlayersFile(String playerName) { return players.resolve(playerName + ".dat"); } public Path getPlayerdataFile(String playerUUID) { return playerdata.resolve(playerUUID + ".dat"); } }
amidst
src\main\java\amidst\mojangapi\file\directory\VersionDirectory.java
package amidst.mojangapi.file.directory; import java.nio.file.Files; import java.nio.file.Path; import amidst.documentation.Immutable; @Immutable public class VersionDirectory { private final Path jar; private final Path json; public VersionDirectory(Path jar, Path json) { this.jar = jar; this.json = json; } public boolean isValid() { return Files.isRegularFile(jar) && Files.isRegularFile(json); } public Path getJar() { return jar; } public Path getJson() { return json; } }
amidst
src\main\java\amidst\mojangapi\file\json\ReleaseType.java
package amidst.mojangapi.file.json; import com.google.gson.annotations.SerializedName; import amidst.documentation.Immutable; @Immutable public enum ReleaseType { @SerializedName("snapshot") SNAPSHOT("snapshot", "S"), @SerializedName("release") RELEASE("release", "R"), @SerializedName("old_beta") OLD_BETA("old_beta", "B"), @SerializedName("old_alpha") OLD_ALPHA("old_alpha", "A"); private final String name; private final String typeChar; private ReleaseType(String name, String typeChar) { this.name = name; this.typeChar = typeChar; } public String getName() { return name; } public String getTypeChar() { return typeChar; } }
amidst
src\main\java\amidst\mojangapi\file\nbt\LevelDatNbt.java
package amidst.mojangapi.file.nbt; import java.io.IOException; import java.nio.file.Path; import net.querz.nbt.tag.ByteTag; import net.querz.nbt.tag.CompoundTag; import net.querz.nbt.tag.StringTag; import net.querz.nbt.tag.Tag; import amidst.documentation.Immutable; import amidst.mojangapi.world.WorldType; import amidst.mojangapi.world.coordinates.CoordinatesInWorld; import amidst.parsing.FormatException; @Immutable public class LevelDatNbt { public static LevelDatNbt from(Path path) throws IOException, FormatException { try { CompoundTag dataTag = readDataTag(NBTUtils.readTagFromFile(path)); long seed = readRandomSeed(dataTag); CoordinatesInWorld worldSpawn = readWorldSpawn(dataTag); WorldType worldType = readWorldType(dataTag); String generatorOptions = readGeneratorOptions(dataTag, worldType); boolean hasPlayer = hasPlayerTag(dataTag); return new LevelDatNbt(seed, worldSpawn, worldType, generatorOptions, hasPlayer); } catch (NullPointerException | ClassCastException e) { throw new FormatException("cannot read level.dat: " + path, e); } } private static CompoundTag readDataTag(CompoundTag root) throws IOException { return root.get(NBTTagKeys.TAG_KEY_DATA, CompoundTag.class); } private static long readRandomSeed(CompoundTag dataTag) { Tag<?> randomSeed = dataTag.get(NBTTagKeys.TAG_KEY_RANDOM_SEED); if (randomSeed != null) { return NBTUtils.getLongValue(randomSeed); } // Minecraft 1.16 format CompoundTag worldGenSettings = dataTag.get(NBTTagKeys.TAG_KEY_WORLD_GEN_SETTINGS, CompoundTag.class); return NBTUtils.getLongValue(worldGenSettings.get(NBTTagKeys.TAG_KEY_SEED)); } private static CoordinatesInWorld readWorldSpawn(CompoundTag dataTag) { return CoordinatesInWorld.from(readSpawnX(dataTag), readSpawnZ(dataTag)); } private static long readSpawnX(CompoundTag dataTag) { return NBTUtils.getLongValue(dataTag.get(NBTTagKeys.TAG_KEY_SPAWN_X)); } private static long readSpawnZ(CompoundTag dataTag) { return NBTUtils.getLongValue(dataTag.get(NBTTagKeys.TAG_KEY_SPAWN_Z)); } private static WorldType readWorldType(CompoundTag dataTag) { WorldType heuristicWorldType = tryGuessWorldType(dataTag); if (heuristicWorldType != null) { return heuristicWorldType; } else if (hasGeneratorName(dataTag)) { return WorldType.from(readGeneratorName(dataTag)); } else { return WorldType.DEFAULT; } } private static boolean hasGeneratorName(CompoundTag dataTag) { return dataTag.containsKey(NBTTagKeys.TAG_KEY_GENERATOR_NAME); } private static String readGeneratorOptions(CompoundTag dataTag, WorldType worldType) { if (worldType == WorldType.CUSTOMIZED) { return readGeneratorOptions(dataTag); } else { return ""; } } private static String readGeneratorName(CompoundTag dataTag) { return dataTag.get(NBTTagKeys.TAG_KEY_GENERATOR_NAME, StringTag.class).getValue(); } // Try to guess world type from Minecraft 1.16 generator settings private static WorldType tryGuessWorldType(CompoundTag dataTag) { // Be careful when handling null values, we don't want to trigger unwanted errors Tag<?> generator = NBTUtils.getNestedTag(dataTag, "WorldGenSettings", "dimensions", "minecraft:overworld", "generator"); Tag<?> generatorType = NBTUtils.getNestedTag(generator, "type"); if (new StringTag("minecraft:flat").equals(generatorType)) { return WorldType.FLAT; } if (new StringTag("minecraft:noise").equals(generatorType)) { Tag<?> settings = NBTUtils.getNestedTag(generator, "settings"); if (new StringTag("minecraft:amplified").equals(settings)) { return WorldType.AMPLIFIED; } Tag<?> largeBiomes = NBTUtils.getNestedTag(generator, "biome_source", "large_biomes"); if (new ByteTag(true).equals(largeBiomes)) { return WorldType.LARGE_BIOMES; } else { return WorldType.DEFAULT; } } return null; } private static String readGeneratorOptions(CompoundTag dataTag) { return dataTag.get(NBTTagKeys.TAG_KEY_GENERATOR_OPTIONS, StringTag.class).getValue(); } private static boolean hasPlayerTag(CompoundTag dataTag) { return dataTag.containsKey(NBTTagKeys.TAG_KEY_PLAYER); } private final long seed; private final CoordinatesInWorld worldSpawn; private final WorldType worldType; private final String generatorOptions; private final boolean hasPlayer; public LevelDatNbt( long seed, CoordinatesInWorld worldSpawn, WorldType worldType, String generatorOptions, boolean hasPlayer) { this.seed = seed; this.worldSpawn = worldSpawn; this.worldType = worldType; this.generatorOptions = generatorOptions; this.hasPlayer = hasPlayer; } public long getSeed() { return seed; } public CoordinatesInWorld getWorldSpawn() { return worldSpawn; } public WorldType getWorldType() { return worldType; } public String getGeneratorOptions() { return generatorOptions; } public boolean hasPlayer() { return hasPlayer; } }
amidst
src\main\java\amidst\mojangapi\file\nbt\NBTTagKeys.java
package amidst.mojangapi.file.nbt; import amidst.documentation.Immutable; @Immutable public class NBTTagKeys { public static final String TAG_KEY_BASE = "Base"; public static final String TAG_KEY_DATA = "Data"; public static final String TAG_KEY_POS = "Pos"; public static final String TAG_KEY_PLAYER = "Player"; public static final String TAG_KEY_SPAWN_X = "SpawnX"; public static final String TAG_KEY_SPAWN_Z = "SpawnZ"; public static final String TAG_KEY_DIMENSION = "Dimension"; public static final String TAG_KEY_RANDOM_SEED = "RandomSeed"; public static final String TAG_KEY_GENERATOR_NAME = "generatorName"; public static final String TAG_KEY_GENERATOR_OPTIONS = "generatorOptions"; public static final String TAG_KEY_WORLD_GEN_SETTINGS = "WorldGenSettings"; public static final String TAG_KEY_SEED = "seed"; }
amidst
src\main\java\amidst\mojangapi\file\nbt\NBTUtils.java
package amidst.mojangapi.file.nbt; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; import net.querz.nbt.io.NBTInputStream; import net.querz.nbt.io.NBTOutputStream; import net.querz.nbt.io.NamedTag; import net.querz.nbt.tag.CompoundTag; import net.querz.nbt.tag.NumberTag; import net.querz.nbt.tag.Tag; import amidst.documentation.Immutable; @Immutable public enum NBTUtils { ; public static CompoundTag readTagFromFile(Path file) throws IOException { try(NBTInputStream inStream = createNBTInputStream(file)) { NamedTag namedRoot = inStream.readTag(Tag.DEFAULT_MAX_DEPTH); if (!namedRoot.getName().isEmpty()) { throw new IOException("Unexpected NBT root name '" + namedRoot.getName() + "' in " + file); } Tag<?> root = namedRoot.getTag(); if (root instanceof CompoundTag) { return (CompoundTag) root; } else { throw new IOException("Invalid NBT tag id " + root.getID() + " in " + file); } } } public static NBTInputStream createNBTInputStream(Path file) throws IOException { return new NBTInputStream(new GZIPInputStream(new BufferedInputStream(Files.newInputStream(file)))); } public static void writeTagToFile(Path out, CompoundTag root) throws IOException { try (NBTOutputStream outStream = createNBTOutputStream(out)) { outStream.writeTag(new NamedTag("", root), Tag.DEFAULT_MAX_DEPTH); } } public static NBTOutputStream createNBTOutputStream(Path file) throws IOException { return new NBTOutputStream(new GZIPOutputStream(new BufferedOutputStream(Files.newOutputStream(file)))); } public static long getLongValue(Tag<?> tag) { if (tag instanceof NumberTag<?>) { return ((NumberTag<?>) tag).asLong(); } else { throw new IllegalArgumentException( "cannot read long value from the class '" + tag.getClass().getName() + "'"); } } public static Tag<?> getNestedTag(Tag<?> tag, String... path) { Tag<?> currentTag = tag; for (String key: path) { if (currentTag == null || !(currentTag instanceof CompoundTag)) { return null; } currentTag = ((CompoundTag) currentTag).get(key); } return currentTag; } public static CompoundTag shallowCopy(CompoundTag tag) { CompoundTag result = new CompoundTag(); for (Entry<String, Tag<?>> entry: tag.entrySet()) { result.put(entry.getKey(), entry.getValue()); } return result; } }
amidst
src\main\java\amidst\mojangapi\file\service\AmidstBackupService.java
package amidst.mojangapi.file.service; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Timestamp; import amidst.documentation.Immutable; import amidst.mojangapi.file.directory.SaveDirectory; @Immutable public class AmidstBackupService { public boolean tryBackupPlayersFile(SaveDirectory saveDirectory, String playerName) { Path toDirectory = saveDirectory.getAmidst().getBackup().getPlayers(); Path from = saveDirectory.getPlayersFile(playerName); Path to = toDirectory.resolve(playerName + ".dat" + "_" + millis()); return tryBackup(toDirectory, from, to); } public boolean tryBackupPlayerdataFile(SaveDirectory saveDirectory, String playerUUID) { Path toDirectory = saveDirectory.getAmidst().getBackup().getPlayerdata(); Path from = saveDirectory.getPlayerdataFile(playerUUID); Path to = toDirectory.resolve(playerUUID + ".dat" + "_" + millis()); return tryBackup(toDirectory, from, to); } public boolean tryBackupLevelDat(SaveDirectory saveDirectory) { Path toDirectory = saveDirectory.getAmidst().getBackup().getRoot(); Path from = saveDirectory.getLevelDat(); Path to = toDirectory.resolve("level.dat" + "_" + millis()); return tryBackup(toDirectory, from, to); } private String millis() { return new Timestamp(System.currentTimeMillis()) .toString() .replace(" ", "_") .replace(":", "-") .replace(".", "_"); } private boolean tryBackup(Path toDirectory, Path from, Path to) { return ensureDirectoryExists(toDirectory) && tryCopy(from, to) && Files.isRegularFile(to); } private boolean ensureDirectoryExists(Path directory) { try { Files.createDirectories(directory); return true; } catch (IOException e) { return false; } } private boolean tryCopy(Path from, Path to) { try { Files.copy(from, to); return true; } catch (IOException e) { return false; } } }
amidst
src\main\java\amidst\mojangapi\file\service\ClassLoaderService.java
package amidst.mojangapi.file.service; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.Optional; import java.util.regex.Pattern; import java.util.stream.Stream; import amidst.documentation.Immutable; import amidst.documentation.NotNull; import amidst.logging.AmidstLogger; import amidst.mojangapi.file.json.version.LibraryJson; import amidst.mojangapi.file.json.version.LibraryRuleJson; import amidst.mojangapi.file.json.version.LibraryRuleOsJson; import amidst.util.OperatingSystemDetector; @Immutable public class ClassLoaderService { private static final String ACTION_ALLOW = "allow"; @NotNull public URLClassLoader createClassLoader(Path path, List<LibraryJson> libraries, Path path2) throws MalformedURLException { List<URL> classLoaderUrls = getAllClassLoaderUrls(path, libraries, path2); return new URLClassLoader(classLoaderUrls.toArray(new URL[classLoaderUrls.size()])); } @NotNull private List<URL> getAllClassLoaderUrls(Path path, List<LibraryJson> libraries, Path path2) throws MalformedURLException { List<URL> result = new ArrayList<>(getLibraryUrls(path, libraries)); result.add(path2.toUri().toURL()); return Collections.unmodifiableList(result); } @NotNull private List<URL> getLibraryUrls(Path path, List<LibraryJson> libraries) { List<URL> result = new ArrayList<>(); AmidstLogger.info("Loading libraries."); for (LibraryJson library : libraries) { if (isLibraryActive(library)) { Optional<Path> libraryFile = getLibraryFile(path, library); if (libraryFile.isPresent()) { try { URL libraryUrl = libraryFile.get().toUri().toURL(); result.add(libraryUrl); AmidstLogger.info("Found library " + library.getName() + " at " + libraryUrl); } catch (MalformedURLException e) { AmidstLogger.warn(e, "Skipping erroneous library {}", library.getName()); } } else { AmidstLogger.warn("Skipping missing library {}", library.getName()); } } else { AmidstLogger.info("Skipping inactive library {}", library.getName()); } } AmidstLogger.info("Finished loading libraries."); return result; } private boolean isLibraryActive(LibraryJson library) { return isLibraryActive(getOsName(), OperatingSystemDetector.getVersion(), library.getRules()); } private String getOsName() { if (OperatingSystemDetector.isWindows()) { return "windows"; } else if (OperatingSystemDetector.isMac()) { return "osx"; } else { return "linux"; } } /** * Note, that multiple rules might be applicable. We take the last * applicable rule. However, this might be wrong so we need to take the most * specific rule? For now this works fine. */ private boolean isLibraryActive(String osName, String osVersion, List<LibraryRuleJson> rules) { if (rules.isEmpty()) { return true; } boolean result = false; for (LibraryRuleJson rule : rules) { if (isApplicable(osName, osVersion, rule)) { result = isAllowed(rule); } } return result; } private boolean isApplicable(String osName, String osVersion, LibraryRuleJson rule) { LibraryRuleOsJson osRule = rule.getOs(); return osRule == null || Objects.equals(osRule.getName(), osName) && (osRule.getVersion() == null || Pattern.matches(osRule.getVersion(), osVersion)); } private boolean isAllowed(LibraryRuleJson rule) { return Objects.equals(rule.getAction(), ACTION_ALLOW); } private Optional<Path> getLibraryFile(Path path, LibraryJson library) { return getLibrarySearchFiles(path, library) .filter(f -> hasFileExtension(f, "jar")) .findFirst() .filter(Files::exists); } private Stream<Path> getLibrarySearchFiles(Path path, LibraryJson library) { return getLibrarySearchFiles(getLibrarySearchPath(path, library.getName())); } private Path getLibrarySearchPath(Path librariesDirectory, String libraryName) { Path path = librariesDirectory.toAbsolutePath(); String separator = path.getFileSystem().getSeparator(); boolean firstPart = true; for (String elem : libraryName.split(":")) { path = path.resolve(firstPart ? elem.replace(".", separator) : elem); firstPart = false; } return path; } private Stream<Path> getLibrarySearchFiles(Path librarySearchPath) { if (Files.isDirectory(librarySearchPath)) { try { return Files.list(librarySearchPath); } catch (IOException e) { AmidstLogger.error(e, "Error while reading library directory " + librarySearchPath); } } return Stream.empty(); } private boolean hasFileExtension(Path file, String extension) { return getFileExtension(file.getFileName().toString()).equals(extension); } private String getFileExtension(String fileName) { int index = fileName.lastIndexOf('.'); if (index > 0) { return fileName.substring(index + 1); } else { return ""; } } }
amidst
src\main\java\amidst\mojangapi\file\service\PlayerInformationService.java
package amidst.mojangapi.file.service; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Base64; import java.util.Optional; import javax.imageio.ImageIO; import amidst.documentation.Immutable; import amidst.documentation.NotNull; import amidst.logging.AmidstLogger; import amidst.mojangapi.file.json.player.PlayerJson; import amidst.mojangapi.file.json.player.PropertyJson; import amidst.mojangapi.file.json.player.SKINJson; import amidst.mojangapi.file.json.player.SimplePlayerJson; import amidst.mojangapi.file.json.player.TexturesJson; import amidst.mojangapi.file.json.player.TexturesPropertyJson; import amidst.mojangapi.world.icon.WorldIconImage; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; import amidst.mojangapi.world.player.PlayerInformation; import amidst.parsing.FormatException; import amidst.parsing.json.JsonReader; @Immutable public class PlayerInformationService { private static final WorldIconImage DEFAULT_HEAD = DefaultWorldIconTypes.PLAYER.getImage(); private static final String SIMPLE_PLAYER_SKIN_URL = "http://s3.amazonaws.com/MinecraftSkins/"; private static final String PLAYERNAME_TO_UUID = "https://api.mojang.com/users/profiles/minecraft/"; private static final String UUID_TO_PROFILE = "https://sessionserver.mojang.com/session/minecraft/profile/"; @NotNull public PlayerInformation fromUUID(String uuid) { Optional<PlayerJson> optionalPlayer = tryGetPlayerJsonByUUID(uuid); Optional<WorldIconImage> head; if (optionalPlayer.isPresent()) { PlayerJson player = optionalPlayer.get(); head = tryGetSkinUrl(player).flatMap(this::tryGetPlayerHeadBySkinUrl); if (head.isPresent()) { return new PlayerInformation(player.getId(), player.getName(), head.get()); } else { return new PlayerInformation(player.getId(), player.getName(), DEFAULT_HEAD); } } else { return new PlayerInformation(uuid, null, DEFAULT_HEAD); } } @NotNull public PlayerInformation fromName(String name) { Optional<PlayerJson> optionalPlayer = tryGetPlayerJsonByName(name); Optional<WorldIconImage> head; if (optionalPlayer.isPresent()) { PlayerJson player = optionalPlayer.get(); head = tryGetSkinUrl(player).flatMap(this::tryGetPlayerHeadBySkinUrl); if (head.isPresent()) { return new PlayerInformation(player.getId(), player.getName(), head.get()); } else { head = tryGetPlayerHeadByName(name); if (head.isPresent()) { return new PlayerInformation(player.getId(), player.getName(), head.get()); } else { return new PlayerInformation(player.getId(), player.getName(), DEFAULT_HEAD); } } } else { head = tryGetPlayerHeadByName(name); if (head.isPresent()) { return new PlayerInformation(null, name, head.get()); } else { return new PlayerInformation(null, name, DEFAULT_HEAD); } } } @NotNull private Optional<String> tryGetSkinUrl(PlayerJson playerJson) { return tryReadTexturesProperty(playerJson) .map(TexturesPropertyJson::getTextures) .map(TexturesJson::getSKIN) .map(SKINJson::getUrl); } @NotNull private Optional<TexturesPropertyJson> tryReadTexturesProperty(PlayerJson playerJson) { try { for (PropertyJson property : playerJson.getProperties()) { if (isTexturesProperty(property)) { return Optional.of(JsonReader.readString(getDecodedValue(property), TexturesPropertyJson.class)); } } return Optional.empty(); } catch (FormatException e) { return Optional.empty(); } } private boolean isTexturesProperty(PropertyJson propertyJson) throws FormatException { String name = propertyJson.getName(); if (name == null) { throw new FormatException("property has no name"); } else { return name.equals("textures"); } } @NotNull private String getDecodedValue(PropertyJson propertyJson) throws FormatException { String value = propertyJson.getValue(); if (value == null) { throw new FormatException("unable to decode property value"); } else { return new String( Base64.getDecoder().decode(value.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8); } } @NotNull private Optional<PlayerJson> tryGetPlayerJsonByName(String name) { try { return Optional.of(getPlayerJsonByName(name)); } catch (IOException | FormatException | NullPointerException e) { AmidstLogger.warn("unable to load player information by name: {}", name); return Optional.empty(); } } @NotNull private Optional<PlayerJson> tryGetPlayerJsonByUUID(String uuid) { try { return Optional.of(getPlayerJsonByUUID(uuid)); } catch (IOException | FormatException | NullPointerException e) { AmidstLogger.warn("unable to load player information by uuid: {}", uuid); return Optional.empty(); } } @NotNull private PlayerJson getPlayerJsonByName(String name) throws FormatException, IOException { return getPlayerJsonByUUID(getUUIDByName(name).getId()); } @NotNull private PlayerJson getPlayerJsonByUUID(String uuid) throws FormatException, IOException { return JsonReader.readLocation(UUID_TO_PROFILE + uuid, PlayerJson.class); } @NotNull private SimplePlayerJson getUUIDByName(String name) throws FormatException, IOException { return JsonReader.readLocation(PLAYERNAME_TO_UUID + name, SimplePlayerJson.class); } @NotNull private Optional<WorldIconImage> tryGetPlayerHeadByName(String name) { try { return Optional.of(WorldIconImage.from(getPlayerHeadByName(name))); } catch (IOException | NullPointerException e) { AmidstLogger.warn("unable to load player head by name: {}", name); return Optional.empty(); } } @NotNull private Optional<WorldIconImage> tryGetPlayerHeadBySkinUrl(String skinUrl) { try { return Optional.of(WorldIconImage.from(getPlayerHeadBySkinUrl(skinUrl))); } catch (IOException | NullPointerException e) { AmidstLogger.warn("unable to load player head by skin url: {}", skinUrl); return Optional.empty(); } } @NotNull private BufferedImage getPlayerHeadByName(String name) throws IOException { return extractPlayerHead(new URL(SIMPLE_PLAYER_SKIN_URL + name + ".png")); } @NotNull private BufferedImage getPlayerHeadBySkinUrl(String skinUrl) throws IOException { return extractPlayerHead(new URL(skinUrl)); } @NotNull private BufferedImage extractPlayerHead(URL url) throws IOException { return extractPlayerHead(ImageIO.read(url)); } @NotNull private BufferedImage extractPlayerHead(BufferedImage skin) { BufferedImage head = new BufferedImage(20, 20, BufferedImage.TYPE_INT_ARGB); Graphics2D g2d = head.createGraphics(); g2d.setColor(Color.black); g2d.fillRect(0, 0, 20, 20); g2d.drawImage(skin, 2, 2, 18, 18, 8, 8, 16, 16, null); g2d.dispose(); skin.flush(); return head; } }
amidst
src\main\java\amidst\mojangapi\file\service\SaveDirectoryService.java
package amidst.mojangapi.file.service; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; import java.util.stream.Stream; import amidst.documentation.Immutable; import amidst.documentation.NotNull; import amidst.logging.AmidstLogger; import amidst.mojangapi.file.directory.SaveDirectory; import amidst.mojangapi.file.nbt.LevelDatNbt; import amidst.mojangapi.file.nbt.player.PlayerLocationLoader; import amidst.mojangapi.file.nbt.player.PlayerLocationSaver; import amidst.mojangapi.file.nbt.player.PlayerNbt; import amidst.mojangapi.world.player.PlayerCoordinates; import amidst.parsing.FormatException; @Immutable public class SaveDirectoryService { private final AmidstBackupService amidstBackupService = new AmidstBackupService(); /** * Returns a new valid instance of the class SaveDirectory. It tries to use * the given file. If that is not valid it tires to use its parent file. If * that is also not valid it will throw a FileNotFoundException. */ @NotNull public SaveDirectory newSaveDirectory(Path file) throws FileNotFoundException { Path currentFile = file; SaveDirectory result = null; if (currentFile == null) { // error } else { result = createValidSaveDirectory(currentFile); currentFile = currentFile.getParent(); if (result != null) { return result; } else if (currentFile == null) { // error } else { result = createValidSaveDirectory(currentFile); currentFile = currentFile.getParent(); if (result != null) { return result; } else { // error } } } throw new FileNotFoundException("unable to load save directory: " + file); } private SaveDirectory createValidSaveDirectory(Path currentFile) { SaveDirectory result = new SaveDirectory(currentFile); if (result.isValid()) { return result; } else { return null; } } public LevelDatNbt readLevelDat(SaveDirectory saveDirectory) throws IOException, FormatException { return LevelDatNbt.from(saveDirectory.getLevelDat()); } /** * We need to let the user decide if he wants to load the singleplayer * player from the level.dat file or if he wants to load the multiplayer * players. That is, because a singleplayer map will have the playerdata * directory. It contains information about each player that ever played on * the map. However, if the map is loaded as singleplayer map, minecraft * will use the information that is stored in the level.dat file. It will * also overwrite the file in the playerdata directory that belongs to the * player that loaded the map in singleplayer mode. So, if we change the * player location in the playerdata directory it will just be ignored if * the map is used as singleplayer map. */ @NotNull public Optional<PlayerNbt> tryReadSingleplayerPlayerNbt(SaveDirectory saveDirectory) { AmidstLogger.info("using player from level.dat"); return tryReadCoordinatesFromLevelDat(saveDirectory).map(this::createLevelDatPlayerNbt); } /** * Since version 1.7.6, minecraft stores players in the playerdata directory * and uses the player uuid as filename. */ @NotNull public List<PlayerNbt> tryReadMultiplayerPlayerNbts(SaveDirectory saveDirectory) { List<PlayerNbt> playerdataPlayers = listFiles(saveDirectory.getPlayerdata()) .filter(Files::isRegularFile) .map(f -> createPlayerdataPlayerNbt(saveDirectory, f)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); if (!playerdataPlayers.isEmpty()) { AmidstLogger.info("using players from the playerdata directory"); return playerdataPlayers; } else { List<PlayerNbt> playersPlayers = listFiles(saveDirectory.getPlayers()) .filter(Files::isRegularFile) .map(f -> createPlayersPlayerNbt(saveDirectory, f)) .filter(Optional::isPresent) .map(Optional::get) .collect(Collectors.toList()); if (!playersPlayers.isEmpty()) { AmidstLogger.info("using players from the players directory"); return playersPlayers; } else { AmidstLogger.info("no multiplayer players found"); return Collections.emptyList(); } } } private Stream<Path> listFiles(Path directory) { if (Files.isDirectory(directory)) { try { return Files.list(directory); } catch (IOException e) { AmidstLogger.error(e, "Error while reading directory " + directory); } } return Stream.empty(); } private Optional<PlayerNbt> createPlayerdataPlayerNbt(SaveDirectory saveDirectory, Path playerdataFile) { String playerUUID = getPlayerUUIDFromPlayerdataFile(playerdataFile); return tryReadCoordinatesFromPlayerdata(saveDirectory, playerUUID) .map(c -> createPlayerdataPlayerNbt(playerUUID, c)); } private String getPlayerUUIDFromPlayerdataFile(Path playerdataFile) { return playerdataFile.getFileName().toString().split("\\.")[0]; } private Optional<PlayerNbt> createPlayersPlayerNbt(SaveDirectory saveDirectory, Path playersFile) { String playerName = getPlayerNameFromPlayersFile(playersFile); return tryReadCoordinatesFromPlayers(saveDirectory, playerName).map(c -> createPlayersPlayerNbt(playerName, c)); } private String getPlayerNameFromPlayersFile(Path playersFile) { return playersFile.getFileName().toString().split("\\.")[0]; } private PlayerNbt createLevelDatPlayerNbt(PlayerCoordinates playerCoordinates) { return new PlayerNbt(playerCoordinates) { @Override public <R> R map( Supplier<R> ifIsLevelDat, Function<String, R> ifIsPlayerdata, Function<String, R> ifIsPlayers) { return ifIsLevelDat.get(); } }; } private PlayerNbt createPlayerdataPlayerNbt(String playerUUID, PlayerCoordinates playerCoordinates) { return new PlayerNbt(playerCoordinates) { @Override public <R> R map( Supplier<R> ifIsLevelDat, Function<String, R> ifIsPlayerdata, Function<String, R> ifIsPlayers) { return ifIsPlayerdata.apply(playerUUID); } }; } private PlayerNbt createPlayersPlayerNbt(String playerName, PlayerCoordinates playerCoordinates) { return new PlayerNbt(playerCoordinates) { @Override public <R> R map( Supplier<R> ifIsLevelDat, Function<String, R> ifIsPlayerdata, Function<String, R> ifIsPlayers) { return ifIsPlayers.apply(playerName); } }; } private Optional<PlayerCoordinates> tryReadCoordinatesFromLevelDat(SaveDirectory saveDirectory) { try { return PlayerLocationLoader.tryReadFromLevelDat(saveDirectory.getLevelDat()); } catch (IOException e) { AmidstLogger.warn(e, "error while reading player coordinates from level.dat"); return Optional.empty(); } } private Optional<PlayerCoordinates> tryReadCoordinatesFromPlayerdata( SaveDirectory saveDirectory, String playerUUID) { try { return PlayerLocationLoader.tryReadFromPlayerFile(saveDirectory.getPlayerdataFile(playerUUID)); } catch (IOException e) { AmidstLogger.warn(e, "error while reading player coordinates for player {}", playerUUID); return Optional.empty(); } } private Optional<PlayerCoordinates> tryReadCoordinatesFromPlayers(SaveDirectory saveDirectory, String playerName) { try { return PlayerLocationLoader.tryReadFromPlayerFile(saveDirectory.getPlayersFile(playerName)); } catch (IOException e) { AmidstLogger.warn(e, "error while reading player coordinates for player {}", playerName); return Optional.empty(); } } public boolean tryBackup(SaveDirectory saveDirectory, PlayerNbt playerNbt) { return playerNbt.map( () -> amidstBackupService.tryBackupLevelDat(saveDirectory), playerUUID -> amidstBackupService.tryBackupPlayerdataFile(saveDirectory, playerUUID), playerName -> amidstBackupService.tryBackupPlayersFile(saveDirectory, playerName)); } public boolean tryWriteCoordinates( SaveDirectory saveDirectory, PlayerNbt playerNbt, PlayerCoordinates coordinates) { return playerNbt.map( () -> tryWriteCoordinatesToLevelDat(saveDirectory, coordinates), playerUUID -> tryWriteCoordinatesToPlayerdata(saveDirectory, playerUUID, coordinates), playerName -> tryWriteCoordinatesToPlayers(saveDirectory, playerName, coordinates)); } private boolean tryWriteCoordinatesToLevelDat(SaveDirectory saveDirectory, PlayerCoordinates coordinates) { try { return PlayerLocationSaver.tryWriteToLevelDat(coordinates, saveDirectory.getLevelDat()); } catch (IOException e) { AmidstLogger.warn(e, "error while writing player coordinates to level.dat"); return false; } } private boolean tryWriteCoordinatesToPlayerdata( SaveDirectory saveDirectory, String playerUUID, PlayerCoordinates coordinates) { try { return PlayerLocationSaver.tryWriteToPlayerFile(coordinates, saveDirectory.getPlayerdataFile(playerUUID)); } catch (IOException e) { AmidstLogger.warn(e, "error while writing player coordinates for player {}", playerUUID); return false; } } private boolean tryWriteCoordinatesToPlayers( SaveDirectory saveDirectory, String playerName, PlayerCoordinates coordinates) { try { return PlayerLocationSaver.tryWriteToPlayerFile(coordinates, saveDirectory.getPlayersFile(playerName)); } catch (IOException e) { AmidstLogger.warn(e, "error while writing player coordinates for player {}", playerName); return false; } } }
amidst
src\main\java\amidst\mojangapi\file\json\filter\WorldFilterJson_Biome.java
package amidst.mojangapi.file.json.filter; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; import amidst.logging.AmidstLogger; import amidst.logging.AmidstMessageBox; import amidst.mojangapi.world.biome.BiomeList; import amidst.mojangapi.world.biome.UnknownBiomeNameException; import amidst.mojangapi.world.filter.WorldFilter_Biome; @Immutable public class WorldFilterJson_Biome { private volatile long distance; private volatile List<String> biomes = Collections.emptyList(); private final BiomeList biomeList; @GsonConstructor public WorldFilterJson_Biome(BiomeList biomeList) { this.biomeList = biomeList; } public void validate(List<String> notifications) { if (biomes.isEmpty()) { notifications.add("No biomes for filter"); } else { for (String name : biomes) { if (!biomeList.doesNameExist(name)) { notifications.add("invalid biome name: '" + name + "'"); } } } } public WorldFilter_Biome createBiomeFilter() { return new WorldFilter_Biome(distance, createValidBiomeIndexes()); } private Set<Short> createValidBiomeIndexes() { Set<Short> result = new HashSet<>(); for (String name : biomes) { try { result.add((short) biomeList.getBiomeFromName(name).getId()); } catch (UnknownBiomeNameException e) { AmidstLogger.error(e); AmidstMessageBox.displayError("Error", e); } } return result; } }
amidst
src\main\java\amidst\mojangapi\file\json\filter\WorldFilterJson_MatchAll.java
package amidst.mojangapi.file.json.filter; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Optional; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; import amidst.logging.AmidstLogger; import amidst.mojangapi.world.filter.WorldFilter; import amidst.mojangapi.world.filter.WorldFilter_MatchAll; import amidst.parsing.FormatException; import amidst.parsing.json.JsonReader; @Immutable public class WorldFilterJson_MatchAll { public static Optional<WorldFilterJson_MatchAll> from(String queryString) { try { return Optional.of(JsonReader.readString(queryString, WorldFilterJson_MatchAll.class)); } catch (FormatException e) { return Optional.empty(); } } private volatile List<WorldFilterJson_Biome> biomeFilters = Collections.emptyList(); private volatile List<WorldFilterJson_Structure> structureFilters = Collections.emptyList(); @GsonConstructor public WorldFilterJson_MatchAll() { } public List<String> getValidationMessages() { List<String> result = new LinkedList<>(); validate(result); return result; } private void validate(List<String> notifications) { biomeFilters.forEach(f -> f.validate(notifications)); structureFilters.forEach(f -> f.validate(notifications)); } public WorldFilter createWorldFilter() { // TODO: the size is 0, because this filter will never use its biome // data return new WorldFilter_MatchAll(0, createFilterList()); } public Optional<WorldFilter> createValidWorldFilter() { if (getValidationMessages().isEmpty()) { return Optional.of(createWorldFilter()); } else { // TODO: use error messages AmidstLogger.debug(getValidationMessages().toString()); return Optional.empty(); } } private List<WorldFilter> createFilterList() { List<WorldFilter> filters = new ArrayList<>(); for (WorldFilterJson_Biome biomeFilterJson : biomeFilters) { filters.add(biomeFilterJson.createBiomeFilter()); } for (WorldFilterJson_Structure structureFilterJson : structureFilters) { filters.add(structureFilterJson.createStructureFilter()); } return filters; } }
amidst
src\main\java\amidst\mojangapi\file\json\filter\WorldFilterJson_Structure.java
package amidst.mojangapi.file.json.filter; import java.util.List; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; import amidst.mojangapi.world.filter.WorldFilter_Structure; import amidst.mojangapi.world.icon.type.DefaultWorldIconTypes; @Immutable public class WorldFilterJson_Structure { private volatile long distance; private volatile String structure; private volatile int minimum; @GsonConstructor public WorldFilterJson_Structure() { } public void validate(List<String> notifications) { if (!DefaultWorldIconTypes.exists(structure)) { notifications.add("invalid structure: '" + structure + "'"); } if (minimum <= 0) { notifications.add("invalid minimum: " + minimum); } } public WorldFilter_Structure createStructureFilter() { return new WorldFilter_Structure(distance, DefaultWorldIconTypes.getByName(structure), minimum); } }
amidst
src\main\java\amidst\mojangapi\file\json\launcherprofiles\LauncherProfileJson.java
package amidst.mojangapi.file.json.launcherprofiles; import java.util.List; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; import amidst.mojangapi.file.json.ReleaseType; @Immutable public class LauncherProfileJson { /** * Some Minecraft installations using the legacy launcher have a profile * with the key "(Default)" and no properties in the actual profile object. * * The JSON looks like this: * "(Default)": {}, * * This profile has the name null. Also, it cannot be deleted from the * launcher. I guess this is a bug in the minecraft launcher. However, the * minecraft launcher displays it with an empty string as name and it uses * the latest stable release for it, so we do the same. */ private volatile String name = ""; private volatile String lastVersionId; private volatile String gameDir; private volatile String icon; private volatile List<ReleaseType> allowedReleaseTypes = ProfileType.LATEST_RELEASE.getAllowedReleaseTypes().get(); private volatile ProfileType type = ProfileType.LEGACY; @GsonConstructor public LauncherProfileJson() { } public String getName() { return type.getDefaultName().orElse(name); } public String getLastVersionId() { return lastVersionId; } public String getGameDir() { return gameDir; } public String getIcon() { return icon; } public List<ReleaseType> getAllowedReleaseTypes() { return type.getAllowedReleaseTypes().orElse(allowedReleaseTypes); } }
amidst
src\main\java\amidst\mojangapi\file\json\launcherprofiles\LauncherProfilesJson.java
package amidst.mojangapi.file.json.launcherprofiles; import java.util.Collections; import java.util.Map; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class LauncherProfilesJson { private volatile Map<String, LauncherProfileJson> profiles = Collections.emptyMap(); @GsonConstructor public LauncherProfilesJson() { } public Map<String, LauncherProfileJson> getProfiles() { return profiles; } }
amidst
src\main\java\amidst\mojangapi\file\json\launcherprofiles\ProfileType.java
package amidst.mojangapi.file.json.launcherprofiles; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import com.google.gson.annotations.SerializedName; import amidst.documentation.Immutable; import amidst.mojangapi.file.json.ReleaseType; /** Profiles types, as used in the new profile format (2) used by the Windows launcher. * A typical installation has to profiles created by default, of type * LATEST_RELEASE and LATEST_SNAPSHOT, and their names can't be changed. * * The LEGACY profile represents a profile in the format used by the old launcher (1). */ @Immutable public enum ProfileType { @SerializedName("latest-release") LATEST_RELEASE("Latest version", ReleaseType.RELEASE), @SerializedName("latest-snapshot") LATEST_SNAPSHOT("Latest snapshot", ReleaseType.RELEASE, ReleaseType.SNAPSHOT), @SerializedName("custom") CUSTOM(null), @SerializedName("") LEGACY(null), ; private Optional<String> defaultName; private Optional<List<ReleaseType>> allowedReleaseTypes; private ProfileType(String defaultName, ReleaseType... releaseTypes) { this.defaultName = Optional.ofNullable(defaultName); if(releaseTypes.length > 0) { this.allowedReleaseTypes = Optional.of(Collections.unmodifiableList(Arrays.asList(releaseTypes))); } else { this.allowedReleaseTypes = Optional.empty(); } } public Optional<String> getDefaultName() { return defaultName; } public Optional<List<ReleaseType>> getAllowedReleaseTypes() { return allowedReleaseTypes; } }
amidst
src\main\java\amidst\mojangapi\file\json\player\MetadataJson.java
package amidst.mojangapi.file.json.player; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class MetadataJson { private volatile String model; @GsonConstructor public MetadataJson() { } public String getModel() { return model; } }
amidst
src\main\java\amidst\mojangapi\file\json\player\PlayerJson.java
package amidst.mojangapi.file.json.player; import java.util.Collections; import java.util.List; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class PlayerJson { private volatile String id; private volatile String name; private volatile List<PropertyJson> properties = Collections.emptyList(); @GsonConstructor public PlayerJson() { } public String getId() { return id; } public String getName() { return name; } public List<PropertyJson> getProperties() { return properties; } }
amidst
src\main\java\amidst\mojangapi\file\json\player\PropertyJson.java
package amidst.mojangapi.file.json.player; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class PropertyJson { private volatile String name; private volatile String value; @GsonConstructor public PropertyJson() { } public String getName() { return name; } public String getValue() { return value; } }
amidst
src\main\java\amidst\mojangapi\file\json\player\SimplePlayerJson.java
package amidst.mojangapi.file.json.player; import amidst.documentation.GsonConstructor; public class SimplePlayerJson { private String id; private String name; @GsonConstructor public SimplePlayerJson() { } public String getId() { return id; } public String getName() { return name; } }
amidst
src\main\java\amidst\mojangapi\file\json\player\SKINJson.java
package amidst.mojangapi.file.json.player; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class SKINJson { private volatile String url; private volatile MetadataJson metadata; @GsonConstructor public SKINJson() { } public String getUrl() { return url; } public MetadataJson getMetadata() { return metadata; } }
amidst
src\main\java\amidst\mojangapi\file\json\player\TexturesJson.java
package amidst.mojangapi.file.json.player; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class TexturesJson { private volatile SKINJson SKIN; @GsonConstructor public TexturesJson() { } public SKINJson getSKIN() { return SKIN; } }
amidst
src\main\java\amidst\mojangapi\file\json\player\TexturesPropertyJson.java
package amidst.mojangapi.file.json.player; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class TexturesPropertyJson { private volatile TexturesJson textures; @GsonConstructor public TexturesPropertyJson() { } public TexturesJson getTextures() { return textures; } }
amidst
src\main\java\amidst\mojangapi\file\json\version\LibraryJson.java
package amidst.mojangapi.file.json.version; import java.util.Collections; import java.util.List; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class LibraryJson { private volatile String name; private volatile List<LibraryRuleJson> rules = Collections.emptyList(); @GsonConstructor public LibraryJson() { } public String getName() { return name; } public List<LibraryRuleJson> getRules() { return rules; } }
amidst
src\main\java\amidst\mojangapi\file\json\version\LibraryRuleJson.java
package amidst.mojangapi.file.json.version; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class LibraryRuleJson { private volatile String action; private volatile LibraryRuleOsJson os; @GsonConstructor public LibraryRuleJson() { } public String getAction() { return action; } public LibraryRuleOsJson getOs() { return os; } }
amidst
src\main\java\amidst\mojangapi\file\json\version\LibraryRuleOsJson.java
package amidst.mojangapi.file.json.version; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class LibraryRuleOsJson { private volatile String name; private volatile String version; @GsonConstructor public LibraryRuleOsJson() { } public String getName() { return name; } public String getVersion() { return version; } }
amidst
src\main\java\amidst\mojangapi\file\json\version\VersionJson.java
package amidst.mojangapi.file.json.version; import java.util.Collections; import java.util.List; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class VersionJson { private volatile String id; private volatile String inheritsFrom; private volatile List<LibraryJson> libraries = Collections.emptyList(); @GsonConstructor public VersionJson() { } public String getId() { return id; } public String getInheritsFrom() { return inheritsFrom; } public List<LibraryJson> getLibraries() { return libraries; } }
amidst
src\main\java\amidst\mojangapi\file\json\versionlist\RemoteVersionJson.java
package amidst.mojangapi.file.json.versionlist; import java.net.URL; import amidst.documentation.GsonConstructor; import amidst.mojangapi.file.json.ReleaseType; public class RemoteVersionJson { private volatile String id; private volatile ReleaseType type; private volatile Inner downloads; @GsonConstructor public RemoteVersionJson() { } public String getId() { return id; } public ReleaseType getType() { return type; } public URL getClientUrl() { return downloads.client == null ? null : downloads.client.url; } public URL getServerUrl() { return downloads.server == null ? null : downloads.server.url; } private static class Inner { public volatile Download client; public volatile Download server; @GsonConstructor public Inner() { } } private static class Download { public volatile URL url; @GsonConstructor public Download() { } } }
amidst
src\main\java\amidst\mojangapi\file\json\versionlist\VersionListEntryJson.java
package amidst.mojangapi.file.json.versionlist; import java.net.URL; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; import amidst.mojangapi.file.json.ReleaseType; @Immutable public class VersionListEntryJson { private volatile String id; private volatile ReleaseType type; private volatile URL url; @GsonConstructor public VersionListEntryJson() { } public String getId() { return id; } public ReleaseType getType() { return type; } public URL getMetaUrl() { return url; } }
amidst
src\main\java\amidst\mojangapi\file\json\versionlist\VersionListJson.java
package amidst.mojangapi.file.json.versionlist; import java.util.Collections; import java.util.List; import amidst.documentation.GsonConstructor; import amidst.documentation.Immutable; @Immutable public class VersionListJson { private volatile List<VersionListEntryJson> versions = Collections.emptyList(); @GsonConstructor public VersionListJson() { } public List<VersionListEntryJson> getVersions() { return versions; } }
amidst
src\main\java\amidst\mojangapi\file\nbt\player\PlayerLocationLoader.java
package amidst.mojangapi.file.nbt.player; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; import net.querz.nbt.tag.CompoundTag; import net.querz.nbt.tag.ListTag; import net.querz.nbt.tag.NumberTag; import net.querz.nbt.tag.Tag; import amidst.documentation.Immutable; import amidst.logging.AmidstLogger; import amidst.mojangapi.file.nbt.NBTTagKeys; import amidst.mojangapi.file.nbt.NBTUtils; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.player.PlayerCoordinates; @Immutable public enum PlayerLocationLoader { ; public static Optional<PlayerCoordinates> tryReadFromPlayerFile(Path file) throws IOException { try { return Optional.of(readPlayerCoordinates(NBTUtils.readTagFromFile(file))); } catch (NullPointerException | ClassCastException e) { AmidstLogger.warn(e, "cannot read player from file: {}", file); return Optional.empty(); } } public static Optional<PlayerCoordinates> tryReadFromLevelDat(Path path) throws IOException { try { return Optional .of(readPlayerCoordinates(getSinglePlayerPlayerTag(getTagRootTag(NBTUtils.readTagFromFile(path))))); } catch (NullPointerException | ClassCastException e) { AmidstLogger.warn(e, "cannot read player from level.dat: {}", path); return Optional.empty(); } } private static CompoundTag getTagRootTag(CompoundTag rootTag) { return rootTag.get(NBTTagKeys.TAG_KEY_DATA, CompoundTag.class); } private static CompoundTag getSinglePlayerPlayerTag(CompoundTag rootDataTag) { return rootDataTag.get(NBTTagKeys.TAG_KEY_PLAYER, CompoundTag.class); } private static PlayerCoordinates readPlayerCoordinates(CompoundTag tag) { Tag<?> dimensionTag = tag.get(NBTTagKeys.TAG_KEY_DIMENSION); Dimension dimension; if (dimensionTag instanceof NumberTag<?>) { dimension = Dimension.fromId(((NumberTag<?>) dimensionTag).asInt()); } else { dimension = Dimension.fromName(dimensionTag.valueToString()); } ListTag<?> posList = getTagPos(tag); return PlayerCoordinates.fromNBTFile( NBTUtils.getLongValue(posList.get(0)), NBTUtils.getLongValue(posList.get(1)), NBTUtils.getLongValue(posList.get(2)), dimension); } private static ListTag<?> getTagPos(CompoundTag tag) { return tag.get(NBTTagKeys.TAG_KEY_POS, ListTag.class); } }
amidst
src\main\java\amidst\mojangapi\file\nbt\player\PlayerLocationSaver.java
package amidst.mojangapi.file.nbt.player; import java.io.IOException; import java.nio.file.Path; import java.util.function.UnaryOperator; import net.querz.nbt.tag.CompoundTag; import net.querz.nbt.tag.DoubleTag; import net.querz.nbt.tag.ListTag; import amidst.documentation.Immutable; import amidst.logging.AmidstLogger; import amidst.mojangapi.file.nbt.NBTTagKeys; import amidst.mojangapi.file.nbt.NBTUtils; import amidst.mojangapi.world.player.PlayerCoordinates; @Immutable public enum PlayerLocationSaver { ; public static boolean tryWriteToPlayerFile(PlayerCoordinates coordinates, Path file) throws IOException { try { CompoundTag dataTag = NBTUtils.readTagFromFile(file); CompoundTag modifiedDataTag = modifyPositionInMultiPlayer(dataTag, coordinates); NBTUtils.writeTagToFile(file, modifiedDataTag); return true; } catch (NullPointerException | ClassCastException e) { AmidstLogger.warn(e, "cannot write player to file: {}", file); return false; } } public static boolean tryWriteToLevelDat(PlayerCoordinates coordinates, Path path) throws IOException { try { CompoundTag dataTag = NBTUtils.readTagFromFile(path); CompoundTag modifiedDataTag = modifyPositionInSinglePlayer(dataTag, coordinates); NBTUtils.writeTagToFile(path, modifiedDataTag); return true; } catch (NullPointerException | ClassCastException e) { AmidstLogger.warn(e, "cannot write player to level.dat: {}", path); return false; } } private static CompoundTag modifyPositionInMultiPlayer(CompoundTag dataTag, PlayerCoordinates coordinates) { return modifyDataRoot(dataTag, root -> modifyPositionInPlayerTag(root, coordinates)); } private static CompoundTag modifyPositionInSinglePlayer(CompoundTag dataTag, PlayerCoordinates coordinates) { return modifyDataRoot(dataTag, root -> { CompoundTag player = root.get(NBTTagKeys.TAG_KEY_PLAYER, CompoundTag.class); CompoundTag modifiedPlayer = modifyPositionInPlayerTag(player, coordinates); CompoundTag result = NBTUtils.shallowCopy(root); result.put(NBTTagKeys.TAG_KEY_PLAYER, modifiedPlayer); return result; }); } private static CompoundTag modifyDataRoot(CompoundTag dataTag, UnaryOperator<CompoundTag> modifier) { CompoundTag root = dataTag.get(NBTTagKeys.TAG_KEY_DATA, CompoundTag.class); CompoundTag modifiedRoot = modifier.apply(root); CompoundTag result = NBTUtils.shallowCopy(dataTag); result.put(NBTTagKeys.TAG_KEY_DATA, modifiedRoot); return result; } private static CompoundTag modifyPositionInPlayerTag(CompoundTag dataTag, PlayerCoordinates coordinates) { CompoundTag result = NBTUtils.shallowCopy(dataTag); result.put(NBTTagKeys.TAG_KEY_POS, getPosListForCoordinates(coordinates)); return result; } private static ListTag<?> getPosListForCoordinates(PlayerCoordinates coordinates) { ListTag<DoubleTag> posList = new ListTag<>(DoubleTag.class); posList.addDouble(coordinates.getXForNBTFile()); posList.addDouble(coordinates.getYForNBTFile()); posList.addDouble(coordinates.getZForNBTFile()); return posList; } }
amidst
src\main\java\amidst\mojangapi\file\nbt\player\PlayerNbt.java
package amidst.mojangapi.file.nbt.player; import java.util.function.Function; import java.util.function.Supplier; import amidst.documentation.Immutable; import amidst.mojangapi.world.player.PlayerCoordinates; @Immutable public abstract class PlayerNbt { private final PlayerCoordinates playerCoordinates; public PlayerNbt(PlayerCoordinates playerCoordinates) { this.playerCoordinates = playerCoordinates; } public PlayerCoordinates getPlayerCoordinates() { return playerCoordinates; } public abstract <R> R map( Supplier<R> ifIsLevelDat, Function<String, R> ifIsPlayerdata, Function<String, R> ifIsPlayers); }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\BetaClassTranslator.java
package amidst.mojangapi.minecraftinterface.legacy; import amidst.clazz.real.RealClass; import amidst.clazz.translator.ClassTranslator; import amidst.mojangapi.minecraftinterface.RecognisedVersion; import java.util.Objects; public enum BetaClassTranslator { INSTANCE; // @formatter:off public static ClassTranslator get(RecognisedVersion version) { return ClassTranslator .builder() .ifDetect(c -> c.searchForInt(5169201)) .thenDeclareRequired(BetaSymbolicNames.CLASS_BIOME) .requiredMethod(BetaSymbolicNames.METHOD_BIOME_FROM_TUPLE, "a").real("float").real("float").end() .next() .ifDetect(c -> c.searchForLong(9871L) && c.searchForLong(39811L) && c.searchForLong(543321L)) .thenDeclareRequired(BetaSymbolicNames.CLASS_BIOMEGENERATOR) .requiredMethod(BetaSymbolicNames.METHOD_BIOMEGENERATOR_GET_BIOME, "a").symbolicArray(BetaSymbolicNames.CLASS_BIOME, 1).real("int").real("int").real("int").real("int").end() .requiredField(BetaSymbolicNames.FIELD_BIOMEGENERATOR_TEMPERATURE, "a") .requiredField(BetaSymbolicNames.FIELD_BIOMEGENERATOR_RAINFALL, "b") .next() .ifDetect(BetaClassTranslator::isDimensionBase) .thenDeclareRequired(BetaSymbolicNames.CLASS_DIMENSION_BASE) .requiredField(BetaSymbolicNames.FIELD_DIMENSION_WORLD, "a") .requiredField(BetaSymbolicNames.FIELD_DIMENSION_BIOMEGENERATOR, "b") .next() .ifDetect((c, mappedNames) -> RecognisedVersion.isOlder(version, RecognisedVersion._b1_6_6) ? isDimensionBase(c) : c.getNumberOfFields() == 0 && c.getNumberOfMethods() == 0 && mappedNames.get(BetaSymbolicNames.CLASS_DIMENSION_BASE).equals(c.getRealSuperClassName())) .thenDeclareRequired(BetaSymbolicNames.CLASS_DIMENSION_OVERWORLD) .next() .ifDetect(c -> { int nMethods = RecognisedVersion.isOlder(version, RecognisedVersion._b1_6_6) ? 5 : 6; return c.getNumberOfFields() == 0 && c.getNumberOfConstructors() == 0 && c.getNumberOfMethods() == nMethods && c.isInterface() && c.hasMethodWithRealArgsReturning("void"); }) .thenDeclareRequired(BetaSymbolicNames.INTERFACE_SOMETHING) .next() .ifDetect(c -> c.searchForInt(1013904223)) .thenDeclareRequired(BetaSymbolicNames.CLASS_WORLD) .optionalConstructor(BetaSymbolicNames.CONSTRUCTOR_WORLD).real("String").symbolic(BetaSymbolicNames.CLASS_DIMENSION_BASE).real("long").end() .optionalConstructor(BetaSymbolicNames.CONSTRUCTOR_WORLD).symbolic(BetaSymbolicNames.INTERFACE_SOMETHING).real("String").symbolic(BetaSymbolicNames.CLASS_DIMENSION_BASE).real("long").end() .next() .ifDetect(c -> c.searchForDouble(10.0) && c.hasConstructorWithRealArgs("java/util/Random", "int") && c.hasMethodWithRealArgsReturning("double", "double", "double") && c.hasMethodWithRealArgsReturning(null, "double", "double", "double", "int", "int", "int", "double", "double", "double", null) && c.getNumberOfConstructors() == 1 && c.getNumberOfMethods() == 3 && c.getNumberOfFields() == 2 ) .thenDeclareRequired(BetaSymbolicNames.CLASS_PERLIN_OCTAVE_NOISE) .requiredMethod(BetaSymbolicNames.METHOD_PERLIN_OCTAVE_NOISE_SAMPLE_3D, "a").realArray("double", 1).real("double").real("double").real("double").real("int").real("int").real("int").real("double").real("double").real("double").end() .requiredMethod(BetaSymbolicNames.METHOD_PERLIN_OCTAVE_NOISE_SAMPLE_2D, "a").realArray("double", 1).real("int").real("int").real("int").real("int").real("double").real("double").real("double").end() .requiredField(BetaSymbolicNames.FIELD_PERLIN_OCTAVE_NOISE_OCTAVES, "a") .next() .ifDetect(c -> c.searchForDouble(109.0134)) .thenDeclareRequired(BetaSymbolicNames.CLASS_OVERWORLD_LEVEL_SOURCE) .requiredConstructor(BetaSymbolicNames.CONSTRUCTOR_OVERWORLD_LEVEL_SOURCE).symbolic(BetaSymbolicNames.CLASS_WORLD).real("long").end() .requiredMethod(BetaSymbolicNames.METHOD_OVERWORLD_LEVEL_SOURCE_SHAPE_CHUNK, "a").real("int").real("int").realArray("byte", 1).symbolicArray(BetaSymbolicNames.CLASS_BIOME, 1).realArray("double", 1).end() .requiredField(BetaSymbolicNames.FIELD_UPPER_INTERPOLATION_NOISE, "k") .requiredField(BetaSymbolicNames.FIELD_LOWER_INTERPOLATION_NOISE, "l") .requiredField(BetaSymbolicNames.FIELD_INTERPOLATION_NOISE, "m") .requiredField(BetaSymbolicNames.FIELD_BIOME_NOISE, "a") .requiredField(BetaSymbolicNames.FIELD_DEPTH_NOISE, "b") .next() .ifDetect(c -> c.searchForDouble(6.0) && c.searchForDouble(15.0) && c.getNumberOfFields() == 4 && c.getNumberOfConstructors() == 2 && c.hasMethodWithRealArgsReturning("[double", "double", "double", "double", "int", "int", "int", "double", "double", "double", "double", null)) .thenDeclareRequired(BetaSymbolicNames.CLASS_PERLIN_NOISE) .requiredField(BetaSymbolicNames.FIELD_PERLIN_NOISE_PERMUTATIONS, "d") .requiredField(BetaSymbolicNames.FIELD_PERLIN_NOISE_X_OFFSET, "a") .requiredField(BetaSymbolicNames.FIELD_PERLIN_NOISE_Y_OFFSET, "b") .requiredField(BetaSymbolicNames.FIELD_PERLIN_NOISE_Z_OFFSET, "c") .construct(); } private static boolean isDimensionBase(RealClass c) { return c.searchForFloat(0.7529412f) && c.searchForFloat(0.84705883f); } // @formatter:on }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\BetaMinecraftInterface.java
package amidst.mojangapi.minecraftinterface.legacy; import amidst.clazz.symbolic.SymbolicClass; import amidst.clazz.symbolic.SymbolicObject; import amidst.mojangapi.minecraftinterface.MinecraftInterface; import amidst.mojangapi.minecraftinterface.MinecraftInterfaceException; import amidst.mojangapi.minecraftinterface.RecognisedVersion; import amidst.mojangapi.minecraftinterface.UnsupportedDimensionException; import amidst.mojangapi.world.Dimension; import amidst.mojangapi.world.WorldOptions; import amidst.mojangapi.world.versionfeatures.DefaultBiomes; import amidst.util.ChunkBasedGen; import java.lang.reflect.InvocationTargetException; import java.util.Collections; import java.util.Map; import java.util.Set; import java.util.function.Function; public class BetaMinecraftInterface implements MinecraftInterface { // Values in [0, 16] progressively increase the accuracy of ocean display, set to -1 to // disable ocean generation entirely. // Vanilla = 16 public static final int OCEAN_PRECISION = 4; // If set to false, only one layer of noise is generated at Y=64 and used directly, instead of // interpolating between two at Y=56 and Y=64. This will introduce inaccuracies, but also // half the amount of time spent on 3D noise. // Vanilla = true public static final boolean INTERPOLATE_NOISE_VERTICALLY = true; public static final RecognisedVersion LAST_COMPATIBLE_VERSION = RecognisedVersion._b1_7_3; private final RecognisedVersion recognisedVersion; private final SymbolicClass dimensionBaseClass; private final SymbolicClass worldClass; private final SymbolicClass overworldLevelSourceClass; private final BiomeMapping biomeMapping; private final SymbolicClass dimensionOverworldClass; private final SymbolicClass perlinNoiseClass; private BetaMinecraftInterface( SymbolicClass biomeClass, SymbolicClass dimensionBaseClass, SymbolicClass dimensionOverworldClass, SymbolicClass worldClass, SymbolicClass overworldLevelSourceClass, SymbolicClass perlinNoiseClass, RecognisedVersion recognisedVersion) { this.recognisedVersion = recognisedVersion; this.dimensionBaseClass = dimensionBaseClass; this.worldClass = worldClass; this.overworldLevelSourceClass = overworldLevelSourceClass; this.perlinNoiseClass = perlinNoiseClass; this.dimensionOverworldClass = dimensionOverworldClass; try { this.biomeMapping = new BiomeMapping(biomeClass); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("failed to get biomes", e); } } public BetaMinecraftInterface(Map<String, SymbolicClass> stringSymbolicClassMap, RecognisedVersion recognisedVersion) { this( stringSymbolicClassMap.get(BetaSymbolicNames.CLASS_BIOME), stringSymbolicClassMap.get(BetaSymbolicNames.CLASS_DIMENSION_BASE), stringSymbolicClassMap.get(BetaSymbolicNames.CLASS_DIMENSION_OVERWORLD), stringSymbolicClassMap.get(BetaSymbolicNames.CLASS_WORLD), stringSymbolicClassMap.get(BetaSymbolicNames.CLASS_OVERWORLD_LEVEL_SOURCE), stringSymbolicClassMap.get(BetaSymbolicNames.CLASS_PERLIN_NOISE), recognisedVersion); } @Override public WorldAccessor createWorldAccessor(WorldOptions worldOptions) throws MinecraftInterfaceException { try { SymbolicObject overworld = constructDimension(); SymbolicObject world = constructWorld(overworld, worldOptions); SymbolicObject biomeGenerator = getBiomeGenerator(overworld); SymbolicObject overworldLevelSource = constructOverworldLevelSource(world, worldOptions); return new OceanProvidingWorldAccessor(biomeGenerator, overworldLevelSource, OCEAN_PRECISION); } catch (InstantiationException | InvocationTargetException | IllegalAccessException | NoSuchMethodException e) { throw new MinecraftInterfaceException("Failed to create world accessor", e); } } @Override public RecognisedVersion getRecognisedVersion() { return recognisedVersion; } private SymbolicObject constructDimension() throws IllegalAccessException, InstantiationException { return new SymbolicObject(dimensionBaseClass, dimensionOverworldClass.getClazz().newInstance()); } private SymbolicObject constructWorld(SymbolicObject overworldDimension, WorldOptions worldOptions) throws InvocationTargetException, IllegalAccessException, InstantiationException { long seed = worldOptions.getWorldSeed().getLong(); Object[] params; if (RecognisedVersion.isOlder(recognisedVersion, RecognisedVersion._b1_3b)) { params = new Object[] {"level name", overworldDimension.getObject(), seed}; } else { params = new Object[] {null, "level name", overworldDimension.getObject(), seed}; } try { worldClass.callConstructor(BetaSymbolicNames.CONSTRUCTOR_WORLD, params); } catch (NullPointerException | InvocationTargetException ex) { // Bwahaha, too late! Before the World constructor raised this NullPointerException // (from trying to use a chunkLoader returned by NullSaveHandler instance, or by trying to get // a chunkLoader from a null SaveHandler, depending on what you passed as the first parameter // of the World constructor) it already assigned // its own seed field and called dimension.setWorld(this), so we have a reference to // a functional-enough World instance despite the constructor failing! // Plus, the Dimension instance has already used the partially constructed World instance // to create the BiomeGenerator, which is the whole goal of this, so World's work here is done. if (ex instanceof InvocationTargetException) { // If we pass a null for the SaveHandler parameter (which saves us having to // identify the obfuscated ISaveHandle interface and NullSaveHandler class) then // for some reason the NullPointerException bubbles up inside a InvocationTargetException, // so here I confirm that the exception is still a NullPointerException. if (!(((InvocationTargetException) ex).getTargetException() instanceof NullPointerException)) { throw (InvocationTargetException) ex; } } } return (SymbolicObject) dimensionBaseClass.getFieldValue(BetaSymbolicNames.FIELD_DIMENSION_WORLD, overworldDimension); } private SymbolicObject getBiomeGenerator(SymbolicObject overworld) throws IllegalAccessException { return (SymbolicObject) overworld.getFieldValue(BetaSymbolicNames.FIELD_DIMENSION_BIOMEGENERATOR); } private SymbolicObject constructOverworldLevelSource(SymbolicObject world, WorldOptions worldOptions) throws IllegalAccessException, InvocationTargetException, InstantiationException { return overworldLevelSourceClass.callConstructor(BetaSymbolicNames.CONSTRUCTOR_OVERWORLD_LEVEL_SOURCE, world.getObject(), worldOptions.getWorldSeed().getLong()); } private OceanOracle makeOceanOracle(SymbolicObject levelSource, int precision) throws IllegalAccessException { return new OceanOracle( (SymbolicObject) levelSource.getFieldValue(BetaSymbolicNames.FIELD_BIOME_NOISE), (SymbolicObject) levelSource.getFieldValue(BetaSymbolicNames.FIELD_DEPTH_NOISE), makeOctaveNoise((SymbolicObject) levelSource.getFieldValue(BetaSymbolicNames.FIELD_INTERPOLATION_NOISE), precision / 2), makeOctaveNoise((SymbolicObject) levelSource.getFieldValue(BetaSymbolicNames.FIELD_UPPER_INTERPOLATION_NOISE), precision), makeOctaveNoise((SymbolicObject) levelSource.getFieldValue(BetaSymbolicNames.FIELD_LOWER_INTERPOLATION_NOISE), precision) ); } private PerlinOctaveNoise makeOctaveNoise(SymbolicObject fieldValue, int precision) throws IllegalAccessException { return PerlinOctaveNoise.fromSymbolic(fieldValue, perlinNoiseClass, precision); } /** Provides both biomes and oceans, at a configurable precision. */ private class OceanProvidingWorldAccessor implements MinecraftInterface.WorldAccessor { private final SymbolicObject biomeGenerator; private final OceanOracle oceanOracle; private final boolean generateOceans; public OceanProvidingWorldAccessor(SymbolicObject biomeGenerator, SymbolicObject overworldLevelSource, int precision) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException, InstantiationException { this.biomeGenerator = biomeGenerator; this.oceanOracle = makeOceanOracle(overworldLevelSource, precision); this.generateOceans = precision >= 0; } @Override public <T> T getBiomeData(Dimension dimension, int x, int y, int width, int height, boolean useQuarterResolution, Function<int[], T> biomeDataMapper) throws MinecraftInterfaceException { if (dimension != Dimension.OVERWORLD) throw new UnsupportedDimensionException(dimension); // The "shapeChunk" method in OverworldLevelSource assumes that its BiomeGenerator was just called for a 16 * 16 area. // Thus, we need to generate biomes chunk-based. int[] result = ChunkBasedGen.mapChunkBased(x, y, width, height, useQuarterResolution, this::biomesInChunk); return biomeDataMapper.apply(result); } private int[] biomesInChunk(int chunkZ, int chunkX) throws MinecraftInterfaceException { try { // Generate real biomes using the BiomeGenerator Object[] biomes = getBiomes(chunkZ, chunkX); int[] out; if (generateOceans) { double[] temperatures = getTemperatures(); double[] rainfall = getRainfall(); out = oceanOracle.determineOceans(chunkX, chunkZ, null, temperatures, rainfall); } else { out = new int[256]; } // Combine that info return determineBiomes(out, biomes); } catch (IllegalAccessException | InvocationTargetException e) { throw new MinecraftInterfaceException("Failed to generate chunk!", e); } } private double[] getTemperatures() throws IllegalAccessException { return (double[]) biomeGenerator.getFieldValue(BetaSymbolicNames.FIELD_BIOMEGENERATOR_TEMPERATURE); } private double[] getRainfall() throws IllegalAccessException { return (double[]) biomeGenerator.getFieldValue(BetaSymbolicNames.FIELD_BIOMEGENERATOR_RAINFALL); } private Object[] getBiomes(int chunkZ, int chunkX) throws IllegalAccessException, InvocationTargetException { return (Object[]) biomeGenerator.callMethod(BetaSymbolicNames.METHOD_BIOMEGENERATOR_GET_BIOME, null, chunkX * 16, chunkZ * 16, 16, 16); } private int[] determineBiomes(int[] out, Object[] biomes) { for (int x = 0; x < 16; ++x) { for (int z = 0; z < 16; ++z) { int outIdx = x + z * 16; if (out[outIdx] == OceanOracle.OCEAN) { out[outIdx] = DefaultBiomes.ocean; } else if (out[outIdx] == OceanOracle.FROZEN_OCEAN) { out[outIdx] = DefaultBiomes.coldOcean; } else { out[outIdx] = biomeMapping.getBiomeInt(biomes[z + x * 16]); } } } return out; } @Override public Set<Dimension> supportedDimensions() { return Collections.singleton(Dimension.OVERWORLD); } } /** Handles mapping of Minecraft's Biome objects to out biome IDs. */ private static class BiomeMapping { private final Object tundra; private final Object taiga; private final Object savanna; private final Object shrubland; private final Object swampland; private final Object forest; private final Object desert; private final Object plains; private final Object seasonalForest; private final Object rainforest; public BiomeMapping(SymbolicClass biomeClass) throws InvocationTargetException, IllegalAccessException { // Matching the static fields containing each biome would be too much work. // Instead, just get the biomes by giving known (temperature, rainfall) inputs. this.tundra = getBiomeFrom(biomeClass, 0.0, 0.0); this.taiga = getBiomeFrom(biomeClass, 0.4, 1.0); this.savanna = getBiomeFrom(biomeClass, 0.6, 0.0); this.shrubland = getBiomeFrom(biomeClass, 0.6, 0.5); this.swampland = getBiomeFrom(biomeClass, 0.6, 1.0); this.forest = getBiomeFrom(biomeClass, 0.7, 1.0); this.desert = getBiomeFrom(biomeClass, 1.0, 0.0); this.plains = getBiomeFrom(biomeClass, 1.0, 0.3); this.seasonalForest = getBiomeFrom(biomeClass, 1.0, 0.6); this.rainforest = getBiomeFrom(biomeClass, 1.0, 1.0); } private static Object getBiomeFrom(SymbolicClass biomeClass, double temperature, double rainfall) throws InvocationTargetException, IllegalAccessException { return ((SymbolicObject) biomeClass.callStaticMethod(BetaSymbolicNames.METHOD_BIOME_FROM_TUPLE, (float) temperature, (float) rainfall)).getObject(); } public int getBiomeInt(Object biome) { // The game uses biomes like an enum, so we can simply check for identity rather than equality. if (biome == tundra) return DefaultBiomes.icePlains; if (biome == taiga) return DefaultBiomes.taiga; if (biome == savanna) return DefaultBiomes.savanna; if (biome == shrubland) return DefaultBiomes.savannaM; if (biome == swampland) return DefaultBiomes.swampland; if (biome == forest) return DefaultBiomes.forest; if (biome == desert) return DefaultBiomes.desert; if (biome == plains) return DefaultBiomes.plains; if (biome == seasonalForest) return DefaultBiomes.forestHills; if (biome == rainforest) return DefaultBiomes.jungle; return DefaultBiomes.theEnd; } } // This class is thread-safe private static class OceanOracle { // Outputs of determineOceans public static final int OCEAN = -1; public static final int FROZEN_OCEAN = -2; public static final int LAND = -3; // Arbitrary constants to make us generate the same noise as vanilla private static final int NOISE_POSITION_FACTOR = 4; private static final double BIOME_NOISE_SCALE = 1.121; private static final double DEPTH_NOISE_SCALE = 200.0; private static final double MAIN_INTERPOLATION_SCALE_XZ = 8.555150000000001; private static final double MAIN_INTERPOLATION_SCALE_Y = 4.277575000000001; private static final double OTHER_INTERPOLATION_SCALE = 684.412; // Offsets to deal with the fact that vanilla generates noise for all Y values private static final double VANILLA_NOISE_HEIGHT = 17; private static final double NOISE_HEIGHT_OFFSET = INTERPOLATE_NOISE_VERTICALLY ? 7 : 8; // Dimensions of the noise arrays private static final int NOISE_WIDTH = 5; private static final int NOISE_HEIGHT = INTERPOLATE_NOISE_VERTICALLY ? 2 : 1; private static final int NOISE_DEPTH = 5; // Various noise sources private final SymbolicObject biomeNoise; private final SymbolicObject depthNoise; private final PerlinOctaveNoise interpolationNoise; private final PerlinOctaveNoise upperInterpolationNoise; private final PerlinOctaveNoise lowerInterpolationNoise; public OceanOracle(SymbolicObject biomeNoise, SymbolicObject depthNoise, PerlinOctaveNoise interpolationNoise, PerlinOctaveNoise upperInterpolationNoise, PerlinOctaveNoise lowerInterpolationNoise) { this.biomeNoise = biomeNoise; this.depthNoise = depthNoise; this.interpolationNoise = interpolationNoise; this.upperInterpolationNoise = upperInterpolationNoise; this.lowerInterpolationNoise = lowerInterpolationNoise; } public int[] determineOceans(int chunkX, int chunkZ, int[] oceansIn, double[] temperatureNoises, double[] rainfallNoises) throws InvocationTargetException, IllegalAccessException { int[] oceans = (oceansIn != null && oceansIn.length >= 16 * 16) ? oceansIn : new int[16 * 16]; double[] noises = this.calculateNoise(chunkX, chunkZ, NOISE_WIDTH, NOISE_HEIGHT, NOISE_DEPTH, temperatureNoises, rainfallNoises); for (int x = 0; x < 16; ++x) { for (int z = 0; z < 16; ++z) { double noiseAtPoint = NOISE_HEIGHT > 1 ? interpolateNoise3d(x, 63 % 8, z, noises, NOISE_HEIGHT, NOISE_DEPTH) : interpolateNoise2d(x, z, noises, NOISE_DEPTH); boolean isOcean = noiseAtPoint <= 0; boolean isFrozen = temperatureNoises[x * 16 + z] < 0.5; oceans[z * 16 + x] = isOcean ? (isFrozen ? FROZEN_OCEAN : OCEAN) : LAND; } } return oceans; } private double[] calculateNoise(int chunkX, int chunkZ, int noiseWidth, int noiseHeight, int noiseDepth, double[] temperatureNoises, double[] rainfallNoises) throws InvocationTargetException, IllegalAccessException { double[] noises = new double[noiseWidth * noiseHeight * noiseDepth]; int sampleX = chunkX * NOISE_POSITION_FACTOR; int sampleZ = chunkZ * NOISE_POSITION_FACTOR; // All sample methods are thread-safe, thus this doesn't require any locks. double[] biomeNoises = (double[]) biomeNoise.callMethod(BetaSymbolicNames.METHOD_PERLIN_OCTAVE_NOISE_SAMPLE_2D, null, sampleX, sampleZ, noiseWidth, noiseDepth, BIOME_NOISE_SCALE, BIOME_NOISE_SCALE, 0); double[] depthNoises = (double[]) depthNoise.callMethod(BetaSymbolicNames.METHOD_PERLIN_OCTAVE_NOISE_SAMPLE_2D, null, sampleX, sampleZ, noiseWidth, noiseDepth, DEPTH_NOISE_SCALE, DEPTH_NOISE_SCALE, 0); double[] interpolationNoises = interpolationNoise.sample3d(sampleX, NOISE_HEIGHT_OFFSET, sampleZ, noiseWidth, noiseHeight, noiseDepth, MAIN_INTERPOLATION_SCALE_XZ, MAIN_INTERPOLATION_SCALE_Y, MAIN_INTERPOLATION_SCALE_XZ); double[] upperInterpolationNoises = upperInterpolationNoise.sample3d(sampleX, NOISE_HEIGHT_OFFSET, sampleZ, noiseWidth, noiseHeight, noiseDepth, OTHER_INTERPOLATION_SCALE, OTHER_INTERPOLATION_SCALE, OTHER_INTERPOLATION_SCALE); double[] lowerInterpolationNoises = lowerInterpolationNoise.sample3d(sampleX, NOISE_HEIGHT_OFFSET, sampleZ, noiseWidth, noiseHeight, noiseDepth, OTHER_INTERPOLATION_SCALE, OTHER_INTERPOLATION_SCALE, OTHER_INTERPOLATION_SCALE); for(int xNoiseIdx = 0; xNoiseIdx < noiseWidth; ++xNoiseIdx) { for(int yNoiseIdx = 0; yNoiseIdx < noiseHeight; ++yNoiseIdx) { for(int zNoiseIdx = 0; zNoiseIdx < noiseDepth; ++zNoiseIdx) { int blockX = (int) Math.floor(16.0 / noiseWidth * (xNoiseIdx + 0.5)); int blockZ = (int) Math.floor(16.0 / noiseDepth * (zNoiseIdx + 0.5)); int climateIdx = blockX * 16 + blockZ; double temperature = temperatureNoises[climateIdx]; double rainfall = rainfallNoises[climateIdx]; int noise2dIdx = xNoiseIdx * noiseDepth + zNoiseIdx; double biome = biomeNoises[noise2dIdx]; double depth = depthNoises[noise2dIdx]; int noise3dIdx = (xNoiseIdx * noiseDepth + zNoiseIdx) * noiseHeight + yNoiseIdx; double upperInter = upperInterpolationNoises[noise3dIdx]; double lowerInter = lowerInterpolationNoises[noise3dIdx]; double inter = interpolationNoises[noise3dIdx]; double mergedNoise = mergeNoises(yNoiseIdx, biome, depth, upperInter, lowerInter, inter, temperature, rainfall); noises[noise3dIdx] = mergedNoise; } } } return noises; } /** Combines the noise values in just the right way. */ private static double mergeNoises(double yNoiseIdx, double biomeNoiseV, double depthNoiseV, double upperInterpolationNoiseV, double lowerInterpolationNoiseV, double interpolationNoiseV, double temperatureV, double rainfallV) { // This took a lot of trial and error to get right... double scaledRainfall = 1.0 - rainfallV * temperatureV; double biomeNoiseValue = biomeNoiseV / 512.0 + 0.5; double biomeFactor = Math.max(0, Math.min(1, biomeNoiseValue * (1 - Math.pow(scaledRainfall, 4)))); double upperInter = upperInterpolationNoiseV / 512.0; double lowerInter = lowerInterpolationNoiseV / 512.0; double mainInter = interpolationNoiseV / 20.0 + 0.5; double clampedInterpolated = PerlinNoise.lerp(Math.max(0, Math.min(1, mainInter)), upperInter, lowerInter); // Why are there so many conditionals for depth noise??? double depth1 = depthNoiseV / 8000.0; double depth2 = depth1 * (depth1 < 0 ? -0.8999999999999999 : 3.0) - 2.0; double depth3 = depth2 < 0 ? Math.max(-2, depth2) / 5.6 : Math.min(1, depth2) / 8.0; double depthAdjustedBiomeFactor = depth2 < 0 ? 0.5 : biomeFactor + 0.5; double depth4 = (NOISE_HEIGHT_OFFSET + yNoiseIdx - VANILLA_NOISE_HEIGHT * (0.5 + depth3 * 0.25)) * 12.0 / depthAdjustedBiomeFactor; double depth5 = depth4 < 0 ? depth4 * 4.0 : depth4; return clampedInterpolated - depth5; } @SuppressWarnings("DuplicateExpressions") private double interpolateNoise3d(int blockX, int blockY, int blockZ, double[] noises, int noiseHeight, int noiseDepth) { int idxX = blockX / 4; int idxY = blockY / 8; int idxZ = blockZ / 4; // Get the noise values surrounding this coordinate // variable names are noise[XYZ corner] // @formatter:off double noise000 = noises[((idxX ) * noiseDepth + idxZ ) * noiseHeight + idxY ]; double noise001 = noises[((idxX ) * noiseDepth + idxZ + 1) * noiseHeight + idxY ]; double noise010 = noises[((idxX ) * noiseDepth + idxZ ) * noiseHeight + idxY + 1]; double noise011 = noises[((idxX ) * noiseDepth + idxZ + 1) * noiseHeight + idxY + 1]; double noise100 = noises[((idxX + 1) * noiseDepth + idxZ ) * noiseHeight + idxY ]; double noise101 = noises[((idxX + 1) * noiseDepth + idxZ + 1) * noiseHeight + idxY ]; double noise110 = noises[((idxX + 1) * noiseDepth + idxZ ) * noiseHeight + idxY + 1]; double noise111 = noises[((idxX + 1) * noiseDepth + idxZ + 1) * noiseHeight + idxY + 1]; // @formatter:on double relX = blockX % 4; double relY = blockY % 8; double relZ = blockZ % 4; // interpolate X double noiseX00 = PerlinNoise.lerp(relX / 4, noise000, noise100); double noiseX01 = PerlinNoise.lerp(relX / 4, noise001, noise101); double noiseX10 = PerlinNoise.lerp(relX / 4, noise010, noise110); double noiseX11 = PerlinNoise.lerp(relX / 4, noise011, noise111); // interpolate Y double noiseXY0 = PerlinNoise.lerp(relY / 8, noiseX00, noiseX10); double noiseXY1 = PerlinNoise.lerp(relY / 8, noiseX01, noiseX11); // interpolate Z return PerlinNoise.lerp(relZ / 4, noiseXY0, noiseXY1); } private double interpolateNoise2d(int blockX, int blockZ, double[] noises, int noiseDepth) { int idxX = blockX / 4; int idxZ = blockZ / 4; double noise00 = noises[(idxX ) * noiseDepth + idxZ ]; double noise01 = noises[(idxX ) * noiseDepth + idxZ + 1]; double noise10 = noises[(idxX + 1) * noiseDepth + idxZ ]; double noise11 = noises[(idxX + 1) * noiseDepth + idxZ + 1]; double relX = blockX % 4; double relZ = blockZ % 4; // interpolate X double noiseX0 = PerlinNoise.lerp(relX / 4, noise00, noise10); double noiseX1 = PerlinNoise.lerp(relX / 4, noise01, noise11); // interpolate Z return PerlinNoise.lerp(relZ / 4, noiseX0, noiseX1); } } /** * A custom implementation of perlin octave noise to speed up interpolation noises * <p> * At full precision, over 95% of the time in shapeChunk would be spent generating the 3D interpolation noise. Only * 2 of the 16 generated y levels are relevant for oceans, so {@link PerlinNoise} is implemented to allow us to avoid * calculating the others. Additionally, this class allows us to configure how many octaves to actually use. Each * octave contributes only half as much as its successor, so using only 8 or even 4 of the 16 octaves can provide * a significant speedup while remaining very accurate. * <p> * We sadly are not able to just re-use Minecraft's perlin noise as that implementation is bugged so that * selecting a different starting Y value alters the results. Minecraft's perlin octave noise only allows us to * skip the n most significant octaves, which is counterproductive, so we had to re-implement that as well. * <p> * This class is immutable and thus thread-safe. */ private static class PerlinOctaveNoise { private final PerlinNoise[] octaves; // will not be modified private final int firstOctave; public PerlinOctaveNoise(PerlinNoise[] octaves, int firstOctave) { this.octaves = octaves; this.firstOctave = firstOctave; } /** Construct an instance by stealing the random state from Minecraft's implementation */ public static PerlinOctaveNoise fromSymbolic(SymbolicObject perlinOctaveNoise, SymbolicClass perlinNoiseClass, int octaveCount) throws IllegalAccessException { Object[] octaveObjects = (Object[]) perlinOctaveNoise.getFieldValue(BetaSymbolicNames.FIELD_PERLIN_OCTAVE_NOISE_OCTAVES); PerlinNoise[] octaves = new PerlinNoise[octaveObjects.length]; for (int i = 0; i < octaves.length; ++i) { octaves[i] = PerlinNoise.fromSymbolic(new SymbolicObject(perlinNoiseClass, octaveObjects[i])); } return new PerlinOctaveNoise(octaves, octaves.length - octaveCount); } public double[] sample3d(double x, double y, double z, int resX, int resY, int resZ, double scaleX, double scaleY, double scaleZ) { double[] resultArr = new double[resX * resY * resZ]; for (int i = firstOctave; i < octaves.length; ++i) { double inverseIntensity = 1.0 / (1 << i); octaves[i].sample(resultArr, x, y, z, resX, resY, resZ, scaleX * inverseIntensity, scaleY * inverseIntensity, scaleZ * inverseIntensity, inverseIntensity); } return resultArr; } } // This class is immutable, thus thread-safe. private static class PerlinNoise { private final int[] permutations; // will not be modified private final double xOffset; private final double yOffset; private final double zOffset; public PerlinNoise(int[] permutations, double xOffset, double yOffset, double zOffset) { this.permutations = permutations; this.xOffset = xOffset; this.yOffset = yOffset; this.zOffset = zOffset; } public static PerlinNoise fromSymbolic(SymbolicObject perlinNoise) throws IllegalAccessException { return new PerlinNoise( (int[]) perlinNoise.getFieldValue(BetaSymbolicNames.FIELD_PERLIN_NOISE_PERMUTATIONS), (double) perlinNoise.getFieldValue(BetaSymbolicNames.FIELD_PERLIN_NOISE_X_OFFSET), (double) perlinNoise.getFieldValue(BetaSymbolicNames.FIELD_PERLIN_NOISE_Y_OFFSET), (double) perlinNoise.getFieldValue(BetaSymbolicNames.FIELD_PERLIN_NOISE_Z_OFFSET) ); } public void sample(double[] array, double x, double y, double z, int resX, int resY, int resZ, double xScale, double yScale, double zScale, double scale) { for (int xIdx = 0; xIdx < resX; ++xIdx) { for (int zIdx = 0; zIdx < resZ; ++zIdx) { for (int yIdx = 0; yIdx < resY; ++yIdx) { double xPos = (x + xIdx) * xScale + xOffset; double yPos = (y + yIdx) * yScale + yOffset; double zPos = (z + zIdx) * zScale + zOffset; // The below is basically just perlinNoise(xPos, yPos, zPos), but some adjustments for Mojank. int cubeX = (int) Math.floor(xPos) & 255; int cubeY = (int) Math.floor(yPos) & 255; int cubeZ = (int) Math.floor(zPos) & 255; xPos -= Math.floor(xPos); yPos -= Math.floor(yPos); zPos -= Math.floor(zPos); double u = fade(xPos); double v = fade(yPos); double w = fade(zPos); // Minecraft re-uses the lerps from the previous y value if cubeY didn't change. // This is incorrect, as the lerps depend on yPos, not cubeY, so we need to figure out // which yPos minecraft would have used to generate the lerps for this index. int lastY = findLastLerpIndex(yScale, (int) Math.round(y + yIdx), cubeY); double[] lerps = calcBuggedLerps(yScale, xPos, zPos, cubeX, cubeZ, u, lastY); array[xIdx * resZ * resY + zIdx * resY + yIdx] += lerp(w, lerp(v, lerps[0], lerps[1]), lerp(v, lerps[2], lerps[3])) * (1 / scale); } } } } private int findLastLerpIndex(double yScale, int yIdx, int cubeY) { int searchIdx = yIdx; while (true) { double searchPos = searchIdx * yScale + yOffset; int searchCube = (int) Math.floor(searchPos) & 255; if (searchIdx < 0 || searchCube != cubeY) break; --searchIdx; } return searchIdx + 1; } private double[] calcBuggedLerps(double yScale, double xPos, double zPos, int cubeX, int cubeZ, double u, int yIdx) { double yPos = yIdx * yScale + yOffset; int cubeY = (int) Math.floor(yPos) & 255; yPos -= Math.floor(yPos); int A = permutations[cubeX] + cubeY; int AA = permutations[A] + cubeZ; int AB = permutations[A + 1] + cubeZ; int B = permutations[cubeX + 1] + cubeY; int BA = permutations[B] + cubeZ; int BB = permutations[B + 1] + cubeZ; double[] lerps = new double[4]; lerps[0] = lerp(u, grad(permutations[AA], xPos, yPos, zPos), grad(permutations[BA], xPos - 1, yPos, zPos)); lerps[1] = lerp(u, grad(permutations[AB], xPos, yPos - 1, zPos), grad(permutations[BB], xPos - 1, yPos - 1, zPos)); lerps[2] = lerp(u, grad(permutations[AA + 1], xPos, yPos, zPos - 1), grad(permutations[BA + 1], xPos - 1, yPos, zPos - 1)); lerps[3] = lerp(u, grad(permutations[AB + 1], xPos, yPos - 1, zPos - 1), grad(permutations[BB + 1], xPos - 1, yPos - 1, zPos - 1)); return lerps; } public static double fade(double t) { return t * t * t * (t * (t * 6 - 15) + 10); } public static double lerp(double t, double a, double b) { return a + t * (b - a); } public static double grad(int hash, double x, double y, double z) { int h = hash & 15; double u = h < 8 ? x : y; double v = h < 4 ? y : h == 12 || h == 14 ? x : z; return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); } } }
amidst
src\main\java\amidst\mojangapi\minecraftinterface\legacy\BetaSymbolicNames.java
package amidst.mojangapi.minecraftinterface.legacy; public enum BetaSymbolicNames { ; public static final String CLASS_BIOME = "Biome"; public static final String METHOD_BIOME_FROM_TUPLE = "getBiomeFromTuple"; public static final String CLASS_BIOMEGENERATOR = "BiomeGenerator"; public static final String METHOD_BIOMEGENERATOR_GET_BIOME = "getBiome"; public static final String FIELD_BIOMEGENERATOR_TEMPERATURE = "temperature"; public static final String FIELD_BIOMEGENERATOR_RAINFALL = "rainfall"; public static final String CLASS_WORLD = "World"; public static final String CONSTRUCTOR_WORLD = "<init>"; public static final String CLASS_DIMENSION_BASE = "DimensionBase"; public static final String FIELD_DIMENSION_WORLD = "world"; public static final String FIELD_DIMENSION_BIOMEGENERATOR = "biomeGenerator"; public static final String INTERFACE_SOMETHING = "ISomething"; public static final String CLASS_DIMENSION_OVERWORLD = "DimensionOverworld"; public static final String CLASS_PERLIN_OCTAVE_NOISE = "PerlinOctaveNoise"; public static final String METHOD_PERLIN_OCTAVE_NOISE_SAMPLE_3D = "sample3d"; public static final String METHOD_PERLIN_OCTAVE_NOISE_SAMPLE_2D = "sample2d"; public static final String FIELD_PERLIN_OCTAVE_NOISE_OCTAVES = "octaves"; public static final String CLASS_OVERWORLD_LEVEL_SOURCE = "OverworldLevelSource"; public static final String CONSTRUCTOR_OVERWORLD_LEVEL_SOURCE = "<init>"; public static final String METHOD_OVERWORLD_LEVEL_SOURCE_SHAPE_CHUNK = "shapeChunk"; public static final String FIELD_UPPER_INTERPOLATION_NOISE = "upperInterpolationNoise"; public static final String FIELD_LOWER_INTERPOLATION_NOISE = "lowerInterpolationNoise"; public static final String FIELD_INTERPOLATION_NOISE = "interpolationNoise"; public static final String FIELD_DEPTH_NOISE = "depthNoise"; public static final String FIELD_BIOME_NOISE = "biomeNoise"; public static final String CLASS_PERLIN_NOISE = "PerlinNoise"; public static final String FIELD_PERLIN_NOISE_PERMUTATIONS = "permutations"; public static final String FIELD_PERLIN_NOISE_X_OFFSET = "xOffset"; public static final String FIELD_PERLIN_NOISE_Y_OFFSET = "yOffset"; public static final String FIELD_PERLIN_NOISE_Z_OFFSET = "zOffset"; }