Place linked carts on a fixed rail path so they stop bouncing.
Co-authored-by: Cursor <cursoragent@cursor.com>
@@ -28,7 +28,7 @@ Introducing Minecart Trains! Experience a whole new level of immersion as you co
28
28
29
29
The standard coupling tool is the chain. Click two minecarts one after the other to couple them. The click order does not matter: free carts, train ends, and whole trains are connected at the carts you click. Furnace minecarts become the front of a new pair when present.
30
30
31
Linked carts copy the engine's speed along their own rails. They only pull when stretched, so they stay rigid instead of bouncing like a spring. Corners no longer shove carts apart just because the straight-line gap got shorter.
31
Linked carts are placed on the rails at a fixed spacing behind (or ahead of) the engine. The locomotive still uses vanilla movement; the wagons are snapped to its path each tick so they cannot bounce. Corners follow the track, not a straight line.
32
32
33
33
**Coal Carts:**
34
34
@@ -72,9 +72,9 @@ You need JDK 25 and Maven. Then run:
72
72
mvn package
73
73
```
74
74
75
Results will be in the `target` folder. With version `1.5.3` that is:
75
Results will be in the `target` folder. With version `1.5.4` that is:
76
76
77
- `MinecartTrains-1.5.3.jar`
77
- `MinecartTrains-1.5.4.jar`
78
78
79
79
Copy this file to the plugins folder of a Paper 26.2 server.
80
80
@@ -28,7 +28,7 @@ Introducing Minecart Trains! Experience a whole new level of immersion as you co28
28
29
The standard coupling tool is the chain. Click two minecarts one after the other to couple them. The click order does not matter: free carts, train ends, and whole trains are connected at the carts you click. Furnace minecarts become the front of a new pair when present.29
The standard coupling tool is the chain. Click two minecarts one after the other to couple them. The click order does not matter: free carts, train ends, and whole trains are connected at the carts you click. Furnace minecarts become the front of a new pair when present.30
30
31
Linked carts copy the engine's speed along their own rails. They only pull when stretched, so they stay rigid instead of bouncing like a spring. Corners no longer shove carts apart just because the straight-line gap got shorter.31
Linked carts are placed on the rails at a fixed spacing behind (or ahead of) the engine. The locomotive still uses vanilla movement; the wagons are snapped to its path each tick so they cannot bounce. Corners follow the track, not a straight line.32
32
33
**Coal Carts:**33
**Coal Carts:**34
34
@@ -72,9 +72,9 @@ You need JDK 25 and Maven. Then run:72
mvn package72
mvn package73
```73
```74
74
75
Results will be in the `target` folder. With version `1.5.3` that is:75
Results will be in the `target` folder. With version `1.5.4` that is:76
76
77
- `MinecartTrains-1.5.3.jar`77
- `MinecartTrains-1.5.4.jar`78
78
79
Copy this file to the plugins folder of a Paper 26.2 server.79
Copy this file to the plugins folder of a Paper 26.2 server.80
80
@@ -6,7 +6,7 @@
6
6
7
7
<groupId>me.fridtjof</groupId>
8
8
<artifactId>minecarttrains</artifactId>
9
<version>1.5.3</version>
9
<version>1.5.4</version>
10
10
<packaging>jar</packaging>
11
11
12
12
<name>MinecartTrains</name>
@@ -6,7 +6,7 @@6
6
7
<groupId>me.fridtjof</groupId>7
<groupId>me.fridtjof</groupId>8
<artifactId>minecarttrains</artifactId>8
<artifactId>minecarttrains</artifactId>9
<version>1.5.3</version>9
<version>1.5.4</version>10
<packaging>jar</packaging>10
<packaging>jar</packaging>11
11
12
<name>MinecartTrains</name>12
<name>MinecartTrains</name>@@ -1,6 +1,7 @@
1
1
package me.fridtjof.minecarttrains.events;
2
2
3
3
import me.fridtjof.minecarttrains.MinecartTrains;
4
import me.fridtjof.minecarttrains.managers.LinkageManager;
4
5
import org.bukkit.entity.Damageable;
5
6
import org.bukkit.entity.Entity;
6
7
import org.bukkit.entity.Minecart;
@@ -14,6 +15,7 @@ public class OnVehicleEntityCollisionEvent implements Listener
14
15
{
15
16
16
17
static MinecartTrains plugin = MinecartTrains.getInstance();
18
private final LinkageManager linkageManager = plugin.linkageManager;
17
19
18
20
boolean runOver = plugin.configManager.mainConfig.getConfig().getBoolean("trains.run_over.entities");
19
21
double damage = plugin.configManager.mainConfig.getConfig().getDouble("trains.run_over.damage");
@@ -22,13 +24,20 @@ public class OnVehicleEntityCollisionEvent implements Listener
22
24
@EventHandler
23
25
public void onVehicleEntityCollision(VehicleEntityCollisionEvent event)
24
26
{
25
if (!runOver)
27
Vehicle vehicle = event.getVehicle();
28
Entity entity = event.getEntity();
29
30
if (vehicle instanceof Minecart cart && entity instanceof Minecart other
31
&& linkageManager.isSameTrain(cart, other))
26
32
{
33
event.setCancelled(true);
27
34
return;
28
35
}
29
36
30
Vehicle vehicle = event.getVehicle();
31
Entity entity = event.getEntity();
37
if (!runOver)
38
{
39
return;
40
}
32
41
33
42
if (!(vehicle instanceof Minecart))
34
43
{
@@ -1,6 +1,7 @@1
package me.fridtjof.minecarttrains.events;1
package me.fridtjof.minecarttrains.events;2
2
3
import me.fridtjof.minecarttrains.MinecartTrains;3
import me.fridtjof.minecarttrains.MinecartTrains;4
import me.fridtjof.minecarttrains.managers.LinkageManager;4
import org.bukkit.entity.Damageable;5
import org.bukkit.entity.Damageable;5
import org.bukkit.entity.Entity;6
import org.bukkit.entity.Entity;6
import org.bukkit.entity.Minecart;7
import org.bukkit.entity.Minecart;@@ -14,6 +15,7 @@ public class OnVehicleEntityCollisionEvent implements Listener14
{15
{15
16
16
static MinecartTrains plugin = MinecartTrains.getInstance();17
static MinecartTrains plugin = MinecartTrains.getInstance();18
private final LinkageManager linkageManager = plugin.linkageManager;17
19
18
boolean runOver = plugin.configManager.mainConfig.getConfig().getBoolean("trains.run_over.entities");20
boolean runOver = plugin.configManager.mainConfig.getConfig().getBoolean("trains.run_over.entities");19
double damage = plugin.configManager.mainConfig.getConfig().getDouble("trains.run_over.damage");21
double damage = plugin.configManager.mainConfig.getConfig().getDouble("trains.run_over.damage");@@ -22,13 +24,20 @@ public class OnVehicleEntityCollisionEvent implements Listener22
@EventHandler24
@EventHandler23
public void onVehicleEntityCollision(VehicleEntityCollisionEvent event)25
public void onVehicleEntityCollision(VehicleEntityCollisionEvent event)24
{26
{25
if (!runOver)27
Vehicle vehicle = event.getVehicle();28
Entity entity = event.getEntity();29
30
if (vehicle instanceof Minecart cart && entity instanceof Minecart other31
&& linkageManager.isSameTrain(cart, other))26
{32
{33
event.setCancelled(true);27
return;34
return;28
}35
}29
36
30
Vehicle vehicle = event.getVehicle();37
if (!runOver)31
Entity entity = event.getEntity();38
{39
return;40
}32
41
33
if (!(vehicle instanceof Minecart))42
if (!(vehicle instanceof Minecart))34
{43
{@@ -35,14 +35,14 @@ public class OnVehicleMoveEvent implements Listener
35
35
return;
36
36
}
37
37
38
if (linkageManager.hasLink(minecart))
38
if (linkageManager.hasLink(minecart) || linkageManager.getChild(minecart) != null)
39
39
{
40
Minecart parent = linkageManager.getParent(minecart);
41
if (parent != null)
40
Minecart reference = linkageManager.findMotionFront(minecart);
41
if (!minecart.getUniqueId().equals(reference.getUniqueId()))
42
42
{
43
minecart.setMaxSpeed(parent.getMaxSpeed());
43
minecart.setMaxSpeed(reference.getMaxSpeed());
44
return;
44
45
}
45
return;
46
46
}
47
47
48
48
Block track = minecart.getLocation().getBlock();
@@ -35,14 +35,14 @@ public class OnVehicleMoveEvent implements Listener35
return;35
return;36
}36
}37
37
38
if (linkageManager.hasLink(minecart))38
if (linkageManager.hasLink(minecart) || linkageManager.getChild(minecart) != null)39
{39
{40
Minecart parent = linkageManager.getParent(minecart);40
Minecart reference = linkageManager.findMotionFront(minecart);41
if (parent != null)41
if (!minecart.getUniqueId().equals(reference.getUniqueId()))42
{42
{43
minecart.setMaxSpeed(parent.getMaxSpeed());43
minecart.setMaxSpeed(reference.getMaxSpeed());44
return;44
}45
}45
return;46
}46
}47
47
48
Block track = minecart.getLocation().getBlock();48
Block track = minecart.getLocation().getBlock();@@ -26,7 +26,6 @@ public class OnVehicleUpdateEvent implements Listener
26
26
27
27
private final int fuelPerTick = plugin.configManager.mainConfig.getConfig().getInt("trains.fuel.consumption_per_tick");
28
28
private final double maxDistance = plugin.configManager.physicsConfig.getConfig().getDouble("link.distance.max");
29
private final double minDistance = plugin.configManager.physicsConfig.getConfig().getDouble("link.distance.min");
30
29
31
30
@EventHandler
32
31
public void onVehicleUpdate(VehicleUpdateEvent event)
@@ -67,14 +66,15 @@ public class OnVehicleUpdateEvent implements Listener
67
66
return;
68
67
}
69
68
70
if (!Rails.isRail(Rails.railBlock(parent.getLocation())))
69
if (!Rails.isRail(Rails.railBlock(parent.getLocation()))
70
|| !Rails.isRail(Rails.railBlock(minecart.getLocation())))
71
71
{
72
72
linkageManager.removeLink(minecart);
73
73
return;
74
74
}
75
75
76
76
double distanceSquared = minecart.getLocation().distanceSquared(parent.getLocation());
77
if (distanceSquared > maxDistance * maxDistance || distanceSquared < minDistance * minDistance)
77
if (distanceSquared > maxDistance * maxDistance)
78
78
{
79
79
linkageManager.removeLink(minecart);
80
80
minecart.setVelocity(new Vector(0, 0, 0));
@@ -26,7 +26,6 @@ public class OnVehicleUpdateEvent implements Listener26
26
27
private final int fuelPerTick = plugin.configManager.mainConfig.getConfig().getInt("trains.fuel.consumption_per_tick");27
private final int fuelPerTick = plugin.configManager.mainConfig.getConfig().getInt("trains.fuel.consumption_per_tick");28
private final double maxDistance = plugin.configManager.physicsConfig.getConfig().getDouble("link.distance.max");28
private final double maxDistance = plugin.configManager.physicsConfig.getConfig().getDouble("link.distance.max");29
private final double minDistance = plugin.configManager.physicsConfig.getConfig().getDouble("link.distance.min");30
29
31
@EventHandler30
@EventHandler32
public void onVehicleUpdate(VehicleUpdateEvent event)31
public void onVehicleUpdate(VehicleUpdateEvent event)@@ -67,14 +66,15 @@ public class OnVehicleUpdateEvent implements Listener67
return;66
return;68
}67
}69
68
70
if (!Rails.isRail(Rails.railBlock(parent.getLocation())))69
if (!Rails.isRail(Rails.railBlock(parent.getLocation()))70
|| !Rails.isRail(Rails.railBlock(minecart.getLocation())))71
{71
{72
linkageManager.removeLink(minecart);72
linkageManager.removeLink(minecart);73
return;73
return;74
}74
}75
75
76
double distanceSquared = minecart.getLocation().distanceSquared(parent.getLocation());76
double distanceSquared = minecart.getLocation().distanceSquared(parent.getLocation());77
if (distanceSquared > maxDistance * maxDistance || distanceSquared < minDistance * minDistance)77
if (distanceSquared > maxDistance * maxDistance)78
{78
{79
linkageManager.removeLink(minecart);79
linkageManager.removeLink(minecart);80
minecart.setVelocity(new Vector(0, 0, 0));80
minecart.setVelocity(new Vector(0, 0, 0));@@ -16,7 +16,7 @@ public class ConfigManager
16
16
public YamlConfig mainConfig, physicsConfig, messagesFile;
17
17
18
18
public static int mainConfigVersion = 4;
19
public static int physicsConfigVersion = 4;
19
public static int physicsConfigVersion = 5;
20
20
public static String versionStringName = "config_version";
21
21
22
22
public ConfigManager(JavaPlugin plugin)
@@ -134,12 +134,9 @@ public class ConfigManager
134
134
135
135
physicsConfig.getConfig().addDefault("link.high_speed.gate_speed", 1.5);
136
136
137
physicsConfig.getConfig().addDefault("link.rigid.stiffness", 0.55);
138
physicsConfig.getConfig().addDefault("link.rigid.damping", 0.75);
139
physicsConfig.getConfig().addDefault("link.rigid.max_correction", 0.28);
140
physicsConfig.getConfig().addDefault("link.rigid.curve_alignment", 0.55);
141
physicsConfig.getConfig().addDefault("link.rigid.stretch_slop", 0.12);
142
physicsConfig.getConfig().addDefault("link.rigid.curve_stretch_slop", 0.55);
137
physicsConfig.getConfig().addDefault("link.kinematic.sample_distance", 0.12);
138
physicsConfig.getConfig().addDefault("link.kinematic.max_path_length", 96);
139
physicsConfig.getConfig().addDefault("link.kinematic.snap_epsilon", 0.01);
143
140
144
141
physicsConfig.getConfig().addDefault("track.high_speed.max_speed", 4);
145
142
physicsConfig.getConfig().addDefault("track.high_speed.acceleration", 0.008);
@@ -16,7 +16,7 @@ public class ConfigManager16
public YamlConfig mainConfig, physicsConfig, messagesFile;16
public YamlConfig mainConfig, physicsConfig, messagesFile;17
17
18
public static int mainConfigVersion = 4;18
public static int mainConfigVersion = 4;19
public static int physicsConfigVersion = 4;19
public static int physicsConfigVersion = 5;20
public static String versionStringName = "config_version";20
public static String versionStringName = "config_version";21
21
22
public ConfigManager(JavaPlugin plugin)22
public ConfigManager(JavaPlugin plugin)@@ -134,12 +134,9 @@ public class ConfigManager134
134
135
physicsConfig.getConfig().addDefault("link.high_speed.gate_speed", 1.5);135
physicsConfig.getConfig().addDefault("link.high_speed.gate_speed", 1.5);136
136
137
physicsConfig.getConfig().addDefault("link.rigid.stiffness", 0.55);137
physicsConfig.getConfig().addDefault("link.kinematic.sample_distance", 0.12);138
physicsConfig.getConfig().addDefault("link.rigid.damping", 0.75);138
physicsConfig.getConfig().addDefault("link.kinematic.max_path_length", 96);139
physicsConfig.getConfig().addDefault("link.rigid.max_correction", 0.28);139
physicsConfig.getConfig().addDefault("link.kinematic.snap_epsilon", 0.01);140
physicsConfig.getConfig().addDefault("link.rigid.curve_alignment", 0.55);141
physicsConfig.getConfig().addDefault("link.rigid.stretch_slop", 0.12);142
physicsConfig.getConfig().addDefault("link.rigid.curve_stretch_slop", 0.55);143
140
144
physicsConfig.getConfig().addDefault("track.high_speed.max_speed", 4);141
physicsConfig.getConfig().addDefault("track.high_speed.max_speed", 4);145
physicsConfig.getConfig().addDefault("track.high_speed.acceleration", 0.008);142
physicsConfig.getConfig().addDefault("track.high_speed.acceleration", 0.008);@@ -1,10 +1,19 @@
1
1
package me.fridtjof.minecarttrains.managers;
2
2
3
import me.fridtjof.minecarttrains.utils.FurnaceCarts;
3
4
import me.fridtjof.minecarttrains.utils.Rails;
5
import org.bukkit.Bukkit;
6
import org.bukkit.Location;
7
import org.bukkit.World;
4
8
import org.bukkit.entity.Minecart;
9
import org.bukkit.entity.minecart.PoweredMinecart;
5
10
import org.bukkit.util.Vector;
6
11
12
import java.util.ArrayList;
13
import java.util.HashMap;
7
14
import java.util.List;
15
import java.util.Map;
16
import java.util.UUID;
8
17
9
18
public class LinkPhysics
10
19
{
@@ -15,12 +24,10 @@ public class LinkPhysics
15
24
private final double aimedDistanceLow;
16
25
private final double aimedDistanceHigh;
17
26
private final double highSpeedGateSquared;
18
private final double stiffness;
19
private final double damping;
20
private final double maxCorrection;
21
private final double curveAlignment;
22
private final double stretchSlop;
23
private final double curveStretchSlop;
27
private final double sampleDistance;
28
private final double maxPathLength;
29
private final double snapEpsilonSquared;
30
private final Map<UUID, Trail> trails = new HashMap<>();
24
31
25
32
public LinkPhysics(LinkageManager linkageManager, ConfigManager configManager)
26
33
{
@@ -29,12 +36,10 @@ public class LinkPhysics
29
36
this.aimedDistanceHigh = configManager.physicsConfig.getConfig().getDouble("link.high_speed.distance.aimed");
30
37
double highSpeedGate = configManager.physicsConfig.getConfig().getDouble("link.high_speed.gate_speed");
31
38
this.highSpeedGateSquared = highSpeedGate * highSpeedGate;
32
this.stiffness = configManager.physicsConfig.getConfig().getDouble("link.rigid.stiffness");
33
this.damping = configManager.physicsConfig.getConfig().getDouble("link.rigid.damping");
34
this.maxCorrection = configManager.physicsConfig.getConfig().getDouble("link.rigid.max_correction");
35
this.curveAlignment = configManager.physicsConfig.getConfig().getDouble("link.rigid.curve_alignment");
36
this.stretchSlop = configManager.physicsConfig.getConfig().getDouble("link.rigid.stretch_slop");
37
this.curveStretchSlop = configManager.physicsConfig.getConfig().getDouble("link.rigid.curve_stretch_slop");
39
this.sampleDistance = configManager.physicsConfig.getConfig().getDouble("link.kinematic.sample_distance");
40
this.maxPathLength = configManager.physicsConfig.getConfig().getDouble("link.kinematic.max_path_length");
41
double snapEpsilon = configManager.physicsConfig.getConfig().getDouble("link.kinematic.snap_epsilon");
42
this.snapEpsilonSquared = snapEpsilon * snapEpsilon;
38
43
}
39
44
40
45
public void updateTrain(Minecart cart)
@@ -50,114 +55,141 @@ public class LinkPhysics
50
55
return;
51
56
}
52
57
53
Minecart leader = linkageManager.findLeader(cart);
54
if (leader == null)
58
Minecart reference = linkageManager.findMotionFront(cart);
59
int referenceIndex = indexOf(train, reference);
60
if (referenceIndex < 0)
55
61
{
56
for (int i = 1; i < train.size(); i++)
57
{
58
constrain(train.get(i), train.get(i - 1), false);
59
}
60
62
return;
61
63
}
62
64
63
int leaderIndex = indexOf(train, leader);
64
if (leaderIndex < 0)
65
{
66
return;
67
}
65
Vector heading = headingOf(reference);
66
boolean lowerIsAhead = lowerIsAhead(train, referenceIndex, heading);
67
UUID trainId = linkageManager.findHead(cart).getUniqueId();
68
recordTrail(trainId, reference, heading);
68
69
69
for (int i = leaderIndex + 1; i < train.size(); i++)
70
double spacing = aimedDistance(reference);
71
for (int i = referenceIndex + 1; i < train.size(); i++)
70
72
{
71
constrain(train.get(i), train.get(i - 1), true);
73
place(train.get(i), reference, heading, (i - referenceIndex) * spacing, !lowerIsAhead, trainId);
72
74
}
73
for (int i = leaderIndex - 1; i >= 0; i--)
75
for (int i = referenceIndex - 1; i >= 0; i--)
74
76
{
75
constrain(train.get(i), train.get(i + 1), true);
77
place(train.get(i), reference, heading, (referenceIndex - i) * spacing, lowerIsAhead, trainId);
76
78
}
79
80
pruneTrails();
77
81
}
78
82
79
private void constrain(Minecart follower, Minecart anchor, boolean driven)
83
private void place(Minecart follower, Minecart reference, Vector heading, double distance, boolean ahead, UUID trainId)
80
84
{
81
Vector followerPos = follower.getLocation().toVector();
82
Vector anchorPos = anchor.getLocation().toVector();
83
Vector between = followerPos.subtract(anchorPos);
84
double distance = between.length();
85
if (distance < 1.0E-6)
85
Rails.Pose pose = ahead
86
? Rails.walk(reference.getLocation(), heading, distance)
87
: poseBehind(trainId, reference, heading, distance);
88
if (pose == null)
86
89
{
87
90
return;
88
91
}
89
92
90
Vector linkAxis = between.multiply(1.0 / distance);
91
Vector hint = follower.getVelocity();
92
if (hint.lengthSquared() < STILL)
93
Vector tangent = pose.tangent().clone();
94
if (tangent.lengthSquared() < STILL)
93
95
{
94
hint = anchor.getVelocity();
96
tangent = heading.clone();
95
97
}
96
if (hint.lengthSquared() < STILL)
98
else
97
99
{
98
hint = linkAxis;
100
tangent.normalize();
99
101
}
100
101
Vector rail = Rails.tangent(follower.getLocation(), hint);
102
if (rail.lengthSquared() < STILL)
102
if (tangent.dot(heading) < 0)
103
103
{
104
rail = linkAxis.clone().setY(0);
105
if (rail.lengthSquared() < STILL)
106
{
107
return;
108
}
109
rail.normalize();
104
tangent.multiply(-1);
110
105
}
111
106
112
if (rail.dot(hint) < 0 && hint.lengthSquared() >= STILL)
107
Location target = pose.location();
108
target.setYaw(Rails.yaw(tangent));
109
target.setPitch(0f);
110
111
if (follower.getLocation().distanceSquared(target) > snapEpsilonSquared)
113
112
{
114
rail.multiply(-1);
113
follower.teleport(target);
114
follower.setRotation(target.getYaw(), 0f);
115
115
}
116
116
117
double alignment = Math.abs(rail.dot(linkAxis));
118
boolean onCurve = alignment < curveAlignment;
119
double aimed = aimedDistance(anchor);
120
double stretch = distance - aimed;
121
122
Vector newVelocity = driven
123
? rail.clone().multiply(anchor.getVelocity().length())
124
: follower.getVelocity().clone();
117
follower.setVelocity(tangent.multiply(reference.getVelocity().length()));
118
follower.setMaxSpeed(reference.getMaxSpeed());
119
}
125
120
126
double correction = spacingCorrection(stretch, onCurve, follower.getVelocity(), anchor.getVelocity(), rail, linkAxis);
127
if (Math.abs(correction) > 1.0E-4)
121
private Rails.Pose poseBehind(UUID trainId, Minecart reference, Vector heading, double distance)
122
{
123
Trail trail = trails.get(trainId);
124
Rails.Pose fromTrail = trail == null ? null : trail.behind(reference.getWorld(), distance);
125
if (fromTrail != null)
128
126
{
129
newVelocity.add(rail.clone().multiply(correction));
127
return fromTrail;
130
128
}
131
else if (!driven)
129
return Rails.walk(reference.getLocation(), heading.clone().multiply(-1), distance);
130
}
131
132
private void recordTrail(UUID trainId, Minecart reference, Vector heading)
133
{
134
Rails.Pose snapped = Rails.snap(reference.getLocation(), heading);
135
Location sample = snapped == null ? reference.getLocation() : snapped.location();
136
trails.computeIfAbsent(trainId, id -> new Trail()).record(sample, heading, sampleDistance, maxPathLength);
137
}
138
139
private void pruneTrails()
140
{
141
if (trails.size() < 16)
132
142
{
133
143
return;
134
144
}
135
136
follower.setVelocity(newVelocity);
145
trails.keySet().removeIf(id -> Bukkit.getEntity(id) == null);
137
146
}
138
147
139
private double spacingCorrection(double stretch, boolean onCurve, Vector followerVel, Vector anchorVel, Vector rail, Vector linkAxis)
148
private Vector headingOf(Minecart cart)
140
149
{
141
double slop = onCurve ? curveStretchSlop : stretchSlop;
142
if (stretch <= slop)
150
Vector velocity = cart.getVelocity();
151
if (velocity.lengthSquared() >= STILL)
143
152
{
144
return 0;
153
return velocity.clone().normalize();
145
154
}
146
147
double towardAnchor = -Math.signum(rail.dot(linkAxis));
148
if (towardAnchor == 0.0)
155
if (cart instanceof PoweredMinecart powered && FurnaceCarts.hasDrive(powered))
149
156
{
150
towardAnchor = -1;
157
return new Vector(powered.getPushX(), 0, powered.getPushZ()).normalize();
151
158
}
159
Vector rail = Rails.tangent(cart.getLocation(), new Vector(0, 0, 1));
160
if (rail.lengthSquared() >= STILL)
161
{
162
return rail;
163
}
164
return new Vector(0, 0, 1);
165
}
152
166
153
double relative = followerVel.clone().subtract(anchorVel).dot(rail);
154
double correction = towardAnchor * stiffness * (stretch - slop) - damping * relative;
155
return Math.max(-maxCorrection, Math.min(maxCorrection, correction));
167
private boolean lowerIsAhead(List<Minecart> train, int referenceIndex, Vector heading)
168
{
169
if (referenceIndex > 0)
170
{
171
Vector toLower = train.get(referenceIndex - 1).getLocation().toVector()
172
.subtract(train.get(referenceIndex).getLocation().toVector());
173
if (toLower.lengthSquared() >= STILL)
174
{
175
return toLower.dot(heading) > 0;
176
}
177
}
178
if (referenceIndex < train.size() - 1)
179
{
180
Vector toHigher = train.get(referenceIndex + 1).getLocation().toVector()
181
.subtract(train.get(referenceIndex).getLocation().toVector());
182
if (toHigher.lengthSquared() >= STILL)
183
{
184
return toHigher.dot(heading) < 0;
185
}
186
}
187
return true;
156
188
}
157
189
158
private double aimedDistance(Minecart anchor)
190
private double aimedDistance(Minecart reference)
159
191
{
160
if (anchor.getVelocity().lengthSquared() > highSpeedGateSquared)
192
if (reference.getVelocity().lengthSquared() > highSpeedGateSquared)
161
193
{
162
194
return aimedDistanceHigh;
163
195
}
@@ -175,4 +207,115 @@ public class LinkPhysics
175
207
}
176
208
return -1;
177
209
}
210
211
private static final class Trail
212
{
213
private final List<double[]> points = new ArrayList<>();
214
private Vector lastHeading;
215
216
private void record(Location location, Vector heading, double sampleDistance, double maxLength)
217
{
218
if (lastHeading != null && heading.lengthSquared() >= STILL && lastHeading.dot(heading) < -0.15)
219
{
220
points.clear();
221
}
222
if (heading.lengthSquared() >= STILL)
223
{
224
lastHeading = heading.clone().normalize();
225
}
226
227
if (points.isEmpty())
228
{
229
points.add(coords(location));
230
return;
231
}
232
233
double[] last = points.get(points.size() - 1);
234
double dx = location.getX() - last[0];
235
double dy = location.getY() - last[1];
236
double dz = location.getZ() - last[2];
237
double gapSquared = dx * dx + dy * dy + dz * dz;
238
if (gapSquared < sampleDistance * sampleDistance)
239
{
240
last[0] = location.getX();
241
last[1] = location.getY();
242
last[2] = location.getZ();
243
return;
244
}
245
246
Location cursor = new Location(location.getWorld(), last[0], last[1], last[2]);
247
Vector alongRails = new Vector(dx, dy, dz);
248
double gap = Math.sqrt(gapSquared);
249
double walked = 0;
250
while (walked + sampleDistance < gap)
251
{
252
Rails.Pose step = Rails.walk(cursor, alongRails, sampleDistance);
253
if (step == null)
254
{
255
break;
256
}
257
cursor = step.location();
258
alongRails = step.tangent();
259
points.add(coords(cursor));
260
walked += sampleDistance;
261
}
262
points.add(coords(location));
263
trim(maxLength);
264
}
265
266
private Rails.Pose behind(World world, double distance)
267
{
268
if (points.size() < 2)
269
{
270
return null;
271
}
272
273
double remaining = distance;
274
for (int i = points.size() - 1; i > 0; i--)
275
{
276
double[] newer = points.get(i);
277
double[] older = points.get(i - 1);
278
double dx = older[0] - newer[0];
279
double dy = older[1] - newer[1];
280
double dz = older[2] - newer[2];
281
double length = Math.sqrt(dx * dx + dy * dy + dz * dz);
282
if (length < 1.0E-8)
283
{
284
continue;
285
}
286
if (remaining <= length)
287
{
288
double t = remaining / length;
289
Location location = new Location(world, newer[0] + dx * t, newer[1] + dy * t, newer[2] + dz * t);
290
return new Rails.Pose(location, new Vector(-dx, -dy, -dz).normalize());
291
}
292
remaining -= length;
293
}
294
return null;
295
}
296
297
private static double[] coords(Location location)
298
{
299
return new double[] {location.getX(), location.getY(), location.getZ()};
300
}
301
302
private void trim(double maxLength)
303
{
304
double length = 0;
305
for (int i = points.size() - 1; i > 0; i--)
306
{
307
double[] newer = points.get(i);
308
double[] older = points.get(i - 1);
309
double dx = older[0] - newer[0];
310
double dy = older[1] - newer[1];
311
double dz = older[2] - newer[2];
312
length += Math.sqrt(dx * dx + dy * dy + dz * dz);
313
if (length > maxLength)
314
{
315
points.subList(0, i).clear();
316
return;
317
}
318
}
319
}
320
}
178
321
}
@@ -1,10 +1,19 @@1
package me.fridtjof.minecarttrains.managers;1
package me.fridtjof.minecarttrains.managers;2
2
3
import me.fridtjof.minecarttrains.utils.FurnaceCarts;3
import me.fridtjof.minecarttrains.utils.Rails;4
import me.fridtjof.minecarttrains.utils.Rails;5
import org.bukkit.Bukkit;6
import org.bukkit.Location;7
import org.bukkit.World;4
import org.bukkit.entity.Minecart;8
import org.bukkit.entity.Minecart;9
import org.bukkit.entity.minecart.PoweredMinecart;5
import org.bukkit.util.Vector;10
import org.bukkit.util.Vector;6
11
12
import java.util.ArrayList;13
import java.util.HashMap;7
import java.util.List;14
import java.util.List;15
import java.util.Map;16
import java.util.UUID;8
17
9
public class LinkPhysics18
public class LinkPhysics10
{19
{@@ -15,12 +24,10 @@ public class LinkPhysics15
private final double aimedDistanceLow;24
private final double aimedDistanceLow;16
private final double aimedDistanceHigh;25
private final double aimedDistanceHigh;17
private final double highSpeedGateSquared;26
private final double highSpeedGateSquared;18
private final double stiffness;27
private final double sampleDistance;19
private final double damping;28
private final double maxPathLength;20
private final double maxCorrection;29
private final double snapEpsilonSquared;21
private final double curveAlignment;30
private final Map<UUID, Trail> trails = new HashMap<>();22
private final double stretchSlop;23
private final double curveStretchSlop;24
31
25
public LinkPhysics(LinkageManager linkageManager, ConfigManager configManager)32
public LinkPhysics(LinkageManager linkageManager, ConfigManager configManager)26
{33
{@@ -29,12 +36,10 @@ public class LinkPhysics29
this.aimedDistanceHigh = configManager.physicsConfig.getConfig().getDouble("link.high_speed.distance.aimed");36
this.aimedDistanceHigh = configManager.physicsConfig.getConfig().getDouble("link.high_speed.distance.aimed");30
double highSpeedGate = configManager.physicsConfig.getConfig().getDouble("link.high_speed.gate_speed");37
double highSpeedGate = configManager.physicsConfig.getConfig().getDouble("link.high_speed.gate_speed");31
this.highSpeedGateSquared = highSpeedGate * highSpeedGate;38
this.highSpeedGateSquared = highSpeedGate * highSpeedGate;32
this.stiffness = configManager.physicsConfig.getConfig().getDouble("link.rigid.stiffness");39
this.sampleDistance = configManager.physicsConfig.getConfig().getDouble("link.kinematic.sample_distance");33
this.damping = configManager.physicsConfig.getConfig().getDouble("link.rigid.damping");40
this.maxPathLength = configManager.physicsConfig.getConfig().getDouble("link.kinematic.max_path_length");34
this.maxCorrection = configManager.physicsConfig.getConfig().getDouble("link.rigid.max_correction");41
double snapEpsilon = configManager.physicsConfig.getConfig().getDouble("link.kinematic.snap_epsilon");35
this.curveAlignment = configManager.physicsConfig.getConfig().getDouble("link.rigid.curve_alignment");42
this.snapEpsilonSquared = snapEpsilon * snapEpsilon;36
this.stretchSlop = configManager.physicsConfig.getConfig().getDouble("link.rigid.stretch_slop");37
this.curveStretchSlop = configManager.physicsConfig.getConfig().getDouble("link.rigid.curve_stretch_slop");38
}43
}39
44
40
public void updateTrain(Minecart cart)45
public void updateTrain(Minecart cart)@@ -50,114 +55,141 @@ public class LinkPhysics50
return;55
return;51
}56
}52
57
53
Minecart leader = linkageManager.findLeader(cart);58
Minecart reference = linkageManager.findMotionFront(cart);54
if (leader == null)59
int referenceIndex = indexOf(train, reference);60
if (referenceIndex < 0)55
{61
{56
for (int i = 1; i < train.size(); i++)57
{58
constrain(train.get(i), train.get(i - 1), false);59
}60
return;62
return;61
}63
}62
64
63
int leaderIndex = indexOf(train, leader);65
Vector heading = headingOf(reference);64
if (leaderIndex < 0)66
boolean lowerIsAhead = lowerIsAhead(train, referenceIndex, heading);65
{67
UUID trainId = linkageManager.findHead(cart).getUniqueId();66
return;68
recordTrail(trainId, reference, heading);67
}68
69
69
for (int i = leaderIndex + 1; i < train.size(); i++)70
double spacing = aimedDistance(reference);71
for (int i = referenceIndex + 1; i < train.size(); i++)70
{72
{71
constrain(train.get(i), train.get(i - 1), true);73
place(train.get(i), reference, heading, (i - referenceIndex) * spacing, !lowerIsAhead, trainId);72
}74
}73
for (int i = leaderIndex - 1; i >= 0; i--)75
for (int i = referenceIndex - 1; i >= 0; i--)74
{76
{75
constrain(train.get(i), train.get(i + 1), true);77
place(train.get(i), reference, heading, (referenceIndex - i) * spacing, lowerIsAhead, trainId);76
}78
}79
80
pruneTrails();77
}81
}78
82
79
private void constrain(Minecart follower, Minecart anchor, boolean driven)83
private void place(Minecart follower, Minecart reference, Vector heading, double distance, boolean ahead, UUID trainId)80
{84
{81
Vector followerPos = follower.getLocation().toVector();85
Rails.Pose pose = ahead82
Vector anchorPos = anchor.getLocation().toVector();86
? Rails.walk(reference.getLocation(), heading, distance)83
Vector between = followerPos.subtract(anchorPos);87
: poseBehind(trainId, reference, heading, distance);84
double distance = between.length();88
if (pose == null)85
if (distance < 1.0E-6)86
{89
{87
return;90
return;88
}91
}89
92
90
Vector linkAxis = between.multiply(1.0 / distance);93
Vector tangent = pose.tangent().clone();91
Vector hint = follower.getVelocity();94
if (tangent.lengthSquared() < STILL)92
if (hint.lengthSquared() < STILL)93
{95
{94
hint = anchor.getVelocity();96
tangent = heading.clone();95
}97
}96
if (hint.lengthSquared() < STILL)98
else97
{99
{98
hint = linkAxis;100
tangent.normalize();99
}101
}100
102
if (tangent.dot(heading) < 0)101
Vector rail = Rails.tangent(follower.getLocation(), hint);102
if (rail.lengthSquared() < STILL)103
{103
{104
rail = linkAxis.clone().setY(0);104
tangent.multiply(-1);105
if (rail.lengthSquared() < STILL)106
{107
return;108
}109
rail.normalize();110
}105
}111
106
112
if (rail.dot(hint) < 0 && hint.lengthSquared() >= STILL)107
Location target = pose.location();108
target.setYaw(Rails.yaw(tangent));109
target.setPitch(0f);110
111
if (follower.getLocation().distanceSquared(target) > snapEpsilonSquared)113
{112
{114
rail.multiply(-1);113
follower.teleport(target);114
follower.setRotation(target.getYaw(), 0f);115
}115
}116
116
117
double alignment = Math.abs(rail.dot(linkAxis));117
follower.setVelocity(tangent.multiply(reference.getVelocity().length()));118
boolean onCurve = alignment < curveAlignment;118
follower.setMaxSpeed(reference.getMaxSpeed());119
double aimed = aimedDistance(anchor);119
}120
double stretch = distance - aimed;121
122
Vector newVelocity = driven123
? rail.clone().multiply(anchor.getVelocity().length())124
: follower.getVelocity().clone();125
120
126
double correction = spacingCorrection(stretch, onCurve, follower.getVelocity(), anchor.getVelocity(), rail, linkAxis);121
private Rails.Pose poseBehind(UUID trainId, Minecart reference, Vector heading, double distance)127
if (Math.abs(correction) > 1.0E-4)122
{123
Trail trail = trails.get(trainId);124
Rails.Pose fromTrail = trail == null ? null : trail.behind(reference.getWorld(), distance);125
if (fromTrail != null)128
{126
{129
newVelocity.add(rail.clone().multiply(correction));127
return fromTrail;130
}128
}131
else if (!driven)129
return Rails.walk(reference.getLocation(), heading.clone().multiply(-1), distance);130
}131
132
private void recordTrail(UUID trainId, Minecart reference, Vector heading)133
{134
Rails.Pose snapped = Rails.snap(reference.getLocation(), heading);135
Location sample = snapped == null ? reference.getLocation() : snapped.location();136
trails.computeIfAbsent(trainId, id -> new Trail()).record(sample, heading, sampleDistance, maxPathLength);137
}138
139
private void pruneTrails()140
{141
if (trails.size() < 16)132
{142
{133
return;143
return;134
}144
}135
145
trails.keySet().removeIf(id -> Bukkit.getEntity(id) == null);136
follower.setVelocity(newVelocity);137
}146
}138
147
139
private double spacingCorrection(double stretch, boolean onCurve, Vector followerVel, Vector anchorVel, Vector rail, Vector linkAxis)148
private Vector headingOf(Minecart cart)140
{149
{141
double slop = onCurve ? curveStretchSlop : stretchSlop;150
Vector velocity = cart.getVelocity();142
if (stretch <= slop)151
if (velocity.lengthSquared() >= STILL)143
{152
{144
return 0;153
return velocity.clone().normalize();145
}154
}146
155
if (cart instanceof PoweredMinecart powered && FurnaceCarts.hasDrive(powered))147
double towardAnchor = -Math.signum(rail.dot(linkAxis));148
if (towardAnchor == 0.0)149
{156
{150
towardAnchor = -1;157
return new Vector(powered.getPushX(), 0, powered.getPushZ()).normalize();151
}158
}159
Vector rail = Rails.tangent(cart.getLocation(), new Vector(0, 0, 1));160
if (rail.lengthSquared() >= STILL)161
{162
return rail;163
}164
return new Vector(0, 0, 1);165
}152
166
153
double relative = followerVel.clone().subtract(anchorVel).dot(rail);167
private boolean lowerIsAhead(List<Minecart> train, int referenceIndex, Vector heading)154
double correction = towardAnchor * stiffness * (stretch - slop) - damping * relative;168
{155
return Math.max(-maxCorrection, Math.min(maxCorrection, correction));169
if (referenceIndex > 0)170
{171
Vector toLower = train.get(referenceIndex - 1).getLocation().toVector()172
.subtract(train.get(referenceIndex).getLocation().toVector());173
if (toLower.lengthSquared() >= STILL)174
{175
return toLower.dot(heading) > 0;176
}177
}178
if (referenceIndex < train.size() - 1)179
{180
Vector toHigher = train.get(referenceIndex + 1).getLocation().toVector()181
.subtract(train.get(referenceIndex).getLocation().toVector());182
if (toHigher.lengthSquared() >= STILL)183
{184
return toHigher.dot(heading) < 0;185
}186
}187
return true;156
}188
}157
189
158
private double aimedDistance(Minecart anchor)190
private double aimedDistance(Minecart reference)159
{191
{160
if (anchor.getVelocity().lengthSquared() > highSpeedGateSquared)192
if (reference.getVelocity().lengthSquared() > highSpeedGateSquared)161
{193
{162
return aimedDistanceHigh;194
return aimedDistanceHigh;163
}195
}@@ -175,4 +207,115 @@ public class LinkPhysics175
}207
}176
return -1;208
return -1;177
}209
}210
211
private static final class Trail212
{213
private final List<double[]> points = new ArrayList<>();214
private Vector lastHeading;215
216
private void record(Location location, Vector heading, double sampleDistance, double maxLength)217
{218
if (lastHeading != null && heading.lengthSquared() >= STILL && lastHeading.dot(heading) < -0.15)219
{220
points.clear();221
}222
if (heading.lengthSquared() >= STILL)223
{224
lastHeading = heading.clone().normalize();225
}226
227
if (points.isEmpty())228
{229
points.add(coords(location));230
return;231
}232
233
double[] last = points.get(points.size() - 1);234
double dx = location.getX() - last[0];235
double dy = location.getY() - last[1];236
double dz = location.getZ() - last[2];237
double gapSquared = dx * dx + dy * dy + dz * dz;238
if (gapSquared < sampleDistance * sampleDistance)239
{240
last[0] = location.getX();241
last[1] = location.getY();242
last[2] = location.getZ();243
return;244
}245
246
Location cursor = new Location(location.getWorld(), last[0], last[1], last[2]);247
Vector alongRails = new Vector(dx, dy, dz);248
double gap = Math.sqrt(gapSquared);249
double walked = 0;250
while (walked + sampleDistance < gap)251
{252
Rails.Pose step = Rails.walk(cursor, alongRails, sampleDistance);253
if (step == null)254
{255
break;256
}257
cursor = step.location();258
alongRails = step.tangent();259
points.add(coords(cursor));260
walked += sampleDistance;261
}262
points.add(coords(location));263
trim(maxLength);264
}265
266
private Rails.Pose behind(World world, double distance)267
{268
if (points.size() < 2)269
{270
return null;271
}272
273
double remaining = distance;274
for (int i = points.size() - 1; i > 0; i--)275
{276
double[] newer = points.get(i);277
double[] older = points.get(i - 1);278
double dx = older[0] - newer[0];279
double dy = older[1] - newer[1];280
double dz = older[2] - newer[2];281
double length = Math.sqrt(dx * dx + dy * dy + dz * dz);282
if (length < 1.0E-8)283
{284
continue;285
}286
if (remaining <= length)287
{288
double t = remaining / length;289
Location location = new Location(world, newer[0] + dx * t, newer[1] + dy * t, newer[2] + dz * t);290
return new Rails.Pose(location, new Vector(-dx, -dy, -dz).normalize());291
}292
remaining -= length;293
}294
return null;295
}296
297
private static double[] coords(Location location)298
{299
return new double[] {location.getX(), location.getY(), location.getZ()};300
}301
302
private void trim(double maxLength)303
{304
double length = 0;305
for (int i = points.size() - 1; i > 0; i--)306
{307
double[] newer = points.get(i);308
double[] older = points.get(i - 1);309
double dx = older[0] - newer[0];310
double dy = older[1] - newer[1];311
double dz = older[2] - newer[2];312
length += Math.sqrt(dx * dx + dy * dy + dz * dz);313
if (length > maxLength)314
{315
points.subList(0, i).clear();316
return;317
}318
}319
}320
}178
}321
}@@ -7,6 +7,7 @@ import org.bukkit.entity.Entity;
7
7
import org.bukkit.entity.Minecart;
8
8
import org.bukkit.entity.minecart.PoweredMinecart;
9
9
import org.bukkit.persistence.PersistentDataType;
10
import org.bukkit.util.Vector;
10
11
11
12
import java.util.ArrayList;
12
13
import java.util.HashMap;
@@ -312,6 +313,37 @@ public class LinkageManager
312
313
return bestEngine;
313
314
}
314
315
316
public Minecart findMotionFront(Minecart cart)
317
{
318
Minecart engine = findLeader(cart);
319
if (engine != null)
320
{
321
return engine;
322
}
323
324
List<Minecart> train = getTrain(cart);
325
if (train.size() < 2)
326
{
327
return train.get(0);
328
}
329
330
Vector motion = new Vector();
331
for (Minecart member : train)
332
{
333
motion.add(member.getVelocity());
334
}
335
if (motion.lengthSquared() < 1.0E-6)
336
{
337
return train.get(0);
338
}
339
340
Minecart head = train.get(0);
341
Minecart tail = train.get(train.size() - 1);
342
Vector headOut = head.getLocation().toVector().subtract(train.get(1).getLocation().toVector());
343
Vector tailOut = tail.getLocation().toVector().subtract(train.get(train.size() - 2).getLocation().toVector());
344
return headOut.dot(motion) >= tailOut.dot(motion) ? head : tail;
345
}
346
315
347
private void refreshTickCache()
316
348
{
317
349
int currentTick = Bukkit.getCurrentTick();
@@ -7,6 +7,7 @@ import org.bukkit.entity.Entity;7
import org.bukkit.entity.Minecart;7
import org.bukkit.entity.Minecart;8
import org.bukkit.entity.minecart.PoweredMinecart;8
import org.bukkit.entity.minecart.PoweredMinecart;9
import org.bukkit.persistence.PersistentDataType;9
import org.bukkit.persistence.PersistentDataType;10
import org.bukkit.util.Vector;10
11
11
import java.util.ArrayList;12
import java.util.ArrayList;12
import java.util.HashMap;13
import java.util.HashMap;@@ -312,6 +313,37 @@ public class LinkageManager312
return bestEngine;313
return bestEngine;313
}314
}314
315
316
public Minecart findMotionFront(Minecart cart)317
{318
Minecart engine = findLeader(cart);319
if (engine != null)320
{321
return engine;322
}323
324
List<Minecart> train = getTrain(cart);325
if (train.size() < 2)326
{327
return train.get(0);328
}329
330
Vector motion = new Vector();331
for (Minecart member : train)332
{333
motion.add(member.getVelocity());334
}335
if (motion.lengthSquared() < 1.0E-6)336
{337
return train.get(0);338
}339
340
Minecart head = train.get(0);341
Minecart tail = train.get(train.size() - 1);342
Vector headOut = head.getLocation().toVector().subtract(train.get(1).getLocation().toVector());343
Vector tailOut = tail.getLocation().toVector().subtract(train.get(train.size() - 2).getLocation().toVector());344
return headOut.dot(motion) >= tailOut.dot(motion) ? head : tail;345
}346
315
private void refreshTickCache()347
private void refreshTickCache()316
{348
{317
int currentTick = Bukkit.getCurrentTick();349
int currentTick = Bukkit.getCurrentTick();@@ -7,9 +7,15 @@ import org.bukkit.block.BlockFace;
7
7
import org.bukkit.block.data.Rail;
8
8
import org.bukkit.util.Vector;
9
9
10
import java.util.HashSet;
11
import java.util.Set;
12
10
13
public final class Rails
11
14
{
12
15
16
public static final double HEIGHT = 0.0625D;
17
private static final int MAX_WALK_BLOCKS = 96;
18
13
19
private Rails()
14
20
{
15
21
}
@@ -32,12 +38,12 @@ public final class Rails
32
38
33
39
public static Vector tangent(Location location, Vector hint)
34
40
{
35
Block block = railBlock(location);
36
if (!(block.getBlockData() instanceof Rail rail))
41
Pose snapped = snap(location, hint);
42
if (snapped != null)
37
43
{
38
return flattened(hint);
44
return snapped.tangent();
39
45
}
40
return tangent(rail.getShape(), hint);
46
return flattened(hint);
41
47
}
42
48
43
49
public static Vector tangent(Rail.Shape shape, Vector hint)
@@ -63,6 +69,286 @@ public final class Rails
63
69
return best.clone();
64
70
}
65
71
72
public static Pose snap(Location location, Vector heading)
73
{
74
Block block = railBlock(location);
75
if (!(block.getBlockData() instanceof Rail rail))
76
{
77
return null;
78
}
79
80
Vector dir = unitOrZero(heading);
81
double[] local = localPoint(block, location);
82
double[][] points = facing(pathPoints(rail.getShape()), dir, local);
83
PathHit hit = project(points, local);
84
if (hit == null)
85
{
86
return null;
87
}
88
return new Pose(worldPoint(block, hit.x, hit.y, hit.z), hit.tangent.clone());
89
}
90
91
public static Pose walk(Location start, Vector heading, double distance)
92
{
93
if (distance <= 1.0E-8)
94
{
95
return snap(start, heading);
96
}
97
98
Pose snapped = snap(start, heading);
99
if (snapped == null)
100
{
101
return null;
102
}
103
104
Vector dir = unitOrZero(heading);
105
if (dir.lengthSquared() < 1.0E-8)
106
{
107
return snapped;
108
}
109
110
Location current = snapped.location();
111
Block block = railBlock(current);
112
double remaining = distance;
113
Set<Long> visited = new HashSet<>();
114
115
for (int guard = 0; guard < MAX_WALK_BLOCKS && remaining > 1.0E-8; guard++)
116
{
117
if (!(block.getBlockData() instanceof Rail rail))
118
{
119
return new Pose(current, dir);
120
}
121
122
Step step = stepInBlock(block, rail.getShape(), current, dir, remaining);
123
current = step.location;
124
dir = step.tangent;
125
remaining -= step.consumed;
126
127
if (remaining <= 1.0E-8)
128
{
129
return new Pose(current, dir);
130
}
131
if (step.exit == null || step.exit == BlockFace.SELF)
132
{
133
return new Pose(current, dir);
134
}
135
136
Block next = nextRail(block, step.exit);
137
if (next == null)
138
{
139
return new Pose(current, dir);
140
}
141
if (step.consumed < 1.0E-7 && !visited.add(packBlock(block)))
142
{
143
return new Pose(current, dir);
144
}
145
146
block = next;
147
Pose entered = snap(current, dir);
148
if (entered != null)
149
{
150
current = entered.location();
151
dir = entered.tangent();
152
}
153
}
154
return new Pose(current, dir);
155
}
156
157
public static float yaw(Vector tangent)
158
{
159
return (float) Math.toDegrees(Math.atan2(-tangent.getX(), tangent.getZ()));
160
}
161
162
private static Step stepInBlock(Block block, Rail.Shape shape, Location world, Vector dir, double remaining)
163
{
164
double[] local = localPoint(block, world);
165
double[][] points = facing(pathPoints(shape), dir, local);
166
PathHit here = project(points, local);
167
double pathLen = pathLength(points);
168
if (here == null)
169
{
170
return new Step(world.clone(), dir.clone(), remaining, null);
171
}
172
173
double target = here.along + remaining;
174
if (target <= pathLen - 1.0E-7)
175
{
176
PathHit dest = atDistance(points, target);
177
return new Step(worldPoint(block, dest.x, dest.y, dest.z), dest.tangent.clone(), remaining, null);
178
}
179
180
PathHit end = atDistance(points, pathLen);
181
double consumed = Math.max(0, pathLen - here.along);
182
return new Step(worldPoint(block, end.x, end.y, end.z), end.tangent.clone(), consumed, exitFace(end.x, end.z));
183
}
184
185
private static Block nextRail(Block current, BlockFace exit)
186
{
187
Block adjacent = current.getRelative(exit);
188
if (isRail(adjacent))
189
{
190
return adjacent;
191
}
192
Block up = adjacent.getRelative(BlockFace.UP);
193
if (isRail(up))
194
{
195
return up;
196
}
197
Block down = adjacent.getRelative(BlockFace.DOWN);
198
return isRail(down) ? down : null;
199
}
200
201
private static double[][] pathPoints(Rail.Shape shape)
202
{
203
return switch (shape)
204
{
205
case NORTH_SOUTH -> new double[][] {{0.5, 0, 0}, {0.5, 0, 1}};
206
case EAST_WEST -> new double[][] {{0, 0, 0.5}, {1, 0, 0.5}};
207
case ASCENDING_NORTH -> new double[][] {{0.5, 0, 1}, {0.5, 1, 0}};
208
case ASCENDING_SOUTH -> new double[][] {{0.5, 0, 0}, {0.5, 1, 1}};
209
case ASCENDING_EAST -> new double[][] {{0, 0, 0.5}, {1, 1, 0.5}};
210
case ASCENDING_WEST -> new double[][] {{1, 0, 0.5}, {0, 1, 0.5}};
211
case SOUTH_EAST -> new double[][] {{0.5, 0, 1}, {0.5, 0, 0.5}, {1, 0, 0.5}};
212
case SOUTH_WEST -> new double[][] {{0.5, 0, 1}, {0.5, 0, 0.5}, {0, 0, 0.5}};
213
case NORTH_WEST -> new double[][] {{0.5, 0, 0}, {0.5, 0, 0.5}, {0, 0, 0.5}};
214
case NORTH_EAST -> new double[][] {{0.5, 0, 0}, {0.5, 0, 0.5}, {1, 0, 0.5}};
215
};
216
}
217
218
private static double[][] facing(double[][] points, Vector dir, double[] local)
219
{
220
PathHit hit = project(points, local);
221
if (hit == null || hit.tangent.dot(dir) >= 0)
222
{
223
return points;
224
}
225
return reverse(points);
226
}
227
228
private static double[][] reverse(double[][] points)
229
{
230
double[][] reversed = new double[points.length][];
231
for (int i = 0; i < points.length; i++)
232
{
233
reversed[i] = points[points.length - 1 - i];
234
}
235
return reversed;
236
}
237
238
private static PathHit project(double[][] points, double[] local)
239
{
240
PathHit best = null;
241
double bestDist = Double.MAX_VALUE;
242
double along = 0;
243
for (int i = 0; i < points.length - 1; i++)
244
{
245
double[] a = points[i];
246
double[] b = points[i + 1];
247
double abx = b[0] - a[0];
248
double aby = b[1] - a[1];
249
double abz = b[2] - a[2];
250
double ab2 = abx * abx + aby * aby + abz * abz;
251
double t = 0;
252
if (ab2 > 1.0E-12)
253
{
254
t = ((local[0] - a[0]) * abx + (local[1] - a[1]) * aby + (local[2] - a[2]) * abz) / ab2;
255
t = Math.max(0, Math.min(1, t));
256
}
257
double px = a[0] + abx * t;
258
double py = a[1] + aby * t;
259
double pz = a[2] + abz * t;
260
double dist = (local[0] - px) * (local[0] - px) + (local[1] - py) * (local[1] - py) + (local[2] - pz) * (local[2] - pz);
261
double segLen = Math.sqrt(ab2);
262
if (dist < bestDist)
263
{
264
bestDist = dist;
265
Vector tangent = segLen > 1.0E-8
266
? new Vector(abx / segLen, aby / segLen, abz / segLen)
267
: new Vector();
268
best = new PathHit(along + segLen * t, px, py, pz, tangent);
269
}
270
along += segLen;
271
}
272
return best;
273
}
274
275
private static PathHit atDistance(double[][] points, double distance)
276
{
277
double along = 0;
278
for (int i = 0; i < points.length - 1; i++)
279
{
280
double[] a = points[i];
281
double[] b = points[i + 1];
282
double seg = dist(a, b);
283
boolean last = i == points.length - 2;
284
if (distance <= along + seg || last)
285
{
286
double t = seg < 1.0E-8 ? 0 : (distance - along) / seg;
287
t = Math.max(0, Math.min(1, t));
288
Vector tangent = seg > 1.0E-8
289
? new Vector((b[0] - a[0]) / seg, (b[1] - a[1]) / seg, (b[2] - a[2]) / seg)
290
: new Vector();
291
return new PathHit(along + seg * t, a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, tangent);
292
}
293
along += seg;
294
}
295
double[] last = points[points.length - 1];
296
return new PathHit(along, last[0], last[1], last[2], new Vector());
297
}
298
299
private static double pathLength(double[][] points)
300
{
301
double length = 0;
302
for (int i = 0; i < points.length - 1; i++)
303
{
304
length += dist(points[i], points[i + 1]);
305
}
306
return length;
307
}
308
309
private static double dist(double[] a, double[] b)
310
{
311
double dx = b[0] - a[0];
312
double dy = b[1] - a[1];
313
double dz = b[2] - a[2];
314
return Math.sqrt(dx * dx + dy * dy + dz * dz);
315
}
316
317
private static BlockFace exitFace(double x, double z)
318
{
319
if (x >= 0.999)
320
{
321
return BlockFace.EAST;
322
}
323
if (x <= 0.001)
324
{
325
return BlockFace.WEST;
326
}
327
if (z >= 0.999)
328
{
329
return BlockFace.SOUTH;
330
}
331
if (z <= 0.001)
332
{
333
return BlockFace.NORTH;
334
}
335
return BlockFace.SELF;
336
}
337
338
private static double[] localPoint(Block block, Location location)
339
{
340
return new double[] {
341
location.getX() - block.getX(),
342
location.getY() - (block.getY() + HEIGHT),
343
location.getZ() - block.getZ()
344
};
345
}
346
347
private static Location worldPoint(Block block, double x, double y, double z)
348
{
349
return new Location(block.getWorld(), block.getX() + x, block.getY() + HEIGHT + y, block.getZ() + z);
350
}
351
66
352
private static Vector[] axes(Rail.Shape shape)
67
353
{
68
354
return switch (shape)
@@ -90,6 +376,20 @@ public final class Rails
90
376
return flat.normalize();
91
377
}
92
378
379
private static Vector unitOrZero(Vector heading)
380
{
381
if (heading == null || heading.lengthSquared() < 1.0E-8)
382
{
383
return new Vector();
384
}
385
return heading.clone().normalize();
386
}
387
388
private static long packBlock(Block block)
389
{
390
return ((long) block.getX() * 73428767L) ^ ((long) block.getZ() * 19349663L) ^ block.getY();
391
}
392
93
393
private static Vector vec(double x, double y, double z)
94
394
{
95
395
return new Vector(x, y, z);
@@ -99,4 +399,60 @@ public final class Rails
99
399
{
100
400
return new Vector(x, y, z).normalize();
101
401
}
402
403
public static final class Pose
404
{
405
private final Location location;
406
private final Vector tangent;
407
408
public Pose(Location location, Vector tangent)
409
{
410
this.location = location;
411
this.tangent = tangent;
412
}
413
414
public Location location()
415
{
416
return location;
417
}
418
419
public Vector tangent()
420
{
421
return tangent;
422
}
423
}
424
425
private static final class PathHit
426
{
427
private final double along;
428
private final double x;
429
private final double y;
430
private final double z;
431
private final Vector tangent;
432
433
private PathHit(double along, double x, double y, double z, Vector tangent)
434
{
435
this.along = along;
436
this.x = x;
437
this.y = y;
438
this.z = z;
439
this.tangent = tangent;
440
}
441
}
442
443
private static final class Step
444
{
445
private final Location location;
446
private final Vector tangent;
447
private final double consumed;
448
private final BlockFace exit;
449
450
private Step(Location location, Vector tangent, double consumed, BlockFace exit)
451
{
452
this.location = location;
453
this.tangent = tangent;
454
this.consumed = consumed;
455
this.exit = exit;
456
}
457
}
102
458
}
@@ -7,9 +7,15 @@ import org.bukkit.block.BlockFace;7
import org.bukkit.block.data.Rail;7
import org.bukkit.block.data.Rail;8
import org.bukkit.util.Vector;8
import org.bukkit.util.Vector;9
9
10
import java.util.HashSet;11
import java.util.Set;12
10
public final class Rails13
public final class Rails11
{14
{12
15
16
public static final double HEIGHT = 0.0625D;17
private static final int MAX_WALK_BLOCKS = 96;18
13
private Rails()19
private Rails()14
{20
{15
}21
}@@ -32,12 +38,12 @@ public final class Rails32
38
33
public static Vector tangent(Location location, Vector hint)39
public static Vector tangent(Location location, Vector hint)34
{40
{35
Block block = railBlock(location);41
Pose snapped = snap(location, hint);36
if (!(block.getBlockData() instanceof Rail rail))42
if (snapped != null)37
{43
{38
return flattened(hint);44
return snapped.tangent();39
}45
}40
return tangent(rail.getShape(), hint);46
return flattened(hint);41
}47
}42
48
43
public static Vector tangent(Rail.Shape shape, Vector hint)49
public static Vector tangent(Rail.Shape shape, Vector hint)@@ -63,6 +69,286 @@ public final class Rails63
return best.clone();69
return best.clone();64
}70
}65
71
72
public static Pose snap(Location location, Vector heading)73
{74
Block block = railBlock(location);75
if (!(block.getBlockData() instanceof Rail rail))76
{77
return null;78
}79
80
Vector dir = unitOrZero(heading);81
double[] local = localPoint(block, location);82
double[][] points = facing(pathPoints(rail.getShape()), dir, local);83
PathHit hit = project(points, local);84
if (hit == null)85
{86
return null;87
}88
return new Pose(worldPoint(block, hit.x, hit.y, hit.z), hit.tangent.clone());89
}90
91
public static Pose walk(Location start, Vector heading, double distance)92
{93
if (distance <= 1.0E-8)94
{95
return snap(start, heading);96
}97
98
Pose snapped = snap(start, heading);99
if (snapped == null)100
{101
return null;102
}103
104
Vector dir = unitOrZero(heading);105
if (dir.lengthSquared() < 1.0E-8)106
{107
return snapped;108
}109
110
Location current = snapped.location();111
Block block = railBlock(current);112
double remaining = distance;113
Set<Long> visited = new HashSet<>();114
115
for (int guard = 0; guard < MAX_WALK_BLOCKS && remaining > 1.0E-8; guard++)116
{117
if (!(block.getBlockData() instanceof Rail rail))118
{119
return new Pose(current, dir);120
}121
122
Step step = stepInBlock(block, rail.getShape(), current, dir, remaining);123
current = step.location;124
dir = step.tangent;125
remaining -= step.consumed;126
127
if (remaining <= 1.0E-8)128
{129
return new Pose(current, dir);130
}131
if (step.exit == null || step.exit == BlockFace.SELF)132
{133
return new Pose(current, dir);134
}135
136
Block next = nextRail(block, step.exit);137
if (next == null)138
{139
return new Pose(current, dir);140
}141
if (step.consumed < 1.0E-7 && !visited.add(packBlock(block)))142
{143
return new Pose(current, dir);144
}145
146
block = next;147
Pose entered = snap(current, dir);148
if (entered != null)149
{150
current = entered.location();151
dir = entered.tangent();152
}153
}154
return new Pose(current, dir);155
}156
157
public static float yaw(Vector tangent)158
{159
return (float) Math.toDegrees(Math.atan2(-tangent.getX(), tangent.getZ()));160
}161
162
private static Step stepInBlock(Block block, Rail.Shape shape, Location world, Vector dir, double remaining)163
{164
double[] local = localPoint(block, world);165
double[][] points = facing(pathPoints(shape), dir, local);166
PathHit here = project(points, local);167
double pathLen = pathLength(points);168
if (here == null)169
{170
return new Step(world.clone(), dir.clone(), remaining, null);171
}172
173
double target = here.along + remaining;174
if (target <= pathLen - 1.0E-7)175
{176
PathHit dest = atDistance(points, target);177
return new Step(worldPoint(block, dest.x, dest.y, dest.z), dest.tangent.clone(), remaining, null);178
}179
180
PathHit end = atDistance(points, pathLen);181
double consumed = Math.max(0, pathLen - here.along);182
return new Step(worldPoint(block, end.x, end.y, end.z), end.tangent.clone(), consumed, exitFace(end.x, end.z));183
}184
185
private static Block nextRail(Block current, BlockFace exit)186
{187
Block adjacent = current.getRelative(exit);188
if (isRail(adjacent))189
{190
return adjacent;191
}192
Block up = adjacent.getRelative(BlockFace.UP);193
if (isRail(up))194
{195
return up;196
}197
Block down = adjacent.getRelative(BlockFace.DOWN);198
return isRail(down) ? down : null;199
}200
201
private static double[][] pathPoints(Rail.Shape shape)202
{203
return switch (shape)204
{205
case NORTH_SOUTH -> new double[][] {{0.5, 0, 0}, {0.5, 0, 1}};206
case EAST_WEST -> new double[][] {{0, 0, 0.5}, {1, 0, 0.5}};207
case ASCENDING_NORTH -> new double[][] {{0.5, 0, 1}, {0.5, 1, 0}};208
case ASCENDING_SOUTH -> new double[][] {{0.5, 0, 0}, {0.5, 1, 1}};209
case ASCENDING_EAST -> new double[][] {{0, 0, 0.5}, {1, 1, 0.5}};210
case ASCENDING_WEST -> new double[][] {{1, 0, 0.5}, {0, 1, 0.5}};211
case SOUTH_EAST -> new double[][] {{0.5, 0, 1}, {0.5, 0, 0.5}, {1, 0, 0.5}};212
case SOUTH_WEST -> new double[][] {{0.5, 0, 1}, {0.5, 0, 0.5}, {0, 0, 0.5}};213
case NORTH_WEST -> new double[][] {{0.5, 0, 0}, {0.5, 0, 0.5}, {0, 0, 0.5}};214
case NORTH_EAST -> new double[][] {{0.5, 0, 0}, {0.5, 0, 0.5}, {1, 0, 0.5}};215
};216
}217
218
private static double[][] facing(double[][] points, Vector dir, double[] local)219
{220
PathHit hit = project(points, local);221
if (hit == null || hit.tangent.dot(dir) >= 0)222
{223
return points;224
}225
return reverse(points);226
}227
228
private static double[][] reverse(double[][] points)229
{230
double[][] reversed = new double[points.length][];231
for (int i = 0; i < points.length; i++)232
{233
reversed[i] = points[points.length - 1 - i];234
}235
return reversed;236
}237
238
private static PathHit project(double[][] points, double[] local)239
{240
PathHit best = null;241
double bestDist = Double.MAX_VALUE;242
double along = 0;243
for (int i = 0; i < points.length - 1; i++)244
{245
double[] a = points[i];246
double[] b = points[i + 1];247
double abx = b[0] - a[0];248
double aby = b[1] - a[1];249
double abz = b[2] - a[2];250
double ab2 = abx * abx + aby * aby + abz * abz;251
double t = 0;252
if (ab2 > 1.0E-12)253
{254
t = ((local[0] - a[0]) * abx + (local[1] - a[1]) * aby + (local[2] - a[2]) * abz) / ab2;255
t = Math.max(0, Math.min(1, t));256
}257
double px = a[0] + abx * t;258
double py = a[1] + aby * t;259
double pz = a[2] + abz * t;260
double dist = (local[0] - px) * (local[0] - px) + (local[1] - py) * (local[1] - py) + (local[2] - pz) * (local[2] - pz);261
double segLen = Math.sqrt(ab2);262
if (dist < bestDist)263
{264
bestDist = dist;265
Vector tangent = segLen > 1.0E-8266
? new Vector(abx / segLen, aby / segLen, abz / segLen)267
: new Vector();268
best = new PathHit(along + segLen * t, px, py, pz, tangent);269
}270
along += segLen;271
}272
return best;273
}274
275
private static PathHit atDistance(double[][] points, double distance)276
{277
double along = 0;278
for (int i = 0; i < points.length - 1; i++)279
{280
double[] a = points[i];281
double[] b = points[i + 1];282
double seg = dist(a, b);283
boolean last = i == points.length - 2;284
if (distance <= along + seg || last)285
{286
double t = seg < 1.0E-8 ? 0 : (distance - along) / seg;287
t = Math.max(0, Math.min(1, t));288
Vector tangent = seg > 1.0E-8289
? new Vector((b[0] - a[0]) / seg, (b[1] - a[1]) / seg, (b[2] - a[2]) / seg)290
: new Vector();291
return new PathHit(along + seg * t, a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, tangent);292
}293
along += seg;294
}295
double[] last = points[points.length - 1];296
return new PathHit(along, last[0], last[1], last[2], new Vector());297
}298
299
private static double pathLength(double[][] points)300
{301
double length = 0;302
for (int i = 0; i < points.length - 1; i++)303
{304
length += dist(points[i], points[i + 1]);305
}306
return length;307
}308
309
private static double dist(double[] a, double[] b)310
{311
double dx = b[0] - a[0];312
double dy = b[1] - a[1];313
double dz = b[2] - a[2];314
return Math.sqrt(dx * dx + dy * dy + dz * dz);315
}316
317
private static BlockFace exitFace(double x, double z)318
{319
if (x >= 0.999)320
{321
return BlockFace.EAST;322
}323
if (x <= 0.001)324
{325
return BlockFace.WEST;326
}327
if (z >= 0.999)328
{329
return BlockFace.SOUTH;330
}331
if (z <= 0.001)332
{333
return BlockFace.NORTH;334
}335
return BlockFace.SELF;336
}337
338
private static double[] localPoint(Block block, Location location)339
{340
return new double[] {341
location.getX() - block.getX(),342
location.getY() - (block.getY() + HEIGHT),343
location.getZ() - block.getZ()344
};345
}346
347
private static Location worldPoint(Block block, double x, double y, double z)348
{349
return new Location(block.getWorld(), block.getX() + x, block.getY() + HEIGHT + y, block.getZ() + z);350
}351
66
private static Vector[] axes(Rail.Shape shape)352
private static Vector[] axes(Rail.Shape shape)67
{353
{68
return switch (shape)354
return switch (shape)@@ -90,6 +376,20 @@ public final class Rails90
return flat.normalize();376
return flat.normalize();91
}377
}92
378
379
private static Vector unitOrZero(Vector heading)380
{381
if (heading == null || heading.lengthSquared() < 1.0E-8)382
{383
return new Vector();384
}385
return heading.clone().normalize();386
}387
388
private static long packBlock(Block block)389
{390
return ((long) block.getX() * 73428767L) ^ ((long) block.getZ() * 19349663L) ^ block.getY();391
}392
93
private static Vector vec(double x, double y, double z)393
private static Vector vec(double x, double y, double z)94
{394
{95
return new Vector(x, y, z);395
return new Vector(x, y, z);@@ -99,4 +399,60 @@ public final class Rails99
{399
{100
return new Vector(x, y, z).normalize();400
return new Vector(x, y, z).normalize();101
}401
}402
403
public static final class Pose404
{405
private final Location location;406
private final Vector tangent;407
408
public Pose(Location location, Vector tangent)409
{410
this.location = location;411
this.tangent = tangent;412
}413
414
public Location location()415
{416
return location;417
}418
419
public Vector tangent()420
{421
return tangent;422
}423
}424
425
private static final class PathHit426
{427
private final double along;428
private final double x;429
private final double y;430
private final double z;431
private final Vector tangent;432
433
private PathHit(double along, double x, double y, double z, Vector tangent)434
{435
this.along = along;436
this.x = x;437
this.y = y;438
this.z = z;439
this.tangent = tangent;440
}441
}442
443
private static final class Step444
{445
private final Location location;446
private final Vector tangent;447
private final double consumed;448
private final BlockFace exit;449
450
private Step(Location location, Vector tangent, double consumed, BlockFace exit)451
{452
this.location = location;453
this.tangent = tangent;454
this.consumed = consumed;455
this.exit = exit;456
}457
}102
}458
}