Use rail-following coupler physics and fix coal-cart refueling.
Co-authored-by: Cursor <cursoragent@cursor.com>
@@ -28,9 +28,11 @@ 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.
32
31
33
**Coal Carts:**
32
34
33
Furnace minecarts will, if already going, refuel from a coal cart in front or behind, or otherwise nearby. Coal carts can be crafted with a minecart and a coal block. Coal carts will only interact with hoppers to refill but only coal and charcoal.
35
Furnace minecarts take one coal or charcoal from a linked coal cart (or a named coal cart within 3 blocks) when they are about to run out. One piece lasts 3600 ticks (3 minutes). A normal chest minecart is ignored unless `trains.fuel.refill_only_from_fuel_cart` is false. Coal carts are crafted with a minecart and a coal block. Hoppers can only insert coal or charcoal into them.
34
36
35
37
Fueling a furnace minecart sets its push direction to the way you are looking, even if it already has fuel. Sneak-right-click an empty hand on a furnace minecart to reverse it. Linked carts keep following on both sides of the engine.
36
38
@@ -70,9 +72,9 @@ You need JDK 25 and Maven. Then run:
70
72
mvn package
71
73
```
72
74
73
Results will be in the `target` folder. With version `1.5.1` that is:
75
Results will be in the `target` folder. With version `1.5.2` that is:
74
76
75
- `MinecartTrains-1.5.1.jar`
77
- `MinecartTrains-1.5.2.jar`
76
78
77
79
Copy this file to the plugins folder of a Paper 26.2 server.
78
80
@@ -28,9 +28,11 @@ 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.32
31
**Coal Carts:**33
**Coal Carts:**32
34
33
Furnace minecarts will, if already going, refuel from a coal cart in front or behind, or otherwise nearby. Coal carts can be crafted with a minecart and a coal block. Coal carts will only interact with hoppers to refill but only coal and charcoal.35
Furnace minecarts take one coal or charcoal from a linked coal cart (or a named coal cart within 3 blocks) when they are about to run out. One piece lasts 3600 ticks (3 minutes). A normal chest minecart is ignored unless `trains.fuel.refill_only_from_fuel_cart` is false. Coal carts are crafted with a minecart and a coal block. Hoppers can only insert coal or charcoal into them.34
36
35
Fueling a furnace minecart sets its push direction to the way you are looking, even if it already has fuel. Sneak-right-click an empty hand on a furnace minecart to reverse it. Linked carts keep following on both sides of the engine.37
Fueling a furnace minecart sets its push direction to the way you are looking, even if it already has fuel. Sneak-right-click an empty hand on a furnace minecart to reverse it. Linked carts keep following on both sides of the engine.36
38
@@ -70,9 +72,9 @@ You need JDK 25 and Maven. Then run:70
mvn package72
mvn package71
```73
```72
74
73
Results will be in the `target` folder. With version `1.5.1` that is:75
Results will be in the `target` folder. With version `1.5.2` that is:74
76
75
- `MinecartTrains-1.5.1.jar`77
- `MinecartTrains-1.5.2.jar`76
78
77
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.78
80
@@ -6,7 +6,7 @@
6
6
7
7
<groupId>me.fridtjof</groupId>
8
8
<artifactId>minecarttrains</artifactId>
9
<version>1.5.1</version>
9
<version>1.5.2</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.1</version>9
<version>1.5.2</version>10
<packaging>jar</packaging>10
<packaging>jar</packaging>11
11
12
<name>MinecartTrains</name>12
<name>MinecartTrains</name>@@ -22,7 +22,13 @@ public class OnVehicleCreateEvent implements Listener
22
22
return;
23
23
}
24
24
25
if (!plugin.cartTags.isFuelCart(cart, FUEL_CART_NAME))
25
plugin.getServer().getScheduler().runTask(plugin, () -> markIfFuelCart(cart));
26
markIfFuelCart(cart);
27
}
28
29
private void markIfFuelCart(StorageMinecart cart)
30
{
31
if (!cart.isValid() || !plugin.cartTags.isFuelCart(cart, FUEL_CART_NAME))
26
32
{
27
33
return;
28
34
}
@@ -22,7 +22,13 @@ public class OnVehicleCreateEvent implements Listener22
return;22
return;23
}23
}24
24
25
if (!plugin.cartTags.isFuelCart(cart, FUEL_CART_NAME))25
plugin.getServer().getScheduler().runTask(plugin, () -> markIfFuelCart(cart));26
markIfFuelCart(cart);27
}28
29
private void markIfFuelCart(StorageMinecart cart)30
{31
if (!cart.isValid() || !plugin.cartTags.isFuelCart(cart, FUEL_CART_NAME))26
{32
{27
return;33
return;28
}34
}@@ -1,16 +1,14 @@
1
1
package me.fridtjof.minecarttrains.events;
2
2
3
import me.fridtjof.minecarttrains.managers.LinkageManager;
4
3
import me.fridtjof.minecarttrains.MinecartTrains;
4
import me.fridtjof.minecarttrains.managers.LinkPhysics;
5
import me.fridtjof.minecarttrains.managers.LinkageManager;
5
6
import me.fridtjof.minecarttrains.utils.FurnaceCarts;
6
import org.bukkit.Location;
7
import me.fridtjof.minecarttrains.utils.Rails;
7
8
import org.bukkit.Material;
8
import org.bukkit.Tag;
9
9
import org.bukkit.World;
10
10
import org.bukkit.block.Block;
11
import org.bukkit.block.BlockFace;
12
11
import org.bukkit.block.data.type.RedstoneRail;
13
import org.bukkit.entity.Entity;
14
12
import org.bukkit.entity.Minecart;
15
13
import org.bukkit.entity.Vehicle;
16
14
import org.bukkit.entity.minecart.PoweredMinecart;
@@ -23,34 +21,18 @@ public class OnVehicleUpdateEvent implements Listener
23
21
{
24
22
25
23
static MinecartTrains plugin = MinecartTrains.getInstance();
26
LinkageManager linkageManager = plugin.linkageManager;
27
28
// config vars
29
int fuelPerTick = plugin.configManager.mainConfig.getConfig().getInt("trains.fuel.consumption_per_tick");
30
31
double maxDistance = plugin.configManager.physicsConfig.getConfig().getDouble("link.distance.max");
32
double minDistance = plugin.configManager.physicsConfig.getConfig().getDouble("link.distance.min");
33
34
double couplingPullSpeedLowSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.low_speed.speed.pull");
35
double couplingPushSpeedLowSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.low_speed.speed.push");
36
double aimedDistanceLowSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.low_speed.distance.aimed");
37
double aimedDistanceToleranceLowSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.low_speed.distance.aimed_tolerance");
38
39
double couplingPullSpeedHighSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.high_speed.speed.pull");
40
double couplingPushSpeedHighSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.high_speed.speed.push");
41
double aimedDistanceHighSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.high_speed.distance.aimed");
42
double aimedDistanceToleranceHighSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.high_speed.distance.aimed_tolerance");
43
44
double highSpeedGate = plugin.configManager.physicsConfig.getConfig().getDouble("link.high_speed.gate_speed");
24
private final LinkageManager linkageManager = plugin.linkageManager;
25
private final LinkPhysics linkPhysics = new LinkPhysics(linkageManager, plugin.configManager);
45
26
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");
29
private final double minDistance = plugin.configManager.physicsConfig.getConfig().getDouble("link.distance.min");
46
30
47
31
@EventHandler
48
32
public void onVehicleUpdate(VehicleUpdateEvent event)
49
33
{
50
34
Vehicle vehicle = event.getVehicle();
51
Entity parent;
52
53
if(!(vehicle instanceof Minecart minecart))
35
if (!(vehicle instanceof Minecart minecart))
54
36
{
55
37
return;
56
38
}
@@ -62,85 +44,37 @@ public class OnVehicleUpdateEvent implements Listener
62
44
handlePoweredCart(poweredCart);
63
45
}
64
46
65
// ensures the below function only works on trains, not on single minecarts
66
if(!linkageManager.hasLink((minecart)))
47
if (!linkageManager.hasLink(minecart))
67
48
{
68
49
return;
69
50
}
70
51
71
parent = linkageManager.getParent(minecart);
72
73
// breaks link if parent cart is broken
74
if(parent == null)
52
Minecart parent = linkageManager.getParent(minecart);
53
if (parent == null || parent == minecart)
75
54
{
55
if (parent == minecart)
56
{
57
plugin.getLogger().warning(plugin.configManager.messagesFile.getConfig().getString("trains.coupling_already_coupled_with_itself"));
58
}
76
59
linkageManager.removeLink(minecart);
77
60
return;
78
61
}
79
62
80
// breaks link if the parent and child are the same cart
81
if(parent == minecart)
82
{
83
plugin.getLogger().warning(plugin.configManager.mainConfig.getConfig().getString("trains.coupling_already_coupled_with_itself"));
84
linkageManager.removeLink(minecart);
85
return;
86
}
87
88
89
//check if parent is in same world
90
63
World childWorld = minecart.getWorld();
91
World parentWorld = parent.getWorld();
92
if(childWorld != parentWorld)
64
if (childWorld != parent.getWorld())
93
65
{
94
66
linkageManager.removeLink(minecart);
95
67
return;
96
68
}
97
69
98
99
Block parentBlock = parent.getLocation().getBlock();
100
if (!isRail(parentBlock.getType()) && !isRail(parentBlock.getRelative(BlockFace.DOWN).getType()))
70
if (!Rails.isRail(Rails.railBlock(parent.getLocation())))
101
71
{
102
72
linkageManager.removeLink(minecart);
103
73
return;
104
74
}
105
75
106
76
double distanceSquared = minecart.getLocation().distanceSquared(parent.getLocation());
107
double maxDistanceSquared = maxDistance * maxDistance;
108
double minDistanceSquared = minDistance * minDistance;
109
110
/* Sets the speed at which carts move towards their dependant. At HSRail speeds, this value must be high
111
to avoid breaking trains during acceleration.
112
Values in excess of 5 require more precision for the 'else if' statements, or else carts will overshoot
113
and collide, disrupting momentum and causing the 'jiggle' bug.*/
114
double pullSpeed;
115
double pushSpeed;
116
117
double aimedDistance;
118
double aimedDistanceTolerance;
119
120
double highSpeedGateSquared = highSpeedGate * highSpeedGate;
121
if(parent.getVelocity().lengthSquared() <= highSpeedGateSquared)
122
{
123
pullSpeed = couplingPullSpeedLowSpeed;
124
aimedDistance = this.aimedDistanceLowSpeed;
125
aimedDistanceTolerance = this.aimedDistanceToleranceLowSpeed;
126
}
127
else
128
{
129
pullSpeed = couplingPullSpeedHighSpeed;
130
aimedDistance = this.aimedDistanceHighSpeed;
131
aimedDistanceTolerance = this.aimedDistanceToleranceHighSpeed;
132
}
133
134
if(minecart.getVelocity().lengthSquared() <= highSpeedGateSquared)
135
{
136
pushSpeed = couplingPushSpeedLowSpeed;
137
}
138
else
139
{
140
pushSpeed = couplingPushSpeedHighSpeed;
141
}
142
143
if((distanceSquared > maxDistanceSquared) || distanceSquared < minDistanceSquared)
77
if (distanceSquared > maxDistance * maxDistance || distanceSquared < minDistance * minDistance)
144
78
{
145
79
linkageManager.removeLink(minecart);
146
80
minecart.setVelocity(new Vector(0, 0, 0));
@@ -148,39 +82,7 @@ public class OnVehicleUpdateEvent implements Listener
148
82
return;
149
83
}
150
84
151
double distance = Math.sqrt(distanceSquared);
152
double aimedLow = aimedDistance - aimedDistanceTolerance;
153
double aimedHigh = aimedDistance + aimedDistanceTolerance;
154
if (distance >= aimedLow && distance <= aimedHigh
155
&& minecart.getVelocity().lengthSquared() < 0.0001
156
&& parent.getVelocity().lengthSquared() < 0.0001)
157
{
158
return;
159
}
160
161
Entity follower = minecart;
162
Entity anchor = parent;
163
Minecart leader = linkageManager.findLeader(minecart);
164
if (leader != null && linkageManager.isCloserToLeader(minecart, (Minecart) parent, leader))
165
{
166
follower = parent;
167
anchor = minecart;
168
}
169
if (leader != null && follower.getUniqueId().equals(leader.getUniqueId()))
170
{
171
Entity swap = follower;
172
follower = anchor;
173
anchor = swap;
174
}
175
176
if (distance < aimedLow)
177
{
178
moveToward(follower, anchor, pushSpeed, (distance - aimedDistance));
179
}
180
else if (distance > aimedHigh)
181
{
182
moveToward(follower, anchor, pullSpeed, (distance - aimedDistance));
183
}
85
linkPhysics.updateTrain(minecart);
184
86
}
185
87
186
88
private void handlePoweredCart(PoweredMinecart poweredCart)
@@ -207,23 +109,4 @@ public class OnVehicleUpdateEvent implements Listener
207
109
poweredCart.setVelocity(new Vector(0, 0, 0));
208
110
poweredCart.setFuel(poweredCart.getFuel() + fuelPerTick);
209
111
}
210
211
// defines moveToward, which handles the elastic movement of dependant carts. Uses the speed and direction set earlier
212
public void moveToward(Entity child, Entity parent, double speed, double distance)
213
{
214
Location childLoc = child.getLocation();
215
Location parentLoc = parent.getLocation();
216
217
double x = childLoc.getX() - parentLoc.getX();
218
double y = childLoc.getY() - parentLoc.getY();
219
double z = childLoc.getZ() - parentLoc.getZ();
220
Vector velocity = new Vector(x, y, z).normalize().multiply(-speed);
221
child.setVelocity(velocity.multiply((distance * distance * distance)));
222
}
223
224
225
private boolean isRail(Material material)
226
{
227
return Tag.RAILS.isTagged(material);
228
}
229
112
}
@@ -1,16 +1,14 @@1
package me.fridtjof.minecarttrains.events;1
package me.fridtjof.minecarttrains.events;2
2
3
import me.fridtjof.minecarttrains.managers.LinkageManager;4
import me.fridtjof.minecarttrains.MinecartTrains;3
import me.fridtjof.minecarttrains.MinecartTrains;4
import me.fridtjof.minecarttrains.managers.LinkPhysics;5
import me.fridtjof.minecarttrains.managers.LinkageManager;5
import me.fridtjof.minecarttrains.utils.FurnaceCarts;6
import me.fridtjof.minecarttrains.utils.FurnaceCarts;6
import org.bukkit.Location;7
import me.fridtjof.minecarttrains.utils.Rails;7
import org.bukkit.Material;8
import org.bukkit.Material;8
import org.bukkit.Tag;9
import org.bukkit.World;9
import org.bukkit.World;10
import org.bukkit.block.Block;10
import org.bukkit.block.Block;11
import org.bukkit.block.BlockFace;12
import org.bukkit.block.data.type.RedstoneRail;11
import org.bukkit.block.data.type.RedstoneRail;13
import org.bukkit.entity.Entity;14
import org.bukkit.entity.Minecart;12
import org.bukkit.entity.Minecart;15
import org.bukkit.entity.Vehicle;13
import org.bukkit.entity.Vehicle;16
import org.bukkit.entity.minecart.PoweredMinecart;14
import org.bukkit.entity.minecart.PoweredMinecart;@@ -23,34 +21,18 @@ public class OnVehicleUpdateEvent implements Listener23
{21
{24
22
25
static MinecartTrains plugin = MinecartTrains.getInstance();23
static MinecartTrains plugin = MinecartTrains.getInstance();26
LinkageManager linkageManager = plugin.linkageManager;24
private final LinkageManager linkageManager = plugin.linkageManager;27
25
private final LinkPhysics linkPhysics = new LinkPhysics(linkageManager, plugin.configManager);28
// config vars29
int fuelPerTick = plugin.configManager.mainConfig.getConfig().getInt("trains.fuel.consumption_per_tick");30
31
double maxDistance = plugin.configManager.physicsConfig.getConfig().getDouble("link.distance.max");32
double minDistance = plugin.configManager.physicsConfig.getConfig().getDouble("link.distance.min");33
34
double couplingPullSpeedLowSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.low_speed.speed.pull");35
double couplingPushSpeedLowSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.low_speed.speed.push");36
double aimedDistanceLowSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.low_speed.distance.aimed");37
double aimedDistanceToleranceLowSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.low_speed.distance.aimed_tolerance");38
39
double couplingPullSpeedHighSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.high_speed.speed.pull");40
double couplingPushSpeedHighSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.high_speed.speed.push");41
double aimedDistanceHighSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.high_speed.distance.aimed");42
double aimedDistanceToleranceHighSpeed = plugin.configManager.physicsConfig.getConfig().getDouble("link.high_speed.distance.aimed_tolerance");43
44
double highSpeedGate = plugin.configManager.physicsConfig.getConfig().getDouble("link.high_speed.gate_speed");45
26
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");29
private final double minDistance = plugin.configManager.physicsConfig.getConfig().getDouble("link.distance.min");46
30
47
@EventHandler31
@EventHandler48
public void onVehicleUpdate(VehicleUpdateEvent event)32
public void onVehicleUpdate(VehicleUpdateEvent event)49
{33
{50
Vehicle vehicle = event.getVehicle();34
Vehicle vehicle = event.getVehicle();51
Entity parent;35
if (!(vehicle instanceof Minecart minecart))52
53
if(!(vehicle instanceof Minecart minecart))54
{36
{55
return;37
return;56
}38
}@@ -62,85 +44,37 @@ public class OnVehicleUpdateEvent implements Listener62
handlePoweredCart(poweredCart);44
handlePoweredCart(poweredCart);63
}45
}64
46
65
// ensures the below function only works on trains, not on single minecarts47
if (!linkageManager.hasLink(minecart))66
if(!linkageManager.hasLink((minecart)))67
{48
{68
return;49
return;69
}50
}70
51
71
parent = linkageManager.getParent(minecart);52
Minecart parent = linkageManager.getParent(minecart);72
53
if (parent == null || parent == minecart)73
// breaks link if parent cart is broken74
if(parent == null)75
{54
{55
if (parent == minecart)56
{57
plugin.getLogger().warning(plugin.configManager.messagesFile.getConfig().getString("trains.coupling_already_coupled_with_itself"));58
}76
linkageManager.removeLink(minecart);59
linkageManager.removeLink(minecart);77
return;60
return;78
}61
}79
62
80
// breaks link if the parent and child are the same cart81
if(parent == minecart)82
{83
plugin.getLogger().warning(plugin.configManager.mainConfig.getConfig().getString("trains.coupling_already_coupled_with_itself"));84
linkageManager.removeLink(minecart);85
return;86
}87
88
89
//check if parent is in same world90
World childWorld = minecart.getWorld();63
World childWorld = minecart.getWorld();91
World parentWorld = parent.getWorld();64
if (childWorld != parent.getWorld())92
if(childWorld != parentWorld)93
{65
{94
linkageManager.removeLink(minecart);66
linkageManager.removeLink(minecart);95
return;67
return;96
}68
}97
69
98
70
if (!Rails.isRail(Rails.railBlock(parent.getLocation())))99
Block parentBlock = parent.getLocation().getBlock();100
if (!isRail(parentBlock.getType()) && !isRail(parentBlock.getRelative(BlockFace.DOWN).getType()))101
{71
{102
linkageManager.removeLink(minecart);72
linkageManager.removeLink(minecart);103
return;73
return;104
}74
}105
75
106
double distanceSquared = minecart.getLocation().distanceSquared(parent.getLocation());76
double distanceSquared = minecart.getLocation().distanceSquared(parent.getLocation());107
double maxDistanceSquared = maxDistance * maxDistance;77
if (distanceSquared > maxDistance * maxDistance || distanceSquared < minDistance * minDistance)108
double minDistanceSquared = minDistance * minDistance;109
110
/* Sets the speed at which carts move towards their dependant. At HSRail speeds, this value must be high111
to avoid breaking trains during acceleration.112
Values in excess of 5 require more precision for the 'else if' statements, or else carts will overshoot113
and collide, disrupting momentum and causing the 'jiggle' bug.*/114
double pullSpeed;115
double pushSpeed;116
117
double aimedDistance;118
double aimedDistanceTolerance;119
120
double highSpeedGateSquared = highSpeedGate * highSpeedGate;121
if(parent.getVelocity().lengthSquared() <= highSpeedGateSquared)122
{123
pullSpeed = couplingPullSpeedLowSpeed;124
aimedDistance = this.aimedDistanceLowSpeed;125
aimedDistanceTolerance = this.aimedDistanceToleranceLowSpeed;126
}127
else128
{129
pullSpeed = couplingPullSpeedHighSpeed;130
aimedDistance = this.aimedDistanceHighSpeed;131
aimedDistanceTolerance = this.aimedDistanceToleranceHighSpeed;132
}133
134
if(minecart.getVelocity().lengthSquared() <= highSpeedGateSquared)135
{136
pushSpeed = couplingPushSpeedLowSpeed;137
}138
else139
{140
pushSpeed = couplingPushSpeedHighSpeed;141
}142
143
if((distanceSquared > maxDistanceSquared) || distanceSquared < minDistanceSquared)144
{78
{145
linkageManager.removeLink(minecart);79
linkageManager.removeLink(minecart);146
minecart.setVelocity(new Vector(0, 0, 0));80
minecart.setVelocity(new Vector(0, 0, 0));@@ -148,39 +82,7 @@ public class OnVehicleUpdateEvent implements Listener148
return;82
return;149
}83
}150
84
151
double distance = Math.sqrt(distanceSquared);85
linkPhysics.updateTrain(minecart);152
double aimedLow = aimedDistance - aimedDistanceTolerance;153
double aimedHigh = aimedDistance + aimedDistanceTolerance;154
if (distance >= aimedLow && distance <= aimedHigh155
&& minecart.getVelocity().lengthSquared() < 0.0001156
&& parent.getVelocity().lengthSquared() < 0.0001)157
{158
return;159
}160
161
Entity follower = minecart;162
Entity anchor = parent;163
Minecart leader = linkageManager.findLeader(minecart);164
if (leader != null && linkageManager.isCloserToLeader(minecart, (Minecart) parent, leader))165
{166
follower = parent;167
anchor = minecart;168
}169
if (leader != null && follower.getUniqueId().equals(leader.getUniqueId()))170
{171
Entity swap = follower;172
follower = anchor;173
anchor = swap;174
}175
176
if (distance < aimedLow)177
{178
moveToward(follower, anchor, pushSpeed, (distance - aimedDistance));179
}180
else if (distance > aimedHigh)181
{182
moveToward(follower, anchor, pullSpeed, (distance - aimedDistance));183
}184
}86
}185
87
186
private void handlePoweredCart(PoweredMinecart poweredCart)88
private void handlePoweredCart(PoweredMinecart poweredCart)@@ -207,23 +109,4 @@ public class OnVehicleUpdateEvent implements Listener207
poweredCart.setVelocity(new Vector(0, 0, 0));109
poweredCart.setVelocity(new Vector(0, 0, 0));208
poweredCart.setFuel(poweredCart.getFuel() + fuelPerTick);110
poweredCart.setFuel(poweredCart.getFuel() + fuelPerTick);209
}111
}210
211
// defines moveToward, which handles the elastic movement of dependant carts. Uses the speed and direction set earlier212
public void moveToward(Entity child, Entity parent, double speed, double distance)213
{214
Location childLoc = child.getLocation();215
Location parentLoc = parent.getLocation();216
217
double x = childLoc.getX() - parentLoc.getX();218
double y = childLoc.getY() - parentLoc.getY();219
double z = childLoc.getZ() - parentLoc.getZ();220
Vector velocity = new Vector(x, y, z).normalize().multiply(-speed);221
child.setVelocity(velocity.multiply((distance * distance * distance)));222
}223
224
225
private boolean isRail(Material material)226
{227
return Tag.RAILS.isTagged(material);228
}229
}112
}@@ -4,7 +4,9 @@ import me.fridtjof.minecarttrains.MinecartTrains;
4
4
import me.fridtjof.minecarttrains.managers.LinkageManager;
5
5
import org.bukkit.Material;
6
6
import org.bukkit.entity.Entity;
7
import org.bukkit.entity.HumanEntity;
7
8
import org.bukkit.entity.Minecart;
9
import org.bukkit.entity.Player;
8
10
import org.bukkit.entity.Vehicle;
9
11
import org.bukkit.entity.minecart.PoweredMinecart;
10
12
import org.bukkit.entity.minecart.StorageMinecart;
@@ -15,8 +17,8 @@ import org.bukkit.event.vehicle.VehicleUpdateEvent;
15
17
import org.bukkit.inventory.Inventory;
16
18
import org.bukkit.inventory.ItemStack;
17
19
18
import java.util.ArrayList;
19
import java.util.List;
20
import java.util.LinkedHashSet;
21
import java.util.Set;
20
22
21
23
public class OnVehicleUpdateEventLowestPriority implements Listener
22
24
{
@@ -32,42 +34,27 @@ public class OnVehicleUpdateEventLowestPriority implements Listener
32
34
public void OnFuelEmptyEvent(VehicleUpdateEvent event)
33
35
{
34
36
Vehicle vehicle = event.getVehicle();
35
36
37
if (!(vehicle instanceof PoweredMinecart cart))
37
38
{
38
39
return;
39
40
}
40
41
41
if ((cart.getFuel() < 2) || (cart.getFuel() > (FUEL_PER_TICK + 1)))
42
linkageManager.remember(cart);
43
44
int fuel = cart.getFuel();
45
if (fuel > FUEL_PER_TICK + 1)
42
46
{
43
47
return;
44
48
}
45
49
46
List<Entity> candidates = new ArrayList<>();
47
Minecart parent = linkageManager.getParent(cart);
48
Minecart child = linkageManager.getChild(cart);
49
if (parent != null)
50
boolean inTrain = linkageManager.hasLink(cart) || linkageManager.getChild(cart) != null;
51
if (fuel < 2 && !inTrain)
50
52
{
51
candidates.add(parent);
52
}
53
if (child != null)
54
{
55
candidates.add(child);
53
return;
56
54
}
57
candidates.addAll(vehicle.getNearbyEntities(3D, 3D, 3D));
58
55
59
for (Entity entity : candidates)
56
for (StorageMinecart storageCart : findTenders(cart))
60
57
{
61
if (!(entity instanceof StorageMinecart storageCart))
62
{
63
continue;
64
}
65
66
if (REFILL_ONLY_FROM_TENDER && !isCartTender(storageCart))
67
{
68
continue;
69
}
70
71
58
if (tryConsumeFuel(storageCart.getInventory(), cart))
72
59
{
73
60
return;
@@ -75,18 +62,77 @@ public class OnVehicleUpdateEventLowestPriority implements Listener
75
62
}
76
63
}
77
64
65
private Set<StorageMinecart> findTenders(PoweredMinecart cart)
66
{
67
Set<StorageMinecart> tenders = new LinkedHashSet<>();
68
for (Minecart trainCart : linkageManager.getTrain(cart))
69
{
70
addIfTender(trainCart, tenders);
71
}
72
73
Minecart parent = linkageManager.getParent(cart);
74
Minecart child = linkageManager.getChild(cart);
75
addIfTender(parent, tenders);
76
addIfTender(child, tenders);
77
78
for (Entity entity : cart.getNearbyEntities(3D, 3D, 3D))
79
{
80
addIfTender(entity, tenders);
81
}
82
return tenders;
83
}
84
85
private void addIfTender(Entity entity, Set<StorageMinecart> tenders)
86
{
87
if (!(entity instanceof StorageMinecart storageCart))
88
{
89
return;
90
}
91
if (REFILL_ONLY_FROM_TENDER && !isCartTender(storageCart))
92
{
93
return;
94
}
95
tenders.add(storageCart);
96
}
97
78
98
private boolean tryConsumeFuel(Inventory inventory, PoweredMinecart cart)
79
99
{
80
if (inventory.contains(Material.COAL))
100
if (removeOne(inventory, Material.COAL) || removeOne(inventory, Material.CHARCOAL))
81
101
{
82
inventory.removeItem(new ItemStack(Material.COAL, 1));
83
102
cart.setFuel(cart.getFuel() + 3600);
103
for (HumanEntity viewer : inventory.getViewers())
104
{
105
if (viewer instanceof Player player)
106
{
107
player.updateInventory();
108
}
109
}
84
110
return true;
85
111
}
86
if (inventory.contains(Material.CHARCOAL))
112
return false;
113
}
114
115
private boolean removeOne(Inventory inventory, Material material)
116
{
117
ItemStack[] contents = inventory.getContents();
118
for (int slot = 0; slot < contents.length; slot++)
87
119
{
88
inventory.removeItem(new ItemStack(Material.CHARCOAL, 1));
89
cart.setFuel(cart.getFuel() + 3600);
120
ItemStack stack = contents[slot];
121
if (stack == null || stack.getType() != material || stack.getAmount() <= 0)
122
{
123
continue;
124
}
125
126
int amount = stack.getAmount() - 1;
127
if (amount <= 0)
128
{
129
inventory.setItem(slot, null);
130
}
131
else
132
{
133
stack.setAmount(amount);
134
inventory.setItem(slot, stack);
135
}
90
136
return true;
91
137
}
92
138
return false;
@@ -4,7 +4,9 @@ import me.fridtjof.minecarttrains.MinecartTrains;4
import me.fridtjof.minecarttrains.managers.LinkageManager;4
import me.fridtjof.minecarttrains.managers.LinkageManager;5
import org.bukkit.Material;5
import org.bukkit.Material;6
import org.bukkit.entity.Entity;6
import org.bukkit.entity.Entity;7
import org.bukkit.entity.HumanEntity;7
import org.bukkit.entity.Minecart;8
import org.bukkit.entity.Minecart;9
import org.bukkit.entity.Player;8
import org.bukkit.entity.Vehicle;10
import org.bukkit.entity.Vehicle;9
import org.bukkit.entity.minecart.PoweredMinecart;11
import org.bukkit.entity.minecart.PoweredMinecart;10
import org.bukkit.entity.minecart.StorageMinecart;12
import org.bukkit.entity.minecart.StorageMinecart;@@ -15,8 +17,8 @@ import org.bukkit.event.vehicle.VehicleUpdateEvent;15
import org.bukkit.inventory.Inventory;17
import org.bukkit.inventory.Inventory;16
import org.bukkit.inventory.ItemStack;18
import org.bukkit.inventory.ItemStack;17
19
18
import java.util.ArrayList;20
import java.util.LinkedHashSet;19
import java.util.List;21
import java.util.Set;20
22
21
public class OnVehicleUpdateEventLowestPriority implements Listener23
public class OnVehicleUpdateEventLowestPriority implements Listener22
{24
{@@ -32,42 +34,27 @@ public class OnVehicleUpdateEventLowestPriority implements Listener32
public void OnFuelEmptyEvent(VehicleUpdateEvent event)34
public void OnFuelEmptyEvent(VehicleUpdateEvent event)33
{35
{34
Vehicle vehicle = event.getVehicle();36
Vehicle vehicle = event.getVehicle();35
36
if (!(vehicle instanceof PoweredMinecart cart))37
if (!(vehicle instanceof PoweredMinecart cart))37
{38
{38
return;39
return;39
}40
}40
41
41
if ((cart.getFuel() < 2) || (cart.getFuel() > (FUEL_PER_TICK + 1)))42
linkageManager.remember(cart);43
44
int fuel = cart.getFuel();45
if (fuel > FUEL_PER_TICK + 1)42
{46
{43
return;47
return;44
}48
}45
49
46
List<Entity> candidates = new ArrayList<>();50
boolean inTrain = linkageManager.hasLink(cart) || linkageManager.getChild(cart) != null;47
Minecart parent = linkageManager.getParent(cart);51
if (fuel < 2 && !inTrain)48
Minecart child = linkageManager.getChild(cart);49
if (parent != null)50
{52
{51
candidates.add(parent);53
return;52
}53
if (child != null)54
{55
candidates.add(child);56
}54
}57
candidates.addAll(vehicle.getNearbyEntities(3D, 3D, 3D));58
55
59
for (Entity entity : candidates)56
for (StorageMinecart storageCart : findTenders(cart))60
{57
{61
if (!(entity instanceof StorageMinecart storageCart))62
{63
continue;64
}65
66
if (REFILL_ONLY_FROM_TENDER && !isCartTender(storageCart))67
{68
continue;69
}70
71
if (tryConsumeFuel(storageCart.getInventory(), cart))58
if (tryConsumeFuel(storageCart.getInventory(), cart))72
{59
{73
return;60
return;@@ -75,18 +62,77 @@ public class OnVehicleUpdateEventLowestPriority implements Listener75
}62
}76
}63
}77
64
65
private Set<StorageMinecart> findTenders(PoweredMinecart cart)66
{67
Set<StorageMinecart> tenders = new LinkedHashSet<>();68
for (Minecart trainCart : linkageManager.getTrain(cart))69
{70
addIfTender(trainCart, tenders);71
}72
73
Minecart parent = linkageManager.getParent(cart);74
Minecart child = linkageManager.getChild(cart);75
addIfTender(parent, tenders);76
addIfTender(child, tenders);77
78
for (Entity entity : cart.getNearbyEntities(3D, 3D, 3D))79
{80
addIfTender(entity, tenders);81
}82
return tenders;83
}84
85
private void addIfTender(Entity entity, Set<StorageMinecart> tenders)86
{87
if (!(entity instanceof StorageMinecart storageCart))88
{89
return;90
}91
if (REFILL_ONLY_FROM_TENDER && !isCartTender(storageCart))92
{93
return;94
}95
tenders.add(storageCart);96
}97
78
private boolean tryConsumeFuel(Inventory inventory, PoweredMinecart cart)98
private boolean tryConsumeFuel(Inventory inventory, PoweredMinecart cart)79
{99
{80
if (inventory.contains(Material.COAL))100
if (removeOne(inventory, Material.COAL) || removeOne(inventory, Material.CHARCOAL))81
{101
{82
inventory.removeItem(new ItemStack(Material.COAL, 1));83
cart.setFuel(cart.getFuel() + 3600);102
cart.setFuel(cart.getFuel() + 3600);103
for (HumanEntity viewer : inventory.getViewers())104
{105
if (viewer instanceof Player player)106
{107
player.updateInventory();108
}109
}84
return true;110
return true;85
}111
}86
if (inventory.contains(Material.CHARCOAL))112
return false;113
}114
115
private boolean removeOne(Inventory inventory, Material material)116
{117
ItemStack[] contents = inventory.getContents();118
for (int slot = 0; slot < contents.length; slot++)87
{119
{88
inventory.removeItem(new ItemStack(Material.CHARCOAL, 1));120
ItemStack stack = contents[slot];89
cart.setFuel(cart.getFuel() + 3600);121
if (stack == null || stack.getType() != material || stack.getAmount() <= 0)122
{123
continue;124
}125
126
int amount = stack.getAmount() - 1;127
if (amount <= 0)128
{129
inventory.setItem(slot, null);130
}131
else132
{133
stack.setAmount(amount);134
inventory.setItem(slot, stack);135
}90
return true;136
return true;91
}137
}92
return false;138
return false;@@ -134,6 +134,13 @@ 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);
143
137
144
physicsConfig.getConfig().addDefault("track.high_speed.max_speed", 4);
138
145
physicsConfig.getConfig().addDefault("track.high_speed.acceleration", 0.008);
139
146
@@ -134,6 +134,13 @@ 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);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);143
137
physicsConfig.getConfig().addDefault("track.high_speed.max_speed", 4);144
physicsConfig.getConfig().addDefault("track.high_speed.max_speed", 4);138
physicsConfig.getConfig().addDefault("track.high_speed.acceleration", 0.008);145
physicsConfig.getConfig().addDefault("track.high_speed.acceleration", 0.008);139
146
@@ -0,0 +1,164 @@
1
package me.fridtjof.minecarttrains.managers;
2
3
import me.fridtjof.minecarttrains.utils.Rails;
4
import org.bukkit.entity.Minecart;
5
import org.bukkit.util.Vector;
6
7
import java.util.List;
8
9
public class LinkPhysics
10
{
11
12
private static final double STILL = 1.0E-4;
13
14
private final LinkageManager linkageManager;
15
private final double aimedDistanceLow;
16
private final double aimedDistanceHigh;
17
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;
24
25
public LinkPhysics(LinkageManager linkageManager, ConfigManager configManager)
26
{
27
this.linkageManager = linkageManager;
28
this.aimedDistanceLow = configManager.physicsConfig.getConfig().getDouble("link.low_speed.distance.aimed");
29
this.aimedDistanceHigh = configManager.physicsConfig.getConfig().getDouble("link.high_speed.distance.aimed");
30
double highSpeedGate = configManager.physicsConfig.getConfig().getDouble("link.high_speed.gate_speed");
31
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");
38
}
39
40
public void updateTrain(Minecart cart)
41
{
42
if (!linkageManager.markTrainSolved(cart))
43
{
44
return;
45
}
46
47
List<Minecart> train = linkageManager.getTrain(cart);
48
if (train.size() < 2)
49
{
50
return;
51
}
52
53
Minecart leader = linkageManager.findLeader(cart);
54
int leaderIndex = indexOf(train, leader);
55
if (leaderIndex < 0)
56
{
57
return;
58
}
59
60
for (int i = leaderIndex + 1; i < train.size(); i++)
61
{
62
constrain(train.get(i), train.get(i - 1));
63
}
64
for (int i = leaderIndex - 1; i >= 0; i--)
65
{
66
constrain(train.get(i), train.get(i + 1));
67
}
68
}
69
70
private void constrain(Minecart follower, Minecart anchor)
71
{
72
Vector followerPos = follower.getLocation().toVector();
73
Vector anchorPos = anchor.getLocation().toVector();
74
Vector between = followerPos.subtract(anchorPos);
75
double distance = between.length();
76
if (distance < 1.0E-6)
77
{
78
return;
79
}
80
81
Vector linkAxis = between.multiply(1.0 / distance);
82
Vector hint = follower.getVelocity();
83
if (hint.lengthSquared() < STILL)
84
{
85
hint = anchor.getVelocity();
86
}
87
if (hint.lengthSquared() < STILL)
88
{
89
hint = linkAxis;
90
}
91
92
Vector rail = Rails.tangent(follower.getLocation(), hint);
93
if (rail.lengthSquared() < STILL)
94
{
95
rail = linkAxis.clone().setY(0);
96
if (rail.lengthSquared() < STILL)
97
{
98
return;
99
}
100
rail.normalize();
101
}
102
103
if (rail.dot(hint) < 0 && hint.lengthSquared() >= STILL)
104
{
105
rail.multiply(-1);
106
}
107
108
double alignment = Math.abs(rail.dot(linkAxis));
109
boolean onCurve = alignment < curveAlignment;
110
double aimed = aimedDistance(anchor);
111
double stretch = distance - aimed;
112
113
double targetSpeed = anchor.getVelocity().length();
114
Vector newVelocity = rail.clone().multiply(targetSpeed);
115
116
double correction = spacingCorrection(stretch, onCurve, follower.getVelocity(), anchor.getVelocity(), rail, linkAxis);
117
if (Math.abs(correction) > 1.0E-4)
118
{
119
newVelocity.add(rail.clone().multiply(correction));
120
}
121
122
follower.setVelocity(newVelocity);
123
}
124
125
private double spacingCorrection(double stretch, boolean onCurve, Vector followerVel, Vector anchorVel, Vector rail, Vector linkAxis)
126
{
127
double slop = onCurve ? curveStretchSlop : stretchSlop;
128
if (stretch <= slop)
129
{
130
return 0;
131
}
132
133
double towardAnchor = -Math.signum(rail.dot(linkAxis));
134
if (towardAnchor == 0.0)
135
{
136
towardAnchor = -1;
137
}
138
139
double relative = followerVel.clone().subtract(anchorVel).dot(rail);
140
double correction = towardAnchor * stiffness * (stretch - slop) - damping * relative;
141
return Math.max(-maxCorrection, Math.min(maxCorrection, correction));
142
}
143
144
private double aimedDistance(Minecart anchor)
145
{
146
if (anchor.getVelocity().lengthSquared() > highSpeedGateSquared)
147
{
148
return aimedDistanceHigh;
149
}
150
return aimedDistanceLow;
151
}
152
153
private int indexOf(List<Minecart> train, Minecart cart)
154
{
155
for (int i = 0; i < train.size(); i++)
156
{
157
if (train.get(i).getUniqueId().equals(cart.getUniqueId()))
158
{
159
return i;
160
}
161
}
162
return -1;
163
}
164
}
@@ -0,0 +1,164 @@1
package me.fridtjof.minecarttrains.managers;2
3
import me.fridtjof.minecarttrains.utils.Rails;4
import org.bukkit.entity.Minecart;5
import org.bukkit.util.Vector;6
7
import java.util.List;8
9
public class LinkPhysics10
{11
12
private static final double STILL = 1.0E-4;13
14
private final LinkageManager linkageManager;15
private final double aimedDistanceLow;16
private final double aimedDistanceHigh;17
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;24
25
public LinkPhysics(LinkageManager linkageManager, ConfigManager configManager)26
{27
this.linkageManager = linkageManager;28
this.aimedDistanceLow = configManager.physicsConfig.getConfig().getDouble("link.low_speed.distance.aimed");29
this.aimedDistanceHigh = configManager.physicsConfig.getConfig().getDouble("link.high_speed.distance.aimed");30
double highSpeedGate = configManager.physicsConfig.getConfig().getDouble("link.high_speed.gate_speed");31
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");38
}39
40
public void updateTrain(Minecart cart)41
{42
if (!linkageManager.markTrainSolved(cart))43
{44
return;45
}46
47
List<Minecart> train = linkageManager.getTrain(cart);48
if (train.size() < 2)49
{50
return;51
}52
53
Minecart leader = linkageManager.findLeader(cart);54
int leaderIndex = indexOf(train, leader);55
if (leaderIndex < 0)56
{57
return;58
}59
60
for (int i = leaderIndex + 1; i < train.size(); i++)61
{62
constrain(train.get(i), train.get(i - 1));63
}64
for (int i = leaderIndex - 1; i >= 0; i--)65
{66
constrain(train.get(i), train.get(i + 1));67
}68
}69
70
private void constrain(Minecart follower, Minecart anchor)71
{72
Vector followerPos = follower.getLocation().toVector();73
Vector anchorPos = anchor.getLocation().toVector();74
Vector between = followerPos.subtract(anchorPos);75
double distance = between.length();76
if (distance < 1.0E-6)77
{78
return;79
}80
81
Vector linkAxis = between.multiply(1.0 / distance);82
Vector hint = follower.getVelocity();83
if (hint.lengthSquared() < STILL)84
{85
hint = anchor.getVelocity();86
}87
if (hint.lengthSquared() < STILL)88
{89
hint = linkAxis;90
}91
92
Vector rail = Rails.tangent(follower.getLocation(), hint);93
if (rail.lengthSquared() < STILL)94
{95
rail = linkAxis.clone().setY(0);96
if (rail.lengthSquared() < STILL)97
{98
return;99
}100
rail.normalize();101
}102
103
if (rail.dot(hint) < 0 && hint.lengthSquared() >= STILL)104
{105
rail.multiply(-1);106
}107
108
double alignment = Math.abs(rail.dot(linkAxis));109
boolean onCurve = alignment < curveAlignment;110
double aimed = aimedDistance(anchor);111
double stretch = distance - aimed;112
113
double targetSpeed = anchor.getVelocity().length();114
Vector newVelocity = rail.clone().multiply(targetSpeed);115
116
double correction = spacingCorrection(stretch, onCurve, follower.getVelocity(), anchor.getVelocity(), rail, linkAxis);117
if (Math.abs(correction) > 1.0E-4)118
{119
newVelocity.add(rail.clone().multiply(correction));120
}121
122
follower.setVelocity(newVelocity);123
}124
125
private double spacingCorrection(double stretch, boolean onCurve, Vector followerVel, Vector anchorVel, Vector rail, Vector linkAxis)126
{127
double slop = onCurve ? curveStretchSlop : stretchSlop;128
if (stretch <= slop)129
{130
return 0;131
}132
133
double towardAnchor = -Math.signum(rail.dot(linkAxis));134
if (towardAnchor == 0.0)135
{136
towardAnchor = -1;137
}138
139
double relative = followerVel.clone().subtract(anchorVel).dot(rail);140
double correction = towardAnchor * stiffness * (stretch - slop) - damping * relative;141
return Math.max(-maxCorrection, Math.min(maxCorrection, correction));142
}143
144
private double aimedDistance(Minecart anchor)145
{146
if (anchor.getVelocity().lengthSquared() > highSpeedGateSquared)147
{148
return aimedDistanceHigh;149
}150
return aimedDistanceLow;151
}152
153
private int indexOf(List<Minecart> train, Minecart cart)154
{155
for (int i = 0; i < train.size(); i++)156
{157
if (train.get(i).getUniqueId().equals(cart.getUniqueId()))158
{159
return i;160
}161
}162
return -1;163
}164
}@@ -35,6 +35,7 @@ public class LinkageManager
35
35
private final Map<UUID, UUID> headByCart = new HashMap<>();
36
36
private final Map<UUID, List<Minecart>> trainByHead = new HashMap<>();
37
37
private final Map<UUID, Minecart> leaderByHead = new HashMap<>();
38
private final Set<UUID> solvedTrains = new HashSet<>();
38
39
private int cacheTick = Integer.MIN_VALUE;
39
40
40
41
public void removeLink(Minecart cart)
@@ -342,6 +343,13 @@ public class LinkageManager
342
343
headByCart.clear();
343
344
trainByHead.clear();
344
345
leaderByHead.clear();
346
solvedTrains.clear();
347
}
348
349
public boolean markTrainSolved(Minecart cart)
350
{
351
refreshTickCache();
352
return solvedTrains.add(findHead(cart).getUniqueId());
345
353
}
346
354
347
355
private void invalidateTrainCache()
@@ -350,6 +358,7 @@ public class LinkageManager
350
358
headByCart.clear();
351
359
trainByHead.clear();
352
360
leaderByHead.clear();
361
solvedTrains.clear();
353
362
}
354
363
355
364
public boolean isCloserToLeader(Minecart candidate, Minecart other, Minecart leader)
@@ -35,6 +35,7 @@ public class LinkageManager35
private final Map<UUID, UUID> headByCart = new HashMap<>();35
private final Map<UUID, UUID> headByCart = new HashMap<>();36
private final Map<UUID, List<Minecart>> trainByHead = new HashMap<>();36
private final Map<UUID, List<Minecart>> trainByHead = new HashMap<>();37
private final Map<UUID, Minecart> leaderByHead = new HashMap<>();37
private final Map<UUID, Minecart> leaderByHead = new HashMap<>();38
private final Set<UUID> solvedTrains = new HashSet<>();38
private int cacheTick = Integer.MIN_VALUE;39
private int cacheTick = Integer.MIN_VALUE;39
40
40
public void removeLink(Minecart cart)41
public void removeLink(Minecart cart)@@ -342,6 +343,13 @@ public class LinkageManager342
headByCart.clear();343
headByCart.clear();343
trainByHead.clear();344
trainByHead.clear();344
leaderByHead.clear();345
leaderByHead.clear();346
solvedTrains.clear();347
}348
349
public boolean markTrainSolved(Minecart cart)350
{351
refreshTickCache();352
return solvedTrains.add(findHead(cart).getUniqueId());345
}353
}346
354
347
private void invalidateTrainCache()355
private void invalidateTrainCache()@@ -350,6 +358,7 @@ public class LinkageManager350
headByCart.clear();358
headByCart.clear();351
trainByHead.clear();359
trainByHead.clear();352
leaderByHead.clear();360
leaderByHead.clear();361
solvedTrains.clear();353
}362
}354
363
355
public boolean isCloserToLeader(Minecart candidate, Minecart other, Minecart leader)364
public boolean isCloserToLeader(Minecart candidate, Minecart other, Minecart leader)@@ -0,0 +1,102 @@
1
package me.fridtjof.minecarttrains.utils;
2
3
import org.bukkit.Location;
4
import org.bukkit.Tag;
5
import org.bukkit.block.Block;
6
import org.bukkit.block.BlockFace;
7
import org.bukkit.block.data.Rail;
8
import org.bukkit.util.Vector;
9
10
public 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
}
@@ -0,0 +1,102 @@1
package me.fridtjof.minecarttrains.utils;2
3
import org.bukkit.Location;4
import org.bukkit.Tag;5
import org.bukkit.block.Block;6
import org.bukkit.block.BlockFace;7
import org.bukkit.block.data.Rail;8
import org.bukkit.util.Vector;9
10
public final class Rails11
{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
}