| 1 | package net.minecraft.util.worldupdate;
|
| 2 |
|
| 3 | import com.google.common.collect.Lists;
|
| 4 | import com.mojang.datafixers.DataFixer;
|
| 5 | import com.mojang.logging.LogUtils;
|
| 6 | import it.unimi.dsi.fastutil.ints.Int2ObjectAVLTreeMap;
|
| 7 | import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
|
| 8 | import it.unimi.dsi.fastutil.ints.Int2ObjectMap.Entry;
|
| 9 | import java.io.File;
|
| 10 | import java.io.IOException;
|
| 11 | import java.nio.file.Files;
|
| 12 | import java.nio.file.Path;
|
| 13 | import java.util.List;
|
| 14 | import java.util.ListIterator;
|
| 15 | import java.util.Objects;
|
| 16 | import java.util.concurrent.CompletableFuture;
|
| 17 | import java.util.concurrent.CompletionException;
|
| 18 | import java.util.regex.Matcher;
|
| 19 | import java.util.regex.Pattern;
|
| 20 | import net.minecraft.ReportedException;
|
| 21 | import net.minecraft.SharedConstants;
|
| 22 | import net.minecraft.nbt.CompoundTag;
|
| 23 | import net.minecraft.nbt.NbtUtils;
|
| 24 | import net.minecraft.resources.ResourceKey;
|
| 25 | import net.minecraft.util.datafix.DataFixTypes;
|
| 26 | import net.minecraft.world.level.ChunkPos;
|
| 27 | import net.minecraft.world.level.Level;
|
| 28 | import net.minecraft.world.level.chunk.storage.RecreatingSimpleRegionStorage;
|
| 29 | import net.minecraft.world.level.chunk.storage.RegionFile;
|
| 30 | import net.minecraft.world.level.chunk.storage.RegionStorageInfo;
|
| 31 | import net.minecraft.world.level.chunk.storage.SimpleRegionStorage;
|
| 32 | import net.minecraft.world.level.storage.LevelStorageSource;
|
| 33 | import org.jspecify.annotations.Nullable;
|
| 34 | import org.slf4j.Logger;
|
| 35 |
|
| 36 | public class RegionStorageUpgrader {
|
| 37 | private static final Logger LOGGER = LogUtils.getLogger();
|
| 38 | private static final String NEW_DIRECTORY_PREFIX = "new_";
|
| 39 | private static final Pattern REGEX = Pattern.compile("^r\\.(-?[0-9]+)\\.(-?[0-9]+)\\.mca$");
|
| 40 | private final DataFixer dataFixer;
|
| 41 | private final UpgradeProgress upgradeProgress;
|
| 42 | private final String type;
|
| 43 | private final String folderName;
|
| 44 | protected @Nullable CompletableFuture<Void> previousWriteFuture;
|
| 45 | protected final DataFixTypes dataFixType;
|
| 46 | protected final int defaultVersion;
|
| 47 | private final boolean recreateRegionFiles;
|
| 48 | private @Nullable ResourceKey<Level> dimensionKey;
|
| 49 | private @Nullable SimpleRegionStorage storage;
|
| 50 | private @Nullable List<FileToUpgrade> files;
|
| 51 | private final int startIndex;
|
| 52 | private final @Nullable CompoundTag dataFixContextTag;
|
| 53 | private final Int2ObjectMap<RegionStorageUpgrader.TagModifier> tagModifiers;
|
| 54 |
|
| 55 | protected RegionStorageUpgrader(
|
| 56 | final DataFixer dataFixer,
|
| 57 | final DataFixTypes dataFixType,
|
| 58 | final String type,
|
| 59 | final String folderName,
|
| 60 | final int defaultVersion,
|
| 61 | final boolean recreateRegionFiles,
|
| 62 | final UpgradeProgress upgradeProgress,
|
| 63 | final int startIndex,
|
| 64 | final @Nullable CompoundTag dataFixContextTag,
|
| 65 | final Int2ObjectMap<RegionStorageUpgrader.TagModifier> tagModifiers
|
| 66 | ) {
|
| 67 | this.dataFixer = dataFixer;
|
| 68 | this.dataFixType = dataFixType;
|
| 69 | this.type = type;
|
| 70 | this.folderName = folderName;
|
| 71 | this.recreateRegionFiles = recreateRegionFiles;
|
| 72 | this.defaultVersion = defaultVersion;
|
| 73 | this.upgradeProgress = upgradeProgress;
|
| 74 | this.startIndex = startIndex;
|
| 75 | this.dataFixContextTag = dataFixContextTag;
|
| 76 | this.tagModifiers = tagModifiers;
|
| 77 | }
|
| 78 |
|
| 79 | public void init(final ResourceKey<Level> dimensionKey, final LevelStorageSource.LevelStorageAccess levelStorage) {
|
| 80 | RegionStorageInfo info = new RegionStorageInfo(levelStorage.getLevelId(), dimensionKey, this.type);
|
| 81 | Path regionFolder = levelStorage.getDimensionPath(dimensionKey).resolve(this.folderName);
|
| 82 | this.dimensionKey = dimensionKey;
|
| 83 | this.storage = this.createStorage(info, regionFolder);
|
| 84 | this.files = this.getFilesToProcess(info, regionFolder);
|
| 85 | }
|
| 86 |
|
| 87 | public void upgrade() {
|
| 88 | if (this.dimensionKey == null || this.storage == null || this.files == null) {
|
| 89 | throw new IllegalStateException("RegionStorageUpgrader has not been initialized");
|
| 90 | }
|
| 91 |
|
| 92 | if (!this.files.isEmpty()) {
|
| 93 | float totalSize = this.upgradeProgress.getTotalFileFixStats().totalOperations();
|
| 94 | this.upgradeProgress.setStatus(UpgradeProgress.Status.UPGRADING);
|
| 95 | ListIterator<FileToUpgrade> iterator = this.files.listIterator();
|
| 96 |
|
| 97 | while (!this.upgradeProgress.isCanceled()) {
|
| 98 | boolean worked = false;
|
| 99 | float totalProgress = 0.0F;
|
| 100 | if (iterator.hasNext()) {
|
| 101 | FileToUpgrade fileToUpgrade = iterator.next();
|
| 102 | boolean converted = true;
|
| 103 |
|
| 104 | for (ChunkPos chunkPos : fileToUpgrade.chunksToUpgrade()) {
|
| 105 | converted = converted && this.processOnePosition(this.storage, chunkPos);
|
| 106 | worked = true;
|
| 107 | }
|
| 108 |
|
| 109 | if (this.recreateRegionFiles) {
|
| 110 | if (converted) {
|
| 111 | this.onFileFinished(fileToUpgrade.file());
|
| 112 | } else {
|
| 113 | LOGGER.error("Failed to convert region file {}", fileToUpgrade.file().getPath());
|
| 114 | }
|
| 115 | }
|
| 116 | }
|
| 117 |
|
| 118 | int nextIndex = iterator.nextIndex();
|
| 119 | float currentDimensionProgress = nextIndex / totalSize;
|
| 120 | float currentTotalProgress = (this.startIndex + nextIndex) / totalSize;
|
| 121 | this.upgradeProgress.setDimensionProgress(this.dimensionKey, currentDimensionProgress);
|
| 122 | totalProgress += currentTotalProgress;
|
| 123 | this.upgradeProgress.setTotalProgress(totalProgress);
|
| 124 | if (!worked) {
|
| 125 | break;
|
| 126 | }
|
| 127 | }
|
| 128 |
|
| 129 | this.upgradeProgress.setStatus(UpgradeProgress.Status.FINISHED);
|
| 130 |
|
| 131 | try {
|
| 132 | this.storage.close();
|
| 133 | } catch (Exception e) {
|
| 134 | LOGGER.error("Error upgrading chunk", e);
|
| 135 | }
|
| 136 | }
|
| 137 | }
|
| 138 |
|
| 139 | protected final SimpleRegionStorage createStorage(final RegionStorageInfo info, final Path regionFolder) {
|
| 140 | return this.recreateRegionFiles
|
| 141 | ? new RecreatingSimpleRegionStorage(
|
| 142 | info.withTypeSuffix("source"), regionFolder, info.withTypeSuffix("target"), resolveRecreateDirectory(regionFolder), this.dataFixer, true, this.dataFixType
|
| 143 | )
|
| 144 | : new SimpleRegionStorage(info, regionFolder, this.dataFixer, true, this.dataFixType);
|
| 145 | }
|
| 146 |
|
| 147 | private List<FileToUpgrade> getFilesToProcess(final RegionStorageInfo info, final Path regionFolder) {
|
| 148 | List<FileToUpgrade> filesToUpgrade = getAllChunkPositions(info, regionFolder);
|
| 149 | this.upgradeProgress.addTotalFileFixOperations(filesToUpgrade.size());
|
| 150 | this.upgradeProgress.addTotalChunks(filesToUpgrade.stream().mapToInt(fileToUpgrade -> fileToUpgrade.chunksToUpgrade().size()).sum());
|
| 151 | return filesToUpgrade;
|
| 152 | }
|
| 153 |
|
| 154 | public int fileAmount() {
|
| 155 | return this.files == null ? 0 : this.files.size();
|
| 156 | }
|
| 157 |
|
| 158 | private static List<FileToUpgrade> getAllChunkPositions(final RegionStorageInfo info, final Path regionFolder) {
|
| 159 | File[] files = regionFolder.toFile().listFiles((dir, name) -> name.endsWith(".mca"));
|
| 160 | if (files == null) {
|
| 161 | return List.of();
|
| 162 | }
|
| 163 |
|
| 164 | List<FileToUpgrade> regionFileChunks = Lists.newArrayList();
|
| 165 |
|
| 166 | for (File regionFile : files) {
|
| 167 | Matcher regex = REGEX.matcher(regionFile.getName());
|
| 168 | if (regex.matches()) {
|
| 169 | int xOffset = Integer.parseInt(regex.group(1)) << 5;
|
| 170 | int zOffset = Integer.parseInt(regex.group(2)) << 5;
|
| 171 | List<ChunkPos> chunkPositions = Lists.newArrayList();
|
| 172 |
|
| 173 | try (RegionFile regionSource = new RegionFile(info, regionFile.toPath(), regionFolder, true)) {
|
| 174 | for (int x = 0; x < 32; x++) {
|
| 175 | for (int z = 0; z < 32; z++) {
|
| 176 | ChunkPos pos = new ChunkPos(x + xOffset, z + zOffset);
|
| 177 | if (regionSource.doesChunkExist(pos)) {
|
| 178 | chunkPositions.add(pos);
|
| 179 | }
|
| 180 | }
|
| 181 | }
|
| 182 |
|
| 183 | if (!chunkPositions.isEmpty()) {
|
| 184 | regionFileChunks.add(new FileToUpgrade(regionSource, chunkPositions));
|
| 185 | }
|
| 186 | } catch (Throwable t) {
|
| 187 | LOGGER.error("Failed to read chunks from region file {}", regionFile.toPath(), t);
|
| 188 | }
|
| 189 | }
|
| 190 | }
|
| 191 |
|
| 192 | return regionFileChunks;
|
| 193 | }
|
| 194 |
|
| 195 | private boolean processOnePosition(final SimpleRegionStorage storage, final ChunkPos pos) {
|
| 196 | boolean converted = false;
|
| 197 |
|
| 198 | try {
|
| 199 | converted = this.tryProcessOnePosition(storage, pos);
|
| 200 | } catch (ReportedException | CompletionException e) {
|
| 201 | Throwable cause = e.getCause();
|
| 202 | if (!(cause instanceof IOException)) {
|
| 203 | throw e;
|
| 204 | }
|
| 205 |
|
| 206 | LOGGER.error("Error upgrading chunk {}", pos, cause);
|
| 207 | }
|
| 208 |
|
| 209 | if (converted) {
|
| 210 | this.upgradeProgress.incrementConverted();
|
| 211 | } else {
|
| 212 | this.upgradeProgress.incrementSkipped();
|
| 213 | }
|
| 214 |
|
| 215 | return converted;
|
| 216 | }
|
| 217 |
|
| 218 | protected boolean tryProcessOnePosition(final SimpleRegionStorage storage, final ChunkPos pos) {
|
| 219 | CompoundTag chunkTag = storage.read(pos).join().orElse(null);
|
| 220 | if (chunkTag != null) {
|
| 221 | int version = NbtUtils.getDataVersion(chunkTag);
|
| 222 | int latestVersion = SharedConstants.getCurrentVersion().dataVersion().version();
|
| 223 | boolean changed = false;
|
| 224 |
|
| 225 | for (Entry<RegionStorageUpgrader.TagModifier> tagFixer : this.tagModifiers.int2ObjectEntrySet()) {
|
| 226 | int neededVersion = tagFixer.getIntKey();
|
| 227 | chunkTag = this.upgradeTag(storage, chunkTag, neededVersion);
|
| 228 | changed |= tagFixer.getValue().modifyTagAfterFix(pos, chunkTag);
|
| 229 | }
|
| 230 |
|
| 231 | CompoundTag upgradedTag = this.upgradeTag(storage, chunkTag, latestVersion);
|
| 232 | changed |= version < latestVersion;
|
| 233 | if (changed || this.recreateRegionFiles) {
|
| 234 | if (this.previousWriteFuture != null) {
|
| 235 | this.previousWriteFuture.join();
|
| 236 | }
|
| 237 |
|
| 238 | this.previousWriteFuture = storage.write(pos, upgradedTag);
|
| 239 | return true;
|
| 240 | }
|
| 241 | }
|
| 242 |
|
| 243 | return false;
|
| 244 | }
|
| 245 |
|
| 246 | protected CompoundTag upgradeTag(final SimpleRegionStorage storage, final CompoundTag chunkTag, final int targetVersion) {
|
| 247 | return storage.upgradeChunkTag(chunkTag, this.defaultVersion, this.dataFixContextTag, targetVersion);
|
| 248 | }
|
| 249 |
|
| 250 | private void onFileFinished(final RegionFile regionFile) {
|
| 251 | if (this.recreateRegionFiles) {
|
| 252 | if (this.previousWriteFuture != null) {
|
| 253 | this.previousWriteFuture.join();
|
| 254 | }
|
| 255 |
|
| 256 | Path filePath = regionFile.getPath();
|
| 257 | Path directoryPath = filePath.getParent();
|
| 258 | Path newFilePath = resolveRecreateDirectory(directoryPath).resolve(filePath.getFileName().toString());
|
| 259 |
|
| 260 | try {
|
| 261 | if (newFilePath.toFile().exists()) {
|
| 262 | Files.delete(filePath);
|
| 263 | Files.move(newFilePath, filePath);
|
| 264 | } else {
|
| 265 | LOGGER.error("Failed to replace an old region file. New file {} does not exist.", newFilePath);
|
| 266 | }
|
| 267 | } catch (IOException e) {
|
| 268 | LOGGER.error("Failed to replace an old region file", e);
|
| 269 | }
|
| 270 | }
|
| 271 | }
|
| 272 |
|
| 273 | protected static Path resolveRecreateDirectory(final Path directoryPath) {
|
| 274 | return directoryPath.resolveSibling("new_" + directoryPath.getFileName().toString());
|
| 275 | }
|
| 276 |
|
| 277 | public static class Builder {
|
| 278 | private final DataFixer dataFixer;
|
| 279 | private @Nullable DataFixTypes dataFixType;
|
| 280 | private @Nullable String type;
|
| 281 | private @Nullable String folderName;
|
| 282 | private int defaultVersion = -1;
|
| 283 | private boolean recreateRegionFiles;
|
| 284 | private UpgradeProgress upgradeProgress = new UpgradeProgress.Noop();
|
| 285 | private @Nullable CompoundTag dataFixContextTag;
|
| 286 | private Int2ObjectAVLTreeMap<RegionStorageUpgrader.TagModifier> tagModifiers = new Int2ObjectAVLTreeMap<>();
|
| 287 |
|
| 288 | public Builder(final DataFixer dataFixer) {
|
| 289 | this.dataFixer = dataFixer;
|
| 290 | }
|
| 291 |
|
| 292 | public RegionStorageUpgrader.Builder setDataFixType(final DataFixTypes dataFixType) {
|
| 293 | this.dataFixType = dataFixType;
|
| 294 | return this;
|
| 295 | }
|
| 296 |
|
| 297 | public RegionStorageUpgrader.Builder setTypeAndFolderName(final String name) {
|
| 298 | return this.setType(name).setFolderName(name);
|
| 299 | }
|
| 300 |
|
| 301 | public RegionStorageUpgrader.Builder setType(final String type) {
|
| 302 | this.type = type;
|
| 303 | return this;
|
| 304 | }
|
| 305 |
|
| 306 | public RegionStorageUpgrader.Builder setFolderName(final String folderName) {
|
| 307 | this.folderName = folderName;
|
| 308 | return this;
|
| 309 | }
|
| 310 |
|
| 311 | public RegionStorageUpgrader.Builder setDefaultVersion(final int defaultVersion) {
|
| 312 | this.defaultVersion = defaultVersion;
|
| 313 | return this;
|
| 314 | }
|
| 315 |
|
| 316 | public RegionStorageUpgrader.Builder setRecreateRegionFiles(final boolean recreateRegionFiles) {
|
| 317 | this.recreateRegionFiles = recreateRegionFiles;
|
| 318 | return this;
|
| 319 | }
|
| 320 |
|
| 321 | public RegionStorageUpgrader.Builder trackProgress(final UpgradeProgress upgradeProgress) {
|
| 322 | this.upgradeProgress = upgradeProgress;
|
| 323 | return this;
|
| 324 | }
|
| 325 |
|
| 326 | public RegionStorageUpgrader.Builder setDataFixContextTag(final @Nullable CompoundTag dataFixContextTag) {
|
| 327 | this.dataFixContextTag = dataFixContextTag;
|
| 328 | return this;
|
| 329 | }
|
| 330 |
|
| 331 | public RegionStorageUpgrader.Builder addTagModifier(final int version, final RegionStorageUpgrader.TagModifier tagModifier) {
|
| 332 | if (this.tagModifiers.containsKey(version)) {
|
| 333 | throw new IllegalStateException("Can't add two fixers for the same data version");
|
| 334 | }
|
| 335 |
|
| 336 | this.tagModifiers.put(version, tagModifier);
|
| 337 | return this;
|
| 338 | }
|
| 339 |
|
| 340 | private RegionStorageUpgrader.Builder setTagModifiers(final Int2ObjectAVLTreeMap<RegionStorageUpgrader.TagModifier> tagModifiers) {
|
| 341 | this.tagModifiers = tagModifiers;
|
| 342 | return this;
|
| 343 | }
|
| 344 |
|
| 345 | public RegionStorageUpgrader.Builder copy() {
|
| 346 | return new RegionStorageUpgrader.Builder(this.dataFixer)
|
| 347 | .setDataFixType(this.dataFixType)
|
| 348 | .setType(this.type)
|
| 349 | .setFolderName(this.folderName)
|
| 350 | .setDefaultVersion(this.defaultVersion)
|
| 351 | .setRecreateRegionFiles(this.recreateRegionFiles)
|
| 352 | .trackProgress(this.upgradeProgress)
|
| 353 | .setDataFixContextTag(this.dataFixContextTag)
|
| 354 | .setTagModifiers(this.tagModifiers.clone());
|
| 355 | }
|
| 356 |
|
| 357 | public RegionStorageUpgrader build(final int previousCopiesFileAmounts) {
|
| 358 | return new RegionStorageUpgrader(
|
| 359 | this.dataFixer,
|
| 360 | Objects.requireNonNull(this.dataFixType),
|
| 361 | Objects.requireNonNull(this.type),
|
| 362 | Objects.requireNonNull(this.folderName),
|
| 363 | this.defaultVersion,
|
| 364 | this.recreateRegionFiles,
|
| 365 | this.upgradeProgress,
|
| 366 | previousCopiesFileAmounts,
|
| 367 | this.dataFixContextTag,
|
| 368 | this.tagModifiers
|
| 369 | );
|
| 370 | }
|
| 371 | }
|
| 372 |
|
| 373 | @FunctionalInterface
|
| 374 | public interface TagModifier {
|
| 375 | boolean modifyTagAfterFix(final ChunkPos pos, final CompoundTag upgradedTag);
|
| 376 | }
|
| 377 | }
|
| 378 |
|