Fix removal scheduling involving server ticks

Signed-off-by: TheMode <themode@outlook.fr>
This commit is contained in:
TheMode 2022-01-30 08:23:34 +01:00
parent f1ca048eb6
commit 5b699e0375
2 changed files with 52 additions and 2 deletions

View File

@ -1453,7 +1453,11 @@ public class Entity implements Viewable, Tickable, Schedulable, TagHandler, Perm
* @param temporalUnit the unit of the delay
*/
public void scheduleRemove(long delay, @NotNull TemporalUnit temporalUnit) {
scheduleRemove(Duration.of(delay, temporalUnit));
if (temporalUnit == TimeUnit.SERVER_TICK) {
scheduleRemove(TaskSchedule.tick((int) delay));
} else {
scheduleRemove(Duration.of(delay, temporalUnit));
}
}
/**
@ -1462,7 +1466,11 @@ public class Entity implements Viewable, Tickable, Schedulable, TagHandler, Perm
* @param delay the time before removing the entity
*/
public void scheduleRemove(Duration delay) {
this.scheduler.buildTask(this::remove).delay(TaskSchedule.duration(delay)).schedule();
scheduleRemove(TaskSchedule.duration(delay));
}
private void scheduleRemove(TaskSchedule schedule) {
this.scheduler.buildTask(this::remove).delay(schedule).schedule();
}
protected @NotNull Vec getVelocityForPacket() {

View File

@ -0,0 +1,42 @@
package net.minestom.server.entity;
import net.minestom.server.api.Env;
import net.minestom.server.api.EnvTest;
import net.minestom.server.coordinate.Pos;
import net.minestom.server.utils.time.TimeUnit;
import org.junit.jupiter.api.Test;
import java.time.temporal.TemporalUnit;
import static org.junit.jupiter.api.Assertions.*;
@EnvTest
public class EntityScheduledRemovalIntegrationTest {
@Test
public void tickRemoval(Env env) throws InterruptedException {
var instance = env.createFlatInstance();
var entity = new TestEntity(2, TimeUnit.SERVER_TICK);
entity.setInstance(instance, new Pos(0, 40, 0)).join();
assertFalse(entity.isRemoved());
assertEquals(0, entity.getAliveTicks());
Thread.sleep(150); // Ensure that time is not used for tick scheduling
env.tick();
assertFalse(entity.isRemoved());
assertEquals(1, entity.getAliveTicks());
env.tick();
assertTrue(entity.isRemoved());
assertEquals(1, entity.getAliveTicks());
}
static final class TestEntity extends Entity {
public TestEntity(long delay, TemporalUnit unit) {
super(EntityType.ZOMBIE);
scheduleRemove(delay, unit);
}
}
}