package me.fridtjof.minecarttrains.utils; import org.bukkit.Location; import org.bukkit.Tag; import org.bukkit.block.Block; import org.bukkit.block.BlockFace; import org.bukkit.block.data.Rail; import org.bukkit.util.Vector; public final class Rails { private Rails() { } public static boolean isRail(Block block) { return Tag.RAILS.isTagged(block.getType()); } public static Block railBlock(Location location) { Block block = location.getBlock(); if (isRail(block)) { return block; } Block below = block.getRelative(BlockFace.DOWN); return isRail(below) ? below : block; } public static Vector tangent(Location location, Vector hint) { Block block = railBlock(location); if (!(block.getBlockData() instanceof Rail rail)) { return flattened(hint); } return tangent(rail.getShape(), hint); } public static Vector tangent(Rail.Shape shape, Vector hint) { Vector[] options = axes(shape); Vector best = options[0]; double bestDot = -2; Vector hintCopy = hint.clone(); if (hintCopy.lengthSquared() < 1.0E-8) { return best.clone(); } hintCopy.normalize(); for (Vector option : options) { double dot = option.dot(hintCopy); if (dot > bestDot) { bestDot = dot; best = option; } } return best.clone(); } private static Vector[] axes(Rail.Shape shape) { return switch (shape) { case NORTH_SOUTH -> new Vector[] {vec(0, 0, 1), vec(0, 0, -1)}; case EAST_WEST -> new Vector[] {vec(1, 0, 0), vec(-1, 0, 0)}; case ASCENDING_NORTH -> new Vector[] {norm(0, 1, -1), norm(0, -1, 1)}; case ASCENDING_SOUTH -> new Vector[] {norm(0, 1, 1), norm(0, -1, -1)}; case ASCENDING_EAST -> new Vector[] {norm(1, 1, 0), norm(-1, -1, 0)}; case ASCENDING_WEST -> new Vector[] {norm(-1, 1, 0), norm(1, -1, 0)}; case SOUTH_EAST -> new Vector[] {vec(0, 0, 1), vec(1, 0, 0)}; case SOUTH_WEST -> new Vector[] {vec(0, 0, 1), vec(-1, 0, 0)}; case NORTH_WEST -> new Vector[] {vec(0, 0, -1), vec(-1, 0, 0)}; case NORTH_EAST -> new Vector[] {vec(0, 0, -1), vec(1, 0, 0)}; }; } private static Vector flattened(Vector hint) { Vector flat = hint.clone().setY(0); if (flat.lengthSquared() < 1.0E-8) { return new Vector(0, 0, 0); } return flat.normalize(); } private static Vector vec(double x, double y, double z) { return new Vector(x, y, z); } private static Vector norm(double x, double y, double z) { return new Vector(x, y, z).normalize(); } }