Unicopia/src/main/java/com/minelittlepony/unicopia/AwaitTickQueue.java

69 lines
1.7 KiB
Java
Raw Normal View History

2020-04-15 19:06:45 +02:00
package com.minelittlepony.unicopia;
2020-04-15 12:37:14 +02:00
import java.util.List;
import java.util.Queue;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import com.google.common.collect.Lists;
import com.google.common.collect.Queues;
2020-04-15 12:37:14 +02:00
import net.minecraft.world.World;
public class AwaitTickQueue {
private static final Queue<Consumer<World>> tickTasks = Queues.newArrayDeque();
private static List<DelayedTask> delayedTasks = Lists.newArrayList();
private static final Object locker = new Object();
public static void enqueueTask(Consumer<World> task) {
synchronized (locker) {
tickTasks.add(task);
}
}
public static void scheduleTask(Consumer<World> task, int ticksLater) {
synchronized (locker) {
delayedTasks.add(new DelayedTask(task, ticksLater));
}
}
public void tick(World world) {
2020-04-15 12:37:14 +02:00
synchronized (locker) {
delayedTasks = delayedTasks.stream().filter(DelayedTask::tick).collect(Collectors.toList());
Consumer<World> task;
while ((task = tickTasks.poll()) != null) {
try {
task.accept(world);
} catch (Exception e) {
2020-04-16 00:44:58 +02:00
Unicopia.LOGGER.error(e);
2020-04-15 12:37:14 +02:00
}
}
}
}
private static class DelayedTask {
final Consumer<World> task;
int ticksDelay;
DelayedTask(Consumer<World> task, int ticks) {
this.task = task;
this.ticksDelay = ticks;
}
boolean tick() {
if (ticksDelay-- <= 0) {
tickTasks.add(task);
return false;
}
return true;
}
}
}