| 1 | package net.minecraft.world.level.entity;
|
| 2 |
|
| 3 | import com.google.common.collect.ImmutableList;
|
| 4 | import com.google.common.collect.Queues;
|
| 5 | import com.google.common.collect.Sets;
|
| 6 | import com.mojang.logging.LogUtils;
|
| 7 | import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
|
| 8 | import it.unimi.dsi.fastutil.longs.Long2ObjectMaps;
|
| 9 | import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
|
| 10 | import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
|
| 11 | import it.unimi.dsi.fastutil.longs.LongSet;
|
| 12 | import it.unimi.dsi.fastutil.longs.Long2ObjectMap.Entry;
|
| 13 | import java.io.IOException;
|
| 14 | import java.io.UncheckedIOException;
|
| 15 | import java.io.Writer;
|
| 16 | import java.util.List;
|
| 17 | import java.util.Queue;
|
| 18 | import java.util.Set;
|
| 19 | import java.util.UUID;
|
| 20 | import java.util.function.Consumer;
|
| 21 | import java.util.stream.Collectors;
|
| 22 | import java.util.stream.Stream;
|
| 23 | import net.minecraft.core.BlockPos;
|
| 24 | import net.minecraft.core.SectionPos;
|
| 25 | import net.minecraft.server.level.FullChunkStatus;
|
| 26 | import net.minecraft.util.CsvOutput;
|
| 27 | import net.minecraft.util.VisibleForDebug;
|
| 28 | import net.minecraft.world.entity.Entity;
|
| 29 | import net.minecraft.world.level.ChunkPos;
|
| 30 | import org.slf4j.Logger;
|
| 31 |
|
| 32 | public class PersistentEntitySectionManager<T extends EntityAccess> implements AutoCloseable {
|
| 33 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 34 | private final Set<UUID> knownUuids = Sets.newHashSet();
|
| 35 | private final LevelCallback<T> callbacks;
|
| 36 | private final EntityPersistentStorage<T> permanentStorage;
|
| 37 | private final EntityLookup<T> visibleEntityStorage;
|
| 38 | private final EntitySectionStorage<T> sectionStorage;
|
| 39 | private final LevelEntityGetter<T> entityGetter;
|
| 40 | private final Long2ObjectMap<Visibility> chunkVisibility = new Long2ObjectOpenHashMap<>();
|
| 41 | private final Long2ObjectMap<PersistentEntitySectionManager.ChunkLoadStatus> chunkLoadStatuses = new Long2ObjectOpenHashMap<>();
|
| 42 | private final LongSet chunksToUnload = new LongOpenHashSet();
|
| 43 | private final Queue<ChunkEntities<T>> loadingInbox = Queues.newConcurrentLinkedQueue();
|
| 44 |
|
| 45 | public PersistentEntitySectionManager(final Class<T> entityClass, final LevelCallback<T> callbacks, final EntityPersistentStorage<T> permanentStorage) {
|
| 46 | this.visibleEntityStorage = new EntityLookup<>();
|
| 47 | this.sectionStorage = new EntitySectionStorage<>(entityClass, this.chunkVisibility);
|
| 48 | this.chunkVisibility.defaultReturnValue(Visibility.HIDDEN);
|
| 49 | this.chunkLoadStatuses.defaultReturnValue(PersistentEntitySectionManager.ChunkLoadStatus.FRESH);
|
| 50 | this.callbacks = callbacks;
|
| 51 | this.permanentStorage = permanentStorage;
|
| 52 | this.entityGetter = new LevelEntityGetterAdapter<>(this.visibleEntityStorage, this.sectionStorage);
|
| 53 | }
|
| 54 |
|
| 55 | private void removeSectionIfEmpty(final long sectionPos, final EntitySection<T> section) {
|
| 56 | if (section.isEmpty()) {
|
| 57 | this.sectionStorage.remove(sectionPos);
|
| 58 | }
|
| 59 | }
|
| 60 |
|
| 61 | private boolean addEntityUuid(final T entity) {
|
| 62 | if (!this.knownUuids.add(entity.getUUID())) {
|
| 63 | LOGGER.warn("UUID of added entity already exists: {}", entity);
|
| 64 | return false;
|
| 65 | } else {
|
| 66 | return true;
|
| 67 | }
|
| 68 | }
|
| 69 |
|
| 70 | public boolean addNewEntity(final T entity) {
|
| 71 | return this.addEntity(entity, false);
|
| 72 | }
|
| 73 |
|
| 74 | private boolean addEntity(final T entity, final boolean loaded) {
|
| 75 | if (!this.addEntityUuid(entity)) {
|
| 76 | return false;
|
| 77 | }
|
| 78 |
|
| 79 | long sectionKey = SectionPos.asLong(entity.blockPosition());
|
| 80 | EntitySection<T> entitySection = this.sectionStorage.getOrCreateSection(sectionKey);
|
| 81 | entitySection.add(entity);
|
| 82 | entity.setLevelCallback(new PersistentEntitySectionManager.Callback(entity, sectionKey, entitySection));
|
| 83 | if (!loaded) {
|
| 84 | this.callbacks.onCreated(entity);
|
| 85 | }
|
| 86 |
|
| 87 | Visibility status = getEffectiveStatus(entity, entitySection.getStatus());
|
| 88 | if (status.isAccessible()) {
|
| 89 | this.startTracking(entity);
|
| 90 | }
|
| 91 |
|
| 92 | if (status.isTicking()) {
|
| 93 | this.startTicking(entity);
|
| 94 | }
|
| 95 |
|
| 96 | return true;
|
| 97 | }
|
| 98 |
|
| 99 | private static <T extends EntityAccess> Visibility getEffectiveStatus(final T entity, final Visibility status) {
|
| 100 | return entity.isAlwaysTicking() ? Visibility.TICKING : status;
|
| 101 | }
|
| 102 |
|
| 103 | public boolean isTicking(final ChunkPos pos) {
|
| 104 | return this.chunkVisibility.get(pos.pack()).isTicking();
|
| 105 | }
|
| 106 |
|
| 107 | public void addLegacyChunkEntities(final Stream<T> entities) {
|
| 108 | entities.forEach(e -> this.addEntity((T)e, true));
|
| 109 | }
|
| 110 |
|
| 111 | public void addWorldGenChunkEntities(final Stream<T> entities) {
|
| 112 | entities.forEach(e -> this.addEntity((T)e, false));
|
| 113 | }
|
| 114 |
|
| 115 | private void startTicking(final T entity) {
|
| 116 | this.callbacks.onTickingStart(entity);
|
| 117 | }
|
| 118 |
|
| 119 | private void stopTicking(final T entity) {
|
| 120 | this.callbacks.onTickingEnd(entity);
|
| 121 | }
|
| 122 |
|
| 123 | private void startTracking(final T entity) {
|
| 124 | this.visibleEntityStorage.add(entity);
|
| 125 | this.callbacks.onTrackingStart(entity);
|
| 126 | }
|
| 127 |
|
| 128 | private void stopTracking(final T entity) {
|
| 129 | this.callbacks.onTrackingEnd(entity);
|
| 130 | this.visibleEntityStorage.remove(entity);
|
| 131 | }
|
| 132 |
|
| 133 | public void updateChunkStatus(final ChunkPos pos, final FullChunkStatus fullChunkStatus) {
|
| 134 | Visibility chunkStatus = Visibility.fromFullChunkStatus(fullChunkStatus);
|
| 135 | this.updateChunkStatus(pos, chunkStatus);
|
| 136 | }
|
| 137 |
|
| 138 | public void updateChunkStatus(final ChunkPos pos, final Visibility chunkStatus) {
|
| 139 | long chunkPosKey = pos.pack();
|
| 140 | if (chunkStatus == Visibility.HIDDEN) {
|
| 141 | this.chunkVisibility.remove(chunkPosKey);
|
| 142 | this.chunksToUnload.add(chunkPosKey);
|
| 143 | } else {
|
| 144 | this.chunkVisibility.put(chunkPosKey, chunkStatus);
|
| 145 | this.chunksToUnload.remove(chunkPosKey);
|
| 146 | this.ensureChunkQueuedForLoad(chunkPosKey);
|
| 147 | }
|
| 148 |
|
| 149 | this.sectionStorage.getExistingSectionsInChunk(chunkPosKey).forEach(section -> {
|
| 150 | Visibility previousStatus = section.updateChunkStatus(chunkStatus);
|
| 151 | boolean wasAccessible = previousStatus.isAccessible();
|
| 152 | boolean isAccessible = chunkStatus.isAccessible();
|
| 153 | boolean wasTicking = previousStatus.isTicking();
|
| 154 | boolean isTicking = chunkStatus.isTicking();
|
| 155 | if (wasTicking && !isTicking) {
|
| 156 | section.getEntities().filter(e -> !e.isAlwaysTicking()).forEach(this::stopTicking);
|
| 157 | }
|
| 158 |
|
| 159 | if (wasAccessible && !isAccessible) {
|
| 160 | section.getEntities().filter(e -> !e.isAlwaysTicking()).forEach(this::stopTracking);
|
| 161 | } else if (!wasAccessible && isAccessible) {
|
| 162 | section.getEntities().filter(e -> !e.isAlwaysTicking()).forEach(this::startTracking);
|
| 163 | }
|
| 164 |
|
| 165 | if (!wasTicking && isTicking) {
|
| 166 | section.getEntities().filter(e -> !e.isAlwaysTicking()).forEach(this::startTicking);
|
| 167 | }
|
| 168 | });
|
| 169 | }
|
| 170 |
|
| 171 | private void ensureChunkQueuedForLoad(final long chunkPos) {
|
| 172 | PersistentEntitySectionManager.ChunkLoadStatus chunkLoadStatus = this.chunkLoadStatuses.get(chunkPos);
|
| 173 | if (chunkLoadStatus == PersistentEntitySectionManager.ChunkLoadStatus.FRESH) {
|
| 174 | this.requestChunkLoad(chunkPos);
|
| 175 | }
|
| 176 | }
|
| 177 |
|
| 178 | private boolean storeChunkSections(final long chunkPos, final Consumer<T> savedEntityVisitor) {
|
| 179 | PersistentEntitySectionManager.ChunkLoadStatus chunkLoadStatus = this.chunkLoadStatuses.get(chunkPos);
|
| 180 | if (chunkLoadStatus == PersistentEntitySectionManager.ChunkLoadStatus.PENDING) {
|
| 181 | return false;
|
| 182 | }
|
| 183 |
|
| 184 | List<T> rootEntitiesToSave = this.sectionStorage
|
| 185 | .getExistingSectionsInChunk(chunkPos)
|
| 186 | .flatMap(section -> section.getEntities().filter(EntityAccess::shouldBeSaved))
|
| 187 | .collect(Collectors.toList());
|
| 188 | if (rootEntitiesToSave.isEmpty()) {
|
| 189 | if (chunkLoadStatus == PersistentEntitySectionManager.ChunkLoadStatus.LOADED) {
|
| 190 | this.permanentStorage.storeEntities(new ChunkEntities<>(ChunkPos.unpack(chunkPos), ImmutableList.of()));
|
| 191 | }
|
| 192 |
|
| 193 | return true;
|
| 194 | } else if (chunkLoadStatus == PersistentEntitySectionManager.ChunkLoadStatus.FRESH) {
|
| 195 | this.requestChunkLoad(chunkPos);
|
| 196 | return false;
|
| 197 | } else {
|
| 198 | this.permanentStorage.storeEntities(new ChunkEntities<>(ChunkPos.unpack(chunkPos), rootEntitiesToSave));
|
| 199 | rootEntitiesToSave.forEach(savedEntityVisitor);
|
| 200 | return true;
|
| 201 | }
|
| 202 | }
|
| 203 |
|
| 204 | private void requestChunkLoad(final long chunkKey) {
|
| 205 | this.chunkLoadStatuses.put(chunkKey, PersistentEntitySectionManager.ChunkLoadStatus.PENDING);
|
| 206 | ChunkPos pos = ChunkPos.unpack(chunkKey);
|
| 207 | this.permanentStorage.loadEntities(pos).thenAccept(this.loadingInbox::add).exceptionally(t -> {
|
| 208 | LOGGER.error("Failed to read chunk {}", pos, t);
|
| 209 | return null;
|
| 210 | });
|
| 211 | }
|
| 212 |
|
| 213 | private boolean processChunkUnload(final long chunkKey) {
|
| 214 | boolean storeSuccessful = this.storeChunkSections(chunkKey, entity -> entity.getPassengersAndSelf().forEach(this::unloadEntity));
|
| 215 | if (!storeSuccessful) {
|
| 216 | return false;
|
| 217 | }
|
| 218 |
|
| 219 | this.chunkLoadStatuses.remove(chunkKey);
|
| 220 | return true;
|
| 221 | }
|
| 222 |
|
| 223 | private void unloadEntity(final EntityAccess e) {
|
| 224 | e.setRemoved(Entity.RemovalReason.UNLOADED_TO_CHUNK);
|
| 225 | e.setLevelCallback(EntityInLevelCallback.NULL);
|
| 226 | }
|
| 227 |
|
| 228 | private void processUnloads() {
|
| 229 | this.chunksToUnload.removeIf(chunkKey -> this.chunkVisibility.get(chunkKey) != Visibility.HIDDEN ? true : this.processChunkUnload(chunkKey));
|
| 230 | }
|
| 231 |
|
| 232 | public void processPendingLoads() {
|
| 233 | ChunkEntities<T> loadedChunk;
|
| 234 | while ((loadedChunk = this.loadingInbox.poll()) != null) {
|
| 235 | loadedChunk.getEntities().forEach(e -> this.addEntity((T)e, true));
|
| 236 | this.chunkLoadStatuses.put(loadedChunk.getPos().pack(), PersistentEntitySectionManager.ChunkLoadStatus.LOADED);
|
| 237 | }
|
| 238 | }
|
| 239 |
|
| 240 | public void tick() {
|
| 241 | this.processPendingLoads();
|
| 242 | this.processUnloads();
|
| 243 | }
|
| 244 |
|
| 245 | private LongSet getAllChunksToSave() {
|
| 246 | LongSet result = this.sectionStorage.getAllChunksWithExistingSections();
|
| 247 |
|
| 248 | for (Entry<PersistentEntitySectionManager.ChunkLoadStatus> entry : Long2ObjectMaps.fastIterable(this.chunkLoadStatuses)) {
|
| 249 | if (entry.getValue() == PersistentEntitySectionManager.ChunkLoadStatus.LOADED) {
|
| 250 | result.add(entry.getLongKey());
|
| 251 | }
|
| 252 | }
|
| 253 |
|
| 254 | return result;
|
| 255 | }
|
| 256 |
|
| 257 | public void autoSave() {
|
| 258 | this.getAllChunksToSave().forEach(chunkKey -> {
|
| 259 | boolean shouldUnload = this.chunkVisibility.get(chunkKey) == Visibility.HIDDEN;
|
| 260 | if (shouldUnload) {
|
| 261 | this.processChunkUnload(chunkKey);
|
| 262 | } else {
|
| 263 | this.storeChunkSections(chunkKey, e -> {});
|
| 264 | }
|
| 265 | });
|
| 266 | }
|
| 267 |
|
| 268 | public void saveAll() {
|
| 269 | LongSet chunksToSave = this.getAllChunksToSave();
|
| 270 |
|
| 271 | while (!chunksToSave.isEmpty()) {
|
| 272 | this.permanentStorage.flush(false);
|
| 273 | this.processPendingLoads();
|
| 274 | chunksToSave.removeIf(chunkKey -> {
|
| 275 | boolean shouldUnload = this.chunkVisibility.get(chunkKey) == Visibility.HIDDEN;
|
| 276 | return shouldUnload ? this.processChunkUnload(chunkKey) : this.storeChunkSections(chunkKey, e -> {});
|
| 277 | });
|
| 278 | }
|
| 279 |
|
| 280 | this.permanentStorage.flush(true);
|
| 281 | }
|
| 282 |
|
| 283 | @Override
|
| 284 | public void close() throws IOException {
|
| 285 | this.saveAll();
|
| 286 | this.permanentStorage.close();
|
| 287 | }
|
| 288 |
|
| 289 | public boolean isLoaded(final UUID uuid) {
|
| 290 | return this.knownUuids.contains(uuid);
|
| 291 | }
|
| 292 |
|
| 293 | public LevelEntityGetter<T> getEntityGetter() {
|
| 294 | return this.entityGetter;
|
| 295 | }
|
| 296 |
|
| 297 | public boolean canPositionTick(final BlockPos pos) {
|
| 298 | return this.chunkVisibility.get(ChunkPos.pack(pos)).isTicking();
|
| 299 | }
|
| 300 |
|
| 301 | public boolean canPositionTick(final ChunkPos pos) {
|
| 302 | return this.chunkVisibility.get(pos.pack()).isTicking();
|
| 303 | }
|
| 304 |
|
| 305 | public boolean areEntitiesLoaded(final long chunkKey) {
|
| 306 | return this.chunkLoadStatuses.get(chunkKey) == PersistentEntitySectionManager.ChunkLoadStatus.LOADED;
|
| 307 | }
|
| 308 |
|
| 309 | public void dumpSections(final Writer output) throws IOException {
|
| 310 | CsvOutput csvOutput = CsvOutput.builder()
|
| 311 | .addColumn("x")
|
| 312 | .addColumn("y")
|
| 313 | .addColumn("z")
|
| 314 | .addColumn("visibility")
|
| 315 | .addColumn("load_status")
|
| 316 | .addColumn("entity_count")
|
| 317 | .build(output);
|
| 318 | this.sectionStorage.getAllChunksWithExistingSections().forEach(chunkKey -> {
|
| 319 | PersistentEntitySectionManager.ChunkLoadStatus loadStatus = this.chunkLoadStatuses.get(chunkKey);
|
| 320 | this.sectionStorage.getExistingSectionPositionsInChunk(chunkKey).forEach(sectionKey -> {
|
| 321 | EntitySection<T> section = this.sectionStorage.getSection(sectionKey);
|
| 322 | if (section != null) {
|
| 323 | try {
|
| 324 | csvOutput.writeRow(SectionPos.x(sectionKey), SectionPos.y(sectionKey), SectionPos.z(sectionKey), section.getStatus(), loadStatus, section.size());
|
| 325 | } catch (IOException e) {
|
| 326 | throw new UncheckedIOException(e);
|
| 327 | }
|
| 328 | }
|
| 329 | });
|
| 330 | });
|
| 331 | }
|
| 332 |
|
| 333 | @VisibleForDebug
|
| 334 | public String gatherStats() {
|
| 335 | return this.knownUuids.size()
|
| 336 | + ","
|
| 337 | + this.visibleEntityStorage.count()
|
| 338 | + ","
|
| 339 | + this.sectionStorage.count()
|
| 340 | + ","
|
| 341 | + this.chunkLoadStatuses.size()
|
| 342 | + ","
|
| 343 | + this.chunkVisibility.size()
|
| 344 | + ","
|
| 345 | + this.loadingInbox.size()
|
| 346 | + ","
|
| 347 | + this.chunksToUnload.size();
|
| 348 | }
|
| 349 |
|
| 350 | @VisibleForDebug
|
| 351 | public int count() {
|
| 352 | return this.visibleEntityStorage.count();
|
| 353 | }
|
| 354 |
|
| 355 | private class Callback implements EntityInLevelCallback {
|
| 356 | private final T entity;
|
| 357 | private long currentSectionKey;
|
| 358 | private EntitySection<T> currentSection;
|
| 359 |
|
| 360 | private Callback(final T entity, final long currentSectionKey, final EntitySection<T> currentSection) {
|
| 361 | this.entity = entity;
|
| 362 | this.currentSectionKey = currentSectionKey;
|
| 363 | this.currentSection = currentSection;
|
| 364 | }
|
| 365 |
|
| 366 | @Override
|
| 367 | public void onMove() {
|
| 368 | BlockPos pos = this.entity.blockPosition();
|
| 369 | long newSectionPos = SectionPos.asLong(pos);
|
| 370 | if (newSectionPos != this.currentSectionKey) {
|
| 371 | Visibility previousStatus = this.currentSection.getStatus();
|
| 372 | if (!this.currentSection.remove(this.entity)) {
|
| 373 | PersistentEntitySectionManager.LOGGER
|
| 374 | .warn("Entity {} wasn't found in section {} (moving to {})", this.entity, SectionPos.of(this.currentSectionKey), newSectionPos);
|
| 375 | }
|
| 376 |
|
| 377 | PersistentEntitySectionManager.this.removeSectionIfEmpty(this.currentSectionKey, this.currentSection);
|
| 378 | EntitySection<T> newSection = PersistentEntitySectionManager.this.sectionStorage.getOrCreateSection(newSectionPos);
|
| 379 | newSection.add(this.entity);
|
| 380 | this.currentSection = newSection;
|
| 381 | this.currentSectionKey = newSectionPos;
|
| 382 | this.updateStatus(previousStatus, newSection.getStatus());
|
| 383 | }
|
| 384 | }
|
| 385 |
|
| 386 | private void updateStatus(final Visibility previousStatus, final Visibility newStatus) {
|
| 387 | Visibility effectivePreviousStatus = PersistentEntitySectionManager.getEffectiveStatus(this.entity, previousStatus);
|
| 388 | Visibility effectiveNewStatus = PersistentEntitySectionManager.getEffectiveStatus(this.entity, newStatus);
|
| 389 | if (effectivePreviousStatus == effectiveNewStatus) {
|
| 390 | if (effectiveNewStatus.isAccessible()) {
|
| 391 | PersistentEntitySectionManager.this.callbacks.onSectionChange(this.entity);
|
| 392 | }
|
| 393 | } else {
|
| 394 | boolean wasAccessible = effectivePreviousStatus.isAccessible();
|
| 395 | boolean isAccessible = effectiveNewStatus.isAccessible();
|
| 396 | if (wasAccessible && !isAccessible) {
|
| 397 | PersistentEntitySectionManager.this.stopTracking(this.entity);
|
| 398 | } else if (!wasAccessible && isAccessible) {
|
| 399 | PersistentEntitySectionManager.this.startTracking(this.entity);
|
| 400 | }
|
| 401 |
|
| 402 | boolean wasTicking = effectivePreviousStatus.isTicking();
|
| 403 | boolean isTicking = effectiveNewStatus.isTicking();
|
| 404 | if (wasTicking && !isTicking) {
|
| 405 | PersistentEntitySectionManager.this.stopTicking(this.entity);
|
| 406 | } else if (!wasTicking && isTicking) {
|
| 407 | PersistentEntitySectionManager.this.startTicking(this.entity);
|
| 408 | }
|
| 409 |
|
| 410 | if (isAccessible) {
|
| 411 | PersistentEntitySectionManager.this.callbacks.onSectionChange(this.entity);
|
| 412 | }
|
| 413 | }
|
| 414 | }
|
| 415 |
|
| 416 | @Override
|
| 417 | public void onRemove(final Entity.RemovalReason reason) {
|
| 418 | if (!this.currentSection.remove(this.entity)) {
|
| 419 | PersistentEntitySectionManager.LOGGER
|
| 420 | .warn("Entity {} wasn't found in section {} (destroying due to {})", this.entity, SectionPos.of(this.currentSectionKey), reason);
|
| 421 | }
|
| 422 |
|
| 423 | Visibility status = PersistentEntitySectionManager.getEffectiveStatus(this.entity, this.currentSection.getStatus());
|
| 424 | if (status.isTicking()) {
|
| 425 | PersistentEntitySectionManager.this.stopTicking(this.entity);
|
| 426 | }
|
| 427 |
|
| 428 | if (status.isAccessible()) {
|
| 429 | PersistentEntitySectionManager.this.stopTracking(this.entity);
|
| 430 | }
|
| 431 |
|
| 432 | if (reason.shouldDestroy()) {
|
| 433 | PersistentEntitySectionManager.this.callbacks.onDestroyed(this.entity);
|
| 434 | }
|
| 435 |
|
| 436 | PersistentEntitySectionManager.this.knownUuids.remove(this.entity.getUUID());
|
| 437 | this.entity.setLevelCallback(NULL);
|
| 438 | PersistentEntitySectionManager.this.removeSectionIfEmpty(this.currentSectionKey, this.currentSection);
|
| 439 | }
|
| 440 | }
|
| 441 |
|
| 442 | private enum ChunkLoadStatus {
|
| 443 | FRESH,
|
| 444 | PENDING,
|
| 445 | LOADED;
|
| 446 | }
|
| 447 | }
|
| 448 |
|