| 1 | package net.minecraft.world.level.chunk.storage;
|
| 2 |
|
| 3 | import com.google.common.collect.ImmutableMap;
|
| 4 | import com.google.common.collect.Maps;
|
| 5 | import com.mojang.logging.LogUtils;
|
| 6 | import com.mojang.serialization.Codec;
|
| 7 | import com.mojang.serialization.DataResult;
|
| 8 | import com.mojang.serialization.Dynamic;
|
| 9 | import com.mojang.serialization.DynamicOps;
|
| 10 | import com.mojang.serialization.OptionalDynamic;
|
| 11 | import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
| 12 | import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
|
| 13 | import it.unimi.dsi.fastutil.longs.Long2ObjectMap;
|
| 14 | import it.unimi.dsi.fastutil.longs.Long2ObjectMaps;
|
| 15 | import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap;
|
| 16 | import it.unimi.dsi.fastutil.longs.LongIterator;
|
| 17 | import it.unimi.dsi.fastutil.longs.LongLinkedOpenHashSet;
|
| 18 | import it.unimi.dsi.fastutil.longs.LongOpenHashSet;
|
| 19 | import it.unimi.dsi.fastutil.longs.LongSet;
|
| 20 | import it.unimi.dsi.fastutil.longs.Long2ObjectMap.Entry;
|
| 21 | import java.io.IOException;
|
| 22 | import java.util.Iterator;
|
| 23 | import java.util.Map;
|
| 24 | import java.util.Optional;
|
| 25 | import java.util.concurrent.CompletableFuture;
|
| 26 | import java.util.concurrent.CompletionException;
|
| 27 | import java.util.function.BiFunction;
|
| 28 | import java.util.function.BooleanSupplier;
|
| 29 | import java.util.function.Function;
|
| 30 | import net.minecraft.SharedConstants;
|
| 31 | import net.minecraft.core.RegistryAccess;
|
| 32 | import net.minecraft.core.SectionPos;
|
| 33 | import net.minecraft.nbt.CompoundTag;
|
| 34 | import net.minecraft.nbt.NbtOps;
|
| 35 | import net.minecraft.nbt.Tag;
|
| 36 | import net.minecraft.resources.RegistryOps;
|
| 37 | import net.minecraft.util.Util;
|
| 38 | import net.minecraft.world.level.ChunkPos;
|
| 39 | import net.minecraft.world.level.LevelHeightAccessor;
|
| 40 | import org.jspecify.annotations.Nullable;
|
| 41 | import org.slf4j.Logger;
|
| 42 |
|
| 43 | public class SectionStorage<R, P> implements AutoCloseable {
|
| 44 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 45 | private static final String SECTIONS_TAG = "Sections";
|
| 46 | private final SimpleRegionStorage simpleRegionStorage;
|
| 47 | private final Long2ObjectMap<Optional<R>> storage = new Long2ObjectOpenHashMap<>();
|
| 48 | private final LongLinkedOpenHashSet dirtyChunks = new LongLinkedOpenHashSet();
|
| 49 | private final Codec<P> codec;
|
| 50 | private final Function<R, P> packer;
|
| 51 | private final BiFunction<P, Runnable, R> unpacker;
|
| 52 | private final Function<Runnable, R> factory;
|
| 53 | private final RegistryAccess registryAccess;
|
| 54 | private final ChunkIOErrorReporter errorReporter;
|
| 55 | protected final LevelHeightAccessor levelHeightAccessor;
|
| 56 | private final LongSet loadedChunks = new LongOpenHashSet();
|
| 57 | private final Long2ObjectMap<CompletableFuture<Optional<SectionStorage.PackedChunk<P>>>> pendingLoads = new Long2ObjectOpenHashMap<>();
|
| 58 | private final Object loadLock = new Object();
|
| 59 |
|
| 60 | public SectionStorage(
|
| 61 | final SimpleRegionStorage simpleRegionStorage,
|
| 62 | final Codec<P> codec,
|
| 63 | final Function<R, P> packer,
|
| 64 | final BiFunction<P, Runnable, R> unpacker,
|
| 65 | final Function<Runnable, R> factory,
|
| 66 | final RegistryAccess registryAccess,
|
| 67 | final ChunkIOErrorReporter errorReporter,
|
| 68 | final LevelHeightAccessor levelHeightAccessor
|
| 69 | ) {
|
| 70 | this.simpleRegionStorage = simpleRegionStorage;
|
| 71 | this.codec = codec;
|
| 72 | this.packer = packer;
|
| 73 | this.unpacker = unpacker;
|
| 74 | this.factory = factory;
|
| 75 | this.registryAccess = registryAccess;
|
| 76 | this.errorReporter = errorReporter;
|
| 77 | this.levelHeightAccessor = levelHeightAccessor;
|
| 78 | }
|
| 79 |
|
| 80 | protected void tick(final BooleanSupplier haveTime) {
|
| 81 | LongIterator iterator = this.dirtyChunks.iterator();
|
| 82 |
|
| 83 | while (iterator.hasNext() && haveTime.getAsBoolean()) {
|
| 84 | ChunkPos chunkPos = ChunkPos.unpack(iterator.nextLong());
|
| 85 | iterator.remove();
|
| 86 | this.writeChunk(chunkPos);
|
| 87 | }
|
| 88 |
|
| 89 | this.unpackPendingLoads();
|
| 90 | }
|
| 91 |
|
| 92 | private void unpackPendingLoads() {
|
| 93 | synchronized (this.loadLock) {
|
| 94 | Iterator<Entry<CompletableFuture<Optional<SectionStorage.PackedChunk<P>>>>> iterator = Long2ObjectMaps.fastIterator(this.pendingLoads);
|
| 95 |
|
| 96 | while (iterator.hasNext()) {
|
| 97 | Entry<CompletableFuture<Optional<SectionStorage.PackedChunk<P>>>> entry = iterator.next();
|
| 98 | Optional<SectionStorage.PackedChunk<P>> chunk = entry.getValue().getNow(null);
|
| 99 | if (chunk != null) {
|
| 100 | long chunkKey = entry.getLongKey();
|
| 101 | this.unpackChunk(ChunkPos.unpack(chunkKey), chunk.orElse(null));
|
| 102 | iterator.remove();
|
| 103 | this.loadedChunks.add(chunkKey);
|
| 104 | }
|
| 105 | }
|
| 106 | }
|
| 107 | }
|
| 108 |
|
| 109 | public void flushAll() {
|
| 110 | if (!this.dirtyChunks.isEmpty()) {
|
| 111 | this.dirtyChunks.forEach(pos -> this.writeChunk(ChunkPos.unpack(pos)));
|
| 112 | this.dirtyChunks.clear();
|
| 113 | }
|
| 114 | }
|
| 115 |
|
| 116 | public boolean hasWork() {
|
| 117 | return !this.dirtyChunks.isEmpty();
|
| 118 | }
|
| 119 |
|
| 120 | protected @Nullable Optional<R> get(final long sectionPos) {
|
| 121 | return this.storage.get(sectionPos);
|
| 122 | }
|
| 123 |
|
| 124 | protected Optional<R> getOrLoad(final long sectionPos) {
|
| 125 | if (this.outsideStoredRange(sectionPos)) {
|
| 126 | return Optional.empty();
|
| 127 | } else {
|
| 128 | Optional<R> r = this.get(sectionPos);
|
| 129 | if (r != null) {
|
| 130 | return r;
|
| 131 | } else {
|
| 132 | this.unpackChunk(SectionPos.of(sectionPos).chunk());
|
| 133 | r = this.get(sectionPos);
|
| 134 | if (r == null) {
|
| 135 | throw (IllegalStateException)Util.pauseInIde(new IllegalStateException());
|
| 136 | } else {
|
| 137 | return r;
|
| 138 | }
|
| 139 | }
|
| 140 | }
|
| 141 | }
|
| 142 |
|
| 143 | protected boolean outsideStoredRange(final long sectionPos) {
|
| 144 | int y = SectionPos.sectionToBlockCoord(SectionPos.y(sectionPos));
|
| 145 | return this.levelHeightAccessor.isOutsideBuildHeight(y);
|
| 146 | }
|
| 147 |
|
| 148 | protected R getOrCreate(final long sectionPos) {
|
| 149 | if (this.outsideStoredRange(sectionPos)) {
|
| 150 | throw (IllegalArgumentException)Util.pauseInIde(new IllegalArgumentException("sectionPos out of bounds"));
|
| 151 | }
|
| 152 |
|
| 153 | Optional<R> r = this.getOrLoad(sectionPos);
|
| 154 | if (r.isPresent()) {
|
| 155 | return r.get();
|
| 156 | }
|
| 157 |
|
| 158 | R newR = this.factory.apply(() -> this.setDirty(sectionPos));
|
| 159 | this.storage.put(sectionPos, Optional.of(newR));
|
| 160 | return newR;
|
| 161 | }
|
| 162 |
|
| 163 | public CompletableFuture<?> prefetch(final ChunkPos chunkPos) {
|
| 164 | synchronized (this.loadLock) {
|
| 165 | long chunkKey = chunkPos.pack();
|
| 166 | return this.loadedChunks.contains(chunkKey)
|
| 167 | ? CompletableFuture.completedFuture(null)
|
| 168 | : this.pendingLoads.computeIfAbsent(chunkKey, k -> this.tryRead(chunkPos));
|
| 169 | }
|
| 170 | }
|
| 171 |
|
| 172 | private void unpackChunk(final ChunkPos chunkPos) {
|
| 173 | long chunkKey = chunkPos.pack();
|
| 174 | CompletableFuture<Optional<SectionStorage.PackedChunk<P>>> future;
|
| 175 | synchronized (this.loadLock) {
|
| 176 | if (!this.loadedChunks.add(chunkKey)) {
|
| 177 | return;
|
| 178 | }
|
| 179 |
|
| 180 | future = this.pendingLoads.computeIfAbsent(chunkKey, k -> this.tryRead(chunkPos));
|
| 181 | }
|
| 182 |
|
| 183 | this.unpackChunk(chunkPos, future.join().orElse(null));
|
| 184 | synchronized (this.loadLock) {
|
| 185 | this.pendingLoads.remove(chunkKey);
|
| 186 | }
|
| 187 | }
|
| 188 |
|
| 189 | private CompletableFuture<Optional<SectionStorage.PackedChunk<P>>> tryRead(final ChunkPos chunkPos) {
|
| 190 | RegistryOps<Tag> registryOps = this.registryAccess.createSerializationContext(NbtOps.INSTANCE);
|
| 191 | return this.simpleRegionStorage
|
| 192 | .read(chunkPos)
|
| 193 | .thenApplyAsync(
|
| 194 | result -> result.map(tag -> SectionStorage.PackedChunk.parse(this.codec, registryOps, tag, this.simpleRegionStorage, this.levelHeightAccessor)),
|
| 195 | Util.backgroundExecutor().forName("parseSection")
|
| 196 | )
|
| 197 | .exceptionally(throwable -> {
|
| 198 | if (throwable instanceof CompletionException) {
|
| 199 | throwable = throwable.getCause();
|
| 200 | }
|
| 201 |
|
| 202 | if (throwable instanceof IOException e) {
|
| 203 | LOGGER.error("Error reading chunk {} data from disk", chunkPos, e);
|
| 204 | this.errorReporter.reportChunkLoadFailure(e, this.simpleRegionStorage.storageInfo(), chunkPos);
|
| 205 | return Optional.empty();
|
| 206 | } else {
|
| 207 | throw new CompletionException(throwable);
|
| 208 | }
|
| 209 | });
|
| 210 | }
|
| 211 |
|
| 212 | private void unpackChunk(final ChunkPos pos, final SectionStorage.@Nullable PackedChunk<P> packedChunk) {
|
| 213 | if (packedChunk == null) {
|
| 214 | for (int sectionY = this.levelHeightAccessor.getMinSectionY(); sectionY <= this.levelHeightAccessor.getMaxSectionY(); sectionY++) {
|
| 215 | this.storage.put(getKey(pos, sectionY), Optional.empty());
|
| 216 | }
|
| 217 | } else {
|
| 218 | boolean versionChanged = packedChunk.versionChanged();
|
| 219 |
|
| 220 | for (int sectionY = this.levelHeightAccessor.getMinSectionY(); sectionY <= this.levelHeightAccessor.getMaxSectionY(); sectionY++) {
|
| 221 | long key = getKey(pos, sectionY);
|
| 222 | Optional<R> section = Optional.ofNullable(packedChunk.sectionsByY.get(sectionY)).map(packed -> this.unpacker.apply((P)packed, () -> this.setDirty(key)));
|
| 223 | this.storage.put(key, section);
|
| 224 | section.ifPresent(s -> {
|
| 225 | this.onSectionLoad(key);
|
| 226 | if (versionChanged) {
|
| 227 | this.setDirty(key);
|
| 228 | }
|
| 229 | });
|
| 230 | }
|
| 231 | }
|
| 232 | }
|
| 233 |
|
| 234 | private void writeChunk(final ChunkPos chunkPos) {
|
| 235 | RegistryOps<Tag> registryOps = this.registryAccess.createSerializationContext(NbtOps.INSTANCE);
|
| 236 | Dynamic<Tag> tag = this.writeChunk(chunkPos, registryOps);
|
| 237 | Tag value = tag.getValue();
|
| 238 | if (value instanceof CompoundTag compoundTag) {
|
| 239 | this.simpleRegionStorage.write(chunkPos, compoundTag).exceptionally(throwable -> {
|
| 240 | this.errorReporter.reportChunkSaveFailure(throwable, this.simpleRegionStorage.storageInfo(), chunkPos);
|
| 241 | return null;
|
| 242 | });
|
| 243 | } else {
|
| 244 | LOGGER.error("Expected compound tag, got {}", value);
|
| 245 | }
|
| 246 | }
|
| 247 |
|
| 248 | private <T> Dynamic<T> writeChunk(final ChunkPos chunkPos, final DynamicOps<T> ops) {
|
| 249 | Map<T, T> sections = Maps.newHashMap();
|
| 250 |
|
| 251 | for (int sectionY = this.levelHeightAccessor.getMinSectionY(); sectionY <= this.levelHeightAccessor.getMaxSectionY(); sectionY++) {
|
| 252 | long key = getKey(chunkPos, sectionY);
|
| 253 | Optional<R> r = this.storage.get(key);
|
| 254 | if (r != null && !r.isEmpty()) {
|
| 255 | DataResult<T> serializedSection = this.codec.encodeStart(ops, this.packer.apply(r.get()));
|
| 256 | String yName = Integer.toString(sectionY);
|
| 257 | serializedSection.resultOrPartial(LOGGER::error).ifPresent(s -> sections.put(ops.createString(yName), (T)s));
|
| 258 | }
|
| 259 | }
|
| 260 |
|
| 261 | return new Dynamic<>(
|
| 262 | ops,
|
| 263 | ops.createMap(
|
| 264 | ImmutableMap.of(
|
| 265 | ops.createString("Sections"),
|
| 266 | ops.createMap(sections),
|
| 267 | ops.createString("DataVersion"),
|
| 268 | ops.createInt(SharedConstants.getCurrentVersion().dataVersion().version())
|
| 269 | )
|
| 270 | )
|
| 271 | );
|
| 272 | }
|
| 273 |
|
| 274 | private static long getKey(final ChunkPos chunkPos, final int sectionY) {
|
| 275 | return SectionPos.asLong(chunkPos.x(), sectionY, chunkPos.z());
|
| 276 | }
|
| 277 |
|
| 278 | protected void onSectionLoad(final long sectionPos) {
|
| 279 | }
|
| 280 |
|
| 281 | protected void setDirty(final long sectionPos) {
|
| 282 | Optional<R> r = this.storage.get(sectionPos);
|
| 283 | if (r != null && !r.isEmpty()) {
|
| 284 | this.dirtyChunks.add(ChunkPos.pack(SectionPos.x(sectionPos), SectionPos.z(sectionPos)));
|
| 285 | } else {
|
| 286 | LOGGER.warn("No data for position: {}", SectionPos.of(sectionPos));
|
| 287 | }
|
| 288 | }
|
| 289 |
|
| 290 | public void flush(final ChunkPos chunkPos) {
|
| 291 | if (this.dirtyChunks.remove(chunkPos.pack())) {
|
| 292 | this.writeChunk(chunkPos);
|
| 293 | }
|
| 294 | }
|
| 295 |
|
| 296 | @Override
|
| 297 | public void close() throws IOException {
|
| 298 | this.simpleRegionStorage.close();
|
| 299 | }
|
| 300 |
|
| 301 | private record PackedChunk<T>(Int2ObjectMap<T> sectionsByY, boolean versionChanged) {
|
| 302 | public static <T> SectionStorage.PackedChunk<T> parse(
|
| 303 | final Codec<T> codec, final DynamicOps<Tag> ops, final Tag tag, final SimpleRegionStorage simpleRegionStorage, final LevelHeightAccessor levelHeightAccessor
|
| 304 | ) {
|
| 305 | Dynamic<Tag> originalTag = new Dynamic<>(ops, tag);
|
| 306 | Dynamic<Tag> fixedTag = simpleRegionStorage.upgradeChunkTag(originalTag, 1945);
|
| 307 | boolean versionChanged = originalTag != fixedTag;
|
| 308 | OptionalDynamic<Tag> sections = fixedTag.get("Sections");
|
| 309 | Int2ObjectMap<T> sectionsByY = new Int2ObjectOpenHashMap<>();
|
| 310 |
|
| 311 | for (int sectionY = levelHeightAccessor.getMinSectionY(); sectionY <= levelHeightAccessor.getMaxSectionY(); sectionY++) {
|
| 312 | Optional<T> section = sections.get(Integer.toString(sectionY))
|
| 313 | .result()
|
| 314 | .flatMap(sectionData -> codec.parse((Dynamic<Tag>)sectionData).resultOrPartial(SectionStorage.LOGGER::error));
|
| 315 | if (section.isPresent()) {
|
| 316 | sectionsByY.put(sectionY, section.get());
|
| 317 | }
|
| 318 | }
|
| 319 |
|
| 320 | return new SectionStorage.PackedChunk<>(sectionsByY, versionChanged);
|
| 321 | }
|
| 322 | }
|
| 323 | }
|
| 324 |
|