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 14:22:03 +02:00
|
|
|
|
2020-04-15 12:37:14 +02:00
|
|
|
import net.minecraft.world.World;
|
|
|
|
|
|
|
|
public class AwaitTickQueue {
|
|
|
|
|
2020-04-24 15:23:36 +02:00
|
|
|
private static final Queue<Consumer<World>> SCHEDULED_TASKS = Queues.newArrayDeque();
|
|
|
|
private static List<DelayedTask> DELAYED_TASKS = Lists.newArrayList();
|
2020-04-15 12:37:14 +02:00
|
|
|
|
2020-04-24 15:23:36 +02:00
|
|
|
private static final Object LOCKER = new Object();
|
2020-04-15 12:37:14 +02:00
|
|
|
|
|
|
|
public static void enqueueTask(Consumer<World> task) {
|
2020-04-24 15:23:36 +02:00
|
|
|
synchronized (LOCKER) {
|
|
|
|
SCHEDULED_TASKS.add(task);
|
2020-04-15 12:37:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public static void scheduleTask(Consumer<World> task, int ticksLater) {
|
2020-04-24 15:23:36 +02:00
|
|
|
synchronized (LOCKER) {
|
|
|
|
DELAYED_TASKS.add(new DelayedTask(task, ticksLater));
|
2020-04-15 12:37:14 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-05-28 18:09:53 +02:00
|
|
|
static void tick(World world) {
|
2020-04-24 15:23:36 +02:00
|
|
|
synchronized (LOCKER) {
|
|
|
|
DELAYED_TASKS = DELAYED_TASKS.stream().filter(DelayedTask::tick).collect(Collectors.toList());
|
2020-04-15 12:37:14 +02:00
|
|
|
|
|
|
|
Consumer<World> task;
|
2020-04-24 15:23:36 +02:00
|
|
|
while ((task = SCHEDULED_TASKS.poll()) != null) {
|
2020-04-15 12:37:14 +02:00
|
|
|
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) {
|
2020-04-24 15:23:36 +02:00
|
|
|
SCHEDULED_TASKS.add(task);
|
2020-04-15 12:37:14 +02:00
|
|
|
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|