BlueGit

timfa minecart-trains

Files

minecart-trains / src / main / java / me / fridtjof / minecarttrains / utils / Rails.java

Rails.java

Rails.java 2.9 KiB Download Raw
1package me.fridtjof.minecarttrains.utils;
2
3import org.bukkit.Location;
4import org.bukkit.Tag;
5import org.bukkit.block.Block;
6import org.bukkit.block.BlockFace;
7import org.bukkit.block.data.Rail;
8import org.bukkit.util.Vector;
9
10public final class Rails
11{
12
13 private Rails()
14 {
15 }
16
17 public static boolean isRail(Block block)
18 {
19 return Tag.RAILS.isTagged(block.getType());
20 }
21
22 public static Block railBlock(Location location)
23 {
24 Block block = location.getBlock();
25 if (isRail(block))
26 {
27 return block;
28 }
29 Block below = block.getRelative(BlockFace.DOWN);
30 return isRail(below) ? below : block;
31 }
32
33 public static Vector tangent(Location location, Vector hint)
34 {
35 Block block = railBlock(location);
36 if (!(block.getBlockData() instanceof Rail rail))
37 {
38 return flattened(hint);
39 }
40 return tangent(rail.getShape(), hint);
41 }
42
43 public static Vector tangent(Rail.Shape shape, Vector hint)
44 {
45 Vector[] options = axes(shape);
46 Vector best = options[0];
47 double bestDot = -2;
48 Vector hintCopy = hint.clone();
49 if (hintCopy.lengthSquared() < 1.0E-8)
50 {
51 return best.clone();
52 }
53 hintCopy.normalize();
54 for (Vector option : options)
55 {
56 double dot = option.dot(hintCopy);
57 if (dot > bestDot)
58 {
59 bestDot = dot;
60 best = option;
61 }
62 }
63 return best.clone();
64 }
65
66 private static Vector[] axes(Rail.Shape shape)
67 {
68 return switch (shape)
69 {
70 case NORTH_SOUTH -> new Vector[] {vec(0, 0, 1), vec(0, 0, -1)};
71 case EAST_WEST -> new Vector[] {vec(1, 0, 0), vec(-1, 0, 0)};
72 case ASCENDING_NORTH -> new Vector[] {norm(0, 1, -1), norm(0, -1, 1)};
73 case ASCENDING_SOUTH -> new Vector[] {norm(0, 1, 1), norm(0, -1, -1)};
74 case ASCENDING_EAST -> new Vector[] {norm(1, 1, 0), norm(-1, -1, 0)};
75 case ASCENDING_WEST -> new Vector[] {norm(-1, 1, 0), norm(1, -1, 0)};
76 case SOUTH_EAST -> new Vector[] {vec(0, 0, 1), vec(1, 0, 0)};
77 case SOUTH_WEST -> new Vector[] {vec(0, 0, 1), vec(-1, 0, 0)};
78 case NORTH_WEST -> new Vector[] {vec(0, 0, -1), vec(-1, 0, 0)};
79 case NORTH_EAST -> new Vector[] {vec(0, 0, -1), vec(1, 0, 0)};
80 };
81 }
82
83 private static Vector flattened(Vector hint)
84 {
85 Vector flat = hint.clone().setY(0);
86 if (flat.lengthSquared() < 1.0E-8)
87 {
88 return new Vector(0, 0, 0);
89 }
90 return flat.normalize();
91 }
92
93 private static Vector vec(double x, double y, double z)
94 {
95 return new Vector(x, y, z);
96 }
97
98 private static Vector norm(double x, double y, double z)
99 {
100 return new Vector(x, y, z).normalize();
101 }
102}