├── settings.gradle.kts ├── gradle.properties ├── .github ├── FUNDING.yml ├── tntlogo.png └── workflows │ ├── triggerjitpack.yml │ ├── maven-release.yaml │ └── maven-development.yaml ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── jitpack.yml ├── src └── main │ └── java │ └── dev │ └── emortal │ └── tnt │ ├── source │ ├── TNTSource.java │ └── FileTNTSource.java │ ├── TNTChunk.java │ ├── StandaloneConverter.java │ ├── TNTLoader.java │ ├── TNT.java │ └── ConversionAnvilLoader.java ├── .gitignore ├── LICENSE ├── README.md ├── gradlew.bat └── gradlew /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | 2 | rootProject.name = "TNT" 3 | 4 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | name=TNT 2 | group=dev.emortal.tnt 3 | version=1.0.0 -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | patreon: emortaldev 2 | custom: ["paypal.me/emortaldev"] 3 | -------------------------------------------------------------------------------- /.github/tntlogo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/emortalmc/TNT/HEAD/.github/tntlogo.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/emortalmc/TNT/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /jitpack.yml: -------------------------------------------------------------------------------- 1 | before_install: 2 | - source "$HOME/.sdkman/bin/sdkman-init.sh" 3 | - sdk update 4 | - sdk install java 17-open 5 | - sdk use java 17-open -------------------------------------------------------------------------------- /src/main/java/dev/emortal/tnt/source/TNTSource.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.tnt.source; 2 | 3 | import java.io.InputStream; 4 | 5 | public interface TNTSource { 6 | InputStream load(); 7 | 8 | void save(byte[] bytes); 9 | } 10 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /.github/workflows/triggerjitpack.yml: -------------------------------------------------------------------------------- 1 | name: Trigger Jitpack Build 2 | on: 3 | push: 4 | branches: [ main ] 5 | 6 | workflow_dispatch: 7 | jobs: 8 | build: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - name: Trigger Jitpack Build 12 | run: curl "https://jitpack.io/com/github/EmortalMC/TNT/${GITHUB_SHA:0:10}/build.log" 13 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled class file 2 | *.class 3 | 4 | # Log file 5 | *.log 6 | 7 | # Common working directory 8 | run/ 9 | 10 | # BlueJ files 11 | *.ctxt 12 | 13 | # Mobile Tools for Java (J2ME) 14 | .mtj.tmp/ 15 | 16 | # Package Files # 17 | *.war 18 | *.nar 19 | *.ear 20 | *.zip 21 | *.tar.gz 22 | *.rar 23 | 24 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml 25 | hs_err_pid* 26 | .idea 27 | .gradle 28 | build 29 | world 30 | world.tnt 31 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/tnt/TNTChunk.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.tnt; 2 | 3 | import net.minestom.server.instance.Section; 4 | import net.minestom.server.instance.batch.ChunkBatch; 5 | 6 | import java.util.Arrays; 7 | 8 | public class TNTChunk { 9 | public ChunkBatch batch; 10 | public Section[] sections; 11 | 12 | public TNTChunk(ChunkBatch batch, int maxSection, int minSection) { 13 | this.sections = new Section[maxSection - minSection]; 14 | Arrays.setAll(sections, (a) -> new Section()); 15 | 16 | this.batch = batch; 17 | } 18 | 19 | } 20 | -------------------------------------------------------------------------------- /.github/workflows/maven-release.yaml: -------------------------------------------------------------------------------- 1 | name: release publish (repo.emortal.dev) 2 | on: 3 | release: 4 | types: [published] 5 | 6 | jobs: 7 | publish: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v3 11 | - name: Get Commit Hash 12 | id: commit 13 | uses: pr-mpt/actions-commit-hash@v2 14 | - name: Set up Java 15 | uses: actions/setup-java@v3 16 | with: 17 | java-version: '17' 18 | distribution: 'adopt' 19 | - name: Validate Gradle wrapper 20 | uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b 21 | - name: Publish package 22 | uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1 23 | with: 24 | arguments: publishMavenPublicationToReleaseRepository 25 | env: 26 | MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} 27 | MAVEN_SECRET: ${{ secrets.MAVEN_SECRET }} 28 | RELEASE_VERSION: ${{ github.event.release.tag_name }} 29 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 EmortalMC 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.github/workflows/maven-development.yaml: -------------------------------------------------------------------------------- 1 | name: snapshot publish (repo.emortal.dev) 2 | on: 3 | push: 4 | branches: [ main ] 5 | pull_request: 6 | branches: [ main ] 7 | 8 | jobs: 9 | publish: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v3 13 | - name: Get Commit Hash 14 | id: commit 15 | uses: pr-mpt/actions-commit-hash@v2 16 | - name: Set up Java 17 | uses: actions/setup-java@v3 18 | with: 19 | java-version: '17' 20 | distribution: 'adopt' 21 | - name: Validate Gradle wrapper 22 | uses: gradle/wrapper-validation-action@e6e38bacfdf1a337459f332974bb2327a31aaf4b 23 | - name: Publish package 24 | uses: gradle/gradle-build-action@67421db6bd0bf253fb4bd25b31ebb98943c375e1 25 | with: 26 | arguments: publishMavenPublicationToDevelopmentRepository 27 | env: 28 | MAVEN_USERNAME: ${{ secrets.MAVEN_USERNAME }} 29 | MAVEN_SECRET: ${{ secrets.MAVEN_SECRET }} 30 | COMMIT_HASH: ${{ steps.commit.outputs.hash }} 31 | COMMIT_HASH_SHORT: ${{ steps.commit.outputs.short }} 32 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/tnt/StandaloneConverter.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.tnt; 2 | 3 | import dev.emortal.tnt.source.FileTNTSource; 4 | import net.minestom.server.Git; 5 | import net.minestom.server.MinecraftServer; 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import java.io.IOException; 10 | import java.nio.file.Files; 11 | import java.nio.file.Path; 12 | import java.util.stream.Stream; 13 | 14 | public class StandaloneConverter { 15 | private static final Logger LOGGER = LoggerFactory.getLogger(StandaloneConverter.class); 16 | 17 | private static final String SERVER_BRAND = MinecraftServer.getBrandName(); 18 | private static final String SERVER_VERSION = MinecraftServer.VERSION_NAME; 19 | 20 | private static final Path WORLDS_PATH = Path.of("worlds"); 21 | 22 | public static void main(String[] args) throws IOException { 23 | MinecraftServer.init(); // We need the instance manager 24 | 25 | LOGGER.info("Beginning conversion for all maps on {} {} ({})", SERVER_BRAND, SERVER_VERSION, Git.commit()); 26 | try (Stream pathStream = Files.list(WORLDS_PATH)) { 27 | pathStream.forEach(st -> { 28 | String worldName = FileTNTSource.getNameWithoutExtension(st.getFileName().toString()); 29 | Path actualPath = st.getParent().resolve(worldName + ".tnt"); 30 | 31 | LOGGER.info("Beginning conversion for map {}", worldName); 32 | 33 | try { 34 | TNT.convertAnvilToTNT(actualPath.getParent().resolve(worldName), new FileTNTSource(actualPath)); 35 | } catch (IOException | InterruptedException e) { 36 | throw new RuntimeException(e); 37 | } 38 | 39 | LOGGER.info("Conversion finished for map {}", worldName); 40 | }); 41 | } 42 | 43 | System.exit(0); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/tnt/source/FileTNTSource.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.tnt.source; 2 | 3 | import dev.emortal.tnt.TNT; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.nio.file.Files; 10 | import java.nio.file.Path; 11 | 12 | public class FileTNTSource implements TNTSource { 13 | private static final Logger LOGGER = LoggerFactory.getLogger(FileTNTSource.class); 14 | 15 | private final Path path; 16 | 17 | public FileTNTSource(Path path) { 18 | this.path = path; 19 | } 20 | 21 | @Override 22 | public InputStream load() { 23 | if (!Files.exists(path)) { // No world folder 24 | String worldName = getNameWithoutExtension(path.getFileName().toString()); 25 | 26 | if (Files.isDirectory(path.getParent().resolve(worldName))) { 27 | LOGGER.info("Path is an anvil world. Converting! (This might take a bit)"); 28 | 29 | try { 30 | TNT.convertAnvilToTNT(path.getParent().resolve(worldName), new FileTNTSource(path)); 31 | } catch (IOException e) { 32 | LOGGER.error("Failed to convert world {} to TNT: {}", worldName, e); 33 | } catch (InterruptedException e) { 34 | throw new RuntimeException(e); 35 | } 36 | LOGGER.info("Converted world {} to TNT", worldName); 37 | } else { 38 | LOGGER.error("No TNT or Anvil world found at path: " + this.path); 39 | } 40 | } 41 | 42 | try { 43 | return Files.newInputStream(path); 44 | } catch (IOException e) { 45 | LOGGER.error("Failed to load TNT file {}: {}", path, e); 46 | return InputStream.nullInputStream(); 47 | } 48 | } 49 | 50 | @Override 51 | public void save(byte[] bytes) { 52 | try { 53 | Files.write(path, bytes); 54 | } catch (IOException e) { 55 | e.printStackTrace(); 56 | } 57 | } 58 | 59 | public static String getNameWithoutExtension(String path) { 60 | int dotIndex = path.lastIndexOf('.'); 61 | return (dotIndex == -1) ? path : path.substring(0, dotIndex); 62 | } 63 | 64 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | EmortalMC Banner 2 | 3 | # TNT 4 | TNT is a world format for Minestom designed for super fast 🚀 loading and portability. 5 | 6 | TNT should only be used for small worlds. 7 | 8 | 9 | ## Check out the [polar](https://github.com/hollow-cube/polar) world format created by Hollow Cube. It handles version updates and will work better. 10 | 11 | ### ⚠ TNT is experimental and is not backwards compatible. Your worlds will break when TNT or Minecraft updates. It is highly recommended to keep your original worlds. 12 | 13 | ## Cool stuff 14 | - Very fast loading times (23ms for my lobby - idk what Anvil is) 15 | - Small file size (~80kb in TNT vs ~13mb in Anvil for my lobby) 16 | - [Converts from Anvil automatically](#anvil-conversion) 17 | - [Very portable - can be loaded from databases](#tnt-sources) 18 | - Stores block nbt (e.g. sign text) 19 | - Stores cached light from Anvil (useful because only minestom-ce has a lighting engine) 20 | - [World saving](#saving) 21 | 22 | Unfortunately does not save entities (yet) as Minestom does not have entity (de)serialisation. 23 | 24 | # Usage 25 | Importing via Gradle (browse versions [here](https://repo.emortal.dev/#/releases/dev/emortal/tnt/TNT)) 26 | ```groovy 27 | repositories { 28 | maven { url "https://repo.emortal.dev/releases" } 29 | } 30 | 31 | dependencies { 32 | implementation("dev.emortal.tnt:TNT:{releaseTag}") 33 | } 34 | ``` 35 | Creating a Minestom instance 36 | 37 | ```java 38 | InstanceContainer instance = MinecraftServer.getInstanceManager().createInstanceContainer(); 39 | TNTLoader tntLoader = new TNTLoader(instance, new FileTNTSource(Path.of("path/to/world.tnt"))); 40 | // or 41 | TNTLoader tntLoader = new TNTLoader(instance, "path/to/world.tnt") 42 | 43 | instance.setChunkLoader(tntLoader); 44 | ``` 45 | 46 | ## Signs are blank? (or any other block has no data) 47 | TNT needs some block handlers in order to load block data. 48 | 49 | You can find some [example handlers in Immortal](https://github.com/EmortalMC/Immortal/tree/main/src/main/kotlin/dev/emortal/immortal/blockhandler) which are then registered like [this](https://github.com/EmortalMC/Immortal/blob/ea9f03249d01b7f2544bd96d588e6341d7bfbc99/src/main/kotlin/dev/emortal/immortal/ImmortalExtension.kt#L409) 50 | 51 | 52 | ## Anvil Conversion 53 | In order for TNT to convert a TNT world automatically, the Anvil folder and TNT file need to be named the same and be in the same folder. 54 | 55 | For example: 56 | - /worlds/world/ <- Anvil world folder 57 | - /worlds/world.tnt <- TNT world file (Put this path into the `TNTSource`) 58 | 59 | You may also convert an anvil world to TNT manually with `TNT.convertAnvilToTNT(pathToAnvil, tntSaveSource)` 60 | 61 | ## TNT Sources 62 | TNT worlds can be loaded and saved wherever you want (however only `FileTNTSource` is built in) 63 | 64 | For example, you could make it read from Redis, MongoDB, MySQL or any sort of datastore. 65 | 66 | You can do this by extending `TNTSource` and creating your own source. 67 | 68 | ## Saving 69 | Use `TNT.convertChunksToTNT(chunkList, source)` 70 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%"=="" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%"=="" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if %ERRORLEVEL% equ 0 goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if %ERRORLEVEL% equ 0 goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | set EXIT_CODE=%ERRORLEVEL% 84 | if %EXIT_CODE% equ 0 set EXIT_CODE=1 85 | if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% 86 | exit /b %EXIT_CODE% 87 | 88 | :mainEnd 89 | if "%OS%"=="Windows_NT" endlocal 90 | 91 | :omega 92 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/tnt/TNTLoader.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.tnt; 2 | 3 | import dev.emortal.tnt.source.TNTSource; 4 | import it.unimi.dsi.fastutil.longs.Long2ObjectOpenHashMap; 5 | import net.minestom.server.MinecraftServer; 6 | import net.minestom.server.instance.Chunk; 7 | import net.minestom.server.instance.DynamicChunk; 8 | import net.minestom.server.instance.IChunkLoader; 9 | import net.minestom.server.instance.Instance; 10 | import net.minestom.server.instance.Section; 11 | import net.minestom.server.instance.batch.BatchOption; 12 | import net.minestom.server.instance.batch.ChunkBatch; 13 | import net.minestom.server.instance.block.Block; 14 | import net.minestom.server.instance.block.BlockManager; 15 | import net.minestom.server.utils.binary.BinaryReader; 16 | import net.minestom.server.utils.chunk.ChunkUtils; 17 | import org.jetbrains.annotations.NotNull; 18 | import org.jetbrains.annotations.Nullable; 19 | import org.jglrxavpok.hephaistos.nbt.CompressedProcesser; 20 | import org.jglrxavpok.hephaistos.nbt.NBT; 21 | import org.jglrxavpok.hephaistos.nbt.NBTCompound; 22 | import org.jglrxavpok.hephaistos.nbt.NBTException; 23 | import org.jglrxavpok.hephaistos.nbt.NBTReader; 24 | import org.slf4j.Logger; 25 | import org.slf4j.LoggerFactory; 26 | 27 | import java.io.IOException; 28 | import java.util.concurrent.CompletableFuture; 29 | 30 | public final class TNTLoader implements IChunkLoader { 31 | private static final Logger LOGGER = LoggerFactory.getLogger(TNTLoader.class); 32 | 33 | private final TNTSource source; 34 | public final Long2ObjectOpenHashMap chunksMap = new Long2ObjectOpenHashMap<>(); 35 | 36 | public TNTLoader(TNTSource source) throws IOException, NBTException { 37 | this.source = source; 38 | 39 | BlockManager blockManager = MinecraftServer.getBlockManager(); 40 | 41 | byte[] byteArray = source.load().readAllBytes(); 42 | // byte[] decompressed = Zstd.decompress(byteArray, (int) Zstd.decompressedSize(byteArray)); 43 | // BinaryReader reader = new BinaryReader(decompressed); 44 | BinaryReader reader = new BinaryReader(byteArray); 45 | NBTReader nbtReader = new NBTReader(reader, CompressedProcesser.NONE); 46 | 47 | int chunks = reader.readInt(); 48 | // LOGGER.info("Reading {} chunks", chunks); 49 | 50 | for (int chunkI = 0; chunkI < chunks; chunkI++) { 51 | ChunkBatch batch = new ChunkBatch(new BatchOption()/*.setSendUpdate(false)*/.setUnsafeApply(true)); 52 | // ChunkBatch batch = new ChunkBatch(); 53 | 54 | int chunkX = reader.readInt(); 55 | int chunkZ = reader.readInt(); 56 | 57 | int minSection = reader.readByte(); 58 | int maxSection = reader.readByte(); 59 | 60 | // LOGGER.info("Load chunk {} {} min max {} {}", chunkX, chunkZ, minSection, maxSection); 61 | 62 | TNTChunk mstChunk = new TNTChunk(batch, maxSection, minSection); 63 | 64 | int airSkip = 0; 65 | 66 | for (int y = minSection * Chunk.CHUNK_SECTION_SIZE; y < maxSection * Chunk.CHUNK_SECTION_SIZE; y++) { 67 | for (int x = 0; x < Chunk.CHUNK_SIZE_X; x++) { 68 | for (int z = 0; z < Chunk.CHUNK_SIZE_X; z++) { 69 | if (airSkip > 0) { 70 | airSkip--; 71 | continue; 72 | } 73 | 74 | short stateId = reader.readShort(); 75 | 76 | if (stateId == 0) { 77 | airSkip = reader.readInt() - 1; 78 | continue; 79 | } 80 | 81 | boolean hasNbt = reader.readBoolean(); 82 | 83 | Block block; 84 | 85 | if (hasNbt) { 86 | NBT nbt = nbtReader.read(); 87 | 88 | Block b = Block.fromStateId(stateId); 89 | block = b.withHandler(blockManager.getHandlerOrDummy(b.name())).withNbt((NBTCompound) nbt); 90 | } else { 91 | block = Block.fromStateId(stateId); 92 | } 93 | 94 | batch.setBlock(x, y, z, block); 95 | } 96 | } 97 | } 98 | 99 | for (int sectionY = minSection; sectionY < maxSection; sectionY++) { 100 | Section section = mstChunk.sections[sectionY - minSection]; 101 | byte[] blockLights = reader.readByteArray(); 102 | byte[] skyLights = reader.readByteArray(); 103 | section.setBlockLight(blockLights); 104 | section.setSkyLight(skyLights); 105 | } 106 | 107 | chunksMap.put(ChunkUtils.getChunkIndex(chunkX, chunkZ), mstChunk); 108 | } 109 | 110 | reader.close(); 111 | nbtReader.close(); 112 | } 113 | 114 | @Override 115 | public @NotNull CompletableFuture<@Nullable Chunk> loadChunk(@NotNull Instance instance, int chunkX, int chunkZ) { 116 | TNTChunk mstChunk = chunksMap.get(ChunkUtils.getChunkIndex(chunkX, chunkZ)); 117 | if(mstChunk == null) 118 | return CompletableFuture.completedFuture(null); 119 | DynamicChunk chunk = new DynamicChunk(instance, chunkX, chunkZ); 120 | 121 | CompletableFuture future = new CompletableFuture<>(); 122 | 123 | // Copy chunk light from mstChunk to the new chunk 124 | chunk.getSections().forEach(it -> { 125 | Section sec = mstChunk.sections[chunk.getSections().indexOf(it)]; 126 | 127 | 128 | 129 | it.setBlockLight(sec.getBlockLight()); 130 | it.setSkyLight(sec.getSkyLight()); 131 | }); 132 | 133 | // We can use unsafe as it does not matter what thread the callback is returned from 134 | mstChunk.batch.unsafeApply(instance, chunk, future::complete); 135 | 136 | return future; 137 | } 138 | 139 | @Override 140 | public @NotNull CompletableFuture saveChunk(@NotNull Chunk chunk) { 141 | return CompletableFuture.completedFuture(null); 142 | } 143 | 144 | @Override 145 | public boolean supportsParallelLoading() { 146 | return true; 147 | } 148 | 149 | @Override 150 | public boolean supportsParallelSaving() { 151 | return true; 152 | } 153 | } -------------------------------------------------------------------------------- /src/main/java/dev/emortal/tnt/TNT.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.tnt; 2 | 3 | import dev.emortal.tnt.source.TNTSource; 4 | import net.minestom.server.MinecraftServer; 5 | import net.minestom.server.instance.AnvilLoader; 6 | import net.minestom.server.instance.Chunk; 7 | import net.minestom.server.instance.InstanceContainer; 8 | import net.minestom.server.instance.InstanceManager; 9 | import net.minestom.server.instance.Section; 10 | import net.minestom.server.instance.block.Block; 11 | import net.minestom.server.utils.binary.BinaryWriter; 12 | import org.jglrxavpok.hephaistos.nbt.NBTCompound; 13 | 14 | import java.io.IOException; 15 | import java.nio.file.Files; 16 | import java.nio.file.Path; 17 | import java.util.ArrayList; 18 | import java.util.Collection; 19 | import java.util.HashSet; 20 | import java.util.Set; 21 | import java.util.concurrent.CountDownLatch; 22 | import java.util.stream.Collectors; 23 | 24 | public class TNT { 25 | 26 | private static byte[] convertChunk(Chunk chunk) throws IOException { 27 | BinaryWriter writer = new BinaryWriter(); 28 | 29 | writer.writeInt(chunk.getChunkX()); 30 | writer.writeInt(chunk.getChunkZ()); 31 | writer.writeByte((byte) chunk.getMinSection()); 32 | writer.writeByte((byte) chunk.getMaxSection()); 33 | 34 | int airSkip = 0; 35 | boolean needsEnding = false; 36 | 37 | for (int y = chunk.getMinSection() * Chunk.CHUNK_SECTION_SIZE; y < chunk.getMaxSection() * Chunk.CHUNK_SECTION_SIZE; y++) { 38 | for (int x = 0; x < Chunk.CHUNK_SIZE_X; x++) { 39 | for (int z = 0; z < Chunk.CHUNK_SIZE_Z; z++) { 40 | Block block = chunk.getBlock(x, y, z); 41 | 42 | // check for the air block state 43 | if (block.stateId() == 0) { 44 | airSkip++; 45 | if (airSkip == 1) { 46 | writer.writeShort((short) 0); 47 | needsEnding = true; 48 | } 49 | 50 | continue; 51 | } 52 | if (airSkip > 0) { 53 | writer.writeInt(airSkip); 54 | needsEnding = false; 55 | } 56 | 57 | airSkip = 0; 58 | 59 | writer.writeShort(block.stateId()); 60 | 61 | NBTCompound nbt = block.nbt(); 62 | writer.writeBoolean(block.hasNbt()); 63 | if (nbt != null) { 64 | writer.writeNBT("blockNBT", nbt); 65 | } 66 | } 67 | } 68 | } 69 | 70 | // Air skip sometimes isn't written, maybe there is a cleaner way? 71 | if (needsEnding) { 72 | writer.writeInt(airSkip); 73 | } 74 | 75 | for (Section section : chunk.getSections()) { 76 | writer.writeByteArray(section.getBlockLight()); 77 | writer.writeByteArray(section.getSkyLight()); 78 | } 79 | 80 | byte[] bytes = writer.toByteArray(); 81 | 82 | writer.close(); 83 | writer.flush(); 84 | 85 | return bytes; 86 | } 87 | 88 | public static void convertAnvilToTNT(Path anvilPath, TNTSource source) throws IOException, InterruptedException { 89 | InstanceManager im = MinecraftServer.getInstanceManager(); 90 | 91 | Set mcas = Files.list(anvilPath.resolve("region")).collect(Collectors.toSet()); 92 | 93 | InstanceContainer convertInstance = im.createInstanceContainer(); 94 | AnvilLoader loader = new AnvilLoader(anvilPath); 95 | convertInstance.setChunkLoader(loader); 96 | 97 | CountDownLatch cdl = new CountDownLatch(mcas.size() * 32 * 32); 98 | 99 | ArrayList convertedChunks = new ArrayList<>(); 100 | 101 | for (Path mca : mcas) { 102 | String[] args = mca.getFileName().toString().split("\\."); 103 | int rX = Integer.parseInt(args[1]); 104 | int rZ = Integer.parseInt(args[2]); 105 | 106 | for (int x = rX * 32; x < rX * 32 + 32; x++) { 107 | for (int z = rZ * 32; z < rZ * 32 + 32; z++) { 108 | convertInstance.loadChunk(x, z).thenAccept(chunk -> { 109 | if (!chunkContainsBlocks(chunk)) { 110 | cdl.countDown(); 111 | return; 112 | } 113 | 114 | byte[] converted = new byte[0]; 115 | try { 116 | converted = convertChunk(chunk); 117 | } catch (IOException e) { 118 | e.printStackTrace(); 119 | } 120 | convertedChunks.add(converted); 121 | converted = null; 122 | 123 | // We're now done with this chunk 124 | convertInstance.unloadChunk(chunk); 125 | 126 | cdl.countDown(); 127 | }); 128 | } 129 | } 130 | } 131 | 132 | cdl.await(); 133 | 134 | MinecraftServer.getInstanceManager().unregisterInstance(convertInstance); 135 | 136 | BinaryWriter writer = new BinaryWriter(); 137 | 138 | writer.writeInt(convertedChunks.size()); 139 | for (byte[] chunk : convertedChunks) { 140 | writer.writeBytes(chunk); 141 | } 142 | 143 | byte[] bytes = writer.toByteArray(); 144 | source.save(bytes); 145 | 146 | writer.close(); 147 | writer.flush(); 148 | } 149 | 150 | 151 | public static Collection filterEmptyChunks(Collection chunks) { 152 | Set newChunks = new HashSet<>(); 153 | 154 | for (Chunk chunk : chunks) { 155 | if (!chunkContainsBlocks(chunk)) continue; 156 | 157 | newChunks.add(chunk); 158 | } 159 | 160 | return newChunks; 161 | } 162 | 163 | public static boolean chunkContainsBlocks(Chunk chunk) { 164 | boolean containsBlocks = false; 165 | for (Section section : chunk.getSections()) { 166 | if (section.blockPalette().count() > 0) { 167 | containsBlocks = true; 168 | break; 169 | } 170 | } 171 | return containsBlocks; 172 | } 173 | 174 | public static void convertChunksToTNT(Collection chunks, TNTSource source) throws IOException { 175 | BinaryWriter writer = new BinaryWriter(); 176 | 177 | writer.writeInt(chunks.size()); 178 | for (Chunk chunk : chunks) { 179 | byte[] converted = new byte[0]; 180 | try { 181 | converted = convertChunk(chunk); 182 | } catch (IOException e) { 183 | e.printStackTrace(); 184 | } 185 | 186 | writer.writeBytes(converted); 187 | } 188 | 189 | byte[] bytes = writer.toByteArray(); 190 | source.save(bytes); 191 | 192 | writer.close(); 193 | writer.flush(); 194 | } 195 | 196 | } 197 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Stop when "xargs" is not available. 209 | if ! command -v xargs >/dev/null 2>&1 210 | then 211 | die "xargs is not available" 212 | fi 213 | 214 | # Use "xargs" to parse quoted args. 215 | # 216 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 217 | # 218 | # In Bash we could simply go: 219 | # 220 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 221 | # set -- "${ARGS[@]}" "$@" 222 | # 223 | # but POSIX shell has neither arrays nor command substitution, so instead we 224 | # post-process each arg (as a line of input to sed) to backslash-escape any 225 | # character that might be a shell metacharacter, then use eval to reverse 226 | # that process (while maintaining the separation between arguments), and wrap 227 | # the whole thing up as a single "set" statement. 228 | # 229 | # This will of course break if any of these variables contains a newline or 230 | # an unmatched quote. 231 | # 232 | 233 | eval "set -- $( 234 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 235 | xargs -n1 | 236 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 237 | tr '\n' ' ' 238 | )" '"$@"' 239 | 240 | exec "$JAVACMD" "$@" 241 | -------------------------------------------------------------------------------- /src/main/java/dev/emortal/tnt/ConversionAnvilLoader.java: -------------------------------------------------------------------------------- 1 | package dev.emortal.tnt; 2 | 3 | import net.minestom.server.MinecraftServer; 4 | import net.minestom.server.instance.Chunk; 5 | import net.minestom.server.instance.DynamicChunk; 6 | import net.minestom.server.instance.IChunkLoader; 7 | import net.minestom.server.instance.Instance; 8 | import net.minestom.server.instance.block.Block; 9 | import net.minestom.server.instance.block.BlockHandler; 10 | import net.minestom.server.utils.NamespaceID; 11 | import net.minestom.server.utils.async.AsyncUtils; 12 | import net.minestom.server.world.biomes.Biome; 13 | import org.jetbrains.annotations.NotNull; 14 | import org.jetbrains.annotations.Nullable; 15 | import org.jglrxavpok.hephaistos.mca.AnvilException; 16 | import org.jglrxavpok.hephaistos.mca.BlockState; 17 | import org.jglrxavpok.hephaistos.mca.ChunkColumn; 18 | import org.jglrxavpok.hephaistos.mca.ChunkSection; 19 | import org.jglrxavpok.hephaistos.mca.CoordinatesKt; 20 | import org.jglrxavpok.hephaistos.mca.RegionFile; 21 | import org.jglrxavpok.hephaistos.mca.SupportedVersion; 22 | import org.jglrxavpok.hephaistos.nbt.NBT; 23 | import org.jglrxavpok.hephaistos.nbt.NBTCompound; 24 | import org.jglrxavpok.hephaistos.nbt.NBTException; 25 | import org.jglrxavpok.hephaistos.nbt.NBTReader; 26 | import org.jglrxavpok.hephaistos.nbt.NBTType; 27 | import org.jglrxavpok.hephaistos.nbt.NBTWriter; 28 | import org.jglrxavpok.hephaistos.nbt.mutable.MutableNBTCompound; 29 | import org.slf4j.Logger; 30 | import org.slf4j.LoggerFactory; 31 | 32 | import java.io.File; 33 | import java.io.IOException; 34 | import java.io.RandomAccessFile; 35 | import java.nio.file.Files; 36 | import java.nio.file.Path; 37 | import java.nio.file.StandardCopyOption; 38 | import java.util.ArrayList; 39 | import java.util.HashMap; 40 | import java.util.List; 41 | import java.util.Map; 42 | import java.util.Objects; 43 | import java.util.concurrent.CompletableFuture; 44 | import java.util.concurrent.ConcurrentHashMap; 45 | 46 | /** 47 | * A modified AnvilLoader simply to remove the annoying errors 48 | */ 49 | public class ConversionAnvilLoader implements IChunkLoader { 50 | private static final Logger LOGGER = LoggerFactory.getLogger(ConversionAnvilLoader.class); 51 | 52 | private static final CompletableFuture COMPLETED_FUTURE = CompletableFuture.completedFuture(null); 53 | private static final Biome BIOME = Biome.PLAINS; 54 | 55 | private final Map alreadyLoaded = new ConcurrentHashMap<>(); 56 | private final Path path; 57 | private final Path levelPath; 58 | public final Path regionPath; 59 | 60 | public ConversionAnvilLoader(@NotNull Path path) { 61 | this.path = path; 62 | this.levelPath = path.resolve("level.dat"); 63 | this.regionPath = path.resolve("region"); 64 | } 65 | 66 | public ConversionAnvilLoader(@NotNull String path) { 67 | this(Path.of(path)); 68 | } 69 | 70 | @Override 71 | public void loadInstance(@NotNull Instance instance) { 72 | if (!Files.exists(levelPath)) { 73 | return; 74 | } 75 | try (var reader = new NBTReader(Files.newInputStream(levelPath))) { 76 | final NBTCompound tag = (NBTCompound) reader.read(); 77 | Files.copy(levelPath, path.resolve("level.dat_old"), StandardCopyOption.REPLACE_EXISTING); 78 | instance.tagHandler().updateContent(tag); 79 | } catch (IOException | NBTException e) { 80 | MinecraftServer.getExceptionManager().handleException(e); 81 | } 82 | } 83 | 84 | @Override 85 | public @NotNull CompletableFuture<@Nullable Chunk> loadChunk(@NotNull Instance instance, int chunkX, int chunkZ) { 86 | LOGGER.debug("Attempt loading at {} {}", chunkX, chunkZ); 87 | if (!Files.exists(path)) { 88 | // No world folder 89 | return CompletableFuture.completedFuture(null); 90 | } 91 | try { 92 | return loadMCA(instance, chunkX, chunkZ); 93 | } catch (Exception e) { 94 | MinecraftServer.getExceptionManager().handleException(e); 95 | } 96 | return CompletableFuture.completedFuture(null); 97 | } 98 | 99 | public @NotNull CompletableFuture<@Nullable Chunk> loadMCA(Instance instance, int chunkX, int chunkZ) throws IOException, AnvilException { 100 | final RegionFile mcaFile = getMCAFile(instance, chunkX, chunkZ); 101 | if (mcaFile == null) 102 | return CompletableFuture.completedFuture(null); 103 | ChunkColumn fileChunk = null; 104 | try { 105 | fileChunk = mcaFile.getChunk(chunkX, chunkZ); 106 | } catch (AnvilException e) { 107 | 108 | } 109 | if (fileChunk == null) 110 | return CompletableFuture.completedFuture(null); 111 | 112 | Chunk chunk = new DynamicChunk(instance, chunkX, chunkZ); 113 | if(fileChunk.getMinY() < instance.getDimensionType().getMinY()) { 114 | return CompletableFuture.completedFuture(null); 115 | } 116 | if(fileChunk.getMaxY() > instance.getDimensionType().getMaxY()) { 117 | return CompletableFuture.completedFuture(null); 118 | } 119 | 120 | // TODO: Parallelize block, block entities and biome loading 121 | 122 | if (fileChunk.getGenerationStatus().compareTo(ChunkColumn.GenerationStatus.Biomes) > 0) { 123 | HashMap biomeCache = new HashMap<>(); 124 | 125 | for (ChunkSection section : fileChunk.getSections().values()) { 126 | if (section.getEmpty()) continue; 127 | for (int y = 0; y < Chunk.CHUNK_SECTION_SIZE; y++) { 128 | for (int z = 0; z < Chunk.CHUNK_SIZE_Z; z++) { 129 | for (int x = 0; x < Chunk.CHUNK_SIZE_X; x++) { 130 | int finalX = fileChunk.getX() * Chunk.CHUNK_SIZE_X + x; 131 | int finalZ = fileChunk.getZ() * Chunk.CHUNK_SIZE_Z + z; 132 | int finalY = section.getY() * Chunk.CHUNK_SECTION_SIZE + y; 133 | String biomeName = section.getBiome(x, y, z); 134 | Biome biome = biomeCache.computeIfAbsent(biomeName, n -> 135 | Objects.requireNonNullElse(MinecraftServer.getBiomeManager().getByName(NamespaceID.from(n)), BIOME)); 136 | chunk.setBiome(finalX, finalY, finalZ, biome); 137 | } 138 | } 139 | } 140 | } 141 | } 142 | 143 | // Blocks 144 | loadBlocks(chunk, fileChunk); 145 | loadTileEntities(chunk, fileChunk); 146 | // Lights 147 | for (int sectionY = chunk.getMinSection(); sectionY < chunk.getMaxSection(); sectionY++) { 148 | var section = chunk.getSection(sectionY); 149 | var chunkSection = fileChunk.getSection((byte) sectionY); 150 | section.setSkyLight(chunkSection.getSkyLights()); 151 | section.setBlockLight(chunkSection.getBlockLights()); 152 | } 153 | mcaFile.forget(fileChunk); 154 | return CompletableFuture.completedFuture(chunk); 155 | } 156 | 157 | public @Nullable RegionFile getMCAFile(Instance instance, int chunkX, int chunkZ) { 158 | final int regionX = CoordinatesKt.chunkToRegion(chunkX); 159 | final int regionZ = CoordinatesKt.chunkToRegion(chunkZ); 160 | return alreadyLoaded.computeIfAbsent(RegionFile.Companion.createFileName(regionX, regionZ), n -> { 161 | try { 162 | final Path regionPath = this.regionPath.resolve(n); 163 | if (!Files.exists(regionPath)) { 164 | return null; 165 | } 166 | return new RegionFile(new RandomAccessFile(regionPath.toFile(), "rw"), regionX, regionZ, instance.getDimensionType().getMinY(), instance.getDimensionType().getMaxY()-1); 167 | } catch (IOException | AnvilException e) { 168 | MinecraftServer.getExceptionManager().handleException(e); 169 | return null; 170 | } 171 | }); 172 | } 173 | 174 | private void loadBlocks(Chunk chunk, ChunkColumn fileChunk) { 175 | for (var section : fileChunk.getSections().values()) { 176 | if (section.getEmpty()) continue; 177 | final int yOffset = Chunk.CHUNK_SECTION_SIZE * section.getY(); 178 | for (int x = 0; x < Chunk.CHUNK_SECTION_SIZE; x++) { 179 | for (int z = 0; z < Chunk.CHUNK_SECTION_SIZE; z++) { 180 | for (int y = 0; y < Chunk.CHUNK_SECTION_SIZE; y++) { 181 | try { 182 | final BlockState blockState = section.get(x, y, z); 183 | final String blockName = blockState.getName(); 184 | if (blockName.equals("minecraft:air")) continue; 185 | Block block = Objects.requireNonNull(Block.fromNamespaceId(blockName)); 186 | // Properties 187 | final Map properties = blockState.getProperties(); 188 | if (!properties.isEmpty()) block = block.withProperties(properties); 189 | // Handler 190 | final BlockHandler handler = MinecraftServer.getBlockManager().getHandler(block.name()); 191 | if (handler != null) block = block.withHandler(handler); 192 | 193 | chunk.setBlock(x, y + yOffset, z, block); 194 | } catch (Exception e) { 195 | MinecraftServer.getExceptionManager().handleException(e); 196 | } 197 | } 198 | } 199 | } 200 | } 201 | } 202 | 203 | private void loadTileEntities(Chunk loadedChunk, ChunkColumn fileChunk) { 204 | for (NBTCompound te : fileChunk.getTileEntities()) { 205 | final var x = te.getInt("x"); 206 | final var y = te.getInt("y"); 207 | final var z = te.getInt("z"); 208 | if (x == null || y == null || z == null) { 209 | LOGGER.warn("Tile entity has failed to load due to invalid coordinate"); 210 | continue; 211 | } 212 | Block block = loadedChunk.getBlock(x, y, z); 213 | 214 | final String tileEntityID = te.getString("id"); 215 | if (tileEntityID != null) { 216 | final BlockHandler handler = MinecraftServer.getBlockManager().getHandlerOrDummy(tileEntityID); 217 | block = block.withHandler(handler); 218 | } 219 | // Remove anvil tags 220 | MutableNBTCompound mutableCopy = te.toMutableCompound(); 221 | mutableCopy.remove("id"); 222 | mutableCopy.remove("x"); 223 | mutableCopy.remove("y"); 224 | mutableCopy.remove("z"); 225 | mutableCopy.remove("keepPacked"); 226 | // Place block 227 | final var finalBlock = mutableCopy.getSize() > 0 ? 228 | block.withNbt(mutableCopy.toCompound()) : block; 229 | loadedChunk.setBlock(x, y, z, finalBlock); 230 | } 231 | } 232 | 233 | @Override 234 | public @NotNull CompletableFuture saveInstance(@NotNull Instance instance) { 235 | final var nbt = instance.tagHandler().asCompound(); 236 | if (nbt.isEmpty()) { 237 | // Instance has no data 238 | return COMPLETED_FUTURE; 239 | } 240 | try (NBTWriter writer = new NBTWriter(Files.newOutputStream(levelPath))) { 241 | writer.writeNamed("", nbt); 242 | } catch (IOException e) { 243 | e.printStackTrace(); 244 | } 245 | return COMPLETED_FUTURE; 246 | } 247 | 248 | @Override 249 | public @NotNull CompletableFuture saveChunk(@NotNull Chunk chunk) { 250 | final int chunkX = chunk.getChunkX(); 251 | final int chunkZ = chunk.getChunkZ(); 252 | RegionFile mcaFile; 253 | synchronized (alreadyLoaded) { 254 | mcaFile = getMCAFile(chunk.getInstance(), chunkX, chunkZ); 255 | if (mcaFile == null) { 256 | final int regionX = CoordinatesKt.chunkToRegion(chunkX); 257 | final int regionZ = CoordinatesKt.chunkToRegion(chunkZ); 258 | final String n = RegionFile.Companion.createFileName(regionX, regionZ); 259 | File regionFile = new File(regionPath.toFile(), n); 260 | try { 261 | if (!regionFile.exists()) { 262 | if (!regionFile.getParentFile().exists()) { 263 | regionFile.getParentFile().mkdirs(); 264 | } 265 | regionFile.createNewFile(); 266 | } 267 | mcaFile = new RegionFile(new RandomAccessFile(regionFile, "rw"), regionX, regionZ); 268 | alreadyLoaded.put(n, mcaFile); 269 | } catch (AnvilException | IOException e) { 270 | LOGGER.error("Failed to save chunk {},{}: {}", chunkX, chunkZ, e); 271 | MinecraftServer.getExceptionManager().handleException(e); 272 | return COMPLETED_FUTURE; 273 | } 274 | } 275 | } 276 | ChunkColumn column; 277 | try { 278 | column = mcaFile.getOrCreateChunk(chunkX, chunkZ); 279 | } catch (AnvilException | IOException e) { 280 | LOGGER.error("Failed to save chunk {},{}: {}", chunkX, chunkZ, e); 281 | MinecraftServer.getExceptionManager().handleException(e); 282 | return COMPLETED_FUTURE; 283 | } 284 | save(chunk, column); 285 | try { 286 | LOGGER.debug("Attempt saving at {} {}", chunk.getChunkX(), chunk.getChunkZ()); 287 | mcaFile.writeColumn(column); 288 | mcaFile.forget(column); 289 | } catch (IOException e) { 290 | LOGGER.error("Failed to save chunk {},{}: {}", chunkX, chunkZ, e); 291 | MinecraftServer.getExceptionManager().handleException(e); 292 | return COMPLETED_FUTURE; 293 | } 294 | return COMPLETED_FUTURE; 295 | } 296 | 297 | private void save(Chunk chunk, ChunkColumn chunkColumn) { 298 | chunkColumn.changeVersion(SupportedVersion.Companion.getLatest()); 299 | chunkColumn.setYRange(chunk.getMinSection()*16, chunk.getMaxSection()*16-1); 300 | List tileEntities = new ArrayList<>(); 301 | chunkColumn.setGenerationStatus(ChunkColumn.GenerationStatus.Full); 302 | for (int x = 0; x < Chunk.CHUNK_SIZE_X; x++) { 303 | for (int z = 0; z < Chunk.CHUNK_SIZE_Z; z++) { 304 | for (int y = chunkColumn.getMinY(); y < chunkColumn.getMaxY(); y++) { 305 | final Block block = chunk.getBlock(x, y, z); 306 | // Block 307 | chunkColumn.setBlockState(x, y, z, new BlockState(block.name(), block.properties())); 308 | chunkColumn.setBiome(x, y, z, chunk.getBiome(x, y, z).name().asString()); 309 | 310 | // Tile entity 311 | final BlockHandler handler = block.handler(); 312 | var originalNBT = block.nbt(); 313 | if (originalNBT != null || handler != null) { 314 | MutableNBTCompound nbt = originalNBT != null ? 315 | originalNBT.toMutableCompound() : new MutableNBTCompound(); 316 | 317 | if (handler != null) { 318 | nbt.setString("id", handler.getNamespaceId().asString()); 319 | } 320 | nbt.setInt("x", x + Chunk.CHUNK_SIZE_X * chunk.getChunkX()); 321 | nbt.setInt("y", y); 322 | nbt.setInt("z", z + Chunk.CHUNK_SIZE_Z * chunk.getChunkZ()); 323 | nbt.setByte("keepPacked", (byte) 0); 324 | tileEntities.add(nbt.toCompound()); 325 | } 326 | } 327 | } 328 | } 329 | chunkColumn.setTileEntities(NBT.List(NBTType.TAG_Compound, tileEntities)); 330 | } 331 | 332 | @Override 333 | public boolean supportsParallelLoading() { 334 | return true; 335 | } 336 | 337 | @Override 338 | public boolean supportsParallelSaving() { 339 | return true; 340 | } 341 | } 342 | --------------------------------------------------------------------------------